Quantcast
Channel: Scott Hanselman's Blog
Viewing all 1148 articles
Browse latest View live

Exploring Application Insights for disconnected or connected deep telemetry in ASP.NET Apps

$
0
0

Today on the ASP.NET Community Standup we learned about how you can use Application Insights in a disconnected scenario to get some cool - ahem - insights into your application.

Typically when someone sees Application Insights in the File | New Project dialog they assume it's a feature that only works in Azure, that will create some account for you and send your data to the cloud. While App Insights totally does do a lot of cool stuff when you have a cloud-hosted app and it does add a lot of value, it also supports a very useful "SDK only" mode that's totally offline.

Click "Add Application Insights to project" and then under "Send telemetry to" you click "Install SDK only" and no data gets sent to the cloud.

Application Insights dropdown - Install SDK only

Once you make your new project, can you learn more about AppInsights here.

For ASP.NET Core apps, Application Insights will include this package in your project.json - "Microsoft.ApplicationInsights.AspNetCore": "1.0.0" and it'll add itself into your middleware pipeline and register services in your Startup.cs. Remember, nothing is hidden in ASP.NET Core, so you can modify all this to your heart's content.

if (env.IsDevelopment())

{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}

Request telemetry and Exception telemetry are added separately, as you like.

Make sure you show the Application Insights Toolbar by right-clicking your toolbars and ensuring it's checked.

Application Insights Dropdown Menu

The button it adds is actually pretty useful.

Application Insights Dropdown Menu

Run your app and click the Application Insights button.

NOTE: I'm using Visual Studio Community. That's the free version of VS you can get at http://visualstudio.com/free. I use it exclusively and I think it's pretty cool that this feature works just great on VS Community.

You'll see the Search window open up in VS. You can keep it running while you debug and it'll fill with Requests, Traces, Exceptions, etc.

image

I added a Exceptional case to /about, and here's what I see:

Searching for the last hours traces

I can dig into each issue, filter, search, and explore deeper:

Unhandled Exception

And once I've found something interesting, I can explore around it with the full details of the HTTP Request. I find the "telemetry 5 minutes before and after" query to be very powerful.

Track Operations

Notice where it says "dependencies for this operation?" That's not dependencies like "Dependency Injection" - that's larger system-wide dependencies like "my app depends on this web service."

You can custom instrument your application with the TrackDependancy API if you like, and that will cause your system's dependency to  light up in AppInsights charts and reports. Here's a dumb example as I pretend that putting data in ViewData is a dependency. It should be calling a WebAPI or a Database or something.

var telemetry = new TelemetryClient();


var success = false;
var startTime = DateTime.UtcNow;
var timer = System.Diagnostics.Stopwatch.StartNew();
try
{
ViewData["Message"] = "Your application description page.";
}
finally
{
timer.Stop();
telemetry.TrackDependency("ViewDataAsDependancy", "CallSomeStuff", startTime, timer.Elapsed, success);
}

Once I'm Tracking external Dependencies I can search for outliers, long durations, categorize them, and they'll affect the generated charts and graphs if/when you do connect your App Insights to the cloud. Here's what I see, after making this one code change. I could build this kind of stuff into all my external calls AND instrument the JavaScript as well. (note Client and Server in this chart.)

Application Insight Maps

And once it's all there, I can query all the insights like this:

Querying Data Live

To be clear, though, you don't have to host your app in the cloud. You can just send the telemetry to the cloud for analysis. Your existing on-premises IIS servers can run a "Status Monitor" app for instrumentation.

Application Insights Charts

There's a TON of good data here and it's REALLY easy to get started either:

  • Totally offline (no cloud) and just query within Visual Studio
  • Somewhat online - Host your app locally and send telemetry to the cloud
  • Totally online - Host your app and telemetry in the cloud

All in all, I am pretty impressed. There's SDKs for Java, Node, Docker, and ASP.NET - There's a LOT here. I'm going to dig deeper.


Sponsor: Big thanks to Telerik! 60+ ASP.NET Core controls for every need. The most complete UI toolset for x-platform responsive web and cloud development. Try now 30 days for free!



© 2016 Scott Hanselman. All rights reserved.
     

Exploring ServiceStack's simple and fast web services on .NET Core

$
0
0

Northwind - ServiceStack styleI've been doing .NET Open Source since the beginning. Trying to get patches into log4net was hard without things like GitHub and Twitter. We emailed .patch files around and hoped for the best. It was a good time.

There's been a lot of feelings around .NET Open Source over the last decade or so - some positive, some negative. There's been some shining lights though and I'm going to do a few blog posts to call them out. I think having .NET Core be cross platform and open source will be a boon for the .NET Community. However, the community needs to also help out by using non-Microsoft OSS, supporting it, doing PRs, helping with docs, giving talks on new tech and spreading the word.

While some OSS projects are purely volunteer projects, ServiceStack has found some balance with a per-developer pricing model. They also support free usage for small projects. They've got deep integration with all major IDEs and support everything from VS, Xcode, IntelliJ IDEA, and the commandline.

ServiceStack Logo

One major announcement in the least few days as been ServiceStack 4.5.2 on .NET Core! Effectively one year to the day from the feature request and they did it! Their announcement paragraph says it best, emphasis mine.

Whilst the development and tooling experience is still in a transitionary period we believe .NET Core puts .NET Web and Server App development on the cusp of an exciting future - the kind .NET hasn’t seen before. The existing Windows hosting and VS.NET restraints have been freed, now anyone can develop using .NET’s productive expertly-designed and statically-typed mainstream C#/F# languages in their preferred editor and host it on the most popular server Operating Systems, in either an all-Linux, all-Windows or mixed ecosystem. Not only does this flexibility increase the value of existing .NET investments but it also makes .NET appeal to the wider and highly productive developer ecosystem who’ve previously disregarded .NET as an option.

Many folks ran (and run) ServiceStack on Mono, but it's time to move forward. While Mono is still a fantastic stack on many platforms that .NET Core doesn't support, for mainstream Linux, .NET Core is likely the better choice.

If you’re currently running ServiceStack on Mono, we strongly recommend upgrading to .NET Core to take advantage of its superior performance, stability and its top-to-bottom supported Technology Stack.

I also want to call out ServiceStack's amazing Release Notes. Frankly, we could all learn from Release Note this good - Microsoft absolutely included. These release notes are the now Gold Standard as far as I'm concerned. Additionally, ServiceStack's Live Demos are unmatched.

Enough gushing. What IS ServiceStack? It's a different .NET way for creating web services. I say you should give it a hard look if you're making Web Services today. They say this:

Service Stack provides an alternate, cleaner POCO-driven way of creating web services.

  • Simplicity
  • Speed
  • Best Practices
  • Model-driven, code-first, friction-free development
  • No XML config, no code-gen, conventional defaults
  • Smart - Infers intelligence from strongly typed DTOs
  • .NET and Mono
  • Highly testable - services are completely decoupled from HTTP
  • Mature - over 5+ years of development
  • Commercially supported and Continually Improved
  • and most importantly - with AutoQuery you get instant queryable APIs. Take a look at what AutoQuery does for a basic Northwind sample.

They've plugged into .NET Core and ASP.NET Core exactly as it was design. They've got sophisticated middleware and fits in cleanly and feels natural. Even more, if you have existing ServiceStack code running on .NET 4.x, they've designed their "AppHost" such that moving over the .NET Core is extremely simple.

ServiceStack has the standard "Todo" application running in both .NET Full Framework and .NET Core. Here's two sites, both .NET and both ServiceStack, but look what's underneath them:

Getting Started with Service Stack

There's a million great demos as I mentioned above with source at https://github.com/NetCoreApps, but I love that ServiceStack has a Northwind Database demo here https://github.com/NetCoreApps/Northwind. It even includes a Dockerfile. Let's check it out. I was able to get it running in Docker in seconds.

>git clone https://github.com/NetCoreApps/Northwind

>cd Northwind
>docker build -t "northwindss/latest" .
>docker run northwindss/latest
Project Northwind.ServiceModel (.NETStandard,Version=v1.6) was previously compiled. Skipping compilation.
Project Northwind.ServiceInterface (.NETStandard,Version=v1.6) was previously compiled. Skipping compilation.
Project Northwind (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
Hosting environment: Production
Content root path: /app/Northwind
Now listening on: https://*:5000
Application started. Press Ctrl+C to shut down.

Let's briefly look at the code, though. It is a great sample and showcases a couple cool features and also is nicely RESTful.

There's some cool techniques in here. It uses SqLITE for the database and the database itself is created with this Unit Test. Here's the ServiceStack AppHost (AppHost is their concept)

public class AppHost : AppHostBase

{
public AppHost() : base("Northwind Web Services", typeof(CustomersService).GetAssembly()) { }

public override void Configure(Container container)
{
container.Register<IDbConnectionFactory>(
new OrmLiteConnectionFactory(MapProjectPath("~/App_Data/Northwind.sqlite"), SqliteDialect.Provider));

//Use Redis Cache
//container.Register<ICacheClient>(new PooledRedisClientManager());

VCardFormat.Register(this);

Plugins.Add(new AutoQueryFeature { MaxLimit = 100 });
Plugins.Add(new AdminFeature());

Plugins.Add(new CorsFeature());
}
}

Note host the AppHost base references the Assembly that contains the CustomersService type. That's the assembly that is the ServiceInterface. There's a number of Services in there - CustomersService just happens to be a simple one:

public class CustomersService : Service

{
public object Get(Customers request) =>
new CustomersResponse { Customers = Db.Select<Customer>() };
}

The response for /customers is just the response and a list of Customers:

[DataContract]

[Route("/customers")]
public class Customers : IReturn<CustomersResponse> {}

[DataContract]
public class CustomersResponse : IHasResponseStatus
{
public CustomersResponse()
{
this.ResponseStatus = new ResponseStatus();
this.Customers = new List<Customer>();
}

[DataMember]
public List<Customer> Customers { get; set; }

[DataMember]
public ResponseStatus ResponseStatus { get; set; }
}

Customers has a lovely clean GET that you can see live here: http://northwind.netcore.io/customers. Compare its timestamp to the cached one at http://northwind.netcore.io/cached/customers.

[CacheResponse(Duration = 60 * 60, MaxAge = 30 * 60)]

public class CachedServices : Service
{
public object Get(CachedCustomers request) =>
Gateway.Send(new Customers());

public object Get(CachedCustomerDetails request) =>
Gateway.Send(new CustomerDetails { Id = request.Id });

public object Get(CachedOrders request) =>
Gateway.Send(new Orders { CustomerId = request.CustomerId, Page = request.Page });
}

You may find yourself looking at the source for the Northwind sample and wondering "where's the rest?" (no pun intended!) Turns out ServiceStack will do a LOT for you if you just let it!

The Northwind project is also an example of how much can be achieved with a minimal amount of effort and code. This entire website literally just consists of these three classes . Everything else seen here is automatically provided by ServiceStack using a code-first, convention-based approach. ServiceStack can infer a richer intelligence about your services to better able to provide more generic and re-usable functionality for free!

ServiceStack is an alternative to ASP.NET's Web API. It's a different perspective and a different architecture than what Microsoft provides out of the box. It's important and useful to explore other points of view when designing your systems. It's especially nice when the systems are so thoughtfully factored, well-documented and designed as ServiceStack. In fact, years ago I wrote their tagline: "Thoughtfully architected, obscenely fast, thoroughly enjoyable web services for all."

Have you used ServiceStack? Have you used other open source .NET Web Service/API frameworks? Share your experience in the comments!


Sponsor: Big thanks to Telerik! 60+ ASP.NET Core controls for every need. The most complete UI toolset for x-platform responsive web and cloud development. Try now 30 days for free!



© 2016 Scott Hanselman. All rights reserved.
     

Free ASP.NET Core 1.0 Training on Microsoft Virtual Academy

$
0
0

This time last year we did a Microsoft Virtual Academy class on what was then called "ASP.NET 5." It made sense to call it 5 since 5 > 4.6, right? But since then ASP.NET 5 has become .NET Core 1.0 and ASP.NET Core 1.0. It's 1.0 because it's smaller, newer, and different. As the .NET "full" framework marches on, on Windows, .NET Core is cross-platform and for the cloud.

Command line concepts like dnx, dnu, and dnvm have been unified into a single "dotnet" driver. You can download .NET Core at http://dot.net and along with http://code.visualstudio.com you can get a web site up and running in 10 minutes on Windows, Mac, or many flavors of Linux.

So, we've decided to update and refresh our Microsoft Virtual Academy. In fact, we've done three days of training. Introduction, Intermediate, and Cross-Platform. The introduction day is out and it's free! We'll be releasing the new two days of training very soon.

NOTE: There's a LOT of quality free courseware for learning .NET Core and ASP.NET Core. We've put the best at http://asp.net/free-courses and I encourage you to check them out!

Head over to Microsoft Virtual Academy and watch our new, free "Introduction to ASP.NET Core 1.0." It's a great relaxed pace if you've been out of the game for a bit, or you're a seasoned .NET "Full" developer who has avoided learning .NET Core thus far. If you don't know the C# language yet, check out our online C# tutorial first, then watch the video.

image

And help me out by adding a few stars there under Ratings. We're new. ;)


Sponsor: Do you deploy the same application multiple times for each of your end customers? The team at Octopus have taken the pain out of multi-tenant deployments. Check out their latest 3.4 release!



© 2016 Scott Hanselman. All rights reserved.
     

Using dotnet watch test for continuous testing with .NET Core and XUnit.net

$
0
0

When teaching .NET Core I do a lot of "dotnet new" Hello World demos to folks who've never seen it before. That has it's place, but I also wanted to show how easy it is to get setup with Unit Testing on .NET Core.

For this blog post I'm going to use the command line so you know there's nothing hidden, but you can also use Visual Studio or Visual Studio Code, of course. I'll start the command prompt then briefly move to Code.

Starting from an empty folder, I'll make a SomeApp folder and a SomeTests folder.

C:\example\someapp> dotnet new

C:\example\someapp> md ..\sometests && cd ..\sometests
C:\example\sometests> dotnet new -t xunittest

At this point I've got a HelloWorld app and a basic test but the two aren't related - They aren't attached and nothing real is being tested.

Tests are run with dotnet test, not dotnet run. Tests are libraries and don't have an entry point, so dotnet run isn't what you want.

c:\example>dotnet test SomeTests

Project SomeTests (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
xUnit.net .NET CLI test runner (64-bit win10-x64)
Discovering: SomeTests
Discovered: SomeTests
Starting: SomeTests
Finished: SomeTests
=== TEST EXECUTION SUMMARY ===
SomeTests Total: 1, Errors: 0, Failed: 0, Skipped: 0, Time: 0.197s
SUMMARY: Total: 1 targets, Passed: 1, Failed: 0.

I'll open my test project's project.json and add a reference to my other project.

{

"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable"
},
"dependencies": {
"System.Runtime.Serialization.Primitives": "4.1.1",
"xunit": "2.1.0",
"dotnet-test-xunit": "1.0.0-rc2-*"
},
"testRunner": "xunit",
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
},
"SomeApp": "1.0.0-*"
},
"imports": [
"dotnet5.4",
"portable-net451+win8"
]
}
}
}

I'll make a little thing to test in my App.

public class Calc {

public int Add(int x, int y) => x + y;
}

And add some tests.

public class Tests

{
[Fact]
public void TwoAndTwoIsFour()
{
var c = new Calc();
Assert.Equal(4, c.Add(2, 2));
}

[Fact]
public void TwoAndThreeIsFive()
{
var c = new Calc();
Assert.Equal(4, c.Add(2, 3));
}
}

Because the Test app references the other app/library, I can just make changes and run "dotnet test" from the command line. It will build both dependencies and run the tests all at once.

Here's the full output inclding both build and test.

c:\example> dotnet test SomeTests

Project SomeApp (.NETCoreApp,Version=v1.0) will be compiled because inputs were modified
Compiling SomeApp for .NETCoreApp,Version=v1.0

Compilation succeeded.
0 Warning(s)
0 Error(s)

Time elapsed 00:00:00.9814887
Project SomeTests (.NETCoreApp,Version=v1.0) will be compiled because dependencies changed
Compiling SomeTests for .NETCoreApp,Version=v1.0

Compilation succeeded.
0 Warning(s)
0 Error(s)

Time elapsed 00:00:01.0266293


xUnit.net .NET CLI test runner (64-bit win10-x64)
Discovering: SomeTests
Discovered: SomeTests
Starting: SomeTests
Tests.Tests.TwoAndThreeIsFive [FAIL]
Assert.Equal() Failure
Expected: 4
Actual: 5
Stack Trace:
c:\Users\scott\Desktop\testtest\SomeTests\Tests.cs(20,0): at Tests.Tests.TwoAndThreeIsFive()
Finished: SomeTests
=== TEST EXECUTION SUMMARY ===
SomeTests Total: 2, Errors: 0, Failed: 1, Skipped: 0, Time: 0.177s
SUMMARY: Total: 1 targets, Passed: 0, Failed: 1.

Oops, I made a mistake. I'll fix that test and run "dotnet test" again.

c:\example> dotnet test SomeTests

xUnit.net .NET CLI test runner (64-bit .NET Core win10-x64)
Discovering: SomeTests
Discovered: SomeTests
Starting: SomeTests
Finished: SomeTests
=== TEST EXECUTION SUMMARY ===
SomeTests Total: 2, Errors: 0, Failed: 0, Skipped: 0, Time: 0.145s
SUMMARY: Total: 1 targets, Passed: 1, Failed: 0.

I can keep changing code and running "dotnet test" but that's tedious. I'll add dotnet watch as a tool in my Test project's project.json.

{

"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable"
},
"dependencies": {
"System.Runtime.Serialization.Primitives": "4.1.1",
"xunit": "2.1.0",
"dotnet-test-xunit": "1.0.0-rc2-*"
},
"tools": {
"Microsoft.DotNet.Watcher.Tools": "1.0.0-preview2-final"
},
"testRunner": "xunit",
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
},
"SomeApp": "1.0.0-*"
},

"imports": [
"dotnet5.4",
"portable-net451+win8"
]
}
}
}

Then I'll go back and rather than typing  "dotnet test" I'll type "dotnet watch test."

c:\example> dotnet watch test

[DotNetWatcher] info: Running dotnet with the following arguments: test
[DotNetWatcher] info: dotnet process id: 14064
Project SomeApp (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
Project SomeTests (.NETCoreApp,Version=v1.0) will be compiled because inputs were modified
Compiling SomeTests for .NETCoreApp,Version=v1.0
Compilation succeeded.
0 Warning(s)
0 Error(s)
Time elapsed 00:00:01.1479348

xUnit.net .NET CLI test runner (64-bit .NET Core win10-x64)
Discovering: SomeTests
Discovered: SomeTests
Starting: SomeTests
Finished: SomeTests
=== TEST EXECUTION SUMMARY ===
SomeTests Total: 2, Errors: 0, Failed: 0, Skipped: 0, Time: 0.146s
SUMMARY: Total: 1 targets, Passed: 1, Failed: 0.
[DotNetWatcher] info: dotnet exit code: 0
[DotNetWatcher] info: Waiting for a file to change before restarting dotnet...

Now if I make a change to either the Tests or the projects under test it will automatically recompile and run the tests!

[DotNetWatcher] info: File changed: c:\example\SomeApp\Program.cs

[DotNetWatcher] info: Running dotnet with the following arguments: test
[DotNetWatcher] info: dotnet process id: 5492
Project SomeApp (.NETCoreApp,Version=v1.0) will be compiled because inputs were modified
Compiling SomeApp for .NETCoreApp,Version=v1.0

I'm able to do all of this with any text editor and a command prompt.

How do YOU test?


Sponsor: Do you deploy the same application multiple times for each of your end customers? The team at Octopus have taken the pain out of multi-tenant deployments. Check out their latest 3.4 release!



© 2016 Scott Hanselman. All rights reserved.
     

ASP.NET Core RESTful Web API versioning made easy

$
0
0

Pic by WoCTechChat used under Creative Commons There's a LOT of interesting and intense arguments that have been made around how you should version your Web API. As soon as you say RESTful it turns into a religious argument where folks may just well quote from the original text. ;)

Regardless of how you personally version your Web APIs, and side-stepping any arguments one way or the other, there's great new repository by Chris Martinez that Jon Galloway turned me on to at https://github.com/Microsoft/aspnet-api-versioning. There's ASP.NET 4.x Web API, ODATA with ASP.NET Web APIs, and now ASP.NET Core 1.x. Fortunately Chris has assembled a nicely factored set of libraries called "ASP.NET API Versioning" that add service API versioning in a very convenient way.

As Chris points out:

The default API versioning configuration is compliant with the versioning semantics outlined by the Microsoft REST Guidelines. There are also a number of customization and extension points available to support transitioning services that may not have supported API versioning in the past or supported API versioning with semantics that are different from the Microsoft REST versioning guidelines.

It's also worth pointing out how great the documentation is given it's mostly a one-contributor project. I'm sure Chris would appreciate your help though, even if you're a first timer.

Chris has NuGet packages for three flavors of Web APIs on ASP.NET:

But you should really clone the repo and check out his excellent samples.

When versioning services there's a few schools of thought and with ASP.NET Core it's super easy to get started:

public void ConfigureServices( IServiceCollection services )

{
services.AddMvc();
services.AddApiVersioning();

// remaining other stuff omitted for brevity
}

Oh, but you already have an API that's not versioned yet?

services.AddApiVersioning(

o =>
{
o.AssumeDefaultVersionWhenUnspecified = true );
o.DefaultApiVersion = new ApiVersion( new DateTime( 2016, 7, 1 ) );
} );

Your versions can look however'd you like them to:

  • /api/foo?api-version=1.0
  • /api/foo?api-version=2.0-Alpha
  • /api/foo?api-version=2015-05-01.3.0
  • /api/v1/foo
  • /api/v2.0-Alpha/foo
  • /api/v2015-05-01.3.0/foo

QueryString Parameter Versioning

I'm not a fan of this one, but here's the general idea:

[ApiVersion( "2.0" )]

[Route( "api/helloworld" )]
public class HelloWorld2Controller : Controller {
[HttpGet]
public string Get() => "Hello world!";
}

So this means to get 2.0 over 1.0 in another Controller with the same route, you'd go here:

/api/helloworld?api-version=2.0

Also, don't worry, you can use namespaces to have multiple HelloWorldControllers without having to have any numbers in the class names. ;)

URL Path Segment Versioning

This happens to be my first choice (yes I know Headers are "better," more on that later). You put the version in the route like this.

Here we're throwing in a little curveball. There's three versions but just two controllers.

[ApiVersion( "1.0" )]

[Route( "api/v{version:apiVersion}/[controller]" )]
public class HelloWorldController : Controller {
public string Get() => "Hello world!";
}

[ApiVersion( "2.0" )]
[ApiVersion( "3.0" )]
[Route( "api/v{version:apiVersion}/helloworld" )]
public class HelloWorld2Controller : Controller {
[HttpGet]
public string Get() => "Hello world v2!";

[HttpGet, MapToApiVersion( "3.0" )]
public string GetV3() => "Hello world v3!";
}

To be clear, you have total control, but the result from the outside is quite clean with /api/v[1|2|3]/helloworld. In fact, you can see with this example where this is more sophisticated than what you can do with routing out of the box. (I know some of you are thinking "meh I'll just make a route table." I think the semantics are much clearer and cleaner this way.

Header Versioning

Or, the hardest way (and the one that a lot of people this is best, but I disagree) is HTTP Headers. Set this up in ConfigureServices for ASP.NET Core:

public void ConfigureServices( IServiceCollection services )

{
services.AddMvc();
services.AddApiVersioning(o => o.ApiVersionReader = new HeaderApiVersionReader("api-version"));
}

When you do HeaderApiVersioning you won't be able to just do a GET in your browser, so I'll use Postman to add the header (or I could use Curl, or WGet, or PowerShell, or a Unit Test):

image

Deprecating

Speaking of semantics, here's a nice one. Let's say an API is going away in the next 6 months.

[ApiVersion( "2.0" )]

[ApiVersion( "1.0", Deprecated = true )]

This advertises that 1.0 is going away soon and that folks should consider 2.0. Where does it advertise this fact? The response headers!

api-supported-versions: 2.0, api-deprecated-versions: 1.0

All in all, this is very useful stuff and I'm happy to add it to my personal toolbox. Should this be built in? I don't know but I sure appreciate that it exists.

SIDE NOTE: There is/was the start of a VersionRoute over in the AspNet.Mvc repo. Maybe these folks need to join forces?

How do YOU version your Web APIs and Services?


Sponsor: Big thanks to Telerik! They recently launched their UI toolset for ASP.NET Core so feel free to check it out or learn more about ASP.NET Core development in their recent whitepaper.



© 2016 Scott Hanselman. All rights reserved.
     

The mystery of dotnet watch and 'Microsoft.NETCore.App', version '1.1.0-preview1-001100-00' was not found

$
0
0
dotnet watch says "specified framework not found"

WARNING: This post is full of internal technical stuff. I think it's interesting and useful. You may not.

I had an interesting Error/Warning happen when showing some folks .NET Core recently and I thought I'd deconstruct it here for you, Dear Reader, because it's somewhat multi-layered and it'll likely help you. It's not just about Core, but also NuGet, Versioning, Package Management in general, version pinning, "Tools" in .NET Core, as well as how .NET Runtimes work and version. That's a lot! All that from this little warning. Let's see what's up.

First, let's say you have .NET Core installed. You likely got it from http://dot.net and you have either 1.0.0 or the 1.0.1 update.

Then say you have a website, or any app at all. I made one with "dotnet new -t web" in an empty folder.

I added "dotnet watch" as a tool in the project.json like this. NOTE the "1.0.0-*" there.

"tools": {

"Microsoft.DotNet.Watcher.Tools": "1.0.0-*"
}

dotnet watch is nice because it watches the source code underneath it while running your app. If you change your code files, dotnet-watch will notice, and exit out, then launch "dotnet run" (or whatever, even test, etc) and your app will pick up the changes. It's a nice developer convenience.

I tested this out on last weekend and it worked great. I went to show some folks on Monday that same week and got this error when I typed "dotnet watch."

C:\Users\scott\Desktop\foofoo>dotnet watch

The specified framework 'Microsoft.NETCore.App', version '1.1.0-preview1-001100-00' was not found.
- Check application dependencies and target a framework version installed at:
C:\Program Files\dotnet\shared\Microsoft.NETCore.App
- The following versions are installed:
1.0.0
1.0.1
- Alternatively, install the framework version '1.1.0-preview1-001100-00'.

Let's really look at this. It says "the specified framework...1.1.0" was not found. That's weird, I'm not using that one. I check my project.json and I see:

"Microsoft.NETCore.App": {

"version": "1.0.1",
"type": "platform"
},

So who wants 1.1.0? I typed "dotnet watch." Can I "dotnet run?"

C:\Users\scott\Desktop\foofoo>dotnet run

Project foofoo (.NETCoreApp,Version=v1.0) will be compiled because expected outputs are missing
Compiling foofoo for .NETCoreApp,Version=v1.0
Hosting environment: Production
Content root path: C:\Users\scott\Desktop\foofoo
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

Hey, my app runs fine. But if I "dotnet watch" I get an error.

Remember that dotnet watch and other "tools" like it are not dependencies per se, but helpful sidecar apps. Tools can watch, squish css and js, precompile views, and do general administrivia that isn't appropriate at runtime.

It seems it's dotnet watch that wants something I don't have.

Now, I could go install the framework 1.1.0 that it's asking for, and the error would disappear, but would I know why? That would mean dotnet watch would use .NET Core 1.1.0 but my app (dotnet run) would use 1.0.1. That's likely fine, but is it intentional? Is it deterministic and what I wanted?

I'll open my generated project.lock.json. That's the calculated tree of what we ended up with after dotnet restore. It's a big calculated file but I can easily search it. I see two things. The internal details aren't interesting but version strings are.

First, I search for "dotnet.watcher" and I see this:

"projectFileToolGroups": {

".NETCoreApp,Version=v1.0": [
"Microsoft.AspNetCore.Razor.Tools >= 1.0.0-preview2-final",
"Microsoft.AspNetCore.Server.IISIntegration.Tools >= 1.0.0-preview2-final",
"Microsoft.DotNet.Watcher.Tools >= 1.0.0-*",
"Microsoft.EntityFrameworkCore.Tools >= 1.0.0-preview2-final",
"Microsoft.Extensions.SecretManager.Tools >= 1.0.0-preview2-final",
"Microsoft.VisualStudio.Web.CodeGeneration.Tools >= 1.0.0-preview2-final"
]

Ah, that's a reminder that I asked for 1.0.0-*. I asked for STAR for dotnet-watch but everything else was very clear. They were specific versions. I said "I don't care about the stuff after 1.0.0 for watch, gimme whatever's good."

It seems that a new version of dotnet-watch and other tools came out between the weekend and my demo.

Search more in project.lock.json and I can see what all it asked for...I can see my dotnet-watch's dependency tree.

"tools": {

".NETCoreApp,Version=v1.0": {
"Microsoft.DotNet.Watcher.Tools/1.0.0-preview3-final": {
"type": "package",
"dependencies": {
"Microsoft.DotNet.Cli.Utils": "1.0.0-preview2-003121",
"Microsoft.Extensions.CommandLineUtils": "1.1.0-preview1-final",
"Microsoft.Extensions.Logging": "1.1.0-preview1-final",
"Microsoft.Extensions.Logging.Console": "1.1.0-preview1-final",
"Microsoft.NETCore.App": "1.1.0-preview1-001100-00"
},

Hey now. I said "1.0.0-*" and I ended up with "1.0.0-preview3-final"

Looks like dotnet-watch is trying to bring in a whole new .NET Core. It wants 1.1.0. This new dotnet-watch is part of the wave of new preview stuff from 1.1.0.

But I want to stay on the released and supported "LTS" (long term support) stuff, not the new fancy builds.

I shouldn't have used 1.0.0-* as it was ambiguous. That might be great for my local versions or when I intend to chase the latest but not in this case.

I updated my version in my project.json to this and did a restore.

"Microsoft.DotNet.Watcher.Tools": "1.0.0-preview2-final",

Now I can reliably run dotnet restore and get what I want, and both dotnet watch and dotnet run use the same underlying runtime.


Sponsor: Big thanks to Telerik! They recently launched their UI toolset for ASP.NET Core so feel free to check it out or learn more about ASP.NET Core development in their recent whitepaper.


© 2016 Scott Hanselman. All rights reserved.
     

Stateless 3.0 - A State Machine library for .NET Core

$
0
0

.NET StandardState Machines and business processes that describe a series of states seem like they'll be easy to code but you'll eventually regret trying to do it yourself. Sure, you'll start with a boolean, then two, then you'll need to manage three states and there will be an invalid state to avoid then you'll just consider quitting all together. ;)

"Stateless" is a simple library for creating state machines in C# code. It's recently been updated to support .NET Core 1.0. They achieved this not by targeting .NET Core but by writing to the .NET Standard. Just like API levels in Android abstract away the many underlying versions of Android, .NET Standard is a set of APIs that all .NET platforms have to implement. Even better, the folks who wrote Stateless 3.0 targeted .NET Standard 1.0, which is the broadest and most compatible standard - it basically works everywhere and is portable across the .NET Framework on Windows, .NET Core on Windows, Mac, and LInux, as well as Windows Store apps and all phones.

Sure, there's Windows Workflow, but it may be overkill for some projects. In Nicholas Blumhardt's words:

...over time, the logic that decided which actions were allowed in each state, and what the state resulting from an action should be, grew into a tangle of if and switch. Inspired by Simple State Machine, I eventually refactored this out into a little state machine class that was configured declaratively: in this state, allow this trigger, transition to this other state, and so-on.

A state machine diagram describing the states a Bug can go throughYou can use state machines for anything. You can certainly describe high-level business state machines, but you can also easily model IoT device state, user interfaces, and more.

Even better, Stateless also serialize your state machine to a standard text-based "DOT Graph" format that can then be generated into an SVG or PNG like this with http://www.webgraphviz.com. It's super nice to be able to visualize state machines at runtime.

Modeling a Simple State Machine with Stateless

Let's look at a few code examples. You start by describing some finite states as an enum, and some finite "triggers" that cause a state to change. Like a switch could have On and Off as states and Toggle as a trigger.

A more useful example is the Bug Tracker included in the Stateless source on GitHub. To start with here are the states of a Bug and the Triggers that cause state to change:

enum State { Open, Assigned, Deferred, Resolved, Closed }

enum Trigger { Assign, Defer, Resolve, Close }

You then have your initial state, define your StateMachine, and if you like, you can pass Parameters when a state is trigger. For example, if a Bug is triggered with Assign you can pass in "Scott" so the bug goes into the Assigned state - assigned to Scott.

State _state = State.Open;

StateMachine<State, Trigger> _machine;
StateMachine<State, Trigger>.TriggerWithParameters<string> _assignTrigger;

string _title;
string _assignee;

Then, in this example, the Bug constructor describes the state machine using a fluent interface that reads rather nicely.

public Bug(string title)

{
_title = title;

_machine = new StateMachine<State, Trigger>(() => _state, s => _state = s);

_assignTrigger = _machine.SetTriggerParameters<string>(Trigger.Assign);

_machine.Configure(State.Open)
.Permit(Trigger.Assign, State.Assigned);

_machine.Configure(State.Assigned)
.SubstateOf(State.Open)
.OnEntryFrom(_assignTrigger, assignee => OnAssigned(assignee))
.PermitReentry(Trigger.Assign)
.Permit(Trigger.Close, State.Closed)
.Permit(Trigger.Defer, State.Deferred)
.OnExit(() => OnDeassigned());

_machine.Configure(State.Deferred)
.OnEntry(() => _assignee = null)
.Permit(Trigger.Assign, State.Assigned);
}

For example, when the State is Open, it can be Assigned. But as this is written (you can change it) you can't close a Bug that is Open but not Assigned. Make sense?

When the Bug is Assigned, you can Close it, Defer it, or Assign it again. That's PermitReentry(). Also, notice that Assigned is a Substate of Open.

You can have events that are fired as states change. Those events can take actions as you like.

void OnAssigned(string assignee)

{
if (_assignee != null && assignee != _assignee)
SendEmailToAssignee("Don't forget to help the new employee.");

_assignee = assignee;
SendEmailToAssignee("You own it.");
}

void OnDeassigned()
{
SendEmailToAssignee("You're off the hook.");
}

void SendEmailToAssignee(string message)
{
Console.WriteLine("{0}, RE {1}: {2}", _assignee, _title, message);
}

With a nice State Machine library like Stateless you can quickly model states that you'd ordinarily do with a "big ol' switch statement."

What have you used for state machines like this in your projects?


Sponsor: Big thanks to Telerik! They recently published a comprehensive whitepaper on The State of C#, discussing the history of C#, what’s new in C# 7 and whether C# is still a viable language. Check it out!



© 2016 Scott Hanselman. All rights reserved.
     

Visual Studio Code just keeps getting better - with extensions

$
0
0
Visual Studio Code

I've been a fan of Visual Studio Code (the free code editor) since it was released. But even though it continues to update itself as I use it, I didn't really grok how much cool stuff has been going on under the hood.

As of this writing. VSCode is on version 1.7.1. Here's the highlights of this new version:

But the REAL star and the REAL magic in VS Code - IMHO - is the growing VS Code Extension Gallery/Marketplace. Go check it out, but here's just a taste of the cool stuff that plugs nicely into Visual Studio Code.

Great Visual Studio Code Extensions

What are your favorite VS Code extensions?


Sponsor: Big thanks to Telerik! They recently published a comprehensive whitepaper on The State of C#, discussing the history of C#, what’s new in C# 7 and whether C# is still a viable language. Check it out!



© 2016 Scott Hanselman. All rights reserved.
     

WinAppDriver - Test any app with Appium's Selenium-like tests on Windows

$
0
0
WinAppDriver - Appium testing Windows Apps

I've found blog posts on my site where I'm using the Selenium Web Testing Framework as far back as 2007! Today there's Selenium Drivers for every web browser including Microsoft Edge. You can write Selenium tests in nearly any language these days including Ruby, Python, Java, and C#.

I'm a big Selenium fan. I like using it with systems like BrowserStack to automate across many different browser on many operating systems.

"Appium" is a great Selenium-like testing framework that implements the "WebDriver" protocol - formerly JsonWireProtocol.

WebDriver is a remote control interface that enables introspection and control of user agents. It provides a platform- and language-neutral wire protocol as a way for out-of-process programs to remotely instruct the behavior of web browsers.

From the Appium website, "Appium is 'cross-platform': it allows you to write tests against multiple platforms (iOS, Android, Windows), using the same API. This enables code reuse between iOS, Android, and Windows testsuites"

Appium is a webserver that exposes a REST API. The WinAppDriver enables Appium by using new APIs that were added in Windows 10 Anniversary Edition that allow you to test any Windows app. That means ANY Windows App. Win32, VB6, WPF, UWP, anything. Not only can you put any app in the Windows Store, you can do full and complete UI testing of those apps with a tool that is already familiar to Web Developers like myself.

Your preferred language, your preferred test runner, the Appium Server, and your app

You can write tests in C# and run them from Visual Studio's Test Runner. You can press any button and basically totally control your apps.

// Launch the calculator app

DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("app", "Microsoft.WindowsCalculator_8wekyb3d8bbwe!App");
CalculatorSession = new RemoteWebDriver(new Uri(WindowsApplicationDriverUrl), appCapabilities);
Assert.IsNotNull(CalculatorSession);
CalculatorSession.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2));
// Make sure we're in standard mode
CalculatorSession.FindElementByXPath("//Button[starts-with(@Name, \"Menu\")]").Click();
OriginalCalculatorMode = CalculatorSession.FindElementByXPath("//List[@AutomationId=\"FlyoutNav\"]//ListItem[@IsSelected=\"True\"]").Text;
CalculatorSession.FindElementByXPath("//ListItem[@Name=\"Standard Calculator\"]").Click();

It's surprisingly easy once you get started.

public void Addition()

{
CalculatorSession.FindElementByName("One").Click();
CalculatorSession.FindElementByName("Plus").Click();
CalculatorSession.FindElementByName("Seven").Click();
CalculatorSession.FindElementByName("Equals").Click();
Assert.AreEqual("Display is 8 ", CalculatorResult.Text);
}

You can automate any part of Windows, even the Start Menu or Cortana.

var searchBox = CortanaSession.FindElementByAccessibilityId("SearchTextBox");

Assert.IsNotNull(searchBox);
searchBox.SendKeys("What is eight times eleven");

var bingPane = CortanaSession.FindElementByName("Bing");
Assert.IsNotNull(bingPane);

var bingResult = bingPane.FindElementByName("88");
Assert.IsNotNull(bingResult);

If you use "AccessibiltyIds" and refer to native controls in a non-locale specific way you can even reuse test code across platforms. For example, you could write sign in code for Windows, iOS, your web app, and even a VB6 Win32 app. ;)

Testing a VB6 app with WinAppDriver

Appium and WebAppDriver a nice alternative to "CodedUI Tests." CodedUI tests are great but just for Windows apps. If you're a web developer or you are writing cross platform or mobile apps you should check it out.


Sponsor: Help your team write better, shareable SQL faster! Discover how your whole team can write better, shareable SQL faster with a free trial of SQL Prompt. Write, refactor and share SQL effortlessly, try it now.



© 2016 Scott Hanselman. All rights reserved.
     

The 2016 Christmas List of Best STEM Toys for your little nerds and nerdettes

$
0
0

Last year my 9 year old asked, "are we nerds yet?" Being a nerd doesn't have the negative stigma it once did. A nerd is a fan, and everyone should be enthusiastic about something. You might be a gardening nerd or a woodworking nerd. In this house, we are Maker Nerds. We've been doing some 3D Printing lately, and are trying to expand into all kinds of makings.

NOTE: We're gearing up for another year of March Is For Makers coming soon in March of 2017. Now is a great time for you to catch up on the last two year's amazing content with made in conjunction with http://codenewbie.org!

Here's a Christmas List of things that I've either personally purchased, tried for a time, or borrowed from a friend. These are great toys and products for kids of all genders and people of all ages.

Sphero Star Wars BB-8 App Controlled Robot

Sphero was a toy the kids got for Christmas last year that they are still playing with. Of course, there's the Original Sphero that's just a white ball with zero personality. I remember when it  came out and I was like, "meh, ok." But then Star Wars happened and I tell ya, you add a little head on the thing and give it some personality and it's a whole new toy.

Sphero Star Wars BB-8 App Controlled Robot

The Sphero team continues to update the firmware and software inside BB-8 even now and recently added a new "Sphero Force Band" so you can control Sphero with gestures.

However, the best part is that Sphero supports a new system called "The SPRK Lightning Lab" (available for Android, iOS, or other devices) that lets kids program BB-8 directly! It's basically Scratch for BB-8. You can even use a C-style language called OVAL when you outgrow their Scratchy system.

Meccano Micronoids

81r9vmEHZvL._SL1500_

I grew up in a world of Lincoln Logs and Erector Sets. We were always building something with metal and screws. Well, sets like this still exist with actual screws and metal...they just include more plastic than before. Any of these Meccano sets are super fun for little builders. They are in some ways cooler than LEGO for my kids because of the shear size of them. The Meccano Meccanoid 2.0 is HUGE at almost two feet tall. It's got 6 motors and there's three ways to program it. There's a large variety of Meccano robot and building kids from $20 on up, so they fit most budgets.

Arduino UNO Project Super Starter Kit from Elegoo

91XepSwZP5L._SL1457_

Arduino Kits are a little touch and go. They usually say things like "1000 pieces!"...but they count all the resistors and screws as a single part. Ignore that and try to look at the underlying pieces and the possibilities. Things move quickly and you'll sometimes need to debug Arudino Programs or search for updates but the fundamentals are great for kids 8-13.

I particularly like this Elegoo Arduino UNO Starter Kit as it includes everything you'll need and more to start playing immediately. If you can swing a little more money you can add on touchscreens, speakers, and even a little robot car kit, although the difficulty ratchets up.

Snap Circuits

Snap Circuits

I recommended these before on twitter, and truly, I can't sing about them enough. I love Snap Circuits and have blogged about them before on my blog. We quickly outgrew the 30 parts in the Snap Circuits Jr. Even though it has 100 projects, I recommend you get the Snap Circuits SC-300 that has 60 parts and 300 projects, or do what we did and just get the Snap Circuits Extreme SC-750 that has 80+ parts and 750 projects. I like this one because it includes a computer interface (via your microphone jack, so any old computer will work!) as well as a Solar Panel.

In 2016 Snap Circuits added a new "3D" kit that lets you build not just on a flat surface but expands building up walls! If you already have a SnapCircuits kit, remember that they all work together so you can pick this one up as well and combine them!

91NYoJujYYL._SL1500_

Secret Messages Kit

It's a fact - little kids LOVE secret messages. My kids are always doing secret notes with lemon juice as invisible ink. This kit brings a ton of "hidden writing systems" together in one inexpensive package. Ciphers, Braille, Code Breaking, and more are all combined into a narrative of secret spy missions.

817VYGOwvkL._SL1200_

What educational toys do YOU recommend this holiday season?

FYI: These Amazon links are referral links. When you use them I get a tiny percentage. It adds up to taco money for me and the kids! I appreciate you - and you appreciate me-  when you use these links to buy stuff.


Sponsor: Help your team write better, shareable SQL faster! Discover how your whole team can write better, shareable SQL faster with a free trial of SQL Prompt. Write, refactor and share SQL effortlessly, try it now.


© 2016 Scott Hanselman. All rights reserved.
     

Publishing ASP.NET Core 1.1 applications to Azure using git deploy

$
0
0

I took an ASP.NET Core 1.0 application and updated its package references to ASP.NET 1.1 today. I also updated to my SDK to the Current (not the LTS - Long Term Support version). Everything worked great building and running locally, but then I made a new Web App in Azure and did a quick git deploy.

Deploying ASP.NET Core 1.1 to Azure

Basically:

c:\aspnetcore11app> azure site create "aspnetcore11test" --location "West US" --git

c:\aspnetcore11app> git add .
c:\aspnetcore11app> git commit -m "initial"
c:\aspnetcore11app> git push azure master

Then I watched the logs go by. You can watch them at the command line or from within the Azure Portal under "Log Stream."

The deployment failed when Azure was building the app and got this error:

Build started 11/25/2016 6:51:54 AM.
2016-11-25T06:51:55         1>Project "D:\home\site\repository\aspnet1.1.xproj" on node 1 (Publish target(s)).
2016-11-25T06:51:55         1>D:\home\site\repository\aspnet1.1.xproj(7,3): error MSB4019: The imported project "D:\Program Files (x86)\dotnet\sdk\1.0.0-preview3-004056\Extensions\Microsoft\VisualStudio\v14.0\DotNet\Microsoft.DotNet.Props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
2016-11-25T06:51:55         1>Done Building Project "D:\home\site\repository\aspnet1.1.xproj" (Publish target(s)) -- FAILED.
2016-11-25T06:51:55    

See where it says "1.0.0-preview3-004056" in there? Looks like Azure Web Apps has some build that isn't the one that I have. Theirs has the new csproj/msbuild stuff and I'm staying a few steps back waiting for things to bake.

Remember that unless you specify the SDK version, .NET Core will use whatever is the latest one on the box.

Well, what do I have locally?

C:\aspnetcore11app>dotnet --version

1.0.0-preview2-1-003177

OK, then that's what I need to use so I'll make a global.json at the root of my project, then move my code into a folder under "src" for example.

{

"projects": [ "src", "test" ],
"sdk": {
"version": "1.0.0-preview2-1-003177"
}
}

Here I'm "pinning" the same SDK version. This will tell Azure (or you, if I gave you the code) to use this SDK version when building.

Now I'll redeploy with a git add, commit, and push. It works.

I think this should be easier, but I'm not sure how it should be easier. Does this mean that everyone should have a global.json with a preferred version? If you have no preferred version should Azure give a smarter error if it has an incompatible newer one?

The learning here for me is that not having a global.json basically says "*.*" to any cloud build servers and you'll get whatever latest SDK they have. It could stop working any day.


Sponsor: Big thanks to Octopus Deploy! Do you deploy the same application multiple times for each of your end customers? The team at Octopus have taken the pain out of multi-tenant deployments. Check out their latest 3.4 release!



© 2016 Scott Hanselman. All rights reserved.
     

Docker on a Synology NAS - Also running ASP.NET and .NET Core!

$
0
0

Docker on Synology is amazingI love my Synology NAS (Network Attached Storage) device. It has sat quietly in my server closet for almost 5 years now. It was a fantastic investment. I've filled it with 8TB of inexpensive Seagate Drives and it does its own flavor of RAID to give me roughly 5TB (which, for my house is effectively infinite) of storage. In my house it's just \\SERVER or http://server. It's a little GNU Linux machine that is easier to manage and maintain (and generally deal with) that just chills in the closet. It's a personal cloud.

It also runs:

  • Plex - It's a media server with over 15 years of home movies and photos. It's even more magical when used with an Xbox One. It transcodes videos that then download to my Windows tablets or iPad...then I watch them offline on the plane.
  • VPN Server - I can remotely connect to my house. Even stream Netflix when I'm overseas.
  • Surveillance Station - It acts as a DVR and manages streams from a dozen cameras both inside and outside the house, scanning for motion and storing nearly a week of video.
  • Murmur/Mumble Server - Your own private VOIP chat service. Used for podcasts, gaming, private calls that aren't over Skype, etc.
  • Cloud Sync/Backup - I have files in Google Drive, Dropbox, and OneDrive...but I have them entirely backed up on my Synology with their Cloud Sync.

51FvMne3PyL._SL1280_Every year my Synology gets better with software upgrades. The biggest and most significant upgrade to Synology has been the addition of Docker and the Docker ecosystem. There is first class support for Docker on Synology. There are some Synology devices that are cheaper and use ARM processors. Make sure you get one with an Intel processor for best compatibility. Get the best one you can and you'll find new uses for it all the time! I have the 1511 (now 1515) and it's amazing.

ASP.NET Core on Docker on Synology

A month ago Glenn Condron and I did a Microsoft Virtual Academy on Containers and Cross-Platform .NET (coming soon!) and we made this little app and put it in Docker. It's "glennc/fancypants." That means I can easily run it anywhere with just:

docker run glennc/fancypants

Sometimes a DockerFile for ASP.NET Core can be as basic as this:

FROM microsoft/aspnetcore:1.0.1

ENTRYPOINT ["dotnet", "WebApplication4.dll"]
ARG source=.
WORKDIR /app
EXPOSE 80
COPY $source .

You could certainly use Docker Compose and have your Synology running Redis, MySql, ASP.NET Core, whatever.

Even better, since Synology has such a great UI, here is Glenn's app in the Synology web-based admin tool:

Docker on Synology - Node and ASP.NET Core Apps 

I can ssh into the Synology (you'll need to SSH in as root, or you'll want to set up Docker to allow another user to avoid this) and run docker commands directly, or I can use their excellent UI. It's really one of the nicest Docker UIs I've seen. I was able to get ASP.NET Core and the Node.js Ghost blog running in minutes with modest RAM requirements.

image

Once Containers exist in Docker on Synology you can "turn them on and off" like any service.

ASP.NET Core on Docker on Synology

This also means that your Synology can now run any Docker-based service like a private version of GitLab (good instructions here)! You could then (if you like) do cool domain mappings like gitlab.hanselman.com:someport and have your Synology do the work. The Synology could then run Jenkins or Travis as well which makes my home server fit nicely into my development workflow without use any compute resources on my main machine (or using any cloud resource at all!)

The next step for me will be to connect to Docker running on Synology remotely from my Windows machine, then setup "F5 Docker Debugging" in Visual Studio.

image

Anyone else using a Synology?

* My Amazon links pay for tacos. Please use them.


Sponsor: Big thanks to Octopus Deploy! Do you deploy the same application multiple times for each of your end customers? The team at Octopus have taken the pain out of multi-tenant deployments. Check out their latest 3.4 release!


© 2016 Scott Hanselman. All rights reserved.
     

I suck at vacation - What I did this week

$
0
0

Well, it seems I'm lousy at vacation. I'm still learning what I'm supposed to do. My wife is working and the kids are still in school so here was my week.

3D Printed Brackets for my new HTC Vive

I treated myself to an HTC Vive Room-Scale VR system. I'll blog extensively about this later but let me just tell you. It's AMAZING. I've used Google Cardboard, I've used Gear VR, I've used Oculus. Vive is it. Full Room-scale VR with something like the Doom 3 VR Mode is amazing. This fellow has a version of Doom 3 coded up at GitHub that modifies your existing purchased version and adds a REALLY compelling VR experience. I will say spent less time fighting demons and more time looking closely at wall textures. I admit it.

There's a joke about folks who have 3D Printers. We just end up printing brackets to hold stuff.  Well, I got a Vive so I wanted a nice way to mount it. Problem solved.

I dig #3Dprinting because you can make EXACTLY the brackets you need in a few hours!

A photo posted by Scott Hanselman (@shanselman) on

3D Printed a Rifle Stock for the Vive

There's a popular VR game called Onward. It's basically a Call of Duty-type squad shooter with a focus on squad teamwork and realism. However, holding two VR controllers up to your cheek and pretending they are a rifle doesn't really work. Fortunately an intrepid maker named SGU7 made a prototype you can 3D Print.

I made one first in Yellow but it broken because it lacked enough infill. I made it again in black (because I had a lot of black. I wish it looked less aggressive, though) and it works great. Note that the part in my hand is a controller and the other controller is attached to the front. The front one can pop off and act as your left hand to reload and throw grenades.

It was a challenging print with five large pieces and two small along with screws and nuts to hold it together. However, it was super fun and it makes the game WAY more realistic. More on this later. I've also been experimenting with some new exotic filaments.

37b7b79b793db7b489b50496b1f5787a_preview_featured

Made an AdaFruit Cupcade Raspberry Pi MAME Arcade

My teenage nephew and I worked on a Cupcade a few months ago but it was his. I 3d printed and made a PiGrrl (Raspberry Pi GameBoy) last year, so I figured I'd make a Cupcade (Raspberry Pi tiny Multi-Arcade Machine Emulator) as well. It's also somewhat challenging but I never really had the time until vacation. You can get the plans and source many of the parts locally, or you can get a complete kit from Adafruit. I did the partial kit for cheaper without the plastic case, then had a local makerspace lasercut a $5 piece of clear acrylic.

Set up Alexa to talk to my Nightscout-based Blood Sugar system

I got a few Amazon Alexa "Echo Dot" devices, so now we have three around the house. I upgraded my Nightscout Site (this is the Azure-based system that that allows remote management and viewing of my blood sugar as a Type 1 Diabetic.

The most recent update of Nightscout added Alexa support. I headed over to https://developer.amazon.com and made a dev account and got it all working. It's pretty slick. I can ask it all kinds of things (as can my kids. They love to know about how I'm doing when I'm out of town.)

image

Here's a video of it working!

"Alexa, what's my blood sugar?" #Diabetes @nightscoutproj #video

A video posted by Scott Hanselman (@shanselman) on


Basically I've been just making stuff and fixing stuff around the house. I even sat in a café and read the news. Madness.

I wonder if I could do this full time? I guess that's called retirement. ;)


Sponsor: Big thanks to Octopus Deploy! Do you deploy the same application multiple times for each of your end customers? The team at Octopus have taken the pain out of multi-tenant deployments. Check out their latest 3.4 release



© 2016 Scott Hanselman. All rights reserved.
     

NoSQL .NET Core development using an local Azure DocumentDB Emulator

$
0
0

I was hanging out with Miguel de Icaza in New York a few weeks ago and he was sharing with me his ongoing love affair with a NoSQL Database called Azure DocumentDB. I've looked at it a few times over the last year or so and though it was cool but I didn't feel like using it for a few reasons:

  • Can't develop locally - I'm often in low-bandwidth or airplane situations
  • No MongoDB support - I have existing apps written in Node that use Mongo
  • No .NET Core support - I'm doing mostly cross-platform .NET Core apps

Miguel told me to take a closer look. Looks like things have changed! DocumentDB now has:

  • Free local DocumentDB Emulator - I asked and this is the SAME code that runs in Azure with just changes like using the local file system for persistence, etc. It's an "emulator" but it's really the essential same core engine code. There is no cost and no sign in for the local DocumentDB emulator.
  • MongoDB protocol support - This is amazing. I literally took an existing Node app, downloaded MongoChef and copied my collection over into Azure using a standard MongoDB connection string, then pointed my app at DocumentDB and it just worked. It's using DocumentDB for storage though, which gives me
    • Better Latency
    • Turnkey global geo-replication (like literally a few clicks)
    • A performance SLA with <10ms read and <15ms write (Service Level Agreement)
    • Metrics and Resource Management like every Azure Service
  • DocumentDB .NET Core Preview SDK that has feature parity with the .NET Framework SDK.

There's also Node, .NET, Python, Java, and C++ SDKs for DocumentDB so it's nice for gaming on Unity, Web Apps, or any .NET App...including Xamarin mobile apps on iOS and Android which is why Miguel is so hype on it.

Azure DocumentDB Local Quick Start

I wanted to see how quickly I could get started. I spoke with the PM for the project on Azure Friday and downloaded and installed the local emulator. The lead on the project said it's Windows for now but they are looking for cross-platform solutions. After it was installed it popped up my web browser with a local web page - I wish more development tools would have such clean Quick Starts. There's also a nice quick start on using DocumentDB with ASP.NET MVC.

NOTE: This is a 0.1.0 release. Definitely Alpha level. For example, the sample included looks like it had the package name changed at some point so it didn't line up. I had to change "Microsoft.Azure.Documents.Client": "0.1.0" to "Microsoft.Azure.DocumentDB.Core": "0.1.0-preview" so a little attention to detail issue there. I believe the intent is for stuff to Just Work. ;)

Nice DocumentDB Quick Start

The sample app is a pretty standard "ToDo" app:

ASP.NET MVC ToDo App using Azure Document DB local emulator

The local Emulator also includes a web-based local Data Explorer:

image

A Todo Item is really just a POCO (Plain Old CLR Object) like this:

namespace todo.Models
{
    using Newtonsoft.Json;
    public class Item
    {
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }
        [JsonProperty(PropertyName = "description")]
        public string Description { get; set; }
        [JsonProperty(PropertyName = "isComplete")]
        public bool Completed { get; set; }
    }
}

The MVC Controller in the sample uses an underlying repository pattern so the code is super simple at that layer - as an example:

[ActionName("Index")]

public async Task<IActionResult> Index()
{
var items = await DocumentDBRepository<Item>.GetItemsAsync(d => !d.Completed);
return View(items);
}

[HttpPost]
[ActionName("Create")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CreateAsync([Bind("Id,Name,Description,Completed")] Item item)
{
if (ModelState.IsValid)
{
await DocumentDBRepository<Item>.CreateItemAsync(item);
return RedirectToAction("Index");
}

return View(item);
}

The Repository itself that's abstracting away the complexities is itself not that complex. It's like 120 lines of code, and really more like 60 when you remove whitespace and curly braces. And half of that is just initialization and setup. It's also DocumentDBRepository<T> so it's a generic you can change to meet your tastes and use it however you'd like.

The only thing that stands out to me in this sample is the loop in GetItemsAsync that's hiding potential paging/chunking. It's nice you can pass in a predicate but I'll want to go and put in some paging logic for large collections.

public static async Task<T> GetItemAsync(string id)
{
    try
    {
        Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id));
        return (T)(dynamic)document;
    }
    catch (DocumentClientException e)
    {
        if (e.StatusCode == System.Net.HttpStatusCode.NotFound){
            return null;
        }
        else {
            throw;
        }
    }
}
public static async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, bool>> predicate)
{
    IDocumentQuery<T> query = client.CreateDocumentQuery<T>(
        UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
        new FeedOptions { MaxItemCount = -1 })
        .Where(predicate)
        .AsDocumentQuery();
    List<T> results = new List<T>();
    while (query.HasMoreResults){
        results.AddRange(await query.ExecuteNextAsync<T>());
    }
    return results;
}
public static async Task<Document> CreateItemAsync(T item)
{
    return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), item);
}
public static async Task<Document> UpdateItemAsync(string id, T item)
{
    return await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), item);
}
public static async Task DeleteItemAsync(string id)
{
    await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id));
}

I'm going to keep playing with this but so far I'm pretty happy I can get this far while on an airplane. It's really easy (given I'm preferring NoSQL over SQL lately) to just through objects at it and store them.

In another post I'm going to look at RavenDB, another great NoSQL Document Database that works on .NET Core that s also Open Source.


Sponsor: Big thanks to Octopus Deploy! Do you deploy the same application multiple times for each of your end customers? The team at Octopus have taken the pain out of multi-tenant deployments. Check out their latest 3.4 release


© 2016 Scott Hanselman. All rights reserved.
     

Awesome, legal, wireless retrogaming with a Hyperkin Retron 5 and 8bitdo's nes30pro

$
0
0

Hyperkin Retron 5 is amazing with an 8bitdo nes30pro!My kids and I are big fans of retrogaming. We have a whole collection of real consoles including N64, Dreamcast, PS2, Genesis, and more. However, playing these older consoles on new systems often involves a bunch of weird AV solutions to get HDMI out to your TV. Additionally, most retro controllers don't have a wire that's long enough for today's 55" and larger flatscreens.

We wanted a nice solution that would let us play a bunch of our games AND include a wireless controller option. Here's the combination of products that we ended up with for retrogaming this Christmas season.

Hyperkin Retro Console

There's a company called Hyperkin that makes a series of retro-consoles. They've got the Hyperkin Retron 2, Hyperkin Retron  3, and my favorite (and the one YOU should get) the Hyperkin Retron 5. You'd think the Hyperkin 5 would let you play five consoles, but it actually lets you play NES, SNES, Super Famicom, Genesis, Mega Drive, Famicom, Game Boy, Game Boy Color, and GBA (Gameboy advance) cartridges on one system. It has five slots. ;)

Everyone's talking about how they can't find the NES Classic Edition. I'd spend that money on a Hyperkin and then go out and buy a few actual game carts from your local retro gaming shop.

I like the Hyperkin Retron 5 over the lesser models for a few reasons.

  • It outputs HDMI natively for all it's emulated consoles.
  • It's got great firmware that is updated fairly often.
  • Its firmware has video features like adding fake CRT scanlines for authenticity (we like playing that way)
  • It supports cheats ;)
  • It's got multiple, real ports that support your existing console gamepads
  • You can use one system's controller for another. For example, a SNES gamepad on an NES game.

The only bad things about the Hyperkin Retron 5 is that the included controller kind of sucks and with all console games, you need to be fairly careful inserting and removing the cartridges.

8bitdo NES30 Pro Game Controller

You might assume the 8bitdo NES30 Pro Game Controller would be a cheap overseas knockoff controller but it's REALLY well made and it's REALLY more useful than I realized when I got it!

8bitdo controller

There are a number of these controllers from this company. The NES30 is nice but the NES30 Pro includes two analog sticks while still keeping the classic style. Think of it as almost a portable Xbox 360 controller! In fact, when you plug it into your PC with a USB cable it shows up as an Xbox 360 controller! That means it works great for Steam games. I've been carrying it in my bag on trips and gaming on my laptop.

for-pcThe build quality of the pad is great, but it's the extendable firmware that really makes the 8bitdo NES30 Pro shine. It has support to act as a Wiimote and even custom firmware for a...wait for it...Retron 5 mode! This means you can use this controller as a replacement for the Retron and play all the consoles it supports.

Even better, the 8bitdo NES30 Pro Game Controller also supports iOS, Android, etc. It's really just about perfect. My only complaint is that you have to turn it on while holding certain buttons in order to start in the various modes. So there's Bluetooth mode, iOS mode, Xbox mode, etc. Not a huge deal, but I've printed out the manual to keep it all straight.

8bitdo Controller Wireless Receiver

Here's where the magic happened. Because the 8bitdo NES30 Pro is a Bluetooth device, there's wireless receivers available for it for most consoles! If you have an NES or you managed to find an NES Classic, there's an 8bitdo Retro Receiver for NES.

However, I recommend you get the 8bitdo Bluetooth SNES Retro Receiver and plug it into the Hyperkin Retron 5. This, for us, has been the sweet spot. It works great with all games and we've got HDMI output from the Retron while still being able to sit back on the couch and game. You can also get two if you like and play multiplayer. As for power, the receiver needs just 100mA and leeches that power from the SNES port.

Even better, this Retro Receiver lets you use existing controllers as wireless controllers to whatever! So you can use your Wii U or PS3 controllers (since they are Bluetooth!) and retrogame with those.

If that wasn't awesome enough, the Retro Receiver can act as a generic "X-Input" controller for your PC or Mac. You plug an included Micro-USB cable into it and then pair your PS3, PS4, or Wii Remote into your computer and use it!

To be clear, I have no relationship with the 8bitdo company but everything they make is gold.


Sponsor: Big thanks to Redgate! Help your team write better, shareable SQL faster. Discover how your whole team can write better, shareable SQL faster with a free trial of SQL Prompt. Write, refactor and share SQL effortlessly, try it now!


© 2016 Scott Hanselman. All rights reserved.
     

Exploring Wyam - a .NET Static Site Content Generator

$
0
0

It's a bit of a renaissance out there when it comes to Static Site Generators. There's Jekyll and GitBook, Hugo and Hexo. Middleman and Pelican, Brunch and Octopress. There's dozens, if not hundreds of static site content generators, and "long tail is long."

Wyam is a great .NET based open source static site generator

Static Generators a nice for sites that DO get updated with dynamic content, but just not updated every few minutes. That means a Static Site Generator can be great for documentation, blogs, your brochure-ware home page, product catalogs, resumes, and lots more. Why install WordPress when you don't need to hit a database or generate HTML on every page view? Why not generate your site only when it changes?

I recently heard about a .NET Core-based open source generator called Wyam and wanted to check it out.

Wyam is a simple to use, highly modular, and extremely configurable static content generator that can be used to generate web sites, produce documentation, create ebooks, and much more.

Wyam is a module system with a pipeline that you can configure and chain processes together however you like. You can generate HTML from Markdown, from Razor, even XSLT2 - anything you like, really. Wyam also integrates nicely into your continuous build systems like Cake and others, so you can also get the Nuget Tools package for Wyam.

There's a few ways to get Wyam but I downloaded the setup.exe from GitHub Releases. You can also just get a ZIP and download it to any folder. When I ran the setup.exe it flashed (I didn't see a dialog, but it's beta so I'll chalk it up to that) and it installed to C:\Users\scott\AppData\Local\Wyam with what looked like the Squirrel installer from GitHub and Paul Betts.

Wyam has a number of nice features that .NET Folks will find useful.

Let's see what I can do with http://wyam.io in just a few minutes!

Scaffolding a Blog

Wyam has a similar command line syntax as dotnet.exe and it uses "recipes" so I can say --recipe Blog and I'll get:

C:\Users\scott\Desktop\wyamtest>wyam new --recipe Blog

Wyam version 0.14.1-beta

,@@@@@ /@\ @@@@@
@@@@@@ @@@@@| $@@@@@h
$@@@@@ ,@@@@@@@ g@@@@@P
]@@@@@M g@@@@@@@ g@@@@@P
$@@@@@ @@@@@@@@@ g@@@@@P
j@@@@@ g@@@@@@@@@p ,@@@@@@@
$@@@@@g@@@@@@@@B@@@@@@@@@@@P
`$@@@@@@@@@@@` ]@@@@@@@@@`
$@@@@@@@P` ?$@@@@@P
`^`` *P*`
**NEW**
Scaffold directory C:/Users/scott/Desktop/wyamtest/input does not exist and will be created
Installing NuGet packages
NuGet packages installed in 101813 ms
Recursively loading assemblies
Assemblies loaded in 2349 ms
Cataloging classes
Classes cataloged in 277 ms

One could imagine recipes for product catalogs, little league sites, etc. You can make your own custom recipes as well.

I'll make a config.wyam file with this inside:

Settings.Host = "test.hanselman.com";

GlobalMetadata["Title"] = "Scott Hanselman";
GlobalMetadata["Description"] = "The personal wyam-made blog of Scott Hanselman";
GlobalMetadata["Intro"] = "Hi, welcome to my blog!";

Then I'll run wyam with:

C:\Users\scott\Desktop\wyamtest>wyam -r Blog

Wyam version 0.14.1-beta
**BUILD**
Loading configuration from file:///C:/Users/scott/Desktop/wyamtest/config.wyam
Installing NuGet packages
NuGet packages installed in 30059 ms
Recursively loading assemblies
Assemblies loaded in 368 ms
Cataloging classes
Classes cataloged in 406 ms
Evaluating configuration script
Evaluated configuration script in 2594 ms
Root path:
file:///C:/Users/scott/Desktop/wyamtest
Input path(s):
file:///C:/Users/scott/.nuget/packages/Wyam.Blog.CleanBlog.0.14.1-beta/content
theme
input
Output path:
output
Cleaning output path output
Cleaned output directory
Executing 7 pipelines
Executing pipeline "Pages" (1/7) with 8 child module(s)
Executed pipeline "Pages" (1/7) in 221 ms resulting in 13 output document(s)
Executing pipeline "RawPosts" (2/7) with 7 child module(s)
Executed pipeline "RawPosts" (2/7) in 18 ms resulting in 1 output document(s)
Executing pipeline "Tags" (3/7) with 10 child module(s)
Executed pipeline "Tags" (3/7) in 1578 ms resulting in 1 output document(s)
Executing pipeline "Posts" (4/7) with 6 child module(s)
Executed pipeline "Posts" (4/7) in 620 ms resulting in 1 output document(s)
Executing pipeline "Feed" (5/7) with 3 child module(s)
Executed pipeline "Feed" (5/7) in 134 ms resulting in 2 output document(s)
Executing pipeline "RenderPages" (6/7) with 3 child module(s)
Executed pipeline "RenderPages" (6/7) in 333 ms resulting in 4 output document(s)
Executing pipeline "Resources" (7/7) with 1 child module(s)
Executed pipeline "Resources" (7/7) in 19 ms resulting in 14 output document(s)
Executed 7/7 pipelines in 2936 ms

I can also run it with -t for different themes, like "wyam -r Blog -t Phantom":

Wyam supports themes

As with most Static Site Generators I can start with a markdown file like "first-post.md" and included name value pairs of metadata at the top:

Title: First Post

Published: 2016-01-01
Tags: Introduction
---
This is my first post!

If I'm working on my site a lot, I could run Wyam with the -w (WATCH) switch and then edit my posts in Visual Studio Code and Wyam will WATCH the input folder and automatically run over and over, regenerating the site each time I change the inputs! A nice little touch, indeed.

There's a lot of cool examples at https://github.com/Wyamio/Wyam/tree/develop/examples that show you how to generate RSS, do pagination, use Razor but still generate statically, as well as mixing Razor for layouts and Markdown for posts.

The AdventureTime sample is fairly sophisticated (be sure to read the comments in the config.wyam for gotcha) example that includes a custom Pipeline, use of Yaml for front matter, and mixes markdown and Razor.

There's also a ton of modules you can use to extend the build however you like. For example, you could have source images be large and then auto-generate thumbnails like this:

Pipelines.Add("Images",

ReadFiles("*").Where(x => x.Contains("images\\") && new[] { ".jpg", ".jpeg", ".gif", ".png"}.Contains(Path.GetExtension(x))),
Image()
.SetJpegQuality(100).Resize(400,209).SetSuffix("-thumb"),
WriteFiles("*")
);

There's a TON of options. You could even use Excel as the source data for your site, generate CSVs from the Excel OOXML and then generate your site from those CSVs. Sounds crazy, but if you run a small business or non-profit you could quickly make a nice workflow for someone to take control of their own site!

GOTCHA: When generating a site locally your initial reaction may be to open the /output folder and open the index.html in your local browser. You MAY be disappointed with you use a static site generator. Often they generate absolute paths for CSS and Javascript so you'll see a lousy version of your website locally. Either change your templates to generate relative paths OR use a staging site and look at your sites live online. Even better, use the Wyam "preview web server" and run Wyam with a "-p" argument and then visit http://localhost:5080 to see your actual site as it will show up online.

Wyam looks like a really interesting start to a great open source project. It's got a lot of code, good docs, and it's easy to get started. It also has a bunch of advanced features that would enable me to easily embed static site generation in a dynamic app. From the comments, it seems that Dave Glick is doing most of the work himself. I'm sure he'd appreciate you reaching out and helping with some issues.

As always, don't just send a PR without talking and working with the maintainers of your favorite open source projects. Also, ask if they have issues that are friendly to http://www.firsttimersonly.com.


Sponsor: Big thanks to Redgate! Help your team write better, shareable SQL faster. Discover how your whole team can write better, shareable SQL faster with a free trial of SQL Prompt. Write, refactor and share SQL effortlessly, try it now!


© 2016 Scott Hanselman. All rights reserved.
     

Playing with an Onion Omega IoT device to show live Blood Sugar on an OLED screen

$
0
0

arduino_lb3dg8I've been playing with IoT stuff on my vacation. Today I'm looking at an Onion Omega. This is a US$19 computer that you can program with Python, Node.js, or C/C++. There's a current IndieGogo happening for the Onion Omega2 for $5. That's a $5 Linux computer with Wi-Fi. Realistically you'd want to spend more and get expansion docks, chargers, batteries, etc, but you get the idea. I got the original Omega along with the bluetooth dongle, Arduino compatible base, tiny OLED screen. A ton of stuff to play with for less than $100.

Note that I am not affiliated with Onion at all and I paid for it with my own money, to use for fun.

One of the most striking things about the Onion Omega line is how polished it is. There's lots of tiny Linux Machines that basically drop you at the command line and say "OK, SSH in and here's root." The Onion Omega is far more polished.

Onion Omega has a very polished Web UI

The Omega can do that for you, but if you have Bonjour installed (for zeroconf networking) and can SSH in once to setup Wi-Fi, you're able to access this lovely web-based interface.

Look at all the info about the Omega's memory, networking, device status, and more

This clean, local web server and useful UI makes the Onion Omega extremely useful as a teaching tool. The Particle line of IoT products has a similarly polished web-interfaces, but while the Onion uses a local web server and app, the Particle Photon uses a cloud-based app that bounces down to a local administrative interface on the device. There's arguments for each, but I remain impressed with how easy it was for me to update the firmware on the Omega and get a new experience. Additionally, I made a few mistakes and "bricked" it and was able - just by following some basic instructions - to totally reflash and reset it to the defaults in just about 10 minutes. Impressive docs for an impressive product.

image

Onion Omega based Glucose Display via NightScout

So it's a cool product, but how quickly can I do something trivial, but useful? Well, I have a NightScout open source diabetes management server with an API that lets me see my blood sugar. The resulting JSON looks like this:

[  

{
"_id":"5851b235b8d1fea108df8b",
"sgv":135,
"date":1481748935000,
"dateString":"2016-12-14T20:55:35.000Z",
"trend":4,
"direction":"Flat",
"device":"share2",
"type":"sgv"
}
]

That number under "sgv" (serum glucose value) is 135 mg/dl. That's my blood sugar right now. I could get n values back from the WebAPI and plot a chart, but baby steps. Note also the "direction" for my sugars is "flat." It's not rising nor falling in any major way.

Let's add the OLED Display to the Onion Omega and show my sugars. Since it's an OpenWRT Linux machine, I can just add Python!

opkg update

opkg install python

Some may (and will) argue that for a small IoT system, Linux is totally overkill. Sure, it likely it. But it's also very productive, fun to prototype with, and functional. Were I to go to market for real, I'd likely use something more hardened.

As I said, I could SSH into the machine but since the Web UI is so nice, it includes an HTML-based terminal!

A Terminal built in!

The Onion Omega includes not just libraries for expansions like the OLED Display, but also command-line utilities. This script clears the display, initializes it, and displays some text. The value of that text will come from my yet-to-be-written python script.

#!/bin/sh    


oled-exp -c

VAR=$(python ./sugar_script.py)

oled-exp -i
oled-exp write "$VAR"

Then in my Python script I could print the value that would be returned into VAR and then printed with the oled-exp command line utility.

OR, I can bypass the shell script entirely and use the Python Module for this OLED screen directly and do this. Grab the JSON, clean it up because apparently the json library sucks (?), then display it.

#!/usr/bin/env python                                                                                                        


from OmegaExpansion import oledExp
import urllib
import json

site="https://hanselmansugars.something/api/v1/entries/sgv.json?count=1"
jfile=urllib.urlopen(site)
jsfile=jfile.read()
jsfile=jsfile.replace("\n","")
jsfile=jsfile.replace("/","")
jsfile=jsfile.replace("]","")
jsfile=jsfile.replace("[","")

a=json.loads(jsfile)
sugar=a['sgv']
direction=a['direction']
info="\n" + str(sugar)+" mg/dl and "+direction

oledExp.driverInit()
oledExp.clear()
oledExp.write(info)

Now here's a pic of my live blood sugar on the Onion Omega with the OLED! I could put this to run on a timer and I'm off to the races.

The OLED Screen says "149 mg/dl and Flat"

The next step might be to clean up the output, parse the date better, and perhaps even dynamically generate a sparkline and display the graphic on the small B&W OLED Screen.

Have you used a small Linux IoT device like the Onion Omega?


Sponsor: Do you deploy the same application multiple times for each of your end customers? The team at Octopus have taken the pain out of multi-tenant deployments. Check out their latest 3.4 release



© 2016 Scott Hanselman. All rights reserved.
     

Free Intermediate ASP.NET Core 1.0 Training on Microsoft Virtual Academy

$
0
0

At the end of October I announced that Maria from my team and I published a Microsoft Virtual Academy on ASP.NET Core. This Free ASP.NET Core 1.0 Training is up on Microsoft Virtual Academy now for you to watch and enjoy! I hope you like it, we worked very hard to bring it to you.

Again, start with Introduction to ASP.NET Core 1.0, and explore this new technology even further in Intermediate ASP.NET Core 1.0.

Intermediate ASP.NET Core 1.0

Intermediate ASP.NET Core 1.0

We've just launched Day 2, the Intermediate day. If the first is 100 level, this is 200 level. In this day, Jeff Fritz and I build on what we learned with Maria in Day 1. We're also joined by Rowan Miller and Maria later in the day as we explore topics like:

  • Tag Helpers
  • Authentication
  • Custom Middleware
  • Dependency Injection
  • Web APIs
  • Single Page Apps
  • Entity Framework Core and Database Access
  • Publishing and Deployment

In a few weeks (maybe sooner) we'll publish Day 3 which we'll do exclusively on Macs and Linux machines. We'll talk about Cross-Platform concerns and Containers.

NOTE: There's a LOT of quality free courseware for learning .NET Core and ASP.NET Core. We've put the best at http://asp.net/free-courses and I encourage you to check them out!

Also, please help me out by adding a few stars there under Ratings. We're new. ;)


Sponsor: Do you deploy the same application multiple times for each of your end customers? The team at Octopus have taken the pain out of multi-tenant deployments. Check out their latest 3.4 release


© 2016 Scott Hanselman. All rights reserved.
     

Connecting my Particle Photon Internet of Things device to the Azure IoT Hub

$
0
0

Particle Photon connected to the cloudMy vacation continues. Yesterday I had shoulder surgery (adhesive capsulitis release) so today I'm messing around with Azure IoT Hub. I had some devices on my desk - some of which I had never really gotten around to exploring - and I thought I'd see if I could accomplish something.

I've got a Particle Photon here, as well as a Tessel 2, a LattePanda, Funduino, and Onion Omega. A few days ago I was able to get the Onion Omega to show my blood sugar on a small OLED screen, which was cool. Tonight I'm going to try to hook the Particle Photon up to the Azure IoT hub for monitoring.

The Photon is a tiny little device with Wi-Fi built-in. It's super easy to setup and it has a cloud-based IDE with tons of examples written in C and Node.js for you to use. Particle Photon also has a node.js based command line. From there you can list out your Photons, see their available functions, and even call functions over the internet! A hacker's delight, to be sure.

Here's a standard "blink an LED" Hello world on a Photon. This one creates a cloud function called "led" and binds it to the "ledToggle" method. Those cloud methods take a string, so there's no enum for the on/off command.

int led1 = D0;

int led2 = D7;
void setup() {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
Spark.function("led",ledToggle);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
}

void loop() {
}

int ledToggle(String command) {
if (command=="on") {
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
return 1;
}
else if (command=="off") {
digitalWrite(led1,LOW);
digitalWrite(led2,LOW);
return 0;
}
else {
return -1;
}
}

From the command line I can use the Particle command line interface (CLI) to enumerate my devices:

C:\Users\scott>particle list

hansel_photon [390039000647xxxxxxxxxxx] (Photon) is online
Functions:
int led(String args)

See how it doesn't just enumerate devices, but also cloud methods that hang off devices? LOVE THIS.

I can get a secret API Key from the Particle Photon's cloud based Console. Then using my Device ID and auth token I can call the method...with an HTTP request! How much easier could this be?

C:\Users\scott\>curl https://api.particle.io/v1/devices/390039000647xxxxxxxxx/led -d access_token=31fa2e6f --insecure -d arg="on"

{
"id": "390039000647xxxxxxxxx",
"last_app": "",
"connected": true,
"return_value": 1
}

At this moment the LED on the Particle Photon turns on. I'm going to change the code a little and add some telemetry using the Particle's online code editor.

Editing Particle Photon Code online

They've got a great online code editor, but I could also edit and compile the code locally:

C:\Users\scott\Desktop>particle compile photon webconnected.ino


Compiling code for photon

Including:
webconnected.ino
attempting to compile firmware
downloading binary from: /v1/binaries/5858b74667ddf87fb2a2df8f
saving to: photon_firmware_1482209089877.bin
Memory use:
text data bss dec hex filename
6156 12 1488 7656 1de8
Compile succeeded.
Saved firmware to: C:\Users\scott\Desktop\photon_firmware_1482209089877.bin

I'll change the code to announce an "Event" when I turn on the LED.

if (command=="on") {

digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);

String data = "Amazing! Some Data would be here! The light is on.";
Particle.publish("ledBlinked", data);

return 1;
}

I can head back over to the http://console.particle.io and see these events live on the web:

Particle Photon's have great online charts

Particle also supports integration with Google Cloud and Azure IoT Hub. Azure IoT Hub allows you to manage billions of devices and all their many billions of events. I just have a few, but we all have to start somewhere. ;)

I created a free Azure IoT Hub in my Azure Account...

Azure IoT Hub has charts and graphs built in

And made a shared access policy for my Particle Devices.

Be sure to set all the Access Policy Permissions you need

Then I told Particle about Azure in their Integrations system.

Particle has Azure IoT Hub integration built in

The Azure IoT SDKS on GitHub at https://github.com/Azure/azure-iot-sdks/releases have both a Windows-based Azure IoT Explorer and a command-line one called IoT Hub Explorer.

I logged in to the IoT Hub Explorer using the connection string from the Azure Portal:

iothub-explorer login "HostName=HanselIoT.azure-devices.net;SharedAccessKeyName=particle-iot-hub;SharedAccessKey=rdWUVMXs="

Then I'll run "iothub-explorer monitor-events" passing in the device ID and the connection string for the shared access policy. Monitor-events is cool because it'll hang and just output the events as they're flowing through the whole system.

IoTHub-Explorer monitor-events command line

So I'm able to call methods on the Particle using their cloud, and monitor events from within Azure IoT Hub. I can explore diagnostics data and query huge amounts of device-to-cloud data that would potentially flow in from my hardware devices.

The IoT Hub Limits are very generous for free/hobbyist users as we learn to develop. I haven't paid anything yet. However, it can scale to thousands of messages a second per unit! That means millions of messages a second if you need it.

I can definitely see how the the value an IoT Hub solution like this would add up quickly after you've got more than one device. Text files don't really scale. Even if I just IoT'ed up my house, it would be nice to have all that data flowing into a single hub I could manage and query securely.


Sponsor: Big thanks to Telerik! They recently published a comprehensive whitepaper on The State of C#, discussing the history of C#, what’s new in C# 7 and whether C# is the top tech to know. Check it out!



© 2016 Scott Hanselman. All rights reserved.
     

Exploring the Tessel 2 IoT and robotics development board

$
0
0

13841-01I'm still on vacation and still on the mend from surgery. I'm continuing to play around with IoT devices on my staycation. Last week I looked at these devices:

Today I'm messing with the Tessel 2. You can buy it from SparkFun for the next few weeks for US$40. The  Tessel is pretty cool as a tiny device because it includes WiFi on the board as well as two USB ports AND on-board Ethernet. It includes a two custom "module" ports where you can pop in 10-pin modules like Accelerometers, Climate sensors, IR and more. There's also community-created Tessel modules for things like Color Sensing and Motion.

Tessel is programmable in JavaScript and runs Node. Here's the tech specs:

  • 580MHz Mediatek MT7620n
  • Linux built on OpenWRT
  • 802.11bgn WiFi
  • WEP, WPA, WPA2-PSK, WPA2-Enterprise
  • 64MB DDR2 RAM
  • 32MB Flash
  • 16 pins GPIO, 7 of which support analog in
  • 2 USB 2.0 ports with per-port power switching

Tessel isn't a company, it's a open source project! They are on Twitter at @tesselproject and on GitHub here https://github.com/tessel.

NOTE: Some users - including me - have had issues with some Windows machines not recognizing the Tessel 2 over USB. I spent some time exploring this thread on their support site and had to update its firmware but I haven't had issues since.

Once you've plugged your Tessel in, you talk to it with their node based "t2" command line:

>t2 list

INFO Searching for nearby Tessels...
USB Tessel-02A3226BCFA3
LAN Tessel-02A3226BCFA3

It's built on OpenWRT and you can even SSH into it if you want. I haven't needed to though as I just want to write JavaScript and push  projects to it. It's nice to know that you CAN get to the low-level stuff I you need to, though.

For example, here's a basic "blink an LED" bit of code:

// Import the interface to Tessel hardware
var tessel = require('tessel');
// Turn one of the LEDs on to start.
tessel.led[2].on();
// Blink!
setInterval(function () {
  tessel.led[2].toggle();
  tessel.led[3].toggle();
}, 600);
console.log("I'm blinking! (Press CTRL + C to stop)");

The programming model is very familiar, and they've abstracted away the complexities of most of the hardware. Here's a GPS example:

var tessel = require('tessel');

var gpsLib = require('gps-a2235h');

var gps = gpsLib.use(tessel.port['A']);

// Wait until the module is connected
gps.on('ready', function () {
console.log('GPS module powered and ready. Waiting for satellites...');
// Emit coordinates when we get a coordinate fix
gps.on('coordinates', function (coords) {
console.log('Lat:', coords.lat, '\tLon:', coords.lon, '\tTimestamp:', coords.timestamp);
});

// Emit altitude when we get an altitude fix
gps.on('altitude', function (alt) {
console.log('Got an altitude of', alt.alt, 'meters (timestamp: ' + alt.timestamp + ')');
});

// Emitted when we have information about a fix on satellites
gps.on('fix', function (data) {
console.log(data.numSat, 'fixed.');
});

gps.on('dropped', function(){
// we dropped the gps signal
console.log("gps signal dropped");
});
});

gps.on('error', function(err){
console.log("got this error", err);
});

Of course, since it's using node and it has great Wifi or wired, the Tessel can also be a web server! Here we return the image from a USB camera.

var av = require('tessel-av');

var os = require('os');
var http = require('http');
var port = 8000;
var camera = new av.Camera();

http.createServer((request, response) => {
response.writeHead(200, { 'Content-Type': 'image/jpg' });

camera.capture().pipe(response);

}).listen(port, () => console.log(`http://${os.hostname()}.local:${port}`));

I'll make a Hello World webserver:

var tessel = require('tessel');
var http = require('http');
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello from Tessel!\n");
});
server.listen(8080);
console.log("Server running at http://192.168.1.101:8080/");

Then push the code to the Tessel like this:

>t2 push index.js

INFO Looking for your Tessel...
INFO Connected to Tessel-02A3226BCFA3.
INFO Building project.
INFO Writing project to Flash on Tessel-02A3226BCFA3 (3.072 kB)...
INFO Deployed.
INFO Your Tessel may now be untethered.
INFO The application will run whenever Tessel boots up.
INFO To remove this application, use "t2 erase".
INFO Running index.js...

Where is my Tessel on my network?

>t2 wifi

INFO Looking for your Tessel...
INFO Connected to Tessel-02A3226BCFA3.
INFO Connected to "HANSELMAN"
INFO IP Address: 192.168.0.147
INFO Signal Strength: (33/70)
INFO Bitrate: 29mbps

Now I'll hit the webserver and there it is!

image

There's a lot of cool community work happening around Tessel.  You can get involved with the Tessel community if you're interested:

  • Join us on Slack — Collaboration and real time discussions (Recommended! - ask your questions here).
  • Tessel Forums — General discussion and support by the Tessel community.
  • tessel.hackster.io — Community-submitted projects made with Tessel.
  • tessel.io/community — Join a Tessel meetup near you! Meetups happen around the world and are the easiest way to play with hardware in person.
  • #tessel on Freenode — IRC channel for development questions and live help.
  • Stack Overflow — Technical questions about using Tessel

Sponsor: Big thanks to Telerik! They recently published a comprehensive whitepaper on The State of C#, discussing the history of C#, what’s new in C# 7 and whether C# is the top tech to know. Check it out!



© 2016 Scott Hanselman. All rights reserved.
     
Viewing all 1148 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>