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:

Wednesday, September 24, 2014

JavaScript Pollution

Intro

Everyone knows pollution is bad. It turns rain acidic, makes our roads look terrible, fouls our drinking water, and can cause naming conflicts in our JavaScript code. What? Yeah that's right, our JavaScript code. Write your congressperson I tellz ya! It's a huge problem. But don't fret, there are ways you can mitigate this danger to our very way of life, and I'll show you 2 simple things you can do to lower your global-carbon-JavaScript-namespace footprint.

Que?

Polluting the global namespace is a common term for a common practice in JavaScript. When I create a plain old function in JavaScript such as the following:

function someFunc() {
    window.alert('some text!');
}

someFunc();

I've now committed a cardinal sin, right up there with sloth and eating the last Oreo. I've polluted the global namespace! See how the function someFunc is just floating around in the ether, available to be called from anywhere and without a class or namespace prefix necessary? This is what polluting the global namespace is. This might not seem like a big deal to you. I mean, so what? You're the one writing this code and it's not like you're going to conflict with your own function names right? Well JavaScript is a very open language, and many people these days use multiple 3rd party libraries. Now pretend all these 3rd party libraries are also polluting the global namespace. You'd have naming conflicts between the 3rd party libraries and with your own local code, and that would be quite painful to deal with. How can you, the lowly programmer, prevent your own code from polluting the global namespace? For those of you used to C#, the answer should come naturally: namespaces and classes!

Namespace Example

There are many ways to skin a platypus, and there are many ways to create a namespace in JavaScript. I won't cover all of them, I'll just show you my favorite:

var MyNamespace = MyNamespace || {};

MyNamespace.myInt = 3;


It doesn't get much simpler than that. The first line of code creates our "namespace". It's not really a namespace as JavaScript doesn't support namespaces, but we can useMyNamespace quite similarly to how we us namespaces. We can even nest them if we feel like it. The 2nd line of code just adds a variable named myInt to our namespace. If you want to later created a 2nd javascript file and reuse your namespace, all you have to do is copy that first line to the top of your new file. The magic here is that when we declare MyNamespace, we set it to itself, or if it's undefined, we set it to an empty new object. So if you do this in 1 file or 50 files, you'll either create a new "namespace" object or assign the namespace object to itself, so it works quite easily.

Class Example

Classes take a little more work but they're still not too bad. Here's an example of how to define a class, create an instance of it, and then use it:

//set namespace
var MyNamespace = MyNamespace || {};

//create our class in the namespace
MyNamespace.MyClass = function () {
    this.stringProp = "some string";
    this.intProp = 42;
};

//add the method myFunc to our class
MyNamespace.MyClass.prototype.myFunc = function () {
    window.alert(this.stringProp + "::" + this.intProp);
};

//create a method within the namespace (but not in the class) that creates an instance of the class, sets a property of the object, and calls a method of the object
MyNamespace.doThisStuff = function () {
    var myObj = new MyNamespace.MyClass();
    myObj.stringProp = "yep, still a string";
    myObj.myFunc();
};


The first chunk of code you've seen before; it sets up our namespace.
The 2nd chunk of code defines the class. More accurately, it defines the constructor for our class, within which we also define our class properties stringProp and intProp. We set them to default values too.
The 3rd chunk adds the method myFunc to our class. I won't get into the keyword "prototype", but suffice it to say you should use it when setting methods of your classes so that the method will be instance-level instead of static/class-level.
The 4th chunk of code is a namespace-level method that creates an instance of our class via the new keyword, sets a property value on the instance, and then calls a method on the instance.

All you would have to do now is setup an html file to call your code and you're good to go. You can create as many instances of the class MyClass, which is defined in the namespace MyNamespace as you want to. Have at it!

Summary

I hope you can see the great benefits of using classes and namespaces in JavaScript (well, the strange equivalent of them anyways). Polluting the global namespace can be a tricky problem if you run across it, and preventing the problem is quite easy. Plus it makes your code easier to organize, and in my opinion easier to read. Try it out! It's easy I promise, it just takes a little practice.

What's Next?

  • Read further on objects in JavaScript, and how JavaScript doesn't really support namespaces and classes (we just faked it).
  • Do some more reading on other ways people have come up with to emulate namespaces and classes in JavaScript. You might find one that you like better than what I chose!
  • Learn how to nest your namespaces.
  • Learn how to do inheritance. It's kind of tricky for a language that doesn't really support classes.
  • There is another way to create an instance of a class, Object.create. Read about it.

Resources

Introduction to Object-Oriented JavaScript
My Code

Wednesday, September 17, 2014

CSS Intermediate: an explanation of CSS Advanced

Introduction:

You're probably wondering at this point: Daniel, you've gone in the wrong order!  Well... kinda :)  Chances are some of the CSS you'd seen last time was interesting to look at but you had no clue what each section was attempting to do with various non alpha-numeric characters used in each declaration.  That's why an intermediate blog is in order.

Onto the explanation of last week's coding fun.  Below is the code from layout.css:


* (asterisk) takes care of all classes in the calling page.
body takes care of the body tag that exists on the calling page.
header takes care of all generic header tags that exist on the calling page.
header h2 takes care of the specific header h2 tag(s) and extends the css from header that was defined above it and modifies all h2 tags that exist on the calling page.
.container takes care of all elements with the id of container on the calling page.

This is some cool stuff!

From the file slideshow.cs we have even more interesting samples:


span.cap takes care of all span tags with the id of cap that exist on the calling page.  Think of this logic in the form of (tag type).(id of tag type).

That covers the bulk of the page layout except for one other declaration type on the page:  span#slide1:target ~ ul.slider li.lArrow a.  Where the . selector uses all generic (id=tag) tags # calls out a specific tag name.  The ~ (tilde/squiggle/twiddle) selector allows you to call a sibling element of the first id'd item getting css'ified to simplify the declarations you declare.

Here's another code sampling from last time, this time a portion of the index.html code written to call the CSS files used for the last tutorial:



for the css declaration span#slide7:target ~ ul.slider li.track .tr7 that makes  the class "tr7" within the list item (li) class "track" within unordered list (ul) have the background color of #f00 (this is the hexadecimal value for Red).

Enjoy!

Source:


Wednesday, September 10, 2014

2 Simple Best Practices for C# Database Coding

Intro

In my many years of .Net coding, more than I'd like to admit sometimes, I've seen a number of mistakes over and over again by people who just don't know any better. I've got 2 in particular that I see when people hit databases with .Net code, and I figured hey, I can call these out so people know not to do it! So here they are.

Best Practice 1

Always, under all circumstances, close your connection to the database. This might sound like common sense, but it's not always as easy as just calling connection.Close(). What happens if your code throws an exception between Open() and Close()? If you don't have the Close() in a try finally and if you're not creating the connection in a using statement, you're leaving that connection open. What happens if you leave those connections hanging? My experience is with SQL Server, and with it you end up eating up all the available connections eventually, which means your queries fail because you can't open any more connections. In the case of a website it means you have to recycle the app pool to free up all those connections, which can be a bit annoying for your users. Let's see some potentially bad code in action first:

using System;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    private void BadSqlConnection()
    {
        var conn = new SqlConnection("some conn string here");
        conn.Open();
        var cmd = new SqlCommand("select * from SomeTable", conn);
        cmd.ExecuteNonQuery();
        conn.Close();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        BadSqlConnection();
    }
}


See the problem? If the SqlCommand cmd throws an exception of any kind, that SqlConnection stays open, eating up one of the connections in our connection pool. Bad! So what can we do to clean it up? My favorite thing is to use a "using" statement. It accomplishes the same thing a try...finally would, but with less code. Here's a sample of some good code:

    private void GoodSqlConnection()
    {
        using (var conn = new SqlConnection("some conn string here"))
        {
            conn.Open();
            var cmd = new SqlCommand("select * from SomeTable", conn);
            cmd.ExecuteNonQuery();
        }
    }


Using the using statement when we create the connection ensures that the connection will be closed and freed before the method ends, regardless of whether or not any exceptions are thrown. It's conceptually the same thing as a try...finally where the Close() call is in the finally. Neato!

Best Practice 2

SQL injection attacks suck! It's a very common way for chodes to attack your data-driven website. Pretend you have a textbox on your website where people can login via userid and password. You've got 2 entries on your page and a button, one for the userid, one for the password, and the button attempts the login. Maybe your login code looks like this:

    private void DoLoginBad()
    {
        using (var conn = new SqlConnection("some conn string here"))
        {
            conn.Open();
            var cmd = new SqlCommand(String.Format("select * from Users where UserId = '{0}' and Password = '{1}'", UserId.Text, Password.Text), conn);
            var reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                //stuff that logs the user in
            }
        }
    }


What's bad about the above code? Think about what will happen if this value is put in the UserId textbox: "peeticus'--". Looks pretty innocuous right? Absolutely, completely, horribly wrong! Think about what this value does to the query which is sent to SQL Server; it now becomes "select * from Users where UserId = 'peeticus'--' and Password = '[blah]'

The key thing there is that our sql statement is terminated after checking the UserId because of the ending of the string value via the apostrophe, then the double-dash "--" which makes the rest of the line a comment. So, with this fairly trivial attempt somebody could log into your system as any user for which they know the userid. Believe it or not there are much worse things they can do with this tactic too, but we'll save that for another day.

How can you thwart the evildoers? Conceptually speaking you need to filter out bad characters such as apostrophes and maybe dashes, or filter in good characters if you want to be even safer. A better idea though would be to use the built-in sql parameters within .Net so that a well-tested library can do the work for you! Here's the same query from above, rewritten to be resistant to SQL Injection:

    private void DoLoginGood()
    {
        using (var conn = new SqlConnection("some conn string here"))
        {
            conn.Open();
            var cmd = new SqlCommand("select * from Users where UserId = @UserId and Password = @Password", conn);
            cmd.Parameters.Add(new SqlParameter("@UserId", UserId.Text));
            cmd.Parameters.Add(new SqlParameter("@Password", Password.Text));
            var reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                //stuff
            }
        }
    }


All you have to do is replace your concatenated values in the query with a couple parameters using @ symbols, and voila! A couple extra lines of code for a lot more peace of mind.

CSS Advanced

Introduction

So the last tutorial showed some cool looking modifications to a web page with not too much code behind to achieve it.  You're probably asking yourself:  Tidwell's annoyance of bards seems to exist (yep!), any other cheese he could potentially code about for an advanced tutorial?  Yeppers, let's take the way back machine to the 80's where my first introduction to Dungeons and Dragons was in the animated form via Saturday morning cartoons.  Lets see if I can make some cheesy images from the "players" in the series somewhat palatable to view in a webpage.

Let the coding begin!

First lets create a webpage.  Nothing too fancy, here's something I "borrowed" from the interwebz (code downloadable in link at the bottom of the tutorial):



Now we need some css to make it work.  The first code sampling is a small css file we'll call layout.css to handle the general layout of the website:




and also a file we'll call slideshow.css to handle the transition from one jpg file to another:




The result looks like this in a web browser:



Wowsers!  Very little HTML, whole lotta love (for DnD the animated series anyways).  Even more powerful stuff for very little code behind!

Source:
http://www.script-tutorials.com/how-to-create-a-pure-css3-slideshow/

Image Source:

http://img4.wikia.nocookie.net/__cb20100224154850/dungeonsanddragonscartoon/images/a/ac/Diana.jpg

http://img1.wikia.nocookie.net/__cb20100224155117/dungeonsanddragonscartoon/images/1/10/Sheila.jpg

http://img2.wikia.nocookie.net/__cb20100224155256/dungeonsanddragonscartoon/images/1/10/Ericavalier.jpg

http://img4.wikia.nocookie.net/__cb20100224155632/dungeonsanddragonscartoon/images/0/07/MAGICIAN.jpg

http://img4.wikia.nocookie.net/__cb20100224155712/dungeonsanddragonscartoon/images/a/af/Barbarian1.jpg

http://img1.wikia.nocookie.net/__cb20100224154119/dungeonsanddragonscartoon/images/2/2a/Hank.jpg

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8iVf9HhZIr-Nv-KjWaPte6MpeT9spJe0c21pFBZJYRszvLgC07Ar3hBCI07AoiydBJe17cRYb4pgR3Z7VcDCQG4EEyehn-vYzyPtk92Jn-aAZcLmo15ROpOskVsYFTHz4y8kwSW7TvqOn/s1600/25th.jpg


Thursday, September 4, 2014

C# Auto-Implemented Properties

Intro

Ferrari; beautiful sunset; big stack of cash; a hilarious comedy...what do all these things have in common? They're all nearly as cool as c# Auto-Implemented Properties. Yes that's right folks, coding is now cool just like me (ahem). What's an auto-implemented property you ask? Well for starters, thanks for asking. An auto-implemented property is one more thing you can take advantage of to save you some keyboard strokes. Yep that's it folks, less keyboard strokes! (the crowd goes wild). Let's see how auto-implemented properties accomplish such a monumental feat here in the next section.

Example

Here is a very simple example of an auto-implemented property.

    public class Aip
    {
        public string Description { get; set; }
    }


I'm sure you're all used to seeing properties in classes by now. What you might not have seen though is a property that just has "get;" or "set;" within the property declaration, which is an auto-implemented property. Believe it or not, this is a functional class that compiles. You can even get and set the property Description with code like this:

        protected void Page_Load(object sender, EventArgs e)
        {
            var aip = new Aip();
            aip.Description = "hi, i'm tom!";
            Response.Write(aip.Description);
        }


Here we create an object of type Aip, set the description, then read the description. It works just like a normal class with a normal property, only you didn't have to create a (usually private) field behind the property. C# did that for you behind the scenes!

Why?

I already covered this fool! But hey, it's because you can save yourself some time. The above class declaration for Aip is easier than what you would normally do prior to auto-implemented properties:

    public class Aip
    {
        private string mDescription;

        public string Description
        {
            get
            {
                return mDescription;
            }
            set
            {
                mDescription = value;
            }
        }
    }


Yeah it's not a big difference, but it does add up. If you've got a lot of properties to define in an object, give it a whirl! You'll appreciate having a couple extra minutes of your time to do other things.

Limitations

One obvious limitation is that you can't do other things in the getter and setter. They're auto-implemented after all, not manual! So if you need to put any extra logic in your setter or getter, you'll need to implement the property fully yourself.

Limitation 2: Auto-implemented properties must have both a getter and a setter. You can however put the private keyword in front of either the getter or setter to hide them from prying eyes if you really need to.

What's Next

Try it out! I'm sure you've got a project coming up where you can use this.

Resources

Auto-Implemented Properties

Wednesday, September 3, 2014

CSS - an introduction

Introduction

What is CSS?  Cascading Style Sheets for the simplest of definitions.  According to Google: "CSS is a cornerstone specification of the web and almost all web pages use CSS style sheets to describe their presentation. CSS is designed primarily to enable the separation of document content from document presentation, including elements such as the layout, colors, and fonts.".

Why use CSS?  You can set the tone for your whole web page/web site.  Reusable code beyond that reasoning, one central location to where a few changes here and there can greatly change the way your web page/web site looks.  Nifty eh.

Let the coding begin!

First lets create a webpage.  Nothing too fancy, here's something i threw together in 10 minutes or less:



The result looks like this in a web browser:




Not too shabby, but we could make that look quite a bit nicer.  Lets go ahead and create a .css file to include into the code above.  With something as simple as the following code (named DnD.css):



Now lets css'ify it! With one line of code added to my code above like the following:

The web page in a web browser looks like the following:


Wowsers!  Full page with blue background, Orange centered text for the heading text, green right justified text for the text within the paragraph tags.  Powerful stuff for very little code behind!

Tune in next time to learn some more advanced css techniques!

Source:

http://www.w3schools.com/css/