How to find out the ExtJs component behind a specific element on your html page

How to find out the ExtJs component behind a specific element on your html page

The Problem

While creating web pages using the ExtJs framework, we do not directly create the html markup. ExtJs is responsible for creating the markup based on the components we define.

But after everything is rendered and you are looking at a particular element on the page, it’s hard to tell which extjs component has rendered that markup. This becomes more apparent when we are dealing with a complex web application with dozens of components defined in different js files.

If we are looking at the html output and wondering which component needs to be modified to change the look of it, it’s not that easy.

The Solution

Here is an easy way to find that out. Browse to your webpage in Chrome. Then right click on the element in question, and click on “Inspect Element”.

Untitled_Clipping_060514_114502_PM

This will open up the Elements tab in the Chrome debugging Tool with that particular element markup highlighted.

Screenshot_060514_114712_PM

Now go to the console tab and type this command: Ext.getCmp($0.id). It will reveal the ExtJs component in the console.

Screenshot_060514_114900_PM

You can expand the object to see all it’s properties and easily identify it. Note that a typical component renders a bunch of html elements. This trick will not work if you are on a child level element. So if this command does not give you any result, click on the parent html element to highlight it on the elements tab. And run this command in the console again. You might have to keep traversing the markup this way a few times as most component render a deeply nested markup.

How it works

$0 is a chrome trick to get the javascript object for a given html element. When you do $0.id, that reveals the id of the element. Now, ExtJs provides a way to select an element by it’s markup id: Ext.getCmp(‘idofelement’);

So running Ext.getCmp($0.id) means select the ext component whose id is the same as the id of the selected html element.

So there you go. Using this trick you no longer have to second guess where your markup is coming from. Hopefully, this will save you a bunch of time like it does for me. Happy debugging!!

 

Javascript: Add more functionality to an existing method of a javascript object

Let’s say we have a class with an existing method.

var MyClass = function() { };

MyClass.prototype = { myMethod: function(parameter1) { console.log(‘called from original method ‘ + parameter1); }}

We can create an instance of the class and call it’s method like this:

var obj = new MyClass();

obj.myMethod(‘p’);

>called from original method p

Now, suppose that for this instance obj, we want to modify the definition of myMethod in such a way that some additional code is executed. But at the same time, we don’t want to lose the original code. In the end, we want that code to be executed as well.

We can achieve this by first storing the original method definition in a variable before modifying the method. Then in the modified method, we can call the original code as well by referring to this variable.

var origFunction = obj.myMethod;

obj.myMethod = function() { console.log(‘called from the modified function’); if(origFunction){origFunction.apply(this, arguments); }}

Now, when we execute myMethod, we get the following output:

obj.myMethod(‘p’);

> called from the modified function

> called from original method p

Note: This was about modifying the object instance. Not the original class. The original class is still intact as you can verify below:

var obj1 = new MyClass();

obj1.myMethod(‘p’);

> called from original method p

Is advanced payment from customer enough for idea validation

When it comes to customer validation, the idea of getting them to pay in advance is mostly touted as the best strategy. Some recommend putting out a landing page with a fake buy or sign up link. But if we actually talk the customer into making an upfront payment even before the product is ready, that speaks volume on how much the product is solving their pain point(s).

While I do not disagree with this, and will possibly try to do the same thing too when validating my business idea, I also wanna know if this is the best we can do. What more can I possibly do? It’s an important question to ask before we go down the route of investing our time and money building something.

I had the privilege of attending a info session at Flashpoint out here in Atlanta. Flashpoint is a well known management and education program here, that works closely with founders to create companies. Merrick who happens to be the biggest pillar at Flashpoint shared some interesting perspectives at this session.

He definitely doesn’t believe getting upfront payments is a guarantee your product will be successful.

Having helped start many startup companies, he makes his student founders go through a rigorous process of customer discovery and validation which is pretty intensive. He didn’t go through the full details of the program in the info session. But the basic idea is in trying to understand what is the thing that the customer cannot do without.

Quoting his exact words: “You can rely on people to do what they cannot not do. If they can avoid it, they would. The opposite of this double negative is not true. Customers are immune to Change.”

So if they can avoid a product that will force them to change, they will avoid using it. So next time we build a product, let’s build something so compelling that the customer is compelled to make the change in their business to use it. Let’s build something so good, he does not have a choice!

Adding Authorization to OData Web Api Service using Visual Studio 2013 Provided Templates

In previous posts I have show how we can easily expose a database table on the web using OData capabilities, by creating a OData Web Api Service. In this post I am going to demonstrate an easy way to make this service secure so that only properly authenticated users can access it.

If you have noticed the new features in Visual Studio 2013, they have done a lot to make Authentication and Authorization a snap. There are built in features to Register and LogIn users through site specific account as well as through a Google, Facebook or Microsoft Account.

I wanted to be able to reuse all this functionality in my OData Service Stack so that I can easily secure my service without reinventing the wheel again. Turns out, it wasn’t too difficult.

The Microsoft implementation of service stack for authentication is not through OData. So I decided to just add the built in authentication side by side to my OData Controllers.

The steps to create a Web Api with Authentication are pretty simple.

It actually gives a dialog window with four different options for Authentication. I chose the Individual Account one which is sufficient for my purpose. Go here to learn more on how to add authentication as well as what the four different options mean.

authentication_options

After that, all I had to do to my OData Controller was put an Authorize attribute on top of it’s class definition. Now this attribute takes care of returning a 401 Unauthorized message if the user tries to access it’s methods without first authenticating himself.
adding_authorize_attribute

One more step that I decided to do was to move around the authentication related tables. When Visual Studio creates the Authentication tables and service layer, the tables are created in an mdf file in the App_Data folder by default. I grabbed the schema of those tables and recreated them in my SQL Server database where the rest of my tables resided. This ensured that all my tables are in one place.

Here is a 15 minute video detailing all the steps I took to create a service stack with Authorization enabled and then test it using fiddler:

4 Amazing Chrome Hacks for Developers

In this age of rich and highly interactive web pages, cutting edge client side scripting skills are in high demand. All modern browsers provide a rich set of developer tools to aid us. I like Google Chrome the most. Here are some cool things that you can do with Chrome.

And first off, if you haven’t seen the chrome dev tools before, just hit F12 while your chrome browser is open and in focus and voilla!! You would be happily surprised to see all the information about the currently loaded page. Anyways, this blog is about some cool hacks for devs who are already using the tool, so let me jump right into it.

1. The Network tabs on Chrome shows the list of requests being sent to the server. We usually monitor errors or logged statuses on the console tab. But if you want to see the network requests here itself, just right click and select the first option “Log HttpXmlRequests”.

log http requests

2. Have you ever got lost trying to find a particular piece of code in the plethora of js files and resources that is loaded. Next time you need to do this, just go to the Chrome Console. Do Ctrl+Shift+F and a search in all files dialog will appear. Put in the search term and hit enter to get the list of matching results across all files. Clicking on them will take you to the specific file.

3. Do you have to read returned json data in the browser window. Have you struggled navigating through the json string. Install this Chrome extension to have the json data presented to you in a nice format: https://chrome.google.com/webstore/detail/json-prettifier/kccpfgilgmgbipamhohknpokhibinhhj

4. A lot of times we change our js files and reload browser to test the change. You need to make sure that the browser does download the latest file. To avoid caching of the files, press F12 in chrome to open the developer tools. Then go to the Network tab, then click on the settings icon on the bottom right. Check the first checkbox (Disable cache (while DevTools is open). Then whenever we access the site, make sure dev tools is open. The load times for each page might increase but you can be certain you are debugging with the latest versions of the file.

disable cache

What are some of the Chrome Dev Tool Features that you like? Please share it in the comments…

Understanding Context in Javascript

The ‘this’ keyword (also referred to as the context) in a javascript function is used heavily to access properties and methods that are defined within the same object.

Code:
function myObject(){
this.property1 = “Something”;
this.alertProperty1 = function(){
alert(this.property1);
}
};

In the above code alertProperty1 function uses the this keyword to get the value of property1 which is defined in the same context.

Now let’s execute this code.

var obj1 = new myObject();
obj1.alertProperty1();

As you would guess, the call obj1.alertProperty1() alerts the text “Something” since property1 value within obj1 is “Something”

Now here comes the tricky part. There are ways to call alertProperty1 in which the context might not be the context of obj1.

One example is when you are calling the function asynchronously. In the below code, we are using setTimeout to call this function after 5 seconds. Interestingly, the alert window shows undefined instead of “Something”.

That’s because setTimeout sets up a new asynchronous thread. When the function is called, the context is not of myObject anymore. It is now the window itself. Since window does not have a property by the name property1this.property1 gives us undefined.

window.setTimeout(obj1.alertProperty1, 5000);

How to fix this?
Thankfully there is a way to force the execution to be in the context of obj1 at all times. This can be done by passing the context explicitly when calling the function. Below is one way to do that. When you run this code, the alert value will be “Something”, as we are using the bind method to call the alertProperty1 while binding the context explicitly to obj1.

window.setTimeout(obj1.alertProperty1.bind(obj1), 10000);

See it in action here: http://jsfiddle.net/uqRzT/2/

Conclusion
A good understanding of how the this keyword or context works in javascript is important if you code regulary in javascript. Context related errors happen frequently and are sometimes hard to debug. Hopefully this article gave you a basic understanding of context and a quick tip on how to avoid such errors.

Creating Service Stack for my database using Entity Framework and OData

Taking the Database First approach, if you already have your database defined with all the tables in place, how soon can you provide the functionality to read and write to it over the web?

I just looked at the latest offerings from Microsoft and pretty impressed by how easy it is to do this using Entity Framework, OData and some code generation wizards.

This is a 15 min video of how I was able to create a service from scratch that would be ready to deploy over the web fulfilling all my basic requirements to access my database and run my CRUD (Create, Read, Update and Delete) operations.

The example is using .Net Framework version 4.5, Entity Framework 6.0 and the OData protocol. I used the Visual Studio 2013 as my development tool.

Create Entity Framework Mappings for tables using a wizard

It always feels exciting when you don’t have to do redundant work. I am currently looking at the best ways to create an ORM layer from an existing database without much overhead. Reading on Entity Framework, I like how easy it is to create the simple mapping classes for my tables.

These classes can then be used to fire CRUD (Create, Read, Update and Delete) operations on the tables. The detailed article on the approach I am demonstrating here is at this microsoft article: http://msdn.microsoft.com/en-us/library/vstudio/cc716703(v=vs.100).aspx but here is a quick 5 minute video demo on how to create the mappings from the database.

Here are the steps:
1. Open or create the project for which you want to create an .edmx file.

2. Right-click the project name in Solution Explorer, point to Add, and then click New Item.

3. Select ADO.NET Entity Data Model in the Templates pane.

4. Enter the name for the file (<project name>.edmx), and then click Add.
The first page of the Entity Data Model Wizard appears.

5. Select Generate from database in the Choose Model Contents dialog box, and then click Next.

6. Click the New Connection button.
The Connection Properties dialog box appears.

7. Enter the server name, select the authentication method, and enter the name of the database for which the model is being created. Click OK.
The Choose Your Data Connections dialog box is updated with the database connection settings.

8. Click Next to continue.
The Choose Your Database Objects dialog box appears. By default, no objects in the database are selected for inclusion in the .edmx file.

9. Expand the nodes for Tables, Views, and Stored Procedures. Cancel the selection of any tables, views, and stored procedures that you do not want included in the .edmx file.

10. Click Finish to create the .edmx file.

The Entity Data Model Wizard does the following:

* Adds references to the System.Data, System.Data.Entity, System.Core, System.Security, and System.Runtime.Serialization assemblies to the project, if they do not already exist.

* Generates an .edmx file that encapsulates the storage model, the conceptual model, and mappings.

* Creates a source code file that contains classes generated from the conceptual model. You can view the source code file by expanding the .edmx node in Solution Explorer.