Popularni postovi

Tuesday, 15 July 2014

Entity Framework: Unable to load the specified metadata resource


After reading this answers article and this blog I changed:
  entity.Metadata = @"res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl";
To:
  entity.Metadata = "res://*/";
And it works :-)

Wednesday, 9 July 2014

Authentication with token and interceptor with AngularJS and WebAPI

Source: http://stackoverflow.com/questions/21255203/angularjs-clientside-routing-and-token-authentication-with-webapi

Interceptors: http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

Explanation with example project: http://www.codeproject.com/Articles/784106/AngularJS-Token-Authentication-using-ASP-NET-Web-A

Another good artcle about WebAPI and AngularJS: http://bitoftech.net/2013/12/03/enforce-https-asp-net-web-api-basic-authentication/

On WebAPI side you must add [RoutePrefix("api/Orders")] before ApiControler declaration and

[Authorize][Route("")] before function declaration, also you sould add code for check authentication:

ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
var userName = principal.Claims.Where(c => c.Type == "sub").Single().Value;

namespace AngularJSAuthentication.API.Controllers
{
    [RoutePrefix("api/Orders")]
    public class OrdersController : ApiController
    {
        [Authorize]
        [Route("")]
        public IHttpActionResult Get()
        {
            ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;

            var userName = principal.Claims.Where(c => c.Type == "sub").Single().Value;

            return Ok(Order.CreateOrders());
        }

    }
}



Interceptor is regular service (factory) which allow us to capture every XHR request and manipulate it before sending it to the back-end API or after receiving the response from the API. In our case, we are interested to capture each request before sending it so we can set the bearer token, as well we are interested in checking if the response from back-end API contains errors which means we need to check the error code returned so if its 401 then we redirect the user to the log-in page.
To do so, add new file named “authInterceptorService.js” under “services” folder and paste the code below:
'use strict';
app.factory('authInterceptorService', ['$q', '$location', 
'localStorageService', function ($q, $location, localStorageService) {

    var authInterceptorServiceFactory = {};

    var _request = function (config) {

        config.headers = config.headers || {};

        var authData = localStorageService.get('authorizationData');
        if (authData) {
            config.headers.Authorization = 'Bearer ' + authData.token;
        }

        return config;
    }

    var _responseError = function (rejection) {
        if (rejection.status === 401) {
            $location.path('/login');
        }
        return $q.reject(rejection);
    }

    authInterceptorServiceFactory.request = _request;
    authInterceptorServiceFactory.responseError = _responseError;

    return authInterceptorServiceFactory;
}]);
By looking at the code above, the method “_request” will be fired before $http sends the request to the back-end API, so this is the right place to read the token from local storage and set it into “Authorization” header with each request. Note that I’m checking if the local storage object is nothing so in this case this means the user is anonymous and there is no need to set the token with each XHR request.
Now the method “_responseError” will be hit after we receive a response from the back-end API and only if there is failure status returned. So we need to check the status code, in case it was 401 we’ll redirect the user to the log-in page where he’ll be able to authenticate again.
Now we need to push this inspector to the inspectors array, so open file "app.js" and add the below code snippet:
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('authInterceptorService');
});
By doing this, there is no need to setup extra code for setting up tokens or checking the status code, any AngularJS service executes XHR requests will use this interceptor. Note: This will work if you are using AngularJS service $httpor $resource.

Select/Dropdown/Combobox controls in angular

These days I tried a lot of select/Dropdown/Combobox controls in angular but on the end I realized that classic select2 (angular version) works best.
Here is link to ui-select2: https://github.com/angular-ui/ui-select2 
After you implenet it you will see that it doesn't look in bootstrap style so you should download aditional css for select2: http://fk.github.io/select2-bootstrap-css/index.html

in your code you need to add this files:

 <link href="content/css/select2/select2.css" rel="stylesheet" />
    <link href="content/css/select2/select2-bootstrap.css" rel="stylesheet" />


    <script src="scripts/select2.min.js"></script>
    <script src="scripts/select2.js"></script>



Here is example:

 <select class="select2-container form-control select2" ui-select2 ng-model="New.opcinaID" data-placeholder="Pick a number" ng-required="true">
                                    <option value=""></option>
                                    <option ng-repeat="kontakt in kontakti" value="{{kontakt.id}}">{{kontakt.naziv}}</option>
                                </select>

Monday, 7 July 2014

Search/Filter/Pagination with WebAPI and AngularJS

In Web API insert this:

  public IHttpActionResult GetKontakti(int page = 1,int itemsPerPage = 30, 
            string sortBy = "Naziv",bool reverse = false, string search = null)
        {
            String sort = sortBy + (reverse ? " descending" : "").ToString();

            var data = db.Kontakti.OrderBy(sort);
            
            // paging
            var usersPaged = data.Skip(((page - 1) * itemsPerPage)).Take(itemsPerPage);

            // json result
            var json = new
            {
                count = data.Count(),
                Kontakti = usersPaged
            };
            return Ok(json);
        }

Before this you need to add dependency:

 using System.Linq.Dynamic;   
This enables you to pass string in OrderBy function, otherwise you would have to write if for every column...


You can test this with url:
http://localhost:26264/api/kontakti?itemsPerPage=2&page=1&reverse=false&search=&sortBy=Naziv&totalItems=0

In JavaScript this code wil call this:



 function getKontakti() {
        kontaktiService.getkontakti(function (results) {

            $scope.kontakti = results.kontakti;
            $scope.pagingInfo.totalItems = results.count;
        }, $scope.pagingInfo)
    }   

  function inittable() {
            $scope.pagingInfo = {
                page: 1,
                itemsPerPage: 5,
                sortBy: 'Naziv',
                reverse: false,
                search: '',
                totalItems: 0
            };
         // You are watching here for sort event
            $scope.$on('ngGridEventSorted', function (event, sortInfo) {
                $scope.pagingInfo.sortBy = sortInfo.fields[0];
                if (sortInfo.directions[0] == 'asc') $scope.pagingInfo.reverse = false; else $scope.pagingInfo.reverse = true;
            });
            // Load data here because event sort runs MULTIPLE times
            $scope.$watch('pagingInfo', function () {
                loadData();
            }, true);

            $scope.search = function () {
                $scope.pagingInfo.page = 1;
                loadData();
            };
 
            $scope.sort = function (sortBy) {
                if (sortBy === $scope.pagingInfo.sortBy) {
                    $scope.pagingInfo.reverse = !$scope.pagingInfo.reverse;
                } else {
                    $scope.pagingInfo.sortBy = sortBy;
                    $scope.pagingInfo.reverse = false;
                }
                $scope.pagingInfo.page = 1;
                loadData();
            };
 
            $scope.selectPage = function (page) {
                $scope.pagingInfo.page = page;
                loadData();
            };
 
            function loadData() {
                
                getKontakti();
            }
 
            // initial table load
            loadData();
    }
    inittable();

Also you need this code to call in service part:

function getkontakti(callback, pagingInfo) {

            if (pagingInfo == undefined)
                $http.get(url).success(callback);
            else $http.get(url, { params: pagingInfo }).success(callback);
        }

HTML Data Table with pagination and sorting:

//ng-grid:
<div class="gridStyle" ng-grid="gridOptions"></div> 
//regular table:
<table class="table table-striped table-bordered table-hover table-condensed">
        <thead>
            <tr>
                <th><a href="" ng-click="sort('Naziv')">Naziv</a></th>
                <th><a href="" ng-click="sort('OpcinaID')">Opcina</a></th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="kontakt in kontakti">
                <td>{{kontakt.naziv}}</td>
                <td>{{kontakt.opcinaID}}</td>
            </tr>
        </tbody>
    </table>

    <pagination page="pagingInfo.page"
                total-items="pagingInfo.totalItems"
                items-per-page="pagingInfo.itemsPerPage"
                on-select-page="selectPage(page)"
                max-size="10"
                rotate="false"
                boundary-links="true"></pagination>

If you are using ng-grid you will have to add this to controller js file:


  $scope.gridOptions = {  
     data: 'kontakti',  
     showGroupPanel: true,  
     columnDefs: [{ field: 'id', displayName: 'Id', width: '20px' },  
           { field: 'naziv', displayName: 'Naziv:', width: '50px' },  
           { field: 'datumRodjenja', displayName: 'Datum rodjenja:', width: '130px' },  
           { field: 'email', displayName: 'Email:', width: '50px' },  
       { displayName: 'Options', cellTemplate: '<input type="button" ng-click="setScope(row.entity,\'edit\')" name="edit" value="Edit">&nbsp;<input type="button" ng-click="DeleteUser(row.entity.id)" name="delete" value="Delete">', width: '25%' }  
     ]  
   };  

Here is pagination in ng-grid way: http://plnkr.co/edit/50vJrs?p=preview

Saturday, 5 July 2014

Find AngularJS modules easily

Visit: http://ngmodules.org/
There are modules for everything...

If module is not working

Every external library you which you want to use in your AngularJS application you MUST declare it in angular.module like this:

var app = angular.module('AngularAuthApp', ['ngRoute', 'LocalStorageModule', 'angular-loading-bar', 'ngGrid', 'ui.bootstrap']);

If you are using UI Bootstrap you must add 'ui.bootstrap' here.
I loose hours trying to make things work and on the end I realize that I forget this....


$http request with custom params

Here is tutorial: http://pointblankdevelopment.com.au/blog/angularjs-aspnet-web-api-2-server-side-sorting-searching-and-paging

Suppose we wanted to fetch a user’s information from our server. If the API is available
at /api/user, and accepts the id as a URL parameter, then our XHR request using Angular’s
core $http service would look something like the following:


$http.get('api/user', {params: {id: '5'}

}).success(function(data, status, headers, config) {

// Do something successful.

}).error(function(data, status, headers, config) {

// Handle the error

});



If you are from the jQuery world, you should notice how similarly AngularJS and jQuery
interact with asynchronous requests.
The $http.get method we used in the preceding example is just one of the many convenience
methods that the core $http AngularJS service provides. Similarly, if you
wanted to make a POST request using AngularJS with the same URL parameters and
some POST data, you would do so as follows:


var postData = {text: 'long blob of text'};

// The next line gets appended to the URL as params

// so it would become a post request to /api/user?id=5

var config = {params: {id: '5'}};

$http.post('api/user', postData, config

).success(function(data, status, headers, config) {

// Do something successful

}).error(function(data, status, headers, config) {

// Handle the error

});




Configuring Your Request Further
At times, the standard request options provided out of the box are not enough. This
could be because you want to:
• Add some authorization headers for your request
• Change how caching is handled for the request
• Transform the request going out, or the response coming in, in certain set ways
In such cases, you can configure your request further through the optional configuration
object passed to the requests. In the prior example, we used the config object to specify
optional URL parameters. But even the GET and POST methods we showed there are
convenience methods. The barebones method call would look something like:
$http(config)

What follows is a basic pseudo-code template for calling this method:

$http({
method: string,
url: string,
params: object,
data: string or object,
headers: object,
transformRequest: function transform(data, headersGetter) or
an array of functions,
transformResponse: function transform(data, headersGetter) or
an array of functions,
cache: boolean or Cache object,
timeout: number,
withCredentials: boolean
});

Communicating Over $http | 103
The GET, POST, and other convenience methods set the method, so you don’t need to.
The config object gets passed in as the last argument to $http.get, $http.post, so you
can still use it while using any of the convenience methods.
You can change the request being made by passing the config object set with the following
keys:
method
A string representing the HTTP request type, like GET, or POST
url
A URL string representing the absolute or relative URL of the resource being requested
params
An object (a map to be precise) of string-to strings, representing keys and values
that will be translated to URL parameters. For example:
[{key1: 'value1', key2: 'value2'}]
would be converted to:
?key1=value1&key2=value2
after the URL. If we use an object, instead of a string or a number, for the value, the
object will be converted to a JSON string.
data
A string or an object that will be sent as the request message data
timeout
The time in milliseconds to wait before the request is treated as timed out
There are a few more options that can be configured, which we will explore in more
depth in the following sections.

Friday, 4 July 2014

jQuery UI datepicker with AngularJS in directive

I found that jQuery UI datepicker when putted in directive is better than Angular UI date picker because it requires less JavaScript code behind. Just add this once into some .js file and you can use it for all datepickers.


app.directive('datepicker', function() {
    return {
        restrict: 'A',
        require : 'ngModel',
        link : function (scope, element, attrs, ngModelCtrl) {
            $(function(){
                element.datepicker({
                    dateFormat:'dd/mm/yy',
                    onSelect:function (date) {
                        scope.$apply(function () {
                            ngModelCtrl.$setViewValue(date);
                        });
                    }
                });
            });
        }
    }
});


After that just add "datepicker" attribute and it will work :)
<input datepicker="" id="Date" name="Date" type="textbox" />


Don’t forget to include the scripts in order:
1 – Jquery
2 – Jquery-ui
3 – angularjs.
Otherwise Angular will use JQlite intead of JQuery and the directive will break.

  http://www.abequar.net/posts/jquery-ui-datepicker-with-angularjs

Wednesday, 2 July 2014

JavaScript Tips



Function tips
  • Declare local variables at the top of the body of your function.
  • ƒƒIf you forget to declare a local variable using var, that variable will be global, which could have unintended consequences in your program.
  • A function can optionally return a value using the return statement.
  • Variables are either in the global scope (visible everywhere in your program) or in the local scope (visible only in the function where they are declared). 
  • If variable in function is the same name as global variable, function variable will be active in that function.
  • There are two ways to define a function: with a function declaration and with a function expression.
  • A function reference is a value that refers to a function.
  • Function declarations are handled before your code is evaluated. Declaration example: function play(sequence) {// code here}
  • Function expressions are evaluated at runtime with the rest of your code. Those functions you can use as variable, pass like parameter etc... Declaration example:  var pause = function() {//code here}
  • Closure example: function makeCounter() { var count = 0; function counter() {count = count + 1; return count;return counter; } - Function makeCounter returns as result subfunction counter and counter function uses count variable from makeCounter function, and that variable is not accesable by others. Calling counter, variable count will be rised by one.
    var doCount = makeCounter(); console.log(doCount()); console.log(doCount()); 
    This code will display: 1 2 3 
Array tips
  • A sparse array is just an array that has values at only a few indices and no values in between. You can create a sparse array easily, like this: var sparseArray = [ ]; sparseArray[0] = true; spraseArray[100] = true; In this example, the sparseArray has only two values, both true, at indices 0 and 100.The values at all the other indices are undefined. The length of the array is 101 even though there are only two values.
  • You can access any item using its index.For example, use myArray[1] to access item one (the second item in the array).
  • Assigning a value to an existing item will change its value. Assigning a value to an item that doesn’t exist in the array will create a new item in the array.
  • You can use a value of any type for an array item. 
  • Not all the values in an array need to be the same type.
  • You can create an empty array with var myArray = [ ];
  • You can add a new value to an array using push.
Objects tips

  • Object without any properties ca be created: var lookNoProps = { }; because they can be added dynamicly! Example: var lookMaNoProps = { }; lookMaNoProps.age = 10;
  • Variables don’t actually hold objects. 
  • Instead they hold a reference to an object.
  • Any changes you make to the object inside a function will still be there when the function 
  • completes.
  • Use this with dot in child functinos in objects to tell JavaScript that you mean the property of THIS object.
  • In child functions od objects and functions, this is referencing on parent object or function, but in parent(which is not child of any) function this is refferening on GLOBAL scope!!!
  • Fuctions in objects are colled methods.
  • You can also delete properties from objects dynamicly, using the delete operator.
  • To know if an object was createdby a specific constructor, use the instanceof operator.
  • Use the new operator with a constructor function call to create an object.
  • Use this in a constructor function to access the object being constructed and add properties to the object.



Tuesday, 1 July 2014

Default values in JavaScript


The||operator can be used to fill in default values:
var middle = stooge["middle-name"] || "(none)";
var status = flight.status || "unknown";

Why JavaScript?

JavaScript is an important language because it is the language of the web browser. Its association with the browser makes it one of the most popular programming languages in the world. At the same time, it is one of the most despised programming languages in the world. The API of the browser, the Document Object Model (DOM) is quite awful, and JavaScript is unfairly blamed. The DOM would be painful to work with in any language. The DOM is poorly specified and inconsistently implemented. This book touches only very lightly on the DOM. I think writing a Good Parts book about the DOM would be extremely challenging. JavaScript is most despised because it isn't SOME OTHER LANGUAGE. If you are good in SOME OTHER LANGUAGE and you have to program in an environment that only supports JavaScript, then you are forced to use JavaScript, and that is annoying. Most people in that situation don't even bother to learn JavaScript first, and then they are surprised when JavaScript turns out to have significant differences from the SOME OTHER LANGUAGE they would rather be using, and that those differences matter. The amazing thing about JavaScript is that it is possible to get work done with it without knowing much about the language, or even knowing much about programming. It is a language with enormous expressive power. It is even better when you know what you're doing. Programming is difficult business. It should never be undertaken in ignorance.

Cited from "The Good Parts"(2008) book written by Douglas Crockford 

Using functions in JavaScript

Using functions in JavaScript is not same as in C++,C#, Java..., for example:
If function make_person_object don't have return statement:

var Joe = make_person_object("Joe", "Smith", 23);
console.log(Joe); //RETURN undefined
console.log(window.firstname) //  "Joe" (oops) without the new operator it will define your this attributes on the current this object (generally window if you are operating in the browser.)

You MUST use "new" and then you will get your class:

var John = new make_person_object("John", "Smith", 45);
console.log(John); // {firstname: "John", lastname: "Smith", age: 45}

http://stackoverflow.com/questions/5958417/javascript-function-and-object

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

Douglas Crockford discusses that topic extensively in The Good Parts. He recommends to avoid the new operator to create new objects. Instead he proposes to create customized constructors. For instance:
var mammal = function (spec) {     
   var that = {}; 
   that.get_name = function (  ) { 
      return spec.name; 
   }; 
   that.says = function (  ) { 
      return spec.saying || ''; 
   }; 
   return that; 
}; 

var myMammal = mammal({name: 'Herb'});
In Javascript a function is an object, and can be used to construct objects out of together with the new operator. By convention, functions intended to be used as constructors start with a capital letter. You often see things like:
function Person() {
   this.name = "John";
   return this;
}

var person = new Person();
alert("name: " + person.name);**
In case you forget to use the new operator while instantiating a new object, what you get is an ordinary function call, and this is bound to the global object instead to the new object.
http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript#1598077

Issues with angularjs ng-grid

In order to show ng-grid you must do this:

  • add 'ngGrid' to app definition like this:
    var app = angular.module('AngularAuthApp', ['ngRoute', 'LocalStorageModule', 'angular-loading-bar', 'ngGrid']);

  • Add custom height to css like this:
    .gridStyle {
     border: 1px solid rgb(212,212,212);
      /*width: 800px;*/
    height: 400px;
    }
    If you don't do this table will shrink and will not display anything.
  • If you want to group column be abowe other rows and dont go over them add this to css:
    .ngGroupPanel {
           overflow: visible;
    }
  • Add this to your code in this order:
    <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
    <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.min.js"></script>
  • Add gridOptions, number of columns does not need to be as in JSON array, remind to add $scope.customerData before calling this code:
        $scope.gridOptions = {
                data: 'customerData',
                  showGroupPanel: true,
                    columnDefs: [{ field: 'name', displayName: 'Name' , width: '15%'},
                          { field: 'city', displayName: 'City', width: '15%' },
                            { field: 'address', displayName: 'Address', width: '15%' },
                              { field: 'contactNo', displayName: 'Contact No', width: '15%' },
                                { field: 'emailId', displayName: 'Email Id', width: '15%' },
                                  { displayName: 'Options', cellTemplate: '<input type="button"  ng-click="setScope(row.entity,\'edit\')" name="edit"  value="Edit">&nbsp;<input type="button" ng-click="DeleteUser(row.entity.id)"  name="delete"  value="Delete">', width: '25%' }
                                ]
                              };