Stackoverflow Banner

Saturday, March 30, 2013

LocalDB ConnectionString and EntityFramework Setup

The world of SQL Server can be fairly confusing to someone who is new to it. Heck, it can be confusing to someone who knows it really, really well.

With the release of Microsoft's 2012 developer products, and particularly with the release of SQL Server Express 2012, Microsoft introduced LocalDB. LocalDB is "a minimal, on-demand, version of SQL Server that is designed for application developers." Namely, LocalDB has these following benefits:

  • Small Installation Footprint
  • Zero Configuration
  • Run as non-admin
  • Offers same/similar features as SQL Server Express

In short, LocalDB is really nice for application developers. If you want to see more of the pros (and cons) of LocalDB, head over to SQLCoffee to see the list.

So, given the goodness of LocalDB, I wanted to start using it for one of my own applications (particularly an application that is using Entity Framework). I started searching the web for the configuration and found way too many different suggestions. So, I'm going to add my own into the mix as this is what worked for me. Below is the connection string and the EF connection information. Typically, this goes into your Web.config or App.config file.

<connectionstrings>
  <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|DatabaseName.mdf';Integrated Security=True" />
</connectionStrings>

...and...

<entityframework>
  <contexts>
    <context type="Com.JasonCavett.Data.DAL.Context, Com.JasonCavett.Data, Version=1.0.0.0, Culture=neutral">
      <databaseinitializer type="MyProject.Migrations.Initializer, MyProject" />
    </context>
  </contexts>
  <defaultconnectionfactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
      <parameter value="v11.0" />
    </parameters>
  </defaultConnectionFactory>
</entityFramework>

Monday, November 5, 2012

Understanding JavaScript "this" Keyword

I know there are a number of blogs and articles on this particular topic (no pun intended) and it only takes a quick Google search to find the information on how JavaScript's this keyword actually works.

However, since this blog was primarily started so I could better understand my craft, I'm going to just add another article to the mix because if I can explain a topic, then I understand it. (Yeah...sorry...it's all about me.)

The reason I even decided to write this article in the first place is I had never really run across problems with the this keyword. In fact, I will admit that I had mistakenly always thought of this to operate how it would as if I were working in Java. Unfortunately (or fortunately, once you understand it), this was not the case, and I ran into an issue that was non-obvious to me until I started doing some research. So, I now present to you the findings of my research and my better understanding of JavaScript's this keyword.

Because this is a blog about code, let's start with an example where I created a simple Contact JavaScript object.

var Contact = { 
  firstName: "Jason",
  lastName: "Cavett",
  email: "example@example.com",
  display: function () { return this.firstName + " " + this.lastName + " email is: " + this.email; }
};

Contact.display();

Fairly simple, right?

Note: In my particular situation, I was loading the objects using the jQuery.getJSON() function and mapping to it with the jQuery.map() function. But, it still does not change the fact that I can access the various properties of the object through my display function. I am simplifying this example quite a bit because I did not want to distract from the main point of this blog post.

At this point, I decided that I wanted to create another type of contact which was a little more specific:

var BusinessContact = {
  firstName: "John",
  lastName: "Doe",
  email: "johndoe@example.com",
  company: "Acme Corp.",
  phone: "555-555-5555",
  display: Contact.display,
  buisnessInformation: function() {
    return "Company: " + this.company + " - " Phone: " + this.phone;
  }
};

BusinessContact.display();

Pretty straightforward again, right?

Well, this is where things start to get a little tricky with this - particularly if you come from a Java background.

In my previous code example, you will get:

John Doe email is: johndoe@example.

In memory, BusinessContact.display() and Contact.display() reference the same object. But, the this keyword will be whatever object is before the period in the call. So, in the case of the BuisnessContact, it is the business contact information, and in the case of the Contact, it is the contact information.

This is why I had a particular problem with my code. I did something like this:

var display = BusinessContact.display;
// Some code went here.
display();

So, there is nothing in front of the period here. What happens?

Well, technically, when there is no object explicitly used, there is the implicit, global object (also known as window - I believe named for the browser window in which the JavaScript would run). As a result, I get the following output:

undefined undefined is: undefined

And that is, of course, because there are no firstName, lastName, or email addresses defined for window. (And, in actuality, I had saved a global variable called email which meant I got
undefined undefined is: blah@example.com
. This is what started my entire confusion in the first place.)

So, what can you do to get around this problem (pun very much intended)? Well, the first thing to do is realize that it's not a problem. The ability for this to change allows for some very powerful uses in JavaScript.

This is where the call and apply become important. In short, you can call your function with either:

Contact.display.call(BusinessContact);
or
Person.display.apply(BusinessContact);

Both are very similar, but slightly different in how you pass in your arguments (if you have a generic function instead of the specific ones I am showing in this example). The different would be:

Contact.display.call(BusinessContact, "FirstName", "LastName", "email");
Contact.display.apply(BusinessContact, ["FirstName", "LastName", "email"]);

This table shows the value of this depending on the syntax of the function call. (Thank you to JavaScript Web Blog for the table.)

Syntax of function callValue of this
1. Method call:
myObject.foo();
myObject
2. Baseless function call:
foo();
global object (e.g. window)
(undefined in strict mode)
3. Using call:
foo.call(context, myArg);
context
4. Using apply:
foo.apply(context, [myArgs]);
context
5. Constructor with new:
var newFoo = new Foo();
the new instance
(e.g. newFoo)

So, as you can see, it's very understandable as to why this gets so confusing - especially if you are used to it in another language. Hopefully this post helped you under this just a little bit better.

Tuesday, August 28, 2012

WebGL Support in Google Chrome in Linux

As any good computer nerd knows, the browser of choice these days is Google Chrome. It's fast. Chrome supports a ton of the latest not-yet-standard standards (AKA HTML5 and CSS3). It has an excellent extension environment. And, it has a great set of built-in tools to support development. And, last of all, it supports WebGL...with a caveat or two.

That brings me to the reason for my post.

I have been recently doing work with GPU rendering in the web browser. Most of the work has been happening on my Windows 7 box (soon to be Windows 8!). But, because my Linux machine is much more powerful, I wanted to move the development to there. So, I did.

And nothing worked.

I quickly learned about chrome://gpu, and after visiting there, I saw this screen:


Hmmm...

So, I did a bit of poking around in Chrome's options, and a little bit of searching around on the web, and I found the exact two commands I was looking for to bypass this problem.

Note: This solution will only work if your graphics card is well supported and you have your drivers properly setup. If you have questions on how to setup OpenGL or proprietary drivers for your card, I would start with a Google search for your graphics card (and, perhaps, distribution).

In order to use WebGL in Linux, run your web browser with this command:
x-www-browser --enable-webgl --ignore-gpu-blacklist
Note that you may need to replace x-www-browser with the path to Chrome. (Make sure that you shut down Chrome completely before running that command so you start a new browser session.) Visit chrome://gpu to make sure everything worked for you.

No, go enjoy WebGL goodness!

Follow-up
I did want to write a follow up based on the discussion that happened after I shared blog post to my Google+ profile. Ryan Sleevi, a Google employee and Chrome developer provided this warning:

Normally the blacklist exists because of known (functional or security) bugs in drivers that make in (unsafe or unstable) to use WebGL. While it may work, I might advise and advocate caution before using that latter flag too widely.

While a lot of work has gone in to sandboxing, securing, and sanitizing the GPU process, one buffer underrun can be your undoing.

You now have been warned. Please keep this in mind.

Saturday, July 14, 2012

Create a Faded List Item Using CSS3

I know there are about 1000 tutorials on various styles that you can give your lists using CSS3 on the web...but I still wanted to add my own voice to the mix.

I wanted to create a CSS list that displayed the name of an item, and an associated value as a set of responses from my users. This is very simple without the styling. Here is my HTML.

<ul id="responseItems">
  <li><a class="answerLink" href="/questions/1">ZIP Code</a><span class="answer">10001</span></li>
  <li><a class="answerLink" href="/questions/3">How Much Time</a><span class="answer">2 Hours</span></li>
  <li><a class="answerLink" href="/questions/4">Maximum Cost</a><span class="answer">$25.00</span></li>
</ul>

As I said, a very simple, unordered list. For the purposes of this post, I will assume it is sitting on a background with a hex value of #424242, but you can place this list wherever you want and on whatever color background you want (that is outside the scope of this post, however). Adjust the colors accordingly.

Now that the list is in place, it's time to do just a quick styling with CSS3. I'm going to show the code first, and then describe what's happening.

#responseItems li {
  margin-bottom: 3px;
}

#responseItems li
{
  background-color: #424242;

  /* Gradient for Fading */
  background-image: linear-gradient(left, #FF7F27 0%, #424242 67%);
  background-image: -webkit-linear-gradient(left, #FF7F27 0%, #424242 67%); /* Safari 5.1+, Mobile Safari, Chrome 10+ */
  background-image: -moz-linear-gradient(left, #FF7F27 0%, #424242 67%); /* Firefox 3.6+ */
  background-image: -ms-linear-gradient(left, #FF7F27 0%, #424242 67%); /* IE 10+ */
  background-image: -o-linear-gradient(left, #FF7F27 0%, #424242 67%); /* Opera 11.10+ */

  border-style: none;
  -moz-border-radius: 15px;
  -webkit-border-radius: 15px;
  border-radius: 15px;
  font-size: 16px;
  padding-left: 5px;
}

#responseItems a:link, #responseItems a:visited, #responseItems a:hover, #responseItems a:active
{
  color: black;
  text-decoration: none;
}

Most of the CSS is fairly straightforward. The part I want to point out starts on line 10. This effect basically takes the box that holds my list item and fades it from one color (#FF7F27) to the background color (#424242) coming from the left side. Unfortunately, every browser supports a different way of doing this (what a pain), which is why you see five different versions of this gradient.

Other than that, I also give the border a radius for browsers that support it starting at line 17. In the next rule, I also remove the text decoration and set the font color on the link itself. The final, resulting look is:


I would recommend playing around with the percentage of the fade (adjust the 67% value after the color). Please note that the rest of the styling is not part of this tutorial.

Also, there is an option to use transparencies within the linear-gradients (at least some of them). I had a little bit of trouble with it, but in case you wish to investigate further, you need to use rgba colors like this:

background-image: -webkit-linear-gradient(left, rgba(255, 255, 255, 1) 0%, rbga(255, 255, 255, 0) 67%);

Hope this helps you out! Check out ImpressiveWeb's CSS3 linear gradients article for more information on the topic.

Thursday, May 24, 2012

A Better Aero Snap with Openbox

While I love running a lightweight system, there are definitely some better UI "stuff" that Windows 7 has that my beloved Openbox setup does not - at least not out of the box. I was specifically looking for information on how to emulate Windows 7 Aero Snap feature with the keyboard that automatically docks windows to the right and the left of my screen as I use this quite frequently when I'm developing. (Note: I didn't worry about using the mouse to drag and drop snap windows as I really dislike lifting my hands up off the keyboard unless I absolutely have to. This also explains my love affair with VIM.)

If you visit Openbox's wiki page on the subject, they eventually send you to this forum post. While the technique does work, it does not feel nearly as smooth as the Windows 7 version does. So, I decided to think about what was I actually trying to accomplish and found a different way to get the snap feature to work and it feels a lot smoother to me.

Open up ~/.config/openbox/rc.xml in your favorite editor.

Add this keybinding to the keybind section:

<!-- Window Tiling: Emulates Windows 7 Snap feature -->
<keybind key="W-Left">
  <action name="UnmaximizeFull"/>
  <action name="MaximizeVert"/>
  <action name="MoveResizeTo">
    <width>50%</width>
  </action>
  <action name="MoveToEdgeWest"/>
</keybind>
<keybind key="W-Right">
  <action name="UnmaximizeFull"/>
  <action name="MaximizeVert"/>
  <action name="MoveResizeTo">
    <width>50%</width>
  </action>
  <action name="MoveToEdgeEast"/>
</keybind>

Save the file and reload Openbox.

Now, this will allow windows to be thrown to the left and the right using Window Key + Left/Right, respectively, and will maximize them and then resize them to 50% of your screen width. In addition, if you have multiple monitors, this will allow you to cross boundaries to the next monitor. There are, however, two, minor flaws with this approach. Here are the flaws and their fixes. (Please make sure you don't bind the keys twice. Keybindings should be unique.)

First, there is no way to go back to the "regular" size of the window if it undocks from the edges. In Windows 7, if you are docked to the left and hit the "Windows + Right" key, you will return to the original window size in between docking it to the left. In the case of my solution, this will never happen. However, a default setting in rc.xml should already take care of this problem. If, at any time, you hit "Windows Key + Down," your window should undock and return to it's normal window size before it was maximized and resized to the right or left. I haven't looked into whether keybindings allow for conditional statements ("if maximized, then just unmaximize"), but it doesn't bother me so I'll leave that as an exercise to you.

Note, the following XML is what you should already have in your rc.xml to configure your unmaximize a window.

<keybind key="W-Down">
    <action name="Unmaximize" />
</keybind>

The second issue that you may run into is that if you have other window open in between the window that is currently being thrown to the right or the left of your screen, it will first dock itself against those other windows (meaning you have to hit right or left more times to get it to the edge of your screen). This, by default, is a feature that is turned on in Openbox which is snap-to-windows. I will admit to not having figured out a fix for this, but, in all honesty, it's never really bothered me.

That's about it. Let me know if you have any suggestions for improving upon what I've done and I will happily update this post to reflect those changes.

Sunday, May 20, 2012

Multiple Commands in Openbox Menu

For those of you who love using a very light window manager (either because you are running on very old hardware, or, like me, you just like things lean and mean), Openbox is an excellent choice. It has a ton of configuration options and is extremely lightweight.

Almost all of Openbox's configuration happens in to XML-based files - rc.xml and menu.xml. menu.xml is for configuring the lightweight, Openbox menu (which you get to by right clicking on the background within Openbox). rc.xml is pretty much there for configuring everything else within Openbox (keyboard commands, number of desktops, etc).

While these files are very easy to configure - just fire up your favorite editor - it is not always intuitive of how to accomplish certain tasks. For example, I wanted to run two commands, one right after the other, with just a single menu selection. In case you are wondering the same thing, here is how you do that:

<item label="Suspend">
    <action name="Execute">
        <execute>sh -c 'xscreensaver-command --lock; sudo pm-suspend'</execute>
    </action>
</item>

Please note (as pointed out by reader, Jabril), you have to add the ampersand character after all the preceding commands so that they will run in parallel and allow the subsequent commands to run. Those of you familiar with the command line are accustomed to this idea. (Thanks for the catch, Jabril!)

Friday, January 20, 2012

Using the Url.Action Helper with JavaScript Variables

Here's a quick little tip. If you are using the ASP.NET Url.Action Helper, but trying to pass a JavaScript variable into it, you need to do a little bit of magic in order to get it to work.

Here is what you might try to do originally:
function loadPageWithId(idValue) {
  $('#myDiv').load('@Url.Action("Action", "Controller", 
                     new { id = idValue })');
}

Unfortunately, this won't work because the variable, idValue, won't evaluate due to the escape sequence. The example below provides the workaround.
function loadPageWithId(idValue) {
  var link = '@Url.Action("Action", "Controller", new { id = "replace" })';
  link = link.replace("replace", idValue);
  $('#myDiv').load(link);
}

In this case, you actually replace the string "replace" with the value in the JavaScript variable which allows it to be evaluated.