Showing posts with label HTML 5. Show all posts
Showing posts with label HTML 5. Show all posts

Thursday, January 8, 2015

CSS3 Transforms


Intro

CSS3 has been around for a few years now. Prior to CSS3 and HTML5 we all lived in the dark ages. I'm pretty sure dinosaurs roamed the earth, Republicans were Democrats, and humans had just learned to fashion clubs. No electricity even! But now with CSS3 we can do a whole lot more on our not-as-primitive-as-before web pages, making them look ever-so-pretty. CSS3 does quite a bit more than just transforms, but this is a blog not a novel so we'll stick with just this one topic for today.

What They Be?

What are CSS transforms? Well they're CSS actions (a single property within a style-sheet definition) that you can use on your tags. I mostly like to use them on images, but they're valid on divs, spans, whatever. It's a nifty way to get cool 2D and 3D actions performed without having to write complicated modification routines using JavaScript.

Example Set #1: 2D Transforms

What all 2D CSS transforms can you do? Rotate, Scale, Skew, Translate. What Are they? Here's a quick example that shows 4 transforms on groovy-looking images.

control
rotate 90°
Scale (x: 1.5, y: 0.5)
Skew (x:10°, y:45°)
Translate (x:30px,y:10px)
 
It might be kinda tough to tell exactly what this did so I'll break it down. The control image has no transformation. It's just a standard HTML image. The rotation transform rotates the image as though it were the hands of a clock. Scale scales your image by the amount given in the parameters, where 1.0 is the same as 100%. Skew stretches/smushes (good technical term huh) your image. I like to think of it as though somebody were to pull on opposite corners of the element, with the corners and direction determined by x/y and the angle. The translate transformation moves your image by the amount specified.

Here's the code used to generate the above effects:

<style type="text/css">
.rotate {
transform: rotate(90deg);
}

.scale {
transform: scale(1.5, 0.5);
}

.skew {
transform: skew(10deg, 45deg);
}

.translate {
transform: translate(30px, 10px);
}
</style>

<div style="float: left;">
control< br />
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
rotate 90&deg; < br />
<img border="0" class="rotate" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
Scale (x: 1.5, y: 0.5)< br />
<img border="0" class="scale" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
Skew (x:10&deg;, y:45&deg;)< br />
<img border="0" class="skew" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
Translate (x:30px,y:10px)< br />
<img border="0" class="translate" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="clear: both;">
&nbsp;
</div>


Cool huh? 2D transforms are fun to play with. But guess what? CSS3 does 3D transforms too!

Example Set #2: 3D Transforms

So yeah, like I said, it's time for some 3D transforms. You can do many of the same 2D transforms as 3D transforms, such as rotation, scaling, and translating. Let's look at a slew of samples again to get a feel for what we can do:

control
rotate x30°,z20°
scale x 1.3
translate z 50px

Let's take a closer look at these homeys. Control is still the control image, no transforms. the 2nd image rotates on the x-axis 30 degrees and the z axis 20 degrees. Image numero tres scales the image on the x-axis by a factor of 1.3, and the final image translates the image on the x-plane by 50px (brings the image forward 50px thus putting it on top of the 3rd image).

Here's the code used in them thar samples:

<style type="text/css">
.rotatey {
transform: rotateY(30deg);
}
.rotatez {
transform: rotateZ(20deg);
}
.scalex { 
transform: scaleX(1.3);
}
.translatez { 
transform: translateZ(50px);
}
</style>

<div style="float: left;">
control< br />
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
rotate x30&deg;,z20&deg;< br />
<img border="0" class="rotatey rotatez" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
scale x 1.3< br />
<img border="0" class="scalex" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="float: left;">
translate z 50px< br />
<img border="0" class="translatez" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitU3xEzE_sCgKe4bMn6K_zmIvbXUqGZPt5ALApt-G1xQAFHaTf40dvrrSQiRhfil3OIfSEOnwqkUv_2yb4Om0i4R79__sBVLMRTg33e_A82_lMmkxAtqeuykU1ExNAH7y-5F5jyjQx8wOR/s1600/monster-icon.png" height="100" width="100" />
</div>
<div style="clear: both;">
</div>



Pretty cool stuff! You can make lots of nifty effects with just some CSS, HTML and time.

What's Next?

Take a look at the resources below, play around with transforms yourself. There's more I didn't cover though it's all pretty similar. Get yerself a beverage of your choice and have at it for an hour or two, see what shakes out.

Resources

CSS3 Transform Property
CSS Transforms
CSS3 2D Transforms

Thursday, December 4, 2014

Lazy Loading of Images With JavaScript and JQuery (a Plugin)

Intro

Have you noticed a growing number of websites that load images while you are scrolling down the page? Even if you haven't, just pretend that you have, or hey read on anyways! I'll try to entertain you. These pages are using a technique called lazy loading for the images. Your browser does not download the image until the image is at or near the viewport (not downloaded until you the client need to see the image), thus potentially saving on bandwidth and initial page display time for the user. Under the assumption that most visitors won't view every image in a large scrollable list, this can be quite a boon for you (the host) and for your users (the clients). If you're intrigued and want to read about one way to accomplish this feat, read on!

How to use the plug-in

There are quite a number of ways to lazy load images, but for this article I'll focus on just one. A JQuery plugin named unveil by Luis Almeida. For those of you unfamiliar with JQuery, I suggest you read up about it on their website before continuing. It will help you to have a basic understanding of what it does and how it works. If you want just the cliff-notes version, it's a lightweight (small download size) JavaScript library that handles a multitude of tedious tasks for you, and it has a very vibrant ecosystem of plugins from thousands of contributors.

Back to unveil...this plugin lets you specify a placeholder image for images as well as the final lazy-loaded ultimate image that the user will see. It's got just a couple other configuration options, but you can read about those on the unveil site linked below. We'll use it in it's most basic capacity, downloading an image lazily when the user scrolls down to that portion of the page. So, let's see how to use it.

Fire up your favorite html editor and create yourself an html page. Paste the content you see below into your html file:

<!DOCTYPE html>
<html>
 <head>
  <!-- link to jquery library hosted by google -->
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <!-- link to unveil library in the same directory as this html file -->
  <script src="jquery.unveil.js"></script>
 </head>
 <body>
  <div style="height: 1000px;">
   hi!
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://digitalis.nwp.org/sites/default/files/stuff_1.png" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://static.tumblr.com/429df189c9e81bb388196fb442db77ba/vbdvuoy/xrUmksw6n/tumblr_static_green-stuff.jpg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://images.electricpig.co.uk/wp-content/uploads/2012/01/internet-stuff.jpg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcT3WjcjnXnXG3MIZZ1rw3dQsjrx-06ogqZbcjArDwM3n1Q9ixrwCw" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://www.abc.net.au/tv/stuff/stuff_wendy.jpg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ-5Ud4e36C7a9xsXgKr6ETuuecqSNorBhiWWelWj4UyfIUzzUwHg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://tosaenglish.com/wp-content/uploads/2012/06/image.png" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://www.seren.bangor.ac.uk/wp-content/uploads/2012/10/story-of-stuff-book-adds-to-the-vision-of-decreased-consumption.jpeg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://i.imgur.com/c6D2qCb.jpg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://sd.keepcalm-o-matic.co.uk/i/keep-calm-and-stop-saving-stuff-on-desktop.png" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSvKoJ_CqT0yZQFelslk6DUralqV73_SfzuiTa30e6YC1cLzkxY" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="https://lh4.googleusercontent.com/-ZknF9DJA52o/AAAAAAAAAAI/AAAAAAAAAB4/JKBNFb96bM0/photo.jpg" />
  </div>
  <script>
   $(document).ready(function() {
     $("img").unveil(-400);
   });
  </script>
 </body>
</html>

Let's go over this code in sections. The first section I want to talk about is the "<head>" section of the html file. The important bits are the 2 script links. The first one links to a version of JQuery hosted by google servers. The 2nd script links to a js file that is expected to exist in the same location as your html file. Save the unveil js file to your hard drive in the same place where you have the html file.

The next part to talk about is all them thar div tags. The first one makes sure we have 1000 pixels taken up by useless stuff. I did this so that you could better play with the scrolling effect of lazy loaded images. The remaining divs are all containers for img tags. For those of you used to using img tags already, you know what the src attribute is; it's the url of the image to display. In the case of the above img tags, we're linking to a single placeholder image file which is a blue circle. Each of these img tags also contains a special data-src attribute which in the case of the unveil JQuery plugin, contains the image that will be downloaded and displayed when the user's viewport scrolls the image into view. Long story short, this is the image you'll actually see.

The last chunk of code I want to discuss is the final script tag. This contains our jquery function (the document.ready) which fires off when the document has finished loading. Our function above will apply the unveil plugin to any img tag on the page. The -400 in there tells unveil to only "unveil" the real image after it's 400 or more pixels into the viewport. If you specify no value here at all the image is unveiled precisely when it gets into the viewport, and this is normally what you'll want, but for this sample I wanted you to see the placeholder images a little better.

OK go ahead and open up the html file in your favorite browser! Depending on your monitor resolution, you might either see just the word "hi!", or maybe you'll see a blue circle or 2 at the bottom of your screen. Now scroll down slowly. You'll see the blue circles come up on screen, and if you keep scrolling they turn into other images (the final destination images as denoted by data-src). Pretty nifty huh? Feel free to play around with that -400, change it to other values to see the change in behavior. The closer you get to 0, the less time (vertical scroll-wise) you'll have to see the blue placeholder circles. The more negative the number gets, the longer you see the blue placeholders.

If you get truly excited by all this, you can bring up the developer tools of your favorite browser (mostly by hitting the F12 key) and watching the timing of image downloads to confirm you're getting what you think you're seeing.



What's Next?

There are other lazy loading JS image libraries out there, including some that are JQuery plugins. Play around with them and see if you find another you like. I like this one because it's extremely light-weight and easy to use, but maybe you'll find one you like better.

You could also create your own sample page from scratch. That's the best way to learn after all, not by copying something another person has already done.

Resources

unveil
JQuery

Thursday, November 6, 2014

Simple Security Tips for .Net Developers

Intro
As developers, it is our responsibility to make sure our code is secure. If you haven't coded with security in mind before, a good place to start is by learning. So, today we'll see a few small tips you can start using right away to make your code more secure. Eventually you might end up designing security into your systems from the get-go, but let's start simple and see a few practical tips.

Use HTTPS

Information transmitted over the web is generally done on port 80 (HTTP), or 443 (HTTPS). Information transmitted via HTTP is insecure; HTTPS is encrypted using keys. If you have sensitive information including personally identifiable information, authentication information such as passwords, sensitive financial information, or anything else you want to protect, get an SSL certificate for your domain. This allows HTTPS traffic, and you can then force clients to use HTTPS instead of HTTP.

Http Header: X-Frame-Options

Have you ever heard of clickjacking? It's a form of attack where the user sitting at a web browser performs actions on one site when they think they are performing actions on another. Picture this: You have a site that allows users to enter and remove widgets. You have a "delete all widgets" button on your website. Someone else, who is just a malicious chode, puts your site in an iframe on their website. They then cover the stuff on your site with their own html elements using sneaky CSS and/or JavaScript, so that the user thinks they're clicking on a button that says "give me a free ipad" on one site, when in reality they're clicking your button that says "delete all widgets". Oops! It turns out this attack is pretty easy to thwart, just set an http header named x-frame-options to a value of "deny". You can do this in IIS, or my preferred method is to do so in code in your global.asax:

void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
}

This simply prevents browsers from rendering your website within a frame or iframe. You may still have to worry about older browsers, but consider this an opportunity for research on your own :)


Meta Tag: Charset

Would you believe that people can attack your website by passing it information using a character set other than what you expect? For example, if you expect users to type in utf-8 information, which is fairly standard, but they enter in utf-8 character sequences, they just might be able to sneak some JavaScript into your entries. Such an attack is called a Cross Site Scripting attack, or CSS or XSS for short. The good news is that this is also quite easy to get around. My preferred method of preventing this type of attack is done within the html of each of your pages, as per the following:

<html>
  <head>
    <meta charset="UTF-8">
  </head>
</html>

This tells the browser not to accept any form of input from the client unless it is UTF-8.


Restrict Access

This is just a general security tip which is useful in many situations: Restrict access by default, and give access only as necessary for a person to get done what needs doing. Don't give more access or rights than are necessary. If someone asks if you want to do the bare minimum, proudly exclaim "yes!". It's more secure.

Sql Parameters

Many .Net developers don't realize just how easy it is to hack the database behind a website using the website to do the dirty work. This is called a SQL Injection attack. I could go into a lot more detail showing you how to make such an attack, but hey, I have a wedding to attend this weekend so my time is gold this evening. Here is some code that will do a pretty good job of preventing such issues, and bonus: your code is cleaner than if you just concatenated the whole query together.

public void DoStuff()
{
  using (var conn = new SqlConnection("some conn string"))
  {
    var command = new SqlCommand("select * from SomeTable where SomeCol = @SomeCol", conn);
    command.Parameters.Add(new SqlParameter("@SomeCol", Request.QueryString["someval"]));
    command.Connection.Open();
    command.ExecuteNonQuery();
  }
}

In this example we are running a query which is based off a value the user typed into the querystring of the request. Using a SqlParameter in the command's Parameters list, we have ensured that the data passed to the database is safe and will not allow the caller to use SQL Injection.

Validate Info Entered/Imported

This is another general bit of information: Validate all information that is input into your system, whether it's from a user, another system, a file, a database, or other. If it's going through your system, validate! You never can tell what type of data might get tossed your way, so be prepared and prevent it from taking your system down by validating it's of the type and size you expect, and possibly within a range of valid values you might expect.

Encrypt Sensitive Data

This might seem like a bit of a no-brainer but I feel it needs mentioning. If you have sensitive information such as passwords, Personally Identifiable Information, sensitive financial information, or other info you don't want unauthorized people to get hold of, encrypt the data. There are many ways to do this in both .Net and in database platforms including SQL Server, you'll have to research this part on your own. Or hey, give me a buzz and I'll help out! I just don't have the time or space on this blog to give examples at the moment, as it can get pretty complex. Good, strong encryption is not for the faint of heart, but it's necessary for many things.

1-Way Encryption for Auth Passwords

Speaking of encryption, passwords! When setting up your authentication system you can take it a step further by creating a 1-way encryption of the passwords of your users. Why do that? Even if an attacker somehow gets hold of your database, they still won't be able to decrypt the passwords in order to use the logins of others. You may be wondering how you can then authenticate your users...the concept is simple, even if the encryption code is more complex: You just make sure that any given input value encrypts to the same value. So for example, I have a user named "bob" whose password is "hi!" The encrypted version of this password is "1234asdlfkj214o2i;;". When bob logs in he types in "hi!", so I then encrypt the typed in value and check to make sure it's the same as the encrypted value stored in my database.

Strong Passwords

So that prior example with a password of "hi!" isn't exactly a great password. Why not? The longer a password is, and the more nonsensical, the less vulnerable it is to something called a brute force attack (more specifically, a dictionary attack) where the attacker has a program try to randomly guess your password. They try words from the dictionary, including 1337-speek. So, make your users use better passwords. Instead of "hi!", suggest "124ksdfAAA!!~x@". This is not going to be vulnerable to a dictionary attack specifically, and makes it less vulnerable to a brute force attack in general. Don't carry this too far though; the stronger password enforcement you have in place, the more likely the user is to rebel and write that super-secure password on a post-it note stuck to their monitor. Backfire-city!

2-Factor Auth

Lately a concept called 2-factor authentication has been gaining steam. It's a simple concept: use more than 1 form of authenticating a specific user. Popular choices include a mobile app with a pseudo-randomly generated code ala World of Warcraft, a text message with a specific code sent to the user's mobile phone, fingerprint analysis, voice recognition, and others. In the world of websites this generally means you have your standard id and password along with some special code that you acquire elsewhere. Neat huh? Simple concept, but the coding might take a bit.

Validate Email Addresses

My last tip of the day: If you make users sign up to your system using their email address, and this is the email address they'll use for password reset and other such administrative features, validate the user actually owns the email address when the account is created. This is usually as simple as sending the user a unique activation link to the email address on the account as soon as the account is created, making sure the user can't login to the account until they activate it via the link you emailed. Once they click said link, the account is usable. 

What's Next?

Clearly there are many more good security tips out there, many more vulnerabilities to discuss, and all of the above topics could use a lot more detail. Spend some time on your own researching a few things.

Do you have a simple secure coding tip to share? Say so in the comments below!

Resources

Clickjacking Defense Cheat Sheet
Html Meta Charset

Thursday, October 16, 2014

SignalR and WebSockets

Intro

WebSocket is a new protocol, developed alongside HTML5, that allows a 2-way communication between client and server. With HTTP and your standard web browsers the communication is all 1-way; the client requests resources from the server and the server serves them. With WebSockets the server can send messages to the client without the client first requesting those resources. Messages can be passed from client to server and from server to client, keeping the socket connection open. Not all the grass is green in this land of Eden though; because this is a newer technology, not all browsers support WebSockets just yet.

This is where SignalR comes in. SignalR is an ASP.Net library that simplifies 2-way communication between the server and the client. It's an implemention of WebSockets, but it's not just that. It will use WebSockets when both the server and client support it, but when one or both does not support WebSockets it will fall back to other technologies that accomplish the same goal in similar ways. Simply put, SignalR allows you to use 2-way communication between client and server using whatever is the best way you are capable of using. Plus, the fallback mechanism happens behind the scenes. This means that you the coder code a single codebase for communication and SignalR makes the choice of which method to use for you. And, one extra bit of info...SignalR allows you to call client-side JavaScript functions from the server. That's some cool stuff!

To the Code!

Create yourself a new Asp.Net web application. Mine's named BlogSignalR1.


Make it an Empty web app with no folders, no core references, and no authentication.

Now add the NuGet package named SignalR.



Now add a class to your project named NotificationHub. Our app will have a single page where we, on the server, can notify our users of things that are about to happen on the website in real-time. This new class is what we'll use on the server-side to send those messages.

Here is the content you'll want for your new class:

using Microsoft.AspNet.SignalR;

namespace BlogSignalR1
{
    public class NotificationHub : Hub
    {
        public void Send(string message)
        {
            Clients.All.broadcastMessage(message);
        }
    }
}


Go ahead and create another new class in your website named Startup. This class will tell Asp.Net to fire up/initialize SignalR. Here's the code for it:

using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(BlogSignalR1.Startup))]
namespace BlogSignalR1
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}


Now it's time to work in client-side code a little. First create a new html page in the project. Name the file default.html. Here's the content of that one:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SignalR Basic User Page</title>
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
</head>
<body>
    Hi user!
    <div id="notificationArea">

    </div>
    <!--Script references. -->
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var notification = $.connection.notificationHub;
            // Create a function that the hub can call to broadcast messages.
            notification.client.broadcastMessage = function (message) {
                // Html encode display name and message.
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.
                $('#notificationArea').text(encodedMsg);
            };

            //create a connection to the hub
            $.connection.hub.start().done(function () {
                //sometimes you might need to do something after creating the connection to your hub; for this example, we do not
                });
        });
    </script>
</body>
</html>


This is a very simple page whose sole purpose is to display notifications from a site admin within the div named notificationArea.

Note: there is a possibility your version of either SignalR or JQuery may be different than mine. If so, please modify the script references as necessary to reflect the version you have in your Scripts folder.

The above html file implies we need one more file, this one for admins to create notifications for users. Go ahead and create a new html file called admin.html. Here's the content:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SignalR Basic Admin Page</title>
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
</head>
<body>
    Hi Admin!
    <label for="message">Message:</label><input type="text" id="message" />
    <button id="disseminate">Disseminate</button>

    <!--Script references. -->
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var notification = $.connection.notificationHub;
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#disseminate').click(function () {
                    // Call the Send method on the hub.
                    notification.server.send($('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
    </script>
</body>
</html>



Another simple page; one entry where you enter text, one button that you click to get it to push out a notification to clients. Let's try it out!

Go ahead and run the solution, navigate to default.html. Open up a 2nd tab in your browser and navigate to admin.html. Type some text into the entry on the admin page and click the Disseminate button.


Now go back over to the other tab containing default.html and your text is there!

Yes that's right folks, with a little bit of server-side code and a little bit of client-side code, you can create a basic site that allows real-time 2-way communication using SignalR. This is some wonderful technology that has tons of potential uses (chat is the most oft-talked-about usage for SignalR and WebSocket technology). If you want to make sure I'm not fooling you, just drop a breakpoint in your server-side and client-side methods and you'll see the trip from admin.html client, to server-side NotificationHub class, back down to default.html. It's mesmerizing!

What's Next?

Play around with the code and see if you can figure out what all of that JavaScript is doing. I find the best way to dig through stuff is to set breakpoints and trace into it and I'm sure you'll have luck with that method too. You can also dig around in the SignalR documentation and tutorials, as I've provided a link to such beasts down in the Resources section.

Resources

SignalR
WebSocket
My Code

Thursday, September 25, 2014

HTML4 versus HTML5: new additions/changes to HTML5

Introduction:

Html was first published in late 1991 by Tim Berners-Lee.  It has equally enriched and tortured our coding experiences on the world wide web ever since :).  This blog shall show the differences between Html 4 (the most current implementation) and Html 5 (new and improved).

New and improved in Html 5:

  1. Consistent defined error handling!  Less effort on the developer to have to write javascript validation when it's built into the newer spec!  Think of creating a text field to validate an email address and then having to hook in a javascript wrapper to require the @ and . characters exist, now think about setting an attribute like required=true within the tag you'd just created.  Time saver!

  2. The <canvas> tag which is aimed at animation (goodbye Flash animations?).

  3. Deprecating tags that can (and should) be done in CSS.  Goodbye <b>,<noframes>, and <font>!

  4. Native support for audio and video similar to the <img> tag.  Injecting the Thundercats theme song into a website based on Hello Kitty or the Dungeons and Dragons 80's animated series?  Yes please :).
  5. Newer and updated APIs!  Better support to have the browser be an online/offline application program!  Adding click(), focus(), and blur() to all elements on the page! Yes putting blur() on most any element on the page is cheesy, but more options are better!

Tune in next week when I attempt to create the same web page using HTML 4 and HTML 5.

Source:

Sunday, February 9, 2014

HTML 5 Semantic Element Basics

Grouping Content With HTML 5 and Semantic Elements

As I prepare to learn more about HTML 5, CSS 3, and JavaScript I figured this may be a good time to share what I am learning with some of you in case you had an interest in learning it yourself.  This is very basic information and there may not be anything new to experienced HTML 5 web developers.
 
Many HTML pages used to have their layout defined with tables.  Tables were followed by more elegant CSS solutions.  Semantic Elements can be used to give your content some grouping making the HTML itself easier to interpret.  CSS still allows you to position items in ways HTML 5 cannot but HTML 5 gives you some basic structures to hold your content in without using <div> just to hold grouped content.

Semantic Elements are not new to HTML 5, they are simply elements in HTML that define what is in their content.  Some examples of Semantic Elements that existed in HTML 4 would be <em> used to show emphasis on any content between the opening and closing element, headings such as <h1> used to display varying title sections, and <table> used to display your content in a tabular format many users are familiar with.
 
The Semantic Elements that are new to HTML 5 are:
  • <article>
  • <aside>
  • <details>
  • <figcaption>
  • <figure>
  • <footer>
  • <header>
  • <mark>
  • <nav>
  • <section>
  • <summary>
  • <time>
In this example we'll be creating a basic HTML 5 page using some of the new Semantic Elements.  Some items in our example would normally appear in a master page file so that we could use the same code from page to page but for simplicity we will be stuffing them all into one Default.html page.
 
The first thing we'll want for our page is a header that lets us brand our site and let people know who we are.  As a side note, <header> can be used in a document or a section of a document.  For now we are going to add a <header> element with an <h1> element to hold a title for our website. 

My Sample Website's Header

Now that we are telling everyone who we are, we are ready to give them a space to navigate our site.  Since we don't have a master page we aren't going to put any actual links in this section.  We'll just put some text in it marking it as the navigation section.  We'll use the <nav> element.


Now we'll want to add a section.  We will create a basic <section> with an <aside> element contained within.  When we get more advanced we'll use CSS to push the aside to actually be to the side of our section content.  For now we're keeping it simple.  A section is used to hold related content that will typically have a title to it.  (otherwise why not just use a div)

My Section

<p> This is my section. There are many like it but this one is mine. </p> <p> This is the remainder of my section now that the side note is gone. </p>
After playing briefly with section and aside, we want to briefly visit <article>.  The <article> element looks an awful lot like a <section> element.  Articles are used to display content that can be distributed independent of the website.  Stories that can be displayed via website, RSS feed, forums, blogs, etc.  Other than that, they are pretty much the same as sections.

This Just In: Programmers are Awesome!!!

<p> This is an example of an article element. Looks a lot like a section doesn't it? </p>
Now we want to add a footer to show a copyright to viewers to protect all our hard work.  This is done with a <footer> element.
This is my footer: &copy;ITC Prog Blog 2014
To help us take a look at the placement of all the sections we are adding to this page I am adding an inline style tag (we aren't on CSS yet) to give us a border.  We'll make our body tag on our page have a gray background and all sections within will have a solid border and white background.  I am not including the style tags in the code here to keep the sections cleaner for you to look at.  Here's what our page looks like:  

It is obvious by looking at the page above that semantic elements in HTML 5 don't give you the best layout for your page, but they do help you group your page items logically.  You'll still want CSS to position items on your page properly.  We'll pick up with what we learned next time.