Featured Post

Monday, November 20, 2017

Dapper - Object Relationship Mapper

Dapper is not a new concept. I implemented this in one of my recent project and I found it interesting so thought I should share with others also who are not using this.
In this article you will get basic explanation of how to use dapper in our projects.

The followings are some benefits of Dapper:
  •         Good performance.
  •          Directly bind database properties with c# objects.
  •          Less number of lines of code for same implementation.
  •          Support for store procedures and inline SQL queries
  •          Well managed connection object.

Example
First, we have to define connection.

using (IDbConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ConnectionString)
   {

   }

And in web config you define the connection string

  <add name="DBConnString" providerName="System.Data.SqlClient" connectionString="Data Source=anujpc/SQL2014;Initial Catalog=DapperDB;Integrated Security=True;MultipleActiveResultSets=True" />

Get List of objects
Write a select query for getting selected records from the database table

Here is the example object class:

public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
 public int RoleId { get;set }
    }

And below is the code for binding the database values with the above written object.

IEnumerable<User> userList = conn.Query<User>(@"
                    SELECT *
                    FROM User
                    WHERE RoleId = @RoleId",
new { RoleId = roleId });

For getting one record only we can use

User user = conn.Query<User>(@"
                    SELECT *
                    FROM User
                    WHERE Id = @Id",
new { Id = id }).FirstOrDefault();

Query is used for getting data from database. For insert and update we can use Execute method

User user = new User();
                user.Name = "Anuj";
                user.Address = "Chandigarh";
                user.RoleId = 1;
                const string query =
                  "INSERT INTO Users([Name],[Address],[RoleId]) " +
                  "VALUES (@Name, @Address,@RoleId)";
                int result = conn.Execute(query, user);

Here we passed user as parameters as the property and database columns name are same, it will map it itself.

For delete also we can use Execute method
const string query = "DELETE FROM User " +
                         "WHERE Id = @Id";
                return conn.Execute(query, new {Id = id });

So here I have covered basic CRUD operations using Dapper. The main purpose of this article is to introduce you all with Dapper classes and give you introduction for methods.

Thursday, June 22, 2017

Upwork 2017 Angular test questions

Q Which of the following is not a valid Angular expression?

Function Definition

Q The ng-change directive must be used with ng-model directive.

True

Q What is the output of the following code:

<div ng-app=”myApp” ng-controller=”myCtrl”>
<p ng-bind=”marks_obtained” ng-if=”(marks_obtained/total_marks)*100 >=40” > </p>
</div>
Var app = angular.module(‘myapp’,[]);
App.controller(‘myCtrl’, function($scope){
$scope.marks_obtained = “60”;
$scope. total_marks = “100”;
});

60

Q What is the output of the following code:

$scope.x = 20;
{{ x | number:2}}

20.00

Q Which module is required for routing?

angular-route.js

Q Which of the following is the correct syntax for using the $q.all method?

«`
$q.all([promise1(),promise2]]).then((values) => {

});
«

Q Convenience methods are provided for most of the common request types, including?

HEAD, PUT, JSONP

All methods are: get(), head(), post(), put() and delete()

Q What is the output of the following code?

$scope.firstName = «John»,
$scope.lastName = «Doe»
{{ firstName | uppercase }} {{ lastName }}

JOHN Doe

Q Which directive is allow us to use form?

NG-FORM

Q Which service is used to retrieve or submit data to the remote server?        

$http

Q Which of the following syntax is True of filter using HTML Template?

{{ filter_expression | filter : expression : comparator : anyPropertyKey}}

Q Which module is used for navigate to different pages without navigating the entire application?

ngRoute

Q Which of the following are methods in an instance of $q.defer() ?

Notify,Resolve, reject

Q The ng-model directive is used for __________.

Two-way data binding

Q  AngularJS applies some basic transformations on all requests and responses made through its $http service?

Note: There may be more than one right answer.

Requests transformations if the data property of the requested conifg object contains an object, serialize it into JSON format

Response transformations if an XSRF prefix is detected, strip it. If a JSON response is detected, deserialize it using a JOSN parser.

Q What can be injected as dependencies? (Choose all that apply)

Services

AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.
  • value
  • factory
  • service
  • provider
  • constant

Q A directive is a behavior which should be triggered when specific HTML constructors are encountered during the _________ process?

Compilation 

Q What is the output of the following code?

< div ng-app=»myApp» >
< h1>{{98 | myFormat}}< /h1>
< /div>
var app = angular.module(‘myApp’, []);
app.service(‘myAlter’, function() {
this.myFunc = function (x) {
return x+’%’;
}
});
app.filter(‘myFormat’,[‘myAlter’, function(myAlter) {
return function(x) {
return myAlter.myFunc(x);
};
}]);

98 %

Q When are the filters executed in the angular application?

When their inputs are changed

Q Dynamically loadable DOM template fragment, called a , through a ?

view, template

Q A promise is an interface that deals with objects that are __ or __ filled in at a future point in time (basically, asynchronous actions)?

returned, get

Q Custom directives are used in AngularJS to extend the functionality of HTML?

Extend

Q Explain $q service, deferred and promises, Select a correct answer?

• Promises are post processing logics which are executed after some operation/action is completed whereas ‘deferred’ is used to control how and when those promise logics will execute.
• We can think about promises as “WHAT” we want to fire after an operation is completed while deferred controls “WHEN” and “HOW” those promises will execute.
• “$q” is the angular service which provides promises and deferred functionality.
• All of the above

Q The Promise proposal dictates the following for asynchronous requests?

Note: There may be more than one right answer.

The Promise has a then function, which takes two arguments, a function to handle the “resolved” or “success” event, and a function to handle the “rejected” or the “failure” event

Q How to use AngularJS promises, read the example code?

 controller(‘MyCtrl’, function($scope, $q) {
function longOperation() {
var q = $q.defer();
somethingLong(function() {
q.resolve();
});
return q.promise;
}
longOperation().then(function() {
});
})

Q What is ng-hide directive used for?

Hide a given control

Q  Which of the following is a valid http get request in AngularJS?

 $http({
url : «someUrl»
}).then(function succesFunction(response) {
$scope.content = response.data;
}, function errorFunction(response) {
$scope.content = response.statusText;
});

Q Which of the following directive bootstraps AngularJS framework?

ng-bootstrap or ng-app

Q  AngularJS supports inbuilt internationalization following types of filters?

Note: There may be more than one right answer.

numbers
date
currency


Q Which of the following is validation css class in AngularJS?

All of the above.

Q Which of the following service is used to handle uncaught exceptions in AngularJS?

$exceptionHandler

Q Out of the following which statement is equivalent to
< p ng-bind=»foo «>< /p >

<p>{{foo}}</p>

Q Which of the following module is required for routing?

angular-route.js

Q Which of the following is not a type of an Angular service?

Controller

Q Which of the following is not valid feature for Angular templates?

Routes

Q Which Angular service simulate the ‘console’ object methods from Javascript?

Log

Q What is Angular Expression, How do you differentiate between Angular expressions and JavaScript expressions?

All of the above

Q  Which of the following is true about lowercase filter?

 Lowercase filter converts a text to lower case text.

Q Which of the following is Angular E2E testing tool?

Protractor

Q What is the output of the following code:

$scope.data = [1, 2, 3, 4, 5];
< span ng-repeat=»item in data» ng-if=»item > 5 && item < 10 «>{{ item }}< /span >

Nothing is output

Q  What can be following validate data in AngularJS?

$dirty − states that value has been changed.
$invalid − states that value entered is invalid.
$error − states the exact error.
All of the above

Q  AngularJS service can be created,registered,created in following different ways?
Note: There may be more than one right answer.

the factory() method
the value() method
the service() method

Q ng-bind directive binds ___.

 Model to HTML element.

Q What is the output of the following code?

< body ng-app=»myApp» >
< !— directive: my-directive — >
< /body>
var app = angular.module(«myApp», []);
app.directive(«myDirective», function() {
return {
replace : true,
template : «<h1>I got printed</h1>»
};
});


<h1 my-directive=»»>I got printed</h1>

Q What kind of filters are supported the inbuilt internationalization in AngularJS?

Currency, date and numbers

Q How can AngularJS promise be used for some objects? (Choose all that apply)

function getCurrentCall() {
  var deferred = $q.defer();

  if (!$scope.currentCall) {
    $scope.currentCall = 'foo';
  }

  deferred.resolve();
  return deferred.promise;
}

$scope.turnOffLocalAudio = function() {
  getCurrentCall().then(function() {
 
    if ($scope.currentCall.chat) {
      $scope.currentCall.chat.offLocalAudio(false);
    }
  }, function() {
    // unable to get CurrentCall
  });
};

Q Which statement is true regarding templates in AngularJS?

In Angular, templates are written with HTML that contains Angular-specific elements and attributes. Angular combines the template with information from the model and controller to render the dynamic view that a user sees in the browser. In other words, if your HTML page is having some Angular specific elements/attributes it becomes a template in AngularJS.

Q How can a controller be defined assuming app is the variable for Angular application?

App.controller(‘myCtrl’, function($scope){----});

Q Pick the correct statement in connection to the ng-include directive?

It is used to embed HTML from an external file

Q Select a true statement regarding the rootrouter concept

The top level Router that interacts with the current URL location

Q data binding in angularjs is the synchronization between the and the?

Model, view

Q explain directives in angularjs and choose the correct statement?

At a high level, directives are markers on a DOM element (such as an attribute, element name, or CSS class).These can be used to create custom HTML tags that serve as new, custom widgets. AnglarJs has bulid-in directives

Q AngularJS filters ___________.

Format the data without changing original data

Q which of the following custom filters will uppercase every third symbol in a string?

«`
app.filter(‘myFormat’, function() {
return function(x) {
var i, c, txt = «»;
for (i = 0; i < x.length; i++) {
c = x[i];
if (i % 3 == 0) {
c = c.toUpperCase();
}
txt += c;
}
return txt;
};
});
«`

Q What is the output of the following code?

< body ng-app=»myApp» >
< !— directive: my-directive — >
< /body>
var app = angular.module(«myApp», []);
app.directive(«myDirective», function() {
return {
replace : true,
template : «<h1>I got printed</h1>»
};
});

<h1 my-directive=»»>I got printed</h1>

Q  What is the difference beetween watchGroup and watchCollection methods?

The `watchCollection` deeply watch the single object properties, while `watchGroup` watch a group of expressions.

Q Which of the following correctly sets a height to 100px for an element?

angular.element(‘#element’).style.height = ‘100px’;

Q How AngularJS expressions are different from the JavaScript expressions?

Angular expressions can be added inside the HTML templates.
Angular expressions doesn’t support control flow statements (conditionals, loops, or exceptions).
Angular expressions support filters to format data before displaying it.
All of the above

Q Which of the following service components in Angular used to create XMLHttpRequest objects?
Note: There may be more than one right answer.

jsonpCallbacks
httpParamSerializer
httpParamSerializerJQLike

http
httpBackend
xhrFactory

Q Using the following Custom AJAX property within AngularJs Service?

myApp.factory(‘GetBalance’, [‘$resource’, function ($resource) {
return $resource(‘/Service/GetBalance’, {}, {
query: { method: ‘GET’, params: {}, headers: { ‘beforeSend’: » } }, isArray: true,
});
}]);

myApp.factory(‘GetBalance’, [‘$resource’, function ($resource) {
return $resource(‘/Service/GetBalance’, {}, {
query: { method: ‘GET’, params: {}, }, isArray: true,
});
}]);

$.ajax({
type: «GET/POST»,
url: ‘http://somewhere.net/’,
data: data,
beforeSend: »,
}).done().fail();

All of the above

Q What are the filters in AngularJS, Choose the right answer?


Filters select a subset of items from an array and return a new array. Filters are used to show filtered items from a list of items based on defined criteria.

Q What is $rootScope, Choose a True statement?

Scope is a special JavaScript object which plays the role of joining controller with the views. Scope contains the model data. In controllers, model data is accessed via $scope object. $rootScope is the parent of all of the scope variables.

Q Which of the following is the correct syntax for using filters?


• «`
<ul>
<li ng-repeat=»user in users | orderBy:’country’»>
{{ user.name + ‘, ‘ user.country}}
</li>
</ul>
«`

Q The ng-model directive is used for ____.


Two-way data binding.

Q What is $rootScope, Choose a True statement?

Scope is a special JavaScript object which plays the role of joining controller with the views. Scope contains the model data. In controllers, model data is accessed via $scope object. $rootScope is the parent of all of the scope variables.

Q AngularJS directives can be written in HTML element as:

All of the above.

Q Which of the following statement is True about provider?


All of the above

Q How you can Get AngularJs Service from Plain Javascript using the following code?


angular.injector([‘ng’, ‘error-handling’, ‘module-that-owns-dialogService’ ]).get(«messagingService»).GetName();

Q Angular loads into the page, waits for the page to be fully loaded, and then looks for ng-app to define its ___ boundaries?


template

Q What is $scope?

It transfers data between a controller and view.

Q Which of the following service is used to retrieve or submit data to the remote server?

$http

Q Which of the following modules will help with routing in the Angular application?


ngRoute

Q What are the services in AngularJS?

Services are singleton objects which are instantiated only once in app an are used to do the defined task.

Q Which of the following methods make $scope dirty-checking?

`$watch, $watchCollection`

Q Which of the following code will clickCount incremented on button click and displayed?

<button ng-click=»clickCount = clickCount + 1″ >
Click me!
</button>
<span> count: {{clickCount}} </span>



Q Which of the following is valid route definition?


app.config(function($ routeProvider) { $routeProvider
.when(«/1», { templateUrl : «1.htm»
})
.when(«/2», { templateUrl : «2.htm»
})
.otherwise( {
templateUrl : «default.htm»
})
});


Q Which of the following is true about ng-model directive?


Both of the above.

Q How can you display the elements which contains given pattern of a collection?


<ul>
<li ng-repeat=»item in collection | filter:’pattern’ «>
{{ item }}
</li>
</ul>

Q What is the output of the following code:

< div ng-app=»myApp» ng-controller=»myCtrl» >
< p ng-bind=»marks_obtained» ng-if=»(marks_obtained/total_marks)*100 >= 40″ > </ p>
< /div>
var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
$scope.marks_obtained= «60»;
$scope.total_marks = «100»;
});


60

Q Which way to hold dependencies in Angular component is more viable ?


The component can have the dependency passed to it, where it is needed.

Q In which component is it right way to use the additional libraries? Such as jQuery and etc.

Controller

Q Which of the following is not a valid for Angular expressions?


Function definition

Q What is deep linking in AngularJS?

Deep linking allows you to encode the state of application in the URL so that it can be bookmarked.

Q How is it possible to emit some event?

`$emit()`

Q AngularJS supports i18n/L10n for the following filters out of the box?

date/time
number
currency

Q What is the output of the following code:

$scope.x = 20;
{{ x | number:2 }}


• 20.00

Q Which of the following syntax is True of filter using HTML Template?


{{ filter_expression | filter : expression : comparator : anyPropertyKey}}

Q Which of the following custom filters will uppercase every third symbol in a string?

• «`
app.filter(‘myFormat’, function() {
return function(x) {
var i, c, txt = «»;
for (i = 0; i < x.length; i++) {
c = x[i];
if (i % 3 == 0) {
c = c.toUpperCase();
}
txt += c;
}
return txt;
};
});
«`


Q Which of the following is the best way to create a shallow copy of an object in Angular?


angular.extend

Q Which directive is responsible for bootstrapping the AngularJS application?


• ng-app

Q Which of the following statements are true?

Expression cannot contain condition, loop or RegEx.
Expression cannot declare a function.
Expression cannot contain comma, void or return keyword.

All of the above.

Q For the given url http://mysite.com:8080/urlpath?q=1 what is the value of the expression below?
var host = $location.host();

 mysite.com

Q What is difference between ng-if and ng-show directives?


When using ng-show directive, the hidden elements are placed in DOM with property display: none. directive ng-if includes those elements in DOM, which are equal to the condition.


Q Which of the following directives changes CSS-style of DOM-element?
Note: There may be more than one right answer.


`ng-class`
`ng-style`


Q Data binding in AngularJS is the synchronization between the and the ?

model, view

Q Which of the following directive allows us to use form?


ng-form

Q How can using ngView directive?

To display the HTML templates or views in the specified routes.

Q What is the output for the following code?
’30’ + 35


3035

Q Which of the following statement True of templates in AngularJS?

In Angular, templates are written with HTML that contains Angular-specific elements and attributes. Angular combines the template with information from the model and controller to render the dynamic view that a user sees in the browser. In other words, if your HTML page is having some Angular specific elements/attributes it becomes a template in AngularJS.

Transfer data to and from the UI:Angular.js helps to eliminate almost all of the boiler plate like validating the form, displaying validation errors, returning to an internal model and so on which occurs due to flow of marshalling data.

Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state.

All of the above

Q How is it possible to pass parameters in $http get request?


in property params

Q What are the services in AngularJS?

Filters select a subset of items from an array and return a new array. Filters are used to show filtered items from a list of items based on defined criteria.

AngularJS come with several built-in services. For example $http service is used to make XMLHttpRequests (Ajax calls). Services are singleton objects which are instantiated only once in app.

Templates are the rendered view with information from the controller and model. These can be a single file (like index.html) or multiple views in one page using «partials».

All of the above

Q What type of the attribute directive data binding is used in code below?

var directive = function(){
return {
scope: {
myParam: ‘@’
}
}
}


Isolate scope one way string binding. Parent changes affect child, child changes doesn’t affect parent

Q Do I need to worry about security holes in AngularJS?
Note: There may be more than one right answer.

Like any other technology, AngularJS is not impervious to attack. Angular does, however, provide built-in protection from basic security holes including cross-site scripting and HTML injection attacks. AngularJS does round-trip escaping on all strings for you and even offers XSRF protection for server-side communication.

AngularJS was designed to be compatible with other security measures like Content Security Policy (CSP), HTTPS (SSL/TLS) and server-side authentication and authorization that greatly reduce the possible attack vectors and we highly recommended their use.

Transfer data to and from the UI:Angular.js helps to eliminate almost all of the boiler plate like validating the form, displaying validation errors, returning to an internal model and so on which occurs due to flow of marshalling data.

All of the above

Q AngularJS has default headers which it applies to all outgoing requests, which include the following?
Note: There may be more than one right answer.


Accept: application/json, text/plain,

Q What makes angular.js better and does?

Registering Callbacks:There is no need to register callbacks . This makes your code simple and easy to debug.

Control HTML DOM programmatically:All the application that are created using Angular never have to manipulate the DOM although it can be done if it is required.

Transfer data to and from the UI:Angular.js helps to eliminate almost all of the boiler plate like validating the form, displaying validation errors, returning to an internal model and so on which occurs due to flow of marshalling data.

No initilization code: With angular.js you can bootstrap your app easily using services, which auto-injected into your application in Guice like dependency injection style.

All of the above

Q What {{::value}} is mean?

The output value

Q How to use and register decorators in AngularJS?
Note: There may be more than one right answer.


$provide.decorator

Q Which method of $routeProvider redirect to a specific page when no other route definition is matched?


otherwise()

Q Which of the following provider can be used to configure routes?

$routeProvider

Q How can you lowercase a given string named examplePattern?


{{ examplePattern | lowercase }}

Q If you want to observe the changes of full object $scope.myObj={one:1, two:2}, what way do you choose?


`$scope.$watch(‘myObj’, function(){ … }, true)`


Q Which of the followings are validation directives?

ng-required
ng-minlength
ng-pattern

All of the above.

Q What is service in AngularJS?

Service is a reusable JavaScript Function.

Q Call angularjs service from simple JS following code?

angular.module(‘main.app’, []).factory(‘MyService’, [‘$http’, function ($http) {
return new function () {
this.GetName = function () {
return «MyName»;
};
};
}]);
angular.injector([‘ng’, ‘main.app’]).get(«MyService»).GetName();


Q Which of the following is valid AngularJS application definition?


var myApp = angular.module(‘myApp’,[]);

Q Which of the following isValid AngularJS Expression?

{{ 2+2 }}

Q What is $rootScope?


$rootScope is single root object scope for the app. All other scopes are descendant scope of the root scope.

Q What kind of filters are supported the inbuilt internationalization in Angularjs?


Currency, date and numbers

Q You can invoke a directive by using following example?

<w3-test-directive></w3-test-directive>
<div w3-test-directive></div>
<div class=”w3-test-directive”></div>
<!– directive: w3-test-directive –>

Q config phase is the phase during which AngularJS bootstraps itself.

True

Q Which of the following is true about currency filter?


Currency filter is a function which takes text as input.