codefoster | All posts tagged 'c#'
Jeremy Foster
@codefoster

7 Reasons I Still Love JavaScript

by Jeremy Foster 27. December 2012 17:15

For many reasons, I still love developing Windows 8 apps using HTML, CSS, and JavaScript. I have extensive C# experience and always want to be able to say "I'm a C# developer", but I'd like to add that "I'm a JavaScript developer" as well. Some months ago I was a little pained to make even a short term commitment to write more JavaScript than C#. It felt a little like when I was learning French and found myself hesitant to start trying to think in French as if I would lose my English. Of course, that won't happen, and we shouldn't be afraid even of immersing ourselves in other languages. In fact, I'm a big advocate of the polyglot theory of intentionally moving into other languages spaces to expand our own scope, our value, and our perspective.

Becomes a way of thinking

I'm sure most development languages become a "way of thinking," but I think JavaScript does even more so because it's so dynamic and so light.

It's the language of the web

Mashups are a breeze when you're ingesting HTML and JSON data into and app that's made with HTML and JavaScript. The WinJS.xhr() method can make web requests with a request type of "document" and then immediately act on the results just like it would any other in-app content. Blob images can be consumed and repurposed. JavaScript objects can be created instantly out of JSON data. Yada yada yada. It's very convenient.

CSS selection of elements is great

Selectors are one huge strengths of the HTML/CSS that take advantage of the fact that HTML markup goes all the way to the client as XML-like syntax. Even on the client (at run-time) CSS can select very specific portions of the UI in order to affect it with styles or layout. JavaScript can take advantage of selectors too (using document.querySelector and .querySelectorAll) and that allows our logic to act on very specific portions of the UI.

One with the masses

There are a LOT of people writing JavaScript. A StackOverflow search on the [javascript] tag returns 300k+ questions on the matter (actually [c#] returns almost 400k!). It's good to have camaraderie in writing code. It's good to have employers looking for your skillset. It's good to have others asking questions on StackOverflow that you can benefit from. It's good to be one with the masses.

Standards driven

JavaScript is broadly adopted and is broadly and inherently appealing because it's based on web standards. The ECMAScript standard that is JavaScript, along with CSS and HTML, are governed by the World Wide Web Consortium (W3C) and that makes developers feel good. It's very democratic and very social and has very high likelihood of moving forward and moving in good directions.

Don't reinvent the wheel

There are a lot of JavaScript libraries out there. A lot. If you want to track faces or get fancy with date calculation or recognize touch gestures or implement IoC or pub/sub or manage Entity Framework data or edit images or any of a plethora of other things, there's a JavaScript library waiting for you.

A full stack of script

When you write C#, you don't usually just write C#. We find the client/server model everywhere and you don't send server code to the client, but you can send script. Whether you're writing an ASP.NET app or a client app, these days it seems you're inevitably going to be interacting with some HTML or even some JSON somewhere… whether you're using REST web services or scraping HTML screens. Having JavaScript on both the server end and the client end just tends to make you smile.

I like exploring languages. I am a veteran of VB. Like I have said, I'm a huge fan of C#. I have huge respect for C++ (though I haven't knocked on that door since college). I am exploring Erlang. Nevertheless, today I am having a blast writing JavaScript, and if you're writing JavaScript, I don't think you'll be hurting for work anytime soon!

Happy coding!

Tags: , , , , , , , , , , , , , , ,

CSS | HTML | JavaScript | Windows 8

One Sweet Stack

by Jeremy Foster 21. June 2012 14:36

Following is a mongo post. A huge post. A massive amount of information. The general recommendation is that blog posts should be short, but rules are made to be broken. You can’t tame me. I’m like a wild stallion. So here is a huge blog post.

Last Saturday at the Seattle Code Camp I delivered a presentation I called One Sweet Stack which showed how to start with a SQL Azure database (though it would work with any relational database really), connect to it using Entity Framework, and extend it as OData with WCF Data Services.

I chose this stack because…

  • I come from corporations that have existing database solutions. These aren’t modern, green-field databases of the myriad of flavors. These are classic, tried-and-true, and very much relational. I’m as excited as the next guy all of the modern ways to persist data, but don’t think for a minute that the relational database story is obsolete. Far from it.
  • I love using Entity Framework. I get a little jolt of excitement when I instantiate a DbContext or call SaveChanges(). Geeky? Of course.
  • I think that WCF DS is oft overlooked and recently especially in light of WebAPI (which is also a great product). I’m a fan of designing a database, mapping it through an ORM, and providing an elegant API (whether it’s internal or external) with so little code that I can write it from scratch in a 1 hr session (including explanations).
  • Windows 8 thrills me even more than EF.

I’m hoping to convey virtually all of the content from the presentation here, so it will be a heavy post. Consider it a reference post and come back to it if/when you need it.

The source code for this project is attached. You can find it at the bottom of this post.

First, the database…

So, as I said, I started with a SQL Azure database.

You connect to a SQL Azure database using a regular connection string just like any other database, so it will be a no-brainer for you to read this and apply it to a SQL Server on premises or even a MySQL or an Oracle database.

My database is a simple schema. It’s just a table of a few attractions that one will find on the island of Kauai, Hawaii and one related table of categories those attractions fall into (i.e. waterfall, scenery, flora, etc.). Here’s a diagram…

image

(my diagram by the way was done using asciiflow.com… very geeky indeed)

In the attached zip file, you’ll find KauaiAttractionsAzureScript.sql that you can use to create this database on your own Azure (or local if you’d rather) instance. Just create the database first and then run the script in the context of your new database. If you want to run through this whole exercise connecting to your own database, however, I would highly recommend it. It would be good practice.

Next, setting up the solution…

Follow these mundane steps to get over the snoozer that is creating projects, adding references, and importing packages…

  1. Create a new solution in VS2012
  2. Add a new Windows Class Library using C# (call it SweetStack.Entities)
  3. Add a new WCF Service Application using C# (SweetStack.Service)
  4. Add a new Cloud project using C# (SweetStack.Cloud)
  5. Add a new Unit Test Project using C# (SweetStack.Tests)
  6. Add a new Navigation App for JavaScript Windows Metro style (SweetStack.Metro)
  7. Add a reference to SweetStack.Entities to the .Service and the .Tests projects
  8. Add the .Service project as a web role to the .Cloud project
    1. In the .Cloud project
    2. Right click Roles
    3. Add | Web Role Project in Solution…
    4. Choose the .Service project
  9. Add the latest version of Entity Framework (currently 5.0.0-rc) to the .Entities, .Services, and .Tests projects
  10. Add the latest version of Microsoft.Data.Services (currently 5.0.1) to the .Services project

Next, creating the .Entities project…

We have our database already in place, and now we want to create an Entity Framework context that will allow us to access our database using code.

Instead of creating an EF model (.edmx file), we are going to reverse engineer the database to POCO classes. Why? Because it’s rad. That’s why. First thing you need to do is install the Entity Framework Power Tools Beta 2 (from Tools | Extensions and Updates in VS2012).

Once that is done, you can right click on your .Entities project and choose Entity Framework | Reverse Engineer Code First. Then enter your connection string information. Remember to check the “Remember my password” box so that it will save your credentials into your connection string for later.

So the tooling should have created a bunch of .cs files in your .Entities project. You not only get POCO classes for each of your database tables, you also get one for the context. That’s the one that derives from DbContext. You also get a folder with a map file for each entity.

All of this is beautiful and I’ll tell you why. You now have a direct 1:1 relationship between your code and your database, but you also have the complete freedom to modify the mappings so that the two don’t necessarily match. If your data architect, for instance, called the database table “first_name” and you’d rather that be called FirstName in your code, then just change that property but keep the mapping to “first_name”. You can even ignore certain properties or add new ones that don’t have a mapping. Furthermore, classes that DO have database mappings can be mixed with other classes that do NOT have mappings. It’s all up to you.

Next, let’s test it…

It’s hard to see a Windows class library work without writing a test for it. In the .Tests project write a simple test that looks something like this…

[TestMethod]
public void TestMethod1()
{
    var context = new SweetStack.Entities.Models.KauaiAttractionsContext();
    Assert.IsTrue(context.Attractions.Any());
}

Before you can run the test, copy the <connectionstrings> element from the app.config, create a new app.config in the .Tests project (right click Add New Item…), and then paste the <connectionstrings> element into the app.config for .Tests.

That test should pass if you haven’t mucked anything up already.

Next, time to create the .Service…

This one just FEELS like it’s going to take a while. Low and behold, however, I bet I could do it in less than 37.5 seconds (not that I’ve timed myself). Do this…

  1. Delete (from the .Service project) the IService1.cs and Service1.cs files that you got for free (even though you didn’t ask for them :)
  2. Right click the .Service project and add a new item… add a WCF Data Service called Entities.svc
  3. Once your file is created, check out the class name and see how it derives from DataService<T> but the T is undefined. Fill that in with SweetStack.Entities.Models.KauaiAttractionsContext
  4. Now uncomment the line in the InitializeService method that says SetEntitySetAccessRule and in the quotes just specify an asterisk (“*”). You can change the EntitySetRights.AllRead to .All if you like, but we won’t be writing any data in this tutorial anyway, so it doesn’t matter so much.
  5. Copy the <connectionstrings> element from the app.config of the .Entities project into the web.config of your .Service project
  6. Put your hands down… you’re done!

Set your .Service project to the startup project and run it. You should get a browser that looks like this…

image

Note: if you get a list of files instead, just click on the Entities.svc first.

Next, we let’s see what we’ve got…

What you’re looking at there is a GEN-YOU-WINE OData feed. That’s exciting. OData rocks. Not only do you get all of your entities extended through OData, but you get type information about them and you get their relationships with each other. Also, you can ask an OData feed for XML or for JSON and it will say “Yes, sir/ma’am.”

Fire up Fiddler and hit that service root URL appending each of the following and see what you get for responses (also add “Accept: application/json;odata=verbose” to the headers in Fiddler to request JSON). Issue the following commands against your service and behold the results…

{root service URL}?$top=1 selects just the first entity.
{root service URL}?$select=Id,Name fetches all entities, but projects them to lighter JSON objects by only including the Id and Name properties.
{root service URL}?$filter=Location%20eq%20'North' gives you entitites that have a Location value of “North”.
{root service URL}?$filter=substringof('Falls',Name)%20eq%20true” gives you only entites with the word “Falls” in their Name
{root service URL}?$select=Name&$orderby=Name selects just the Name property and sorts it
{root service URL}?$expand=Category this one brings in the related Category entity… this a significant point and a differentiator from flat GET web service operations. Look at the JSON message in the response with and without this URL property.

If that doesn’t turn your crank then you should check your Geek card… it might be expired.

Next, we go Metro…

We’re ready to consume our data. We’re going to be working here with an HTML/JS Metro application which makes it reasonable brainless to consume JSON. Here we go…

I had you create your Metro app from the navigation template, so you should have a pages folder (assuming your using Visual Studio 2012 as opposed to Visual Studio 11). In there you have home.html, home.css, and home.js. Those three files are all we’re going to concern ourselves with for now.

In the .html file, you need to create a ListView and define an item template and a header template (because we want our items to appear in groups). Here’s what that would look like…

<div id="itemtemplate" data-win-control="WinJS.Binding.Template">
    <div data-win-bind="onclick:click">
        <img data-win-bind="src:ImageUrl" />
        <div data-win-bind="innerText:Name"></div>
    </div>
</div>
<div id="headertemplate" data-win-control="WinJS.Binding.Template">
    <div data-win-bind="innerText:category"></div>
</div>
<div id="list" data-win-control="WinJS.UI.ListView"></div>

Then in the .css file add the following so that our images are the right size and our ListView is tall enough to show two rows…

.homepage section[role=main] {
    margin-left: 120px;
}

.homepage #list {
    height: 100%;
}

    .homepage #list img {
        width: 280px;
        height: 210px;
    }

Finally, in the .js file we need to add just a little bit of code. I’ll just drop it all on you and then explain each section. Put this inside the page’s ready method…

var attractionsListGrouped = new WinJS.Binding.List().createGrouped(
    function (i) { return i.Category.Name; },
    function (i) { return { category: i.Category.Name }; }
);

var list = document.querySelector("#list").winControl;
list.itemDataSource = attractionsListGrouped.dataSource;
list.itemTemplate = document.querySelector("#itemtemplate");
list.groupDataSource = attractionsListGrouped.groups.dataSource;
list.groupHeaderTemplate = document.querySelector("#headertemplate");
            
WinJS.xhr({
    url: "http://onesweetstack.cloudapp.net/Entities.svc/Attractions?$expand=Category",
    headers: {"Accept":"application/json;odata=verbose"}
    }).then(function(xhr) {
        JSON.parse(xhr.response).d.forEach(function (i) {
            i.click = function (args) { WinJS.Navigation.navigate("/pages/attraction/attraction.html", i); }
            i.click.supportedForProcessing = true;
            attractionsListGrouped.push(i);
        });
    });

The first part (var attractionsListGrouped…) creates a new WinJS.Binding.List that groups the items by their .Category.Name. This necessitates that we bring our Attraction entities down with that $expand property included to get the related Category, but that’s easy so we worry not.

The next part imperatively sets the item and header templates and the data sources of both the items and the groups. This can be done before our list has even been populated with any items. In fact, we need to do it that way because the call we make to get the items is asynchronous and we need that list that we’re binding to to exist before we even get back from that call.

The last part is the xhr call. You can see the syntax. The xhr expects an object within which we’re specifying the url and a custom header. The function we pass in to the subsequent .then is going to run after we get back from the xhr call. At that point, we can look at the response, parse it as JSON, and then for each item, push it into our list. This list is a WinJS.Binding.List which means that it is essentially observable and will tell the UI when updates have been made so it can change accordingly. So when our items are fetched and filled in, the user will see them pop into the ListView in his view.

Tangent about application/JSON;odata=verbose…

Remember how we added application/JSON;odata=verbose to our headers for the xhr call? Why would we do that? It’s because we’re using the prerelease version of WCF DS, and the existing OData JSON syntax has been dubbed “verbose” to make room for some awesome new methods for expressing rich, typed, interrelated OData while keeping the payload light, light, light. More on that at a later time.

Conclusion

Attached you’ll find the complete source code. Hope it helps you learn Windows 8 development and I hope you get your first app done soon and are rewarded with huge royalty checks :)

And that does it for this walk through. It was a marathon post, so if you’re read this far email me your mailing address and I’ll send you a gift in the mail. I’m betting I won’t be troubled to send too many gifts :) (offer expires the end of June 2012)

OneSweetStackLive.zip (9.90 mb)

Tags: , , , , , , , , , , , , , , ,

C# | CSS | JavaScript | Visual Studio | Windows 8

Windows 8: Top 10 Reasons Why I Choose HTML5 Over XAML

by Jeremy Foster 23. May 2012 10:26

My colleague and friend Jerry Nixon recently wrote an article on the top 10 reasons why he chooses XAML over HTML5 and it begged me for a reply. Alas, here it is...

Following are the top 10 reasons why I’m in the HTML/CSS/JS space right now.

I should qualify. I completely adore C# and XAML. I geek out on the nuances of the C# language, lambda expressions give me joy, and LINQ is like dreams and starlight. But that’s not where I am right now. I’m moving on but not moving away. I want both bullets in my belt... the sheer power of C# and the wit and fancy of JavaScript.

More qualification. I love JavaScript and at the same time I hate JavaScript. Sometimes it makes me feel like a coding cowboy and other times like I’m in its gallows.

So here we go...

1. Skill Ready

I and about a kazillion other people in the world have gathered a ton of experience on the HCJ stack. Websites became applications as some point, and they became essential in the enterprise. I would guess that the web stack has drastically more developers than any other stack... but that’s a guess.

2. Triptych

HTML, CSS, and JavaScript form what I like to call the happy triptych. Instead of separating code into two roles, HCJ has three. HTML defines the structure, CSS defines the layout and style, and JavaScript defines the logic. This makes things like modifying the layout and style for different view states or devices as simple as swapping out the style sheet.

3. Dynamic

I know that C# has the DLR and I’ve used it in numerous real scenarios, and it’s some awesome functionality added to the language. JavaScript, however, is truly dynamic. If I want to add a property to my app like lastLaunched, I just type app.lastLaunched = “5/1/2012” and voila I have a new property. If I want to add a function called detectLastLaunched, I just type app.detectLastLaunched = function() { ... }. That’s way cool.

4. JSON

JavaScript has JSON. I know that C# can speak JSON too, but not like JavaScript. JavaScript and JSON go together like peas and carrots.

5. Light

JavaScript is light. Super light. The absence of some of C#’s heavy artillery (I’m thinking polymorphism, inheritance, type safety, etc.) leaves it light and agile. The fancier things like inheritance and even asynchronicity are implemented as patterns instead of as language features. This means they’re not baked in so they can be adapted to suit.

I was newing up some sample data in both languages the other day. I had to declare all of my types in C# and then even with object and collection initializers, the code to create the sample data was quite large and repetitive. In JavaScript on the other hand, it’s a matter of declaring a variable and setting it with very terse object initializer syntax... thing of beauty.

Just compare the default Metro style Grid Application in XAML/C# and then in HTML/JS and you’ll see how light JavaScript is.

 

6. Libraries

Again, there are a ton of web stack developers out there and consequently there are a ton of web stack libraries and helpers. Bing something like “javascript face detection” and you’ll find an open source library that’s ready to go. Glance at microjs.com to see what I mean about JavaScript library support.

7. Query Selection

In XAML, it’s easy enough to give a control an ID and then select it in the code. But how do you select all of every third paragraph, the third element in the grid, or something like that. The answer is imperative code. There’s no part of the object model that you can’t access, but with query selectors in CSS and JS, you can use simple strings like “div#myDiv p:nth-child(3n)” to select every third paragraph in the div with the ID of myDiv.

8. CSS

CSS is amazing. With a collection of style rules, I can style, animate, layout, add images, position things, and a ton more. With declarative CSS code I can make the same HTML view look entirely different. Style rules cascade down to the eventual screen element and allow a developer to set a style globally and then override that style locally given the need.

There’s a JS library called LESS that extends CSS’s capabilities and allows me to set style variable and even do variable math. So I can set the base color of my app to red and then create a number of derived colors (darker or lighter for instance). That way, the change of a single color variable will result in a complete change to my app’s color palette.

9. Blend

The nature of HTML/JS apps means that Blend for Visual Studio can dynamically execute the application while you’re designing it. Expression Blend (the XAML designer for classic Windows apps, Silverlight, Windows Phone, etc.) has some robust support for sample data and designer data because it’s not able to drag in the application data at runtime. With Blend, however, when working on a Metro style app using JavaScript, the entire need for sample data goes away. Instead, you look at your real app data... even if you’re pulling it down from the sky (I’m a little tired of the word cloud, so I choose to use the word sky).

10. Name

I live in Seattle. I drink coffee. Fancy coffee. The people that make coffee in this town are insane about their technique, the quality of their bean, and the nanosecond precision of their brew pull. So I’m enjoying JavaScript because it goes so well with the french press of Ecuadorean joe I hold before me.

Sorry, C#. Your name is sharp, but it’s so technical and boring compared to JavaScript.

Nail. Coffin. JavaScript wins hands down! Oh, whatever. It’s all in fun.

Tags: , , , , , ,

C# | CSS | JavaScript | Windows 8 | XAML

Feed Subscribe