Wednesday, 25 February 2015

Cordova Build Fails with Exit Code 2 and 8

When building or debugging an Android app using Apache Cordova and Visual Studio, if you encounter this kind of error below:
Could not create the Java Virtual Machine. C:\...\MyApp\EXEC 1 1 MyApp 
A fatal exception has occurred. Program will exit. C:\...\MyApp\EXEC 1 1 MyApp 
C:\...\MyApp\bld\Debug\platforms\android\cordova\build.bat: Command failed with exit code 2 C:\...\MyApp\EXEC 1 1 MyApp 
The command ""C:\Users\Me\AppData\Roaming\npm\node_modules\vs-mda\vs-cli" build --platform "Android" --configuration "Debug" --projectDir . --projectName "MyApp" --language "en-US" --buildServerUrl "" --buildTarget "AndroidDevice"" exited with code 8. C:\Users\Me\AppData\Roaming\npm\node_modules\vs-mda-targets\Microsoft.MDA.targets 99 5 MyApp
You can try to kill Android Debug Bridge process using task manager or command prompt. To do the first way, open Windows Task Manager (ctrl + shift + esc), find adb.exe and then right click and select 'End Process Tree'. Otherwise using command prompt, type adb kill-server and adb start server commands. For example, in my environment:
C:\Users\Me\AppData\Local\Android\android-sdk\platform-tools\adb kill-server
C:\Users\Me\AppData\Local\Android\android-sdk\platform-tools\adb start server
After that, try to build or debug again. If it is still not good then restart Visual Studio.

If you would like to try other ways before restarting Visual Studio, you can try these steps as well:
- close the emulator if you are using emulator
- clean the build files in Visual Studio using 'Clean Solution'
- if still there are files under 'My_App_Name\bld\Debug\platforms' folder then delete those manually
- then try to rebuild or start debugging again

Wednesday, 11 February 2015

Handling Exceptions in ASP.NET MVC Application

There are several ways to handle uncaught exceptions in ASP.NET MVC. We could use the default HandleErrorAttribute filter, extend the filter, create our own error filter, override OnException method in controller or use Application_Error method in global.asax.


Using Default MVC Error Handler
By default an MVC project applies HandleErrorAttribute filter globally in global.asax.
public static void RegisterGlobalFilters(GlobalFiltersCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}
It returns the default error view (Error.cshtml) created inside Views\Shared folder.

To have this error handler working, CustomErrors must be set to 'On' in web.config:
<customErrors mode="On">
</customErrors>


Using HandleErrorAttribute Filter in Controller or Action
If we only want to apply the HandleError filter in some controllers or actions, then we need to remove HandleErrorAttribute filter addition in RegisterGlobalFilters method in global.asax. Then apply the filter on specific controllers or actions only.

We can simply use this one:
[HandleError]
This will handle all possible errors it could catch and show the default error view (Error.cshtml) located inside Views\Shared folder.

Otherwise we can specify what type of error to be handled and what view to be displayed. For example:
[HandleError(ExceptionType=typeof(ArgumentException), View="ArgumentError")]
We can also stack these filters to handle different types of error on controllers or actions.

This filter only catches errors originated from inside controller actions and other filters applied to them. It also only handles HTTP 500 Internal Server error. The filter does not do much. After catching errors, it will only show the error page.

Apart from this filter, if we want to catch other than HTTP 500 error, we can set the customErrors in the config file for a particular view to be loaded when the error happens. This is commonly used for HTTP 404 Not Found error:
<customerrors mode="On">
 <error statuscode="404" redirect="~/Error/PageNotFound">
 </error>
</customerrors>


Extending HandleErrorAttribute Filter
By extending this filter, we can add more capabilities such as to log error and handle errors generated from AJAX requests. Below is an example:
public class ExtendedHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        // if exception is handled already
        if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
        {
            return;
        }

        // pass other HTTP exceptions to global application error handler
        if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
        {
            return;
        }

        if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
        {
            return;
        }

        // if the request is AJAX then return JsonResult else normal view
        if (filterContext.HttpContext.Request["X-Requested-With"] == "XMLHttpRequest" || ((filterContext.HttpContext.Request.Headers != null) && (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")))
        {
            filterContext.Result = new JsonResult
                    {
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                        Data = new
                        {
                            error = true,
                            message = filterContext.Exception.Message
                        }
                    };
        }
        else
        {
            base.OnException(filterContext);
        }

        // log the error
        //. . .

    }
}
In this example, we are just handling HTTP 500 error (Internal Server error) to comply with HTTP standards. Other errors will be passed to global application error handler (Application_Error() method). If you'd like to return a different view, please see that part of codes in the next example (creating custom error filter).


Creating Custom Error Filter
If extending HandleErrorAttribute above is not enough then we can create our own custom error filter. The filter class will inherit from FilterAttribute and IExceptionFilter.
public class CustomHandleErrorAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        // if exception is handled already
        if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
        {
            return;
        }

        // pass other HTTP exceptions to global application error handler
        if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
        {
            return;
        }

        /*if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
        {
            return;
        }*/

        // if the request is AJAX then return JsonResult else ViewResult
        if (filterContext.HttpContext.Request["X-Requested-With"] == "XMLHttpRequest" || ((filterContext.HttpContext.Request.Headers != null) && (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")))
        {
            filterContext.Result = new JsonResult
                        {
                            JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                            Data = new
                            {
                                error = true,
                                message = filterContext.Exception.Message
                            }
                        };
        }
        else
        {
            // if we want to pass detailed error info to the view
            var controllerName = (string)filterContext.RouteData.Values["controller"];
            var actionName = (string)filterContext.RouteData.Values["action"];
            var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

            filterContext.Result = new ViewResult
            {
                ViewName = "theViewName",
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData
            };
        }

        // log the error
        //. . .

        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = 500;

        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}
The example codes handle AJAX and normal requests, log error and return a particular view for a normal request.


Overriding OnException Method in Controller
Another way to handle error in ASP.NET MVC application is by overriding OnException method in controller. However, like the HandleErrorAttribute filter above, this method only catches errors that happen inside a controller. Other errors such as data binding or route errors will not be caught. We could also return a view by assigning a ViewResult to its ExceptionContext object's Result property. Below is an example:
protected override void OnException(ExceptionContext context)
{
    // pass other errors to global application error handler
    if (context.Exception is InvalidOperationException)
    {
        // do some error logging
        //. . .

        // if we want to pass detailed error info to the view
        var controllerName = (string)context.RouteData.Values["controller"];
        var actionName = (string)context.RouteData.Values["action"];
        var model = new HandleErrorInfo(context.Exception, controllerName, actionName);

        var result = new ViewResult
                {
                    ViewName = "theViewName",
                    ViewData = new ViewDataDictionary(model),
                    TempData = context.Controller.TempData
                };
        context.Result = result;

        // configure the response object
        context.ExceptionHandled = true;
        context.HttpContext.Response.Clear();
        context.HttpContext.Response.StatusCode = 500;
        context.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}


Using Application Global Error Handler
Lastly, we can also use Application_Error() method in global.asax. This method catches all unhandled errors and is the last resort before the yellow error screen. Many developers only use this method to handle all kind of errors in the application. In most of the cases, we will need to use this method only when we need customised error handling. We might need to implement the other error handlers mentioned above in addition to this method only when we want to handle errors (or some specific errors) for selected controllers or actions in the application.

Below is an example:
protected void Application_Error(object sender, EventArgs e)
{
    HttpContext httpContext = ((MyApplicationName)sender).Context;
    Exception exception = Server.GetLastError();

    if (httpContext.Request["X-Requested-With"] == "XMLHttpRequest" || ((httpContext.Request.Headers != null) && (httpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")))
    {
        // handle AJAX request

        httpContext.ClearError();
        Response.StatusCode = 500;
        Response.ContentType = "application/json";
        Response.StatusDescription = "my custom status description";    // => Response.StatusDescription maps to jqXHR or XMLHttpRequest.statusText

        // => Response.Write() maps to jqXHR or XMLHttpRequest.responseText  
#if DEBUG
        Response.Write(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new
        {
            errorMessage = exception.ToString()
        }));
        //Response.Write(exception.ToString());
#else
        Response.Write("an application error has occurred");
#endif
    }
    else
    {
        // non AJAX request

        IController errorController = new MyWebProject.Controllers.ErrorController();
#if DEBUG
        {
            // get information to be passed to view as model
            string currentController = string.Empty;
            string currentAction = string.Empty;
            RouteData currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
            if (currentRouteData != null)
            {
                if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
                {
                    currentController = currentRouteData.Values["controller"].ToString();
                }

                if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
                {
                    currentAction = currentRouteData.Values["action"].ToString();
                }
            }

            ((Controller)errorController).ViewData.Model = new HandleErrorInfo(exception, currentController, currentAction);
        }
#else
        {
            // only show a message
            ((Controller)errorController).ViewData.Model = "error message . . .";
        }
#endif

        string action = "Error";

        if (exception is HttpException)
        {
            // get the action for different error codes
            switch (((HttpException)exception).GetHttpCode())
            {
                case 404:
                    action = "NotFound";
                    break;

                // other errors
            }
        }

        httpContext.ClearError();
        httpContext.Response.Clear();
        httpContext.Response.StatusCode = exception is HttpException ? ((HttpException)exception).GetHttpCode() : 500;

        // avoid IIS7 getting involved
        httpContext.Response.TrySkipIisCustomErrors = true;

        // execute the error controller
        RouteData routeData = new RouteData();
        routeData.Values["controller"] = "Error";
        routeData.Values["action"] = action;
        //IController errorController = new NSWHealth.ICPBS.Web.Controllers.ErrorController(); // for readability only, this is already done above 
        //((Controller)errorController).ViewData.Model = new HandleErrorInfo(exception, currentController, currentAction); // for readability only, this is already done above
        errorController.Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
    }
}


An example of an error view:
@{
    ViewBag.Title = "Error";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Error</h2>
<div>
    @if (Html.IsDebug())
    {
        <div>
            <p>
                <b>Exception:</b> @Model.Exception.Message<br />
                <b>Controller:</b> @Model.ControllerName<br />
                <b>Action:</b> @Model.ActionName
            </p>
            <div style="overflow:scroll">
                <pre>
                @Model.Exception.StackTrace
                </pre>
            </div>
        </div>
    }
    else
    {
        <div style="min-height:460px">
            An error has occurred: @Model 
        </div>
    }
</div>


References and further reading:
Handling Errors Effectively in ASP.NET MVC
Exception Handling in ASP.NET MVC
Exception Handling in MVC

Friday, 6 February 2015

IsDebuggingEnabled, #if DEBUG, Conditional("DEBUG") and Debugger.IsAttached

HttpContext.IsDebuggingEnabled checks the <compilation debug="..."/> value inside <system.web> node in web.config.
if (HttpContext.Current.IsDebuggingEnabled)
{
    // if debug mode is enabled in web.config
    . . .
}

#if DEBUG or #if RELEASE checks for particular build configuration. Whether a build configuration uses DEBUG or RELEASE, this is defined in the project build properties (right click the project -> Properties -> Build tab).
The drawback with this is if there is a property or method declared outside being renamed (through refactoring) then the property or method called inside one of its if ... else ... conditions might not be renamed as well causing error when the build configuration is switched.
#if DEBUG
. . .
#else
. . .
#endif

The Conditional attribute helps to overcome this issue. An example:
[System.Diagnostics.Conditional("DEBUG")]
public void MyMethod()
{ 
   . . . 
}


System.Diagnostics.Debugger.IsAttached checks whether an active debugger is attached to the system.
if(System.Diagnostics.Debugger.IsAttached)
{
   . . . 
}

Tuesday, 13 January 2015

Using JavaScript Prototype for Object Oriented Approach


Prototype property
Every object in JavaScript has a prototype. This prototype can be seen by accessing __proto__ property in recent modern browsers except IE.
var n = 5;
console.log(n.__proto__);

var myObj = {};
console.log(myObj.__proto__);


Function prototype property
There is another similar term that is quite confusing in JavaScript world, it is the prototype property. This is not the real prototype property like the one above. However this is a property that is found in every function in JavaScript. I prefer to call this property; function prototype.
function Person(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.fullName = function () {
        return this.firstName + ' ' + this.lastName;
    }
}
console.log(Person.prototype);

// below will yield 'undefined' because it is not a function
var n = 5;
console.log(n.prototype);

// this will be false as a function prototype is not the same as its prototype property
Person.prototype == Person.__proto__;


Creating object with new keyword
When we initialise a new object with new keyword, the object's real prototype will point to the constructor function's function prototype property.
var john = new Person('john', 'king');

// john's prototype will point to Person's function prototype property
console.log(john.__proto__ == Person.prototype)  // true
The new object will have whatever defined inside the constructor function plus access to whatever in its prototype. So if we add more properties to the constructor function's function prototype, these will be accessible by the created objects. This will be explained more in details below.

A very important rule that need to be remembered from here is:
newObject.__proto__ = TheFunction.prototype


Prototypes chain
In JavaScript, when an object property is called, if it is not found within the object, JavaScript will try to traverse up it's prototypes chain to find it. If it already reaches the root but still cannot find the property, undefined will be returned.
var animal = { name: 'animal', eats: true };

var fish = { name: 'fish', swims: true };
// set fish prototype to animal
fish.__proto__ = animal;

var tuna = { name: 'tuna', canBeCanned: true };
// set tuna prototype to fish
tuna.__proto__ = fish;

console.log(tuna.swims);
console.log(tuna.eats);
Below is the structure created (on Firebug):

As we can see tuna's prototype is fish object and fish's prototype is animal object. The text in bold are properties that are available to the containing objects.


Adding a property to a prototype chain
When we have an established prototypes chain then if we added a new property to one of the prototype objects in the chain, this new property would be accessible by the lower objects in the chain.
// based on the example above we add a new property to animal
animal.moves = true;
console.log(tuna.moves) // lower objects in the chain can access it

// we can also add a new property through a prototype link
// this example below add a new property at animal's level because we have set fish.__proto__ = animal
fish.__proto__.breathes = true;
console.log(tuna.breathes)


Using these prototype behaviours for object oriented approach
Having knowledge of prototype behaviours described above, we can implement object oriented concept in our JavaScript codes. We will also need to use function prototype and new keyword to set up relationships as the __proto__ property is not available in some browsers. As an example, we could have something like this:
function Coder() {
    this.name = 'coder';
    this.code = function () {
        return "coding now";
    }
}

function JSCoder() {
    this.name = 'JSCoder';
    this.writeSomeJSCodes = function () {
        return "writing: this.__proto__ = . . .";
    }
}

// set up the relationship
JSCoder.prototype = new Coder();
// this is saying that every newly created JSCoder object will have its prototype property points to a Coder object

var jack = new JSCoder();
// because we have set above JSCoder.prototype = new Coder()
//  and because of the rule: newObject.__proto__ = TheFunction.prototype
//  then this one below is implemented implicitly when jack is created:
//  jack.__proto__ = JSCoder.prototype  which equals to a Coder object ( new Coder() )

console.log(jack.writeSomeJSCodes());
console.log(jack.code());

// we can also add a new property to a function prototype then it will be accessible by existing child object(s)
JSCoder.prototype.debugging = function () { return 'debugging some codes' };
// this is saying that because of the rule: newObject.__proto__ = TheFunction.prototype
//  when a new JSCoder object is created: var jack = new JSCoder()
//  then this will apply: jack.__proto__ = JSCoder.prototype
//  and JSCoder.prototype has been set to a Coder object ( new Coder() )
//  so when a new property is added,
//  JSCoder.prototype is a Coder object plus the new property
//  thus jack's prototype ( jack.__proto__ ) is a Coder object plus the new property

console.log(jack.debugging());

What will happen if we modify the function prototype to point to a new object? Existing objects will not be affected, however new objects created after the modification will have their prototypes point to the new object.
// modify JSCoder function prototype to point to a new object
JSCoder.prototype = { sing: function () { return 'singing' } };
console.log(jack); // existing objects' prototypes do not change

// however new objects' prototypes will point to the new object
var jim = new JSCoder();
console.log(jim);


References and further readings:
A Plain English Guide to JavaScript Prototypes
Understanding “Prototypes” in JavaScript
Understanding JavaScript Prototypes
Prototypal inheritance
OOP in JS, Part 2 : Inheritance

Monday, 5 January 2015

Implementing Asynchronous Tasks with $q in AngularJS

AngularJS has provided $q service that can be used to implement asynchronous tasks. It uses deferred objects and the promises they return to accomplish asynchronous runs.

A basic example of using $q:
function myAsyncFunc() {
  // create a deferred object
  var deferredObject = $q.defer();

  . . .

  // if for a reason, we want to cancel this task
  if (errorOccured) {
        deferredObject.reject('an error has occured');
        return deferredObject.promise;
  }

  // after the job is completed, call resolve()
  deferredObject.resolve();

  . . .

  // return the promise
  return deferredObject.promise;
}

// then on the caller
myAsyncFunc().then(
  // success (when resolve() was called)
  function() {
    alert('success')
  },
  // error (when reject() was called)
  function(reason) {
    alert('failed: ' + reason)
  }
)

We can also return an object when the task is completed. To do this, just pass the object as an argument to the resolve() function instead of nothing. Below is an example:
function myAsyncFunc() {
  var myObject = . . .
  deferredObject.resolve(myObject);
}

// then on the caller, we can use the passed object
myAsyncFunc().then(
  // success
  function(passedObj) {
    . . .
  }
);

When resolving a deferred object, we can use deep nesting functions if required. As long as the deferred object variable is accessible, this should not be an issue:
var deferredObject; // need to make sure that this deferred object variable will be accessible from inside nesting function

function myAsyncFunc() {
  // create a deferred object
  deferredObject = $q.defer();

  . . .

  nestedOne();

  // return the promise
  return deferredObject.promise;
}

function nestedOne() {
  nestedTwo();
}

function nestedTwo() {
  deferredObject.resolve();
}

Wednesday, 10 December 2014

Some Guidelines to Design Clean Controller and Service

An AngularJS controller should not be burdened with other tasks other than mediating interaction between view and data that comes from one or more services. The data model, data management and application business logic should be written in services. I also like to use controllerAs with 'this' approach. Also include as few services as possible in the controller. If a controller has too many services then this should be questioned. Instead we should try to use services that aggregate other required services inside.

Below is an example of a controller:
myApp.controller('MedicineCtrl', ['medicineService',
 function (medicineService) {
     var vm = this;
     vm.medicineNames = medicineService.medicineNames;
     vm.addMedicine = function (input) {
         medicineService.addMedicine(input);
     };
     vm.updateMedicine = function (input) {
         medicineService.updateMedicine(input);
     };
     vm.deleteMedicine = function (id) {
         medicineService.deleteMedicine(id);
     };
}]);
Of course, this is a simplified example however this should give us a picture of what a controller should be designed like.

For the service, it's recommended to have 'private' variables and functions needed and only expose publicly the ones that are necessary as service object's properties. Also whenever possible, try to design the functions to run asynchronously using AngularJS promise (will show an example in the next post). Below is an example of a service:
myApp.factory('medicineService', ['otherService1', 'otherService2', 
  function (otherService1, otherService2) {
    // 'private' variables and functions
    var _medicines = [];
    var _privateVarOne;
    var _privateVarTwo;
    
    _addMedicine = function (input) {
       . . .
       // some business logic
       . . .
    };

    _updateMedicine = function (input) {
       . . .
       // some business logic
       . . .
    };

    _deleteMedicine = function (id) {
       . . .
       // some business logic
       . . .
    };

    _anotherPrivateFunction = function () {
       . . .
       // some business logic
       . . .
    };

    // only expose publicly the required members
    return {
        medicineNames: _medicineNames,
        addMedicine: _addMedicine,
        updateMedicine: _updateMedicine,
        deleteMedicine : _deleteMedicine 
    }
}]);

Wednesday, 3 December 2014

AngularJS ControllerAs and Scope

If we set up a view and controller with controllerAs like below:
// in routing configuration
. . .
.when('/pageOne', {
        templateUrl: 'partials/page-one.html',
        controller: 'CtrlOne',
        controllerAs: 'vm'
})
. . .
// the controller
userApp.controller('CtrlOne', [function () {
    var vm = this;
    vm.nameOne = "test";
    vm.getName = function () {
        return 'aaa';
    };

    this.nameTwo = "blah";
    var nameThree = "ggg"; // not visible from outside
}]);
then we will have these scopes when the page loads:



The first scope is the root scope and the one underneath it is the scope created for the controller. As the picture shows, the variables are created as properties of 'vm' object. If we had used the traditional approach by defining variables on $scope such as $scope.myVariable = ... then these variables would be created on the first level on controller scope (not wrapped inside an object). We can also see when we use controllerAs, other variable that is defined directly not through 'this' object will not be visible from outside.


Adding a Child Controller

Let us add a child controller inside our controller. The child controller:
userApp.controller('ChildCtrl', [function () {
    var vm = this;
    vm.dataOne = 'sss';
    vm.getData = function () {
        return 'bbb';
    }
}]);
And change our view to be like this:
<div>
    Page One
    <div>
        <div>{{parentVm.nameOne}}</div>
        <div ng-controller="ChildCtrl as childVm">
            {{childVm.dataOne}}
            {{parentVm.nameOne}}
        </div>
    </div>
</div>

Now we can see that a new scope is created for the child controller:




Accessing Parent Controller's Variables

On the view, we can simply use '{{parentVm.variableName}}' to refer to a parent controller's variable.

In the child controller script function, accessing parent's variables which controller uses controllerAs is not as easy as if the parent controller had used $scope to register its properties. One way to do this is by using $scope help in the child controller. We need to inject $scope to the controller then refer to the parent controller's instance name to be able to access its variables/properties. Below is an example:
$scope.parentVm.nameOne = 'modify parent var';
//$scope.$parent.parentVm.nameOne = 'modify parent var';    // or could use $parent
The code on the first line is utilising JavaScript prototypal inheritance where it will try to find the property 'parentVm.nameOne' on the current scope then if it is not found, it will try to find on the parent scope and so on until it reaches the root scope. This AngularJS documentation 'Understanding Scope' explains it in more details.
The second code is finding the property on the parent scope. We could append many $parent if required.

If we had tried to do these below inside child controller:
vm.nameOne = 'modified';
$scope.nameOne = 'hhh';
new variables would be created on the current scope. One is on the scope's root level and the other one is inside an object. The picture below shows this:




Creating Local Variables that Hold References

If we want to create a local variable that holds reference to a variable in parent controller then we need to create that variable as an object in parent controller. This is explained as well in the referred AngularJS documentation above. For example:
// create an object variable in parent controller
vm.objVar = { name: 'aaa' };
then in our child controller:
// create the local variable in child controller
vm.childRefVar = $scope.$parent.parentVm.objVar;

// try to do some update
$scope.$parent.parentVm.objVar.name = 'jjj'; // when we update the variable in parent controller, this will reflect in both parent and local variables
vm.childRefVar.name = 'bbb'; // when we modify the local variable, this will reflect in parent variable as well


Best Practices

As we have seen above, accessing variables in parent controller is not straight forward. If you are going to have nested controllers in your view, it is recommended to use a service to share data between the controllers rather than using variables/properties in your controller.

If you do not want to use a service then I think it is better to register the variables or functions that are going to be shared on $scope rather than on 'this' object unless you are going to decide/know the controller's alias object name in advance to be used from codes inside child controller.