codefoster | All posts tagged 'css'
Jeremy Foster
@codefoster

Code for CSS for Windows 8 App Development

by Jeremy Foster 10. January 2013 20:00

Hello. I wrote a little book (my first actually) called CSS for Windows 8 App Development published by Apress. It's available at aka.ms/cssbook. All of the code listings from the book are available in a Windows 8 app that I have created, and you can download all of the source code for this app at cssbookcode.codeplex.com. The code is not polished yet as the book is still in alpha, but it should build and run and you're welcome to take a look as early as you like. Thanks for reading my book. I wish you lots of fun and success in developing apps for Windows 8.

Tags: , , , , , ,

CSS | HTML | JavaScript | Windows 8 | WinJS

Loading States of the WinJS.UI.ListView

by Jeremy Foster 8. January 2013 16:37

If you make Windows 8 apps using HTML and JavaScript, you are definitely going to be chums with the WinJS ListView control. It's the fundamental list control. You use it to create item grids as are so typical to Windows 8 apps, and you use it as well for lists - more vertically item lists like you might often find in the snap view of various apps.

The ListView is a rather rich control that does a lot of layout for you and offers you a lot of rich functionality as well. It can be bound to a list of data and then can load asynchronously for performance and responsiveness and also conditionally so you can selectively choose item templates or render methods.

It's often times important to find out what the ListView is doing so you can coordinate some of your own custom functions.

The ListView has a loading process that has various milestones or loading states - each of which fires the onloadingstatechanged event and includes the exact loading state. You can wire in to this event, figure out which loading state the ListView is currently in, and do something of your own.

As an example, let me show you something from my codeSHOW app. In case you aren't familiar, codeSHOW is a Windows 8 app for learning how to make Windows 8 apps using HTML and JavaScript. You can download it from the Windows Store at http://aka.ms/codeshowapp or download the full source code for the app from http://codeshow.codeplex.com.

In codeSHOW, the user may choose from a large list of demos, spend a little time using the chosen demo, and then click back to return to the home page. When the user returns to the homepage, it would be convenient to recall their scroll position so they don't have to keep finding their place each time.

Here's how it was implemented in codeSHOW.

When the user chooses a demo, the WinJS navigation framework unloads the home page and loads the demo page. In the unload event of the home page, I added...

app.sessionState.homeScrollPosition = demosListView.scrollPosition;

This adds the scroll position of the ListView to the sessionState. This means that even if the app crashes or the user switches away and lets it get suspended, the scroll position is going to be saved for later recall.

Now, when the user returns to the home page by pressing the back button from the demo page, the following code fires from the ready event...

demosListView.onloadingstatechanged = function () {
    if (app.sessionState.homeScrollPosition && demosListView.loadingState == "viewPortLoaded") {
        demosListView.scrollPosition = app.sessionState.homeScrollPosition;
        app.sessionState.homeScrollPosition = null;
    }
};

This hooks up an event handler for the onloadingstatechanged event, so that each time the loading state changes, we have an opportunity to intercept, check to see if the loading state is a certain one, and do something.

In this case, we're checking to see if the loading state of the ListView is "viewPortLoaded". Some experimentation told me that after the viewPortLoaded state is reached, the ListView has fleshed itself out enough that a setting of the scroll position will actually work. If you try to set the scroll position before the ListView gets to this loading state, the ListView will have no width and thus setting the scroll position will be a futile effort.

Here are all of the loading states of a ListView in order...

  • viewPortLoaded
  • itemsLoading
  • itemsLoaded
  • complete

So if you need to do something only after the entire ListView is loaded, you would use code similar to my last listing, except check to see that the loading state is "complete".

I hope this helps. Keep having fun with your web development in Windows 8, and if you've got a cool app you're working on, send me a tweet and I'll mention your project.

Tags: , , , , , , , , ,

CSS | HTML | JavaScript | Windows 8 | WinJS

Your First Game in YoYo GameMaker

by Jeremy Foster 7. January 2013 11:59

I'm presenting tonight at the Microsoft Store in Seattle on building your first game with YoYo GameMaker. YoYo was generous enough to provide GameMaker licenses for all attendees! We're going to be going through the first game tutorial with some slight tweaks to make it work better on Windows 8. If time permits, we'll look at one more game tutorial - a scrolling shooter.

Attached you'll find the PDF files that we'll be walking through this evening. I hope you get some skills and inspiration to make your first game! 

GameMakerTutorial_FirstGame.pdf (466.59 kb)

GameMakerTutorial_ScrollingShooter.pdf (791.98 kb)

FirstGameAssets.zip (797.52 kb)

ScrollingShooterAssets.zip (854.63 kb)

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

Windows 8

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

Unintentionally Open Source?

by Jeremy Foster 11. December 2012 12:42

I saw this tweet and decided to respond.

The technical answer is YES. You can access the source code for Windows Store apps written in HTML/JavaScript. But there are a few reasons that you should forego panic.

First, this is no surprise. App packaging and distribution has a ton of design and testing behind it. The designers knew exactly what was going to the client and exactly how much effort it takes to discover it. Developers are responsible for their own obfuscation strategy. If Microsoft created their own, it would just get pwned in a couple weeks and then it would be a senseless inclusion in the product. It's better for obfuscation to be out of band with the Windows product and for it to be contributed by third parties.

Next, the way it works with HTML/JavaScript apps is actually similar to many other language stacks. JavaScript is clear text and translated script so it's very easy to look for a .js file and read it. Managed languages such as .NET languages are only logistically more difficult to reverse engineer and capture the source from.

Next, the source code is available on the client, but the package is tamper proof. If a hacker finds it and changes one of the .js files so that the script now does something it wasn't intended to do (such as validate that an in-app purchase has been paid for or that the app is not in trial mode), then Windows will not allow that package to execute.

Finally, the bottom line is that you should never trust code on a client. It doesn't matter the language, the platform, or even the obfuscation technique. It can and eventually will be hacked. You should consider how sensitive your intellectual property is and protect accordingly. If you have very valuable business logic that would hurt you or your company if it's taken then I wouldn't even put that logic into the client app. I would put it in the cloud and make it available through service calls. That's a better architecture for a lot of other reasons as well. If you are a hobby app developer and you wrote a silly app, I wouldn't worry about it. It's a very small portion of the population that's going to try to take your code. The chances that your stolen code is going to turn into much added value for them is low and the chances that their efforts with it are going to hurt your business is even lower.

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

JavaScript | Windows 8

MCSD HTML5 Exam Offer

by Jeremy Foster 9. November 2012 21:39

It's was a big day in Building 33 as 100 or so people gathered to write Windows 8 apps, compete for prizes, and hopefully learn a little something along the way. One of the things attendees learned was that Microsoft Learning (MSL) is really rockin' the Microsoft certifications lately. Paul Lee joined us at the hackathon to talk about the state of Microsoft certifications. They have tracks that based on software solutions and the technologies a developer would use to create them.

The one I'm excited about is the MCSD: Windows Store Apps - HTML5. Which you can earn if you take the 70-480, 70-481, and 70-482 exams. And actually, the first of those exams is free (for now) if you go to http://www.register.prometric.com to schedule your exam and use HTMLJMP as your promo code. If you want help studying for 70-480 and 70-481, you can take a look at the JumpStart videos that Michael Palermo and I recorded at http://aka.ms/jump480 and http://aka.ms/jump481.

Attached are the slides that Paul presented.

HackathonOffer.pptx (429.56 kb)

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

Windows 8 | WinRT

Jump Start Your Brain

by Jeremy Foster 20. September 2012 17:40

My colleague Michael Palermo and I are scheduled to present two Jump Start video series on Channel 9. The first will cover basic HTML, CSS, and JavaScript development, and the second will cover those web technologies as they apply to creating Windows 8 apps.

You can get a lot more information about this content and register to attend by going to http://aka.ms/Win8Dev-JS.

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

CSS | HTML | JavaScript | Windows 8

Referring to Package Files

by Jeremy Foster 6. September 2012 01:21

When you’re working with a Windows 8 project in VS2012, you have some number of project files in your Solution Explorer. You have HTML files, CSS files, JavaScript files, images, and perhaps some XML or JSON or TXT files - something like that.

If, in the course of executing logic in your app, you need to access these files, there are a number of ways and you should know when you might use what and why… that’s as opposed to being incapacitated or stabbing in the dark.

Option 1 - relative or ms-appx reference

Your first option is to refer to the file using a relative or an ms-appx reference.

You’re working with a web app here, so remember that if you’re sourcing an image on an HTML page, you can include a relative link like myimage.png to refer to an image of that name in the same location as that HTML file.

Remember that ms-appx is a scheme analogous to the http in http://, but instead of referring to the hyper text transfer protocol (the transfer protocol of the Interweb) it refers to the current package. If you’re making a breakfast cereal inventory app (don’t ask me how I came up with that as an example, but I think it’d sell!) then ms-appx:// is the scheme to use to access your app’s assets and  ms-appx:///cereals.xml would refer to the cereals.xml file. This doesn’t give you a benefit over a relative link, though.

And wait… hold the phone. Why did we use three slashes? That’s simple. It’s because we want to refer the current package self as opposed to any referenced packages within the current package. Actually, ms-appx:///cereals.xml is equivalent to ms-appx://{packageid}/cereals.xml where {packageid} is the package identifier from the manifest file.

Option 2 - WinJS.xhr()

The first option is likely your best choice if you’re referencing declaratively from within an HTML file. Your second option and the one you’ll likely use when you’re working imperatively within JavaScript is to hit the local asset using xhr. The WinJS.xhr method takes a URL and returns gives you its word (a promise) that it will return with a response and will call your then/done when it’s back.

The response from your xhr call might be some JSON data, some XML, an HTML document, or just some random text. Anyway, you get to decide what happens with it.

Option 3 - installedLocation

The third option is one most recent one that I discovered and I like it.

If you look at the Windows.ApplicationModel.Package class, you’ll see that you can access the current package using the current method. If you look at the current package, you’ll see that you have an installedLocation property. And if you look at that installedLocation, you’ll see that you have a getFileAsync method.

The getFileAsync method returns (via a promise) a StorageFolder, and that folder contains all of the files in your project. Tada!

One good example of a use of this method is the online documentation for the setHtmlFormat method that hangs off of DataPackage.

Conclusion

As always, it’s possible there are even more ways to skin the cat than I’ve enumerated. These are the three I know. I hope it’s helpful.

Happy reflecting!

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

JavaScript | Windows 8

msMatchMedia: programmatic access to media queries

by Jeremy Foster 25. August 2012 13:23

If you throw down with a media query like this…

@media screen and (-ms-view-state: fullscreen-portrait) {
    p { color: purple; }
}

…then you’re going to get purple text in all of your paragraphs, right?

Well, what if you wanted to check to see if you were in fullscreen-portrait from your code so you could do something fancy. Of course, you get some help from Windows with that. If you’re using the navigation project template then you can implement an updateLayout method when you define a page and one of the parameters you’ll receive is viewState.

But you might not be in the updateLayout method and you might want to check some other media query property such as whether the screen is at least 600px wide.

That’s where you may benefit from accessing media queries programmatically.

To execute the media query above from could you can do this…

if (msMatchMedia("(-ms-view-state: fullscreen-portrait)").matches) {
    //do something if we're in portrait
}

This msMatchMedia method hangs off of the window object.

I know that there are usually properties in the DOM API that will allow you to discover these things about your environment, but if media queries are your thing and you can solve the issue that way, then there you go.

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

CSS | HTML | JavaScript | Windows 8

CSS Tip: nth-child and nth-of-type Pseudoclasses

by Jeremy Foster 23. August 2012 11:15

Let’s say we have the following HTML…

<ul class="list">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
</ul>

That’s not difficult. It’s a ul (unordered list) which is by default rendered with bullets, although you’ve got full control over how exactly you want it to render. In this case, we have 6 items. Simple. And here’s how it should render in an empty Windows 8 app (with the default dark theme)…

image

Now what if we wanted every item to be yellow? Go ahead and think about how you’d do it before you look at my answer.

Here it is…

.list li {
    color: yellow;
}

And it looks like this…

image

That’s nice. Now what if we wanted to give every other item a dark blue background? Well, there are at least four ways I can think of to do that. I’ll include all four.

The following two are equivalent and will highlight every other line starting with the first…

.list li:nth-child(2n-1) {
    color: yellow;
}

.list li:nth-child(odd) {
    color: yellow;
}

And that looks like…

image

As you can see, the first contains a formula and the second simply contains the word odd. This nth-child is called a pseudo-class because we didn’t have to manually decorate every other li tag with a class in order to “grab” them. Instead, we use a pseudo-class. Much easier.

The nth-child pseudo-class uses a formula that is always of the form: an+b. Essentially, CSS is going to plug a set of positive integers starting with 0 into the n in that equation. The result will be a set of integers. CSS will omit the negative and zero values and use the resulting positive integers to determine which items should be matches.

Our 2n-1 formula then would evaluate to an integer set that looked like [-1,1,3,5,7,9,…]. CSS would then ignore the -1 and apply this style to the 1st, 3rd, and 5th elements. Because highlighting every other row is likely a very common case, CSS defines the odd keyword to simplify matters.

The following two are also equivalent and will highlight every other line starting with the second

.list li:nth-child(2n) {
    color: yellow;
}
.list li:nth-child(even) {
    color: yellow;
}

Again, the first is an equation and the second is a keyword. The set of positive integers [0,1,2,3,4,5,…] would get evaluated in that equation to [0,2,4,6,8,10,…]. The 0 would be ignored, and the 2nd, 4th, and 6th list items would have the style applied. Here’s the result…

image

Here are some other, more advanced uses of the nth-child pseudo-class…

3n Every 3rd element
10n Every 10th element
-n+7 The first 7 elements
n All elements (pointless)
n+4 All elements starting with the 4th
2n+3 Every other element starting with the 3rd

And if you want to see some more, go to nth-child recipe  on CSS Tricks.

So there you have it. That’s nth-child. Pretty handy, eh?

Now let’s look at nth-of-type and see how it differs from nth-child. Consider the following HTML now…

<div class="list">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <div>Child Div 1</div>
    <div>Child Div 2</div>
    <p>Paragraph 3</p>
    <p>Paragraph 4</p>
    <p>Paragraph 5</p>
    <p>Paragraph 6</p>
</div>

Now we have a div that has mixed child types. It has some p elements and some child div elements.

Watch what happens when we attempt to apply the same blue style to the second div using our nth-child syntax…

.list div:nth-child(2) {
    color: yellow;
}

And that results in…

image

That’s not right. Didn’t we expect our second div to be highlighted?

Well, actually. It’s all working correctly. See, the nth-child pseudo-class is indicating that our target element has to be the 2nd child, but it’s not. It’s the second div, but it’s not the second child. To specify that we’re looking for the second div, we use nth-of-type like this…

.list div:nth-of-type(2) {
    color: yellow;
}

…and we end up with…

image

Boom. Perfect.

And that brings us to the end of the post. If you have any questions or comments, please feel free to leave them below.

Tags: , , , , , , , ,

CSS | HTML | Windows 8

Feed Subscribe