Re-Learning Backbone.js – View Render

In this post we learn about different ways to render HTML using Backbone.js view and Underscore templates.

A Backbone view should include a render function. The render function should have the responsibility of manipulating the view’s el property. The el property is then used to update the DOM.

This post builds on the following posts:
Re-Learning Backbone.js – View Basics
Re-Learning Backbone.js – Templates (Underscore)
Re-Learning Backbone.js – Models
 

Here are a couple of quotes about Backbone.js Views:

“Backbone views are almost more convention than they are code — they don’t determine anything about your HTML or CSS for you, and can be used with any JavaScript templating library. The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page. Instead of digging into a JSON object, looking up an element in the DOM, and updating the HTML by hand, you can bind your view’s render function to the model’s “change” event — and now everywhere that model data is displayed in the UI, it is always immediately up to date.” http://backbonejs.org/#View

“At a technical level, a Backbone view is simply a JavaScript object that manages a specific DOM element and its descendants.” http://aaronhardy.com/javascript/javascript-architecture-backbone-js-views/

In this first example we are going to add some text to a DOM div element.



    
    
   	
	


    
Close Bitnami banner


Continue reading “Re-Learning Backbone.js – View Render”

Re-Learning Backbone.js – View Basics

There is probably more confusion with Backbone.js Views than with other features of Backbone. In this post I’m going to describe some basic features of Backbone Views. Also, In this post we will not be rendering any HTML, but I believe the concepts that you will learn will provide the bedrock for understanding Views better.

The end goal of a Backbone View is to represents an object in the DOM. Many times a view will be created that will manipulate an object that represents an element that is not originally assigned to the DOM. At some point the view object will be assigned to the DOM element and displayed.

A view usually builds up an element and adds it to the DOM. Here’s an example of what a view represents.

Title: Happy Gilmore; Rating: PG; Year: 2008

This element would be built by the Backbone view and then added to the DOM.

It’s important to understand that once a view is added to the DOM, the view is still aware of that element in the DOM and can manage that element. So if events occur on the DOM element, such as click or keyUp, the view can be notified of these changes and take action. Also if a view references a model and the model changes, the view can be automatically updated and in-turn the DOM element will be updated to reflect the changes in the model.

“At a technical level, a Backbone view is simply a JavaScript object that manages a specific DOM element and its descendants.” http://aaronhardy.com/javascript/javascript-architecture-backbone-js-views/

“How does Backbone relate to “traditional” MVC?
Different implementations of the Model-View-Controller pattern tend to disagree about the definition of a controller. If it helps any, in Backbone, the View class can also be thought of as a kind of controller, dispatching events that originate from the UI, with the HTML template serving as the true view. We call it a View because it represents a logical chunk of UI, responsible for the contents of a single DOM element.”
http://backbonejs.org/#FAQ-mvc

I don’t want to overwhelm you with a lot of content, so I’m going to take very small step to explain some core features of Backbone views. Even though it’s our end goal, in these examples we will not assign a view to a DOM element. Everything will be logged to the browser console.


        var MovieView1 = Backbone.View.extend({
            //model: the Model is usually passed in through the initializer
            //tagName: use default - "div"
            //className: is static, dynamic or passed in through initializer - is empty by default
            //el: is static, created based on tagName, or passed in through initializer
            //container: this is a custom property which can be static, dynamic, or passed in through initializer

            initialize: function () {
                console.log("MovieView initialize");
                console.log(this.model);
                console.log(this.tagName);
                console.log(this.className);
                console.log(this.el);
                console.log(this.$el);
            }
        });

        $(function(){
            var movieView1 = new MovieView1();        
        })

Continue reading “Re-Learning Backbone.js – View Basics”

Re-Learning Backbone.js – Templates (Underscore)

Even though templates are not part of Backbone.js, I believe it’s critical to have a basic understanding of templates. Templates are a core component that will be used with Backbone.js Views.

Templates will help us separate code from the HTML markup. When MVC is discussed in regards to server side (Ruby on Rails, ASP.NET MVC) the “V” is for view. Views are implemented different in Backbone than in most server side technologies. On the server side, views should be extremely dumb and very little logic if any should be include.

Backbone.js has a key object called View. The Backbone.js View does not resemble server side views. Backbone.js Views are not dumb and they do have logic. Some people have described Backbone.js Views as being more similar to Controllers on server side. I believe that templates on the client (JavaScript) side work more like the views on the server side. It’s definitely a mind shift when moving from a server MVC mindset to a client side MVC mindset. Hopefully this will make the transition easier.

I want to keep this as simple as possible. We will take very small steps to help you learn about templates. Only 2 JavaScript libraries will be needed, jQuery and Underscore. We will not be using the Backbone.js library. There are many options for templating, but we will use the built in option that Underscore provides. In case you didn’t know, Backbone.js has a dependency on Underscore. This is why we are using Underscore’s template engine, but other template engines can be substituted for the Underscore template engine.

Very, Very Simple Template



    
    
    


    
Close Bitnami banner

Continue reading “Re-Learning Backbone.js – Templates (Underscore)”

Re-Learning Backbone.js – Models

Over the past few days I’ve started to re-learn Backbone.js. It’s been a good while since I have worked with it. One of the many resource that I used during this endeavor is the post that I created January of this year. Understanding Backbone.js – Simple Example

Since I’m re-educating myself on Backbone.js, I thought this would be a good opportunity to Blog about the process I’m going through while re-learn Backbone.js again. In this post I will present the concept of Backbone.js Model.

So here I go again.

Based on past experience, I believe creating an application on Backbone.js there’s are few key concepts that should be understood: Model, View, Collection, Template and Router.

The first thing we are going to do is create a Movie class and instantiate an instance of the movie. Nothing fancy, this should be very simple. This Movie class will be based on a Backbone.js Model. JavaScript does not support classes, but here we will simulate a class.

Movie Sample 1


Movie Sample 1

    
    
   	
	


    Movie Sample 1

    
  
Close Bitnami banner

The code above is creating a Movie class from Backbone.Model.Extend. When an object is created from the Movie class the intialize function should be called and the message “Movie Model Created” should be written to the console.

If you load this page in a web browser, I’m using chrome, the results should be displayed in the console.

There is a problem here, everything is a global variable. Since we will be creating many Models, Views, Collections and templates, lets create a place to organize these structures.

var MovieApp = {
	Models: {},
	Collections: {},
	Views: {},
	Templates: {}
};

MovieApp.Models.Movie = Backbone.Model.extend({
	initialize: function () {
		console.log("Movie Model created");
	}
});

var movie = new MovieApp.Models.Movie();


Continue reading “Re-Learning Backbone.js – Models”

SQL Server Create Index – sys.dm_exec_requests Percent Completed

I had an observation today in regards to creating an index that you may find interesting.  Per SQL Server 2008 (not R2) documentation for sys.dm_exec_requests it mentions that percent_completed works for the following commands:

  • ALTER INDEX REORGANIZE
  • AUTO_SHRINK option with ALTER DATABASE
  • BACKUP DATABASE
  • CREATE INDEX
  • DBCC CHECKDB
  • DBCC CHECKFILEGROUP
  • DBCC CHECKTABLE
  • DBCC INDEXDEFRAG
  • DBCC SHRINKDATABASE
  • DBCC SHRINKFILE
  • KILL (Transact-SQL)
  • RESTORE DATABASE,
  • UPDATE STATISTICS.

sys.dm_exec_requests (Transact-SQL)
http://msdn.microsoft.com/en-us/library/ms177648(v=sql.100).aspx

I was creating an index and I wanted to know how much time was remaining until the index creation finished.

So I executed the following query. I constantly ran this query, but percent_complete never changed from 0.

SELECT percent_complete, estimated_completion_time, *
FROM
sys.dm_exec_requests AS r
WHERE
r.session_id <> @@SPID
AND r.session_id > 50

This seemed odd. Based on SQL Server documentation percent_completed should have been provided for Create Index.

Here’s an individual that talks about the discrepancies for sys.dm_exec_requests
Differences in documentation for sys.dm_exec_requests
http://sqlblog.com/blogs/aaron_bertrand/archive/2011/02/07/differences-in-documentation-for-sys-dm-exec-requests.aspx

SQL Server documentation for 2008 R2 and 2012 does not include Create Index for percent_complete.

The conclusion here is that for sys.dm_exec_requests, percent_complete is not provided for Create Index.  And I’m not sure if it ever was supported.

Other links
DOC : sys.dm_exec_requests topic is inconsistent between versions
http://connect.microsoft.com/SQLServer/feedback/details/641790/doc-sys-dm-exec-requests-topic-is-inconsistent-between-versions

SQL Server Objects In Memory VS Disk

For a few months I’ve been meaning to do an extensive post on a SQL Server query that would show the amount of each index/table in memory (Data Cache). I haven’t had the time to do this write-up, so I’m jut providing the query at this time. Hopefully in the future I will have time to describe this better.

The following query has been extremely beneficial at my work. It has help to identify indexes that should not be in memory and performance issues. This query doesn’t usually identify a root-cause, but it does seem to point you into the correct direction.

In the past there was a situation where a Cluster Index Scan was being used on a 20 GB table. This caused major performance problems for our system. The Cluster Index was loaded into memory (data cache) which forced other important data out of the data cache. By using this query to show indexes in memory, it was easy to identify the table that was being queried and inturn find the query that was causing the problem.

IF OBJECT_ID('tempdb..#PhysicalBufferSize') IS NOT NULL
BEGIN
PRINT 'DROP TABLE tempdb..#PhysicalBufferSize'
DROP TABLE #PhysicalBufferSize
END

SELECT
PhysicalSize.TableName
,PhysicalSize.IndexName
,PhysicalSize.Index_MB
,BufferSize.Buffer_MB
,CASE
WHEN Index_MB != 0 AND Buffer_MB != 0 THEN
CAST(Buffer_MB AS Float) / CAST(Index_MB AS Float)
ELSE 0
END IndexInBuffer_Percent
INTO #PhysicalBufferSize
FROM
(
--Index Disk Allocation per file
SELECT
OBJECT_NAME(i.OBJECT_ID) AS TableName,
i.name AS IndexName,
i.index_id AS IndexID,
SUM(a.used_pages) / 128 AS 'Index_MB'
FROM sys.indexes AS i
JOIN sys.partitions AS p ON
p.OBJECT_ID = i.OBJECT_ID
AND p.index_id = i.index_id
JOIN sys.allocation_units AS a ON
a.container_id = p.partition_id
WHERE
i.object_id > 100
GROUP BY i.OBJECT_ID,i.index_id,i.name
--ORDER BY 8 * SUM(a.used_pages) DESC--OBJECT_NAME(i.OBJECT_ID),i.index_id
) PhysicalSize

LEFT JOIN
(
--Index Memory Allocations per file
SELECT
obj.[name] TableName,
i.[name] IndexName,
obj.[index_id] IndexID,
i.[type_desc],
count_BIG(*)AS Buffered_Page_Count ,
count_BIG(*) /128 as Buffer_MB --8192 / (1024 * 1024)
FROM sys.dm_os_buffer_descriptors AS bd
INNER JOIN
(
SELECT object_name(object_id) AS name
,index_id ,allocation_unit_id, object_id
FROM sys.allocation_units AS au
INNER JOIN sys.partitions AS p ON
au.container_id = p.hobt_id
AND (au.type = 1 OR au.type = 3 OR au.type = 2)
) AS obj ON
bd.allocation_unit_id = obj.allocation_unit_id
LEFT JOIN sys.indexes i on
i.object_id = obj.object_id
AND i.index_id = obj.index_id
WHERE database_id = db_id()
GROUP BY obj.name, obj.index_id , i.[name],i.[type_desc]
--ORDER BY Buffered_Page_Count DESC
) BufferSize ON
PhysicalSize.TableName = BufferSize.TableName
AND PhysicalSize.IndexID = BufferSize.IndexID
ORDER BY Buffer_MB DESC

--*****************************************************************
-- Queries that work of Temp Table
--*****************************************************************
SELECT *
FROM #PhysicalBufferSize
ORDER By Buffer_MB DESC--TableName, IndexName DESC

SELECT TableName, SUM(Index_MB) Index_MB, SUM(Buffer_MB) Buffer_MB,
CASE
WHEN SUM(Index_MB) != 0 AND SUM(Buffer_MB) != 0 THEN
CAST(SUM(Buffer_MB) AS Float) / CAST(SUM(Index_MB) AS Float)
ELSE 0
END IndexInBuffer_Percent
FROM #PhysicalBufferSize
GROUP BY TableName
ORDER BY Buffer_MB DESC

SELECT SUM(Index_MB) Index_MB, SUM(Buffer_MB) Buffer_MB,
CASE
WHEN SUM(Index_MB) != 0 AND SUM(Buffer_MB) != 0 THEN
CAST(SUM(Buffer_MB) AS Float) / CAST(SUM(Index_MB) AS Float)
ELSE 0
END IndexInBuffer_Percent
FROM #PhysicalBufferSize

SELECT *
FROM #PhysicalBufferSize
ORDER By Index_MB DESC

The following grid shows an example output from AdventureWorks database. The grid identifes the size of the index on disk (Index MB) and the amount of the index in the Data Cache.

Table
Name
Index Name Index MB Buffer MB Percent
Person PK_Person_BusinessEntityID 29 29 1.00
SalesOrderDetail PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID 9 9 1.00
TransactionHistory PK_TransactionHistory_TransactionID 6 6 1.00
DatabaseLog NULL 6 6 1.00
WorkOrderRouting PK_WorkOrderRouting_WorkOrderID_ProductID_OperationSequence 5 5 1.00
SalesOrderHeader PK_SalesOrderHeader_SalesOrderID 5 5 1.00
WorkOrder PK_WorkOrder_WorkOrderID 4 4 1.00
TransactionHistoryArchive PK_TransactionHistoryArchive_TransactionID 5 4 0.80
Address PK_Address_AddressID 2 2 1.00
CreditCard PK_CreditCard_CreditCardID 1 1 1.00
EmailAddress PK_EmailAddress_BusinessEntityID_EmailAddressID 1 1 1.00
Password PK_Password_BusinessEntityID 1 1 1.00
PersonPhone PK_PersonPhone_BusinessEntityID_PhoneNumber_PhoneNumberTypeID 1 1 1.00
Address IX_Address_AddressLine1_AddressLine2_City_StateProvinceID_PostalCode 1 1 1.00
Shift AK_Shift_StartTime_EndTime 0 0 0.00

Resource:
SQLTEAM - What Data is in SQL Server's Memory?
MSDN - sys.dm_os_buffer_descriptors (Transact-SQL)
Glenn Berry - SQL Server Performance 1
Glenn Berry - SQL Server Performance 2

Understanding Backbone.js – Simple Example

I’m by no means an expert in Backbone.js.  I created this post because I had difficulty understanding backbone, and I hope that the information that I provide will help others grasp Backbone.js a little faster.  This post is directed to individuals who understand the concepts of Backbone.js, but are having a difficult time implementing a simple solution.

This post provides a simple example on Backbone.js Routers, Models and Collections and Views.  I’m going to try to make this example extremely simple. But also show key Backbone.js concepts

I’m probably not the best writer.  It would take me days, if I were to validate all the grammar, spelling and such.  So I’m just going to try to get it done.  Even though the grammar and such may not be perfect, the technical parts of the article should be correct.  I hope you enjoy.

A few months after writting this post, my priorites and technology direction changed. For probably 6 months I did little work with Backbone.js. When I came back to Backbone.js in November, I was a little lost. I had to become familar with the technology once again. I thought it would be a good opportunity to write about Backbone.js basics. Here are posts where I describe the basics of Backbone.js.

This post will be based on a contrived idea of displaying a list of movies at a theater.
Continue reading “Understanding Backbone.js – Simple Example”

Change Internet Explorer default editor for View Source

I’m currently running IE 8 on a windows 7 machine. When I select “View Source” from the browser, Notepad is open. In IE 8 this editor is lot better then in previous version.   But I like NotePad++ as my default editor. In previous versions of IE I had to edit the registry to make NotePad++ the default view. In IE 8 the registry changes do not seem to work. 

To enable NotePad++, or any editor, to be the default for View Source, you must open Developer Tools.  The Developer tools can be open by the F12 key or the Tools menu (see image blow).

image

Once you have Developer Tools open, select “File” –> “Customize Internet Explorer View Source”.  Here you can select the Default Viewer, Notepad or other.

image

If you select other, a dialog will be presented for you to select the application you want as the for View Source

image

Error when opening Visual Studio 2008 project in Visual Studio 2010

The error I receive when trying to open Visual Studio 2008 project/solution in Visual Studio 2010 is “cannot be opened because its project type (.csproj) is not supported by this version of the application.” and “To open it, please use a version that supports this type of project”

image

I found a few link to this issue but they all refer to opening a Visual Studio 2005 project in 2008.  Since I couldn’t find an answer pertaining to VS 2010, I decided to use the solutions that I found for 2008. 

All the solution I found mention running this command “devenv.exe /resetskippkgs”.  So I open the Command Prompt and navigated to “C:Program Files (x86)Microsoft Visual Studio 10.0Common7IDE” and ran “devenv.exe /resetskippkgs”.  This seem to fix the issue.  Visual Studio 2010 started and I receive the usual notification when opening a 2008 project in 2010.

image

I still have problems in all addition attempts to load 2008 project in Visual Studio 2010, I still need to go through this same process.

Resources

Default Enable Quick Edit for Windows Command Prompt (Console)

It seems that I’ve used Windows and the Command Prompt (Console) for ever and I never new of this feature.  Every time I wanted to copy or paste from the Command Prompt I had to right click and select “mark” or “paste” in the the window or click and bring up the menu.  It’s not that big of a deal, but saving 2 clicks or keystrokes adds up in 10 years.  I’ve must have wasted at least 30 minutes.   Here are my steps to set Quick Edit Mode as the default for the Command Prompt.

I know the following steps work for Windows XP and Windows 7.

The following screen show how to change the options for Command Prompt that is currently open.  When you close the Command Prompt this option is not saved, so the next time you open the Command Prompt this option will need to be reset.

image

The following image shows how to change the default configuration so that Quick Edit Mode is enabled by default.

image

Resources:
TechNet – QuickEdit –http://technet.microsoft.com/en-us/library/cc978582.aspx