I am a huge fan of ADO.NET’s Entity Framework (EF) that bridges the gap between modelling entities\business logic and data engines. It allows web-programmers like myself to focus on the solution instead of worrying about properly setting up databases, keys, foreign-keys, constraints, and indexes. Because of it’s quick turn-around, EF is perfect for prototyping and proof of concepts. For enterprise sized solutions, code-first created databases may require some greater optimization, but that can always be achieved after the fact if not in the solution itself. Querying and operations are a simple endeavour–simply work with the abstracted model and let EF worry about performing the correct database transactions for you.
Setting up a Code First EF MVC4 project is simple enough, but because I don’t do it often, I sometimes forget some steps. After all, most of my time is spent working with the solutions, and not setting them up. For this reason, I have decided to make a graphical guide as well as this blog post, which I hope helps my readers as much ad it helps me. In this tutorial, I create a simple model that goes over many of the features that you might use.
Step 1 – Create a new Project
First create the project in VS2012 by going to new project, giving it a name, selecting ASP.NET MVC4, selecting Internet Application, and ensuring Razor is selected. This will give you the base for a Code First EF MVC4 application. In fact, the Accounts Model is already set up with Entity Framework!
Step 2 – Define the Model
Next we create a very simple model that exemplifies how a 1 to many relationship using ICollection. The UML diagram above is coded in code example below entitled, “TestModels.cs.” The model is a little inconsistent to illustrate different techniques and annotation of the entity framework: custom db table names, custom KEY, and custom FK name; as well, it illustrates that traditional EF naming, which doesn’t require the annotation described.
[Table("dbUsers")] // Use this to use a different table name other than "Users"
public class User
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DbUserId { get; set; }
public string Name { get; set; }
public virtual ICollection Purchases { get; set; }
}
// This table will be called "Purchases" automatically
public class Purchase
{
// Because standard naming is used, no need for [Key] ...
public int PurchaseId { get; set; }
public int UserId { get; set; }
public int ProductId { get; set; }
[ForeignKey("UserId")] // Use this if the name of FK is different
public virtual User User { get; set; }
// No need to use ForeignKey because FK name is same as Key of Product
public virtual Product Product { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection Purchases { get; set; }
}
Step 3 – Create the DbContext
In the same model file, I create a the DbContex object that tells EF which classes are going to be stored in the database. In this case, I name this “TestContext” as seen in code segment below. It may be useful to note that other options are available here such as turning off pluralization, pointing to a specific db connection, etc.
public class TestContext : DbContext
{
public DbSet Users { get; set; }
public DbSet Purchases { get; set; }
public DbSet Products { get; set; }
}
Step 4 – Add a Connection String
Next open up your “Web.config” and add a connection string in the <connectionStrings> node. If you followed the steps above, you should already have one named “DefaultConnection.” Whatever your choice of storage system, make sure you name your connection, “TestContext.” Entity framework will automatically associate this connection with the db context we created in step 3.
Step 5 – Add a Data Initializer
Entity Framework provides a very useful feature: the ability to initialize your tables with some sample data whenever the model changes. To do this create a new class that inherits from DropCreateDatabaseifModelChanges<DbContext>. Next we override the Seed(context) function where we add our products, purchases, and users. The method SaveChanges() in the DbContext object is run whenever you want to update the DB.
public class TestInitializer :
DropCreateDatabaseIfModelChanges
{
protected override void Seed(TestContext context)
{
var products = new List
{
new Product { Name = "Widget",
Description = "A widget is a widget." },
new Product { Name = "Crank",
Description = "A crank for the widget." }
};
products.ForEach(p => context.Products.Add(p));
context.SaveChanges();
var users = new List
{
new User { Name = "Joe" },
new User { Name = "Lillith" }
};
users.ForEach(u => context.Users.Add(u));
context.SaveChanges();
var purchases = new List
{
new Purchase {
Product =
products.Where(p => p.Name == "Widget").First(),
User =
users.Where(u => u.Name == "Joe").First() }
};
purchases.ForEach(pr => context.Purchases.Add(pr));
context.SaveChanges();
}
}
Step 6 – Set the Initializer in Global.asax.cs
Next we set the initializer in the Global.asax.cs file to ensure that it runs when it needs (when the model changes and the context is used).
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Database.SetInitializer(new TestInitializer());
...
Step 7 – Add the DbContext Object to a View in Order to Test
Usually I add the dbContext to the HomeController first (without even touching the Home View) in order to test out the implementation inside an ActionResult that I know I will run (visit with browser after running); I also add something to the data to ensure proper functionality and saving.
public class HomeController : Controller
{
private TestContext db = new TestContext();
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
db.Products.Add(new Product { Name = "asdf" });
db.SaveChanges();
return View();
}
...
The last step is to verify that the database, tables, and sample data were created properly in the DB. For this I usually run SQL Managment Studio and inspect the DB directly. If you did everything correctly, you should see a new database with the name that you’ve described in the connection string.
There are several option in implementing LESS (the dynamic style sheet language) with your asp.net MVC application. While MVC 4.5 provides bundling and, with that, minification, it still does not provide the same dynamism as LESS; that being said, you can take advantage of both using the following technique.
An aside for those unfamiliar with LESS: it’s a dynamic stylesheet language that allows you to extend CSS to allow variables, “mixins,” operations and function. It’s a powerful tool that can help decrease dev time while making your style code more robust. It allows you, for example, to declare a variable for your main and accent colors at the top of the style sheet so that when you want to change the palette of your entire site, you can do that by editing three or four lines. That alone deserves great props. More info on http://lesscss.org/
So if you’re familiar with LESS you’ll know that you have 3 options: implement LESS on the client-side, dynamically on the server-side, or compile to CSS. There may already be some Asp.net LESS compilers our there (and if there isn’t, there should be), but my favorite option is the simplest: compile to CSS.
I use the program winless to watch the content folder of my MVC application where I have my .less file. I then add the compiled .css to the bundle(s). That’s it! Now anytime I make a change to the .less style it will automatically get compiled to the CSS file which my bundles use. No mess; no fuss.
Perhaps the most elegant solution would be if we have a LESS parser with the bundling implementation, but this is a pretty painless solution as well.
It’s amazing how flexible JavaScript is–it can do anything! It can even do OOP. As our JS implementations become more and more complicated, it’s great that ECMAScript allows us utilize the power of OOP, which should help us with code maintainability, re-use, and task-division. Although interfaces aren’t practical in a dynamic language that encouraged duck-typing, we can still take advantage of controlling variable scope (topic for another day), classes, and (pseudo) inheritance. In this article, I will go over one method of implementing classes and later I will talk about how to inherit that class in a new one. What I present in this article is one way of implementing classes with some variations of syntax, but because of the language’s flexibility, other methods exist as well.
Creating a Class
First we create the construct for a vehicle class. This will get run as soon as an object is created based on that class:
// Create new class to work with to better show the example
var Vehicle = function vehicle(model,type,totalWheels)
{
this.setModel(model);
this.setType(type);
this.setTotalWheels(totalWheels);
};
Next we implement the getter and setter functions for the properties of our Vehicle class. Note that above, I already use the setter methods in my object, but alternatively you can call “this.model = model;” directly in the constructor. Here is how we implement the getter and setter methods:
// Setter methods for the class
Vehicle.prototype.setModel = function(model)
{
this.model = model;
};
Vehicle.prototype.setType = function(type)
{
this.type = type;
};
Vehicle.prototype.setTotalWheels = function(wheels)
{
this.totalWheels = wheels;
};
// Get method that returns a string.
Vehicle.prototype.getVehicle = function()
{
return this.model + " " + this.type + " with " + this.totalWheels + " wheels";
};
The first two methods set an object’s attributes and can be run on the object itself at any time. The second is a method that returns a phrase that describes the object. If you need to return each individual attribute, you would simply do the opposite of the first 3 setter methods.
One thing to note is that the object’s attributes are NOT private–you can always access them with [object].[attribute]. There is a way to hide these attributes (using closures) to follow the open-closed principle, but I’ll leave that for another article.
Inheriting from the Class
ECMAScript only supports single class inheritance; essentially you can create a more specialized form of the parent class. In this example, I’m going to create a “Sedan” class based on the “Vehicle” class:
var Sedan = function(model,safetyRating)
{
this.safetyRating = safetyRating;
Vehicle.call(this, model,"Sedan",4);
};
// Here we point to the first class (Vehicle) and the constructor is Sedan
Sedan.prototype = new myExamples.Vehicle();
Sedan.prototype.constructor = myExamples.Sedan;
Now I am creating a child class of the Vehicle class. In this example, I choose to automatically set some parameters for Sedan. For example, a Sedan will always be of type “Sedan” and have 4 wheels. As well, to illustrate how you can extend the parent class, I add a new attribute: safetyRating. This time, I don’t have a setter method for the “safetyRating” to illustrate the other way you can initialize an object parameter with the constructor.
Creating Objects
Finally we can create objects based on the above two classes. This is very simple and you use the constructors that we created:
// Create an object of the parent class "Vehicle"
var someVehicle = new Vehicle("MAK","Truck",18);
// Create an object of the child class "Sedan"
var subaruSedan = new Sedan("Subaru", "5/5");
// Check inheritance
var isSubaruSedan = subaruSedan instanceof this.Sedan; // True
var isSubaruVehicle = subaruSedan instanceof this.Vehicle; // True
var isTruckSedan = someVehicle instanceof this.Sedan; // False
In the above example I create an instance of Vehicle and an instance of Sedan. In the sedan instance I have all of the methods and attributes available in Vehicle and Sedan class, while the vehicle instance only has the methods and attributes of vehicle.
Conclusion
ECMAScript is a prototype based language that does not include OOP specific statements. For example, it doesn’t have “class” or “extends” or “inherits” … however, the language is so versatile we can still have classes and inheritance (albeit limited).
I should also say that it’s possible to recreate OOP syntax more closely by creating a dummy class constructor, methods, etc. John Resig wrote an excellent article and re-usable script (MIT Liscence). Check out his article here.
Part deux of the jQuery plugins focuses on layout. I will talk about 2 awesome plugins that I’ve used before (whether at work or in my ventures). First, what I mean by a layout jQuery plugin is one that places and controls major content elements on a screen.
SlideJS
This is a great plugin that creates the very popular effect of displaying a set of images that slide through. We’ve seen it before above the fold on the splash page on almost any corporate website–image one will talk about a fancy new product; a few seconds pass by and image 2 will push out image 1; few more seconds, image 3 does the same to image 2… At any point if you want to go back to a particular image, some sort of navigation is provided that allows you to do that.
While SlideJS doesn’t give you the capabilities nor the handy utility of Wow Slider, it’s free and open source so you can modify it to suit your needs.
Official Website – Check the official slide js website for documentation and live examples Github – The repo page for latest release, docs, and branches SlidesJS 3.0 - Download right from here (you may want to check the official webpage or github page for the latest release)
jQuery Masonry
So this is an awesome look, especially when it’s animated. Basically you put a bunch of small <div>s of various sizes inside a container <div> and this plugin will re-arrange the items to make it fit as well as possible (or according to a certain pattern). Awesome already, right? Yes. It gets better because when you filder your set of <div>s by hidding some, or you resize the window or the container div, the objects will re-arrange automatically. Not only that, they will animate (fly?) into their new position!
Originally I used isotope, which is great, but unfortunately it’s not free. If you have a non-commercial website you may use it, but you’ll have to pay a dev licence for commercial use. Enter jQuery Masonry. This plugin might not be as well rounded as isotope (although I couldn’t find any issue with it), but it’s free (MIT Liscence).
Official Website – This is a great place for docs and examples. Highly recommend going there when implementing. Github – Repo page. jQuery Masonry Download - Don’t want to go anywhere else? Just download the it here.
I thought that this would be a great post to go over an easy implementation of JSONP, and also the b1t.co API (for JSONP). If you do not want to invest the time and energy in creating some AJAX proxy server-side implementation, there’s a great work around the cross-domain AJAX call issue.
It’s simple:
You create a function that creates a JavaScript script that points to the web service of another domain
You implement a callback funtion that does something with the returned JSON
When the JavaScript script get’s “loaded” (aka, when the web service returns the JS response), it will call the callback function.
An Example
The url for b1t.co’s API is: http://b1t.co/Site/api/External/MakeUrlWithGet?callback=[resultsCallBack]&url=[escapedUrlToMinify]
For example the call, http://b1t.co/Site/api/External/MakeUrlWithGet?callback=whateverJavascriptName&url=google.com
And as soon as it loads, it will run the function, whateverJavascriptName with the JSON as it’s parameter.
So with that knowledge, let’s say that you want to implement a function minify(urlToMinify) that will run the function, minifyResultCallBack(data).
Here is the first function–it creates the JS file, sets the “src” following the API and put’s it in the header:
function minify(urlToMinify)
{
url = escape(urlToMinify);
var s = document.createElement('script');
s.id = 'dynScript';
s.type='text/javascript';
s.src = "http://b1t.co/Site/api/External/MakeUrlWithGet?callback=resultsCallBack&url=" + url;
document.getElementsByTagName('head')[0].appendChild(s);
}
Implementing the callback
This function will be run as soon as the JavaScript source of the above call gets loaded. So do what you will with the data:
function minifyResultsCallBack(data)
{
document.getElementById("results").innerHTML = JSON.stringify(data);
}
Fin. You’re done. Simple, right? Almost simpler than AJAX.
In this example, I solely use JavaScript; jQuery has a useful JSONP implementation that automatically creates and names the callback functions. I will write about us jQuery for JSONP sometime in the future.
If you’re interested in the full source code of the above example, you can get it here: test JSONP Source
Tom, Nick, and I (affectionately known as Tominick by some) have launched a new website called b1t.co, which is a simple url shortner and QR Code generator. We have plans for more functionality currently available on bit.ly or goo.gl, but this is a great start for now.
We’re still ironing out the kinks and have over 11 bugs and improvements before we move past the beta stage. Despite that, b1t.co has already seen over 500 page views!
There are some great jQuery plugins out there that make our life a little easier. I’m not going to talk about any of the jQuery UI components which I use on a regular basis, but rather some of the 3rd party plugins that are available. They are all open source and free (this is the reason why I’m not including isotope). This is the first of a 4 part article.
For some reasons I’ve used a lot of different scrolling plugins. The following are very useful plugins to make your pages a little more interactive:
Waypoints
This is an awesome plugin that comes with some great extensions that give you the ability to trigger events at different scroll points, supports infinite scrolling, create sticky elements, and even get scrolling statistics.
Great plugin if you have elements that you want to scroll within divs. I use it on the menu of this blog. This plugin uses the subtle mac-l;ke scroll bars that display when you mouse over the scrollable element.
I passed Microsoft’s Javascript, HTML5, and CSS3 Exam with a great mark, and it helped that I made thorough notes. Please note that these notes are incomplete and I also relied heavily on writing out JS code in JSFiddle so that I would better comprehend the code. I will post the links to JSFiddle sometime in the future after I go over them (they are very rough). However, my notes provide a great start and some excellent links. I recommend that you use them as a starting point. You will notice that many of the topics are missing (especially towards the end) because I was running out of time.
So I completed the first stage of my new user interface for this blog. You’re looking at it right now, but don’t look too critically as it’s only in the beta phase. As I’m writing this, I’m aware of several layout issues, and some parts aren’t complete at all. For one, I still need to style the comments section of single blog pages. I also need to fix the overflow issue of many categories in the footer.
All that aside, I’m very happy with the new look and feel. I will soon post all about this new UI in an article entitled, Content is King. For now I’m going to simply list all the things that still need I need to work on.
Short Term
These are all the items I plan to complete within the week:
Testing: A thorough test of
Layout: Styling the input of the email subscribe in the menu
Layout: Fixing overflow issues of footer
Layout: Styling <strong> and <ul> elements
Layout: Styling comments section
Layout: Styling links
Functionality: Bug with left nav on window resize
Content: Properly tagging and categorizing past posts
Content: Going over past content to ensure it is encoded properly
Content: Completing the about page
Long Term
Items that I plan to complete within one month:
Adding share functionality on individual blog posts
Popularize my blog by exchanging links with other writers
Putting my twitter feed on the blog(?)
Responsive design: for now, the website is only designed for a screen with a width resolution of 1024 or more. Soon, I hope to make this UI responsive for any screen including mobile. I already programmed many of the functions I will need to make this happen, but implementing it will take time.
Technology has revolutionized modern art. Today, even revolutionary contemporaries like Warhol seem to belong more with modern classics like Picasso or Munch. That’s because modern installations immerse us with media-rich (sometimes interactive) abstractions and realisms. It’s easier than ever for an artist to shoot, edit, and produce a video; artists now can easily make digital sounds previously unheard by human ears. And as the cost of these technologies fall, the frequency of their implementation increases.
It’s appropriate that modern art is increasingly digital since our lives are as well. We socialize on social networks instead of bars or homes. We text instead of talk. We have on-line girlfriends and cyber sex. We LOL and LMAO instead of laughing; we <3 instead of loving.
Our memories live in the sub-folders of our file-systems as digitized media: images, audio, video… Our minds as ascii representation on blogs, e-walls, and comments.
Although it may not seem like it, my commentary is more observational than judgemental. Perhaps it’s natural (after all it comes so easy); perhaps it’s better. After all, who’s to say that LOL is any less of an emotional experience than laughing out loud? Or that a cyber-lover is any less in love? Who knows.
This gave me an idea for a design. I wanted to represent this digitization graphically by using some simple algorithms to take human-readable patterns (such as words in my first set) and showing it as a pattern–how it may be stored on a machine or viewed by an alien. In this piece I include the original (human-readable) representation, the code behind the algorithm, and the graphic result. In this way, the algorithm used to create the art becomes art itself–a cyclic statement.
I hope that this series reminds people that while our digital footprint may indeed live forever, it is nothing but noise (perhaps not random) when looked from a third perspective. Another ode to existentialism.
Hamlet Digitized
This piece uses the words of Hamlet’s famous soliloquy in act 3 as data to generate the graphics. It turns each character into an ascii code and then renders the value in a orthographic bar (the two colours represent two different values). The result is a unique graphical fingerprint of that piece; all of the data (each box) exists in the original SVG so it would be possible to decode the original text. The algorithm used to generate the graphic is placed below to reinforce Hamlet’s digitization.
Technical details: It’s simple javascript that I used to create an SVG (in this case it’s Hamlet’s famous soliloquy in act 3). I used Node.js and express.js to generate the actual files. I’m hoping to eventually create an interactive gallery where you can “digitize” your own life.