Showing posts with label angularjs. Show all posts
Showing posts with label angularjs. Show all posts

Angular AutoComplete

Angular AutoComplete 


Today Discuss Angular AutoComplete Typescript Search and more data finding dropdown method or autocomplete simple way angular typeahead is default one.

npm ERR! Only HTTP(S) protocols are supported
npm ERR! Only HTTP(S) protocols are supported



npm install --save ngx-type-ahead

@NgModule({
  imports: [
    TypeaheadModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

<type-ahead formControlName="myControl" [suggestions]="mySuggestions"></type-ahead>

TypeaheadSettings



export interface TypeaheadSettings {
  /** how much should be user's typing debounced */
  typeDelay: number; // Default is `50`
  /** maximal number of visible items in dropdown. If value is 0, list will not be limited */
  suggestionsLimit: number; // Default is `10`
  /** text shown when there are no matches */
  noMatchesText: string; // Default is `No matches found`
 
  /** css classes for parts of type-ahead */
  tagClass: string; // Default is `btn badge badge-primary`
  tagRemoveIconClass: string; // Default is ``
  dropdownMenuClass: string; // Default is `dropdown-menu`
  dropdownMenuExpandedClass: string; // Default is `dropdown-menu show`
  dropdownMenuItemClass: string; // Default is `dropdown-item`
  dropdownToggleClass: string; // Default is `dropdown-toggle`
}

Angular AutoComplete

Angular AutoComplete 


Today Discuss Angular AutoComplete Typescript Search and more data finding dropdown method or autocomplete simple way angular typeahead is default one.

npm ERR! Only HTTP(S) protocols are supported
npm ERR! Only HTTP(S) protocols are supported



npm install --save ngx-type-ahead

@NgModule({
  imports: [
    TypeaheadModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

<type-ahead formControlName="myControl" [suggestions]="mySuggestions"></type-ahead>

TypeaheadSettings



export interface TypeaheadSettings {
  /** how much should be user's typing debounced */
  typeDelay: number; // Default is `50`
  /** maximal number of visible items in dropdown. If value is 0, list will not be limited */
  suggestionsLimit: number; // Default is `10`
  /** text shown when there are no matches */
  noMatchesText: string; // Default is `No matches found`
 
  /** css classes for parts of type-ahead */
  tagClass: string; // Default is `btn badge badge-primary`
  tagRemoveIconClass: string; // Default is ``
  dropdownMenuClass: string; // Default is `dropdown-menu`
  dropdownMenuExpandedClass: string; // Default is `dropdown-menu show`
  dropdownMenuItemClass: string; // Default is `dropdown-item`
  dropdownToggleClass: string; // Default is `dropdown-toggle`
}

Angular 5 Role Permission and Role Based Access Control

Angular 5 Role Permission and Role Based Access Control

Hi Guys Today Discuss Angular 5 Role Permission and Role based Access Control Typescript Admin Dashboard various roles like guest, user, admin, superadmin page access control  based Role Permission How to implement that role permission in Angular 5 typescript let discuss today.

Angular 5 Role Permission or Access Control
Angular 5 Role Permission or Access Control

ngx-permission

First install npm package and then install npm permission package ngx-permission


   npm i ngx-permissions


or


                                                        npm install ngx-permissions --save


and  then from your angular main module AppModule



mport { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

// Import your library
import { NgxPermissionsModule } from 'ngx-permissions';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,

    // Specify your library as an import
     NgxPermissionsModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


And your app component sharemodule that import in multiple other feature modules, you can export the ngxpermissionsmodule to make sure you don't have to import in every module.


@NgModule({
    exports: [
        CommonModule,
        NgxPermissionsModule
    ]
})
export class SharedModule { }

and then lazy loaded modules should be add ngxpermission

when you lazy load a module, you should use the for child static method to import the ngxpermissionsmodule.

You can also  isolate the services by using permissionIsolate: true


@NgModule({
    imports: [
        NgxPermissionsModule.forChild()
    ]
})
export class LazyLoadedModule { }


@NgModule({
    imports: [
        NgxPermissionsModule.forChild({
        permissionsIsolate: true, 
        rolesIsolate: true})
    ]
})
export class LazyIsolatedLoadedModule { }

Once your library is imported, you can use its components, directives and pipes in your Angular application: Import service to the main application and load permissions

import { Component, OnInit } from '@angular/core'; import { NgxPermissionsService } from 'ngx-permissions'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'app'; constructor(private permissionsService: NgxPermissionsService, private http: HttpClient) {} ngOnInit(): void { const perm = ["ADMIN", "EDITOR"]; this.permissionsService.loadPermissions(perm); this.http.get('url').subscribe((permissions) => { //const perm = ["ADMIN", "EDITOR"]; example of permissions this.permissionsService.loadPermissions(permissions); }) } }


template view file

<div *ngxPermissionsOnly="['ADMIN', 'GUEST']"> <div>You can see this text congrats</div> </div> <ng-template ngxPermissionsOnly="ADMIN"> <div>You can see this text congrats</div> </ng-template> <ng-template [ngxPermissionsExcept]="['JOHNY']"> <div> All will see it except JOHNY</div> </ng-template>

npm ERR! Only HTTP(S) protocols are supported

npm ERR! Only HTTP(S) protocols are supported

npm ERR! Only HTTP(S) protocols are supported Angular 5 TypeScript npm installing facing issue.

Solve this issue you make change follows step:

npm ERR! Only HTTP(S) protocols are supporte
npm ERR! Only HTTP(S) protocols are supporte

npm config set registry https://registry.npmjs.org/


npm config set registry http://registry.npmjs.org/ 

you set http only after you should run its working fine.





Angular CLI 6 & Material 6 Features

Angular CLI 6 & Material 6 Features



Hai Friends November 1, 2017 Angular 5 Released TypeScript Super Set Script Angular 5 Brings some new features to the popular Javascript Framework for building mobile, desktop and web application. Now Angular cli 6 & Material 6 Features Recently NG-CONF 2018 was organized from  18th April in Salt Lake City, UT. As always this three days conference brought a lot of incredible sessions, workshops, and announcements.

Angular CLI 6 & Material 6 Features
Angular CLI 6 & Material 6 Features
NG-CONF 2018 was started with the session by brad green, misko Hevery and Kara Erickson.

Brad has Introduced 
  1. Clarity Design pattern,
  2. NgRx Library,
  3. StackBlitz
Clarity Design Pattern 

UX guidelines, HTML/CSS framework, and Angular components working together to craft exceptional experience.

NgRx Library

NgRx is becoming popular for Reactive State Management. 
@ngrx provides a set of clean, well-tested libraries for reactive programming in Angular applications.

StackBlitz

StackBlitz online IDE for web application powered by vscode. ReadMore

One Page Template Scrolling Script

One Page Template Scrolling Script


Hi Today discussed Bootstrap template one page template Scrollig Script url passing id and the scroll script.Follow us script.

One Page Template Scrolling Script
One Page Template Scrolling Script


JavaScript

<script type="text/javascript">
!function(t){"use strict";t("a.page-scroll").bind("click",function(a){var o=t(this);t("html, body").stop().animate({scrollTop:t(o.attr("href")).offset().top-50},1250,"easeInOutExpo"),a.preventDefault()}),t("body").scrollspy({target:".navbar-fixed-top",offset:51}),t(".navbar-collapse ul li a").click(function(){t(".navbar-toggle:visible").click()}),t("#mainNav").affix({offset:{top:100}})}(jQuery);
</script>

angularjs single line json data how to display table format split \r\n

angularjs single line json data how to display table format split \r\n






Hi Today Discussed i handle one task default angularjs single line json data how to display table format split \r\n json data single line json data split \r\n first \r\n table heading <th> tag another table data  <td> followus code.

angularjs single line json data how to display table format split \r\n
angularjs single line json data how to display table format split \r\n

 index.html
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="Jsondatadisplay">
    <div class="container">
  
      <br>
        <h3>Data Details:</h3>
        <table class="table table-striped" id="myTable2">
            <thead>
            <tr>
                <th data-ng-repeat="tr in tableHeader track by $index">{{tr}}</th>
            </tr>
            </thead>
            <tr data-ng-repeat="data in tableData track by $index">
                <td data-ng-repeat="col in data track by $index">{{ col }}</td>

            </tr>
        </table>

        <div>

        </div>

        <script>
            var app = angular.module('myApp', []);
            app.controller('Jsondatadisplay', function ($scope, $http) {
            
                $http
                    .get("data.json")
                    .then(function (res) {
                        var dataToParse = res.data.Data;
                        var replaced = dataToParse.split("\r\n");
                        $scope.tableHeader = replaced[1].split(",");
                        var tempArray = [];
                        angular.forEach(replaced, function (element) {
                            tempArray.push(element.split(","));
                        });

                        delete tempArray[0];
                        delete tempArray[1];
                        $scope.tableData = tempArray;
                    })
            });
        </script>

</body>
</html>
data.json

json data very largest json data so please click github link and download file Click Here

output Click Here

Angularjs push list elements to an array

Angularjs push list elements to an array


Hi Guys Today Discussed Angularjs push list elemetns to an array view list form data push array same method used ionic framework. controller data array push element angularjs push list elements to an array follows code.

Angularjs push list elements to an array
Angularjs push list elements to an array

var app = angular.module('angularjs-starter', []);

Controller

app.controller('MainCtrl', function($scope) {
   $scope.submitForm = function () {
       alert($scope.choicesMade);
   };

  $scope.radioValue = {};
   
  $scope.choicesMade = [];
  
  $scope.wordsPresent=['King', 'Garden', 'America', 'Sky', 'Potato', 'Germany', 'Rose', 'Whisky', 'Mumbai', 'Walk'];

  $scope.pushToArray = function(item) {
    if ($scope.choicesMade.indexOf($scope.radioValue[item]) > -1) {
      alert("already in choices");
      return;
    }
    $scope.choicesMade.push($scope.radioValue[item]);
  }

  $scope.removeFromArray = function(item) {
    
    var index = $scope.choicesMade.indexOf($scope.radioValue[item].substring(1));
    if (index > -1) {
      $scope.choicesMade.splice(index, 1);  
    }
    

  }
});
html page

<!DOCTYPE html>
<html ng-app="angularjs-starter">
  
  <head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <script>
      document.write('<base href="' + document.location + '" />');
    </script>
    <script src="app.js"></script>
  </head>
  
  <body ng-controller="MainCtrl">
          <div ng-repeat="item in wordsPresent">
            <b>{{ item }}</b><br>
            <label><input type="radio" name="name_{{item}}" ng-change="pushToArray(item)" ng-model="radioValue[item]" value="{{item}}"/> Yes</label>
           <label><input type="radio" name="name_{{item}}" ng-change="removeFromArray(item)" ng-model="radioValue[item]" value="_{{item}}"/> No</label>
          </div>
           <pre>{{choicesMade}}</pre>
  </body> 

</html>


Angularjs Mouse Right Click Custom Menu

 Angularjs Mouse Right Click Custom Menu

Hi Today Discussed Angularjs Mouse Right Click Custom Menu Normally Angularjs Site is very nice look and pretty site and fast loading and in build ajax and animated pretty site or application. So mouse right click customized is another pretty and security proposed and user friendly menu click so how to this task handle follows code.

Angularjs Mouse Right Click Custom Menu
Angularjs Mouse Right Click Custom Menu

First You used node server or bower is identified and then install menu follows code.

npm install angular-bootstrap-contextmenu
or
bower install angular-bootstrap-contextmenu
Inject reference or Add a reference to contextMenu.js. In your app config add ui.bootstrap.contextMenu as a dependency module.

reference

Your Index Page Main Controller write this code follows and then main controller behind div add

context-menu="menuOptions" this content.

AppCtrl Controller.js

$scope.menuOptions = [
    ['Select', function ($itemScope, $event, modelValue, text, $li) {
        $scope.selected = $itemScope.item.name;
    }],
Downlink Link : Click Here

Angularjs idle timeout auto go to lock screen

Angularjs idle timeout auto go to lock screen


Hi Guys Today discussed Angularjs idle timeout Auto go to lock screen Frontend developer very looks and pretty sides example 5 mins or 10 mins without mouse overing and not working auto go to lock screen and then enter password go to continue work.
Angularjs idle timeout auto go to lock screen
Angularjs idle timeout auto go to lock screen

Html Page

This Page index page Main Controller Config and this controller used full application working this function. follows code controller code.


Controller.js

function Appctrl($scope, $interval, $document) {
    var int = null;
    var callbacks = [];
    var idleTime = 0;
    
    $scope.isIdle = function() {
        return (idleTime > 0);
$state.go(app.lock);
    };
    
    angular.element($document).bind('mousemove', function(e) {
        idleTime = 0;
        $interval.cancel(int);
        startInterval();
        $scope.$apply();
    });
    
    function startInterval() {
        int = $interval(function() {
         idleTime += 3000;
     }, 3000);
    }
    
    startInterval();
}

Angularjs table ng-repeate Simple Pagination

Angularjs table ng-repeate Simple Pagination

Hi Today discussed Angularjs table ng-repeate Simple Pagination Angularjs api web services data provide table ng-repeate custom features sorting and filter and Pagination added follows code.

html Files
Angularjs table ng-repeate Simple Pagination
Angularjs table ng-repeate Simple Pagination


<div ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="item in data | startFrom:currentPage*pageSize | limitTo:pageSize">
            {{item}}
        </li>
    </ul>
    <button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
        Previous
    </button>
    {{currentPage+1}}/{{data.length/pageSize}}
    <button ng-disabled="currentPage >= data.length/pageSize - 1" ng-click="currentPage=currentPage+1">
        Next
    </button>
</div>

controller.js

var app=angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.currentPage = 0;
    $scope.pageSize = 10;
    $scope.data = [];
    for (var i=0; i<50; i++) {
        $scope.data.push("Item "+i);
    }
}

//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
    return function(input, start) {
        start = +start; //parse to int
        return input.slice(start);
    }
});

Angularjs CSV Import and Insert Core PHP Mysql

Angularjs CSV Import and Insert Core PHP Mysql

Hi, Today Discussed Angularjs CSV Import and Insert Core PHP Mysql backend database. Frontend Angularjs CSV or other file Upload  get this formdata backend post and insert mysql database follows Code.
Angularjs CSV Import and Insert Core PHP Mysql
Angularjs CSV Import and Insert Core PHP Mysql

Controller.js

$scope.submit1=function(){

  var s = $scope.fileContent;
  var d = JSON.stringify(s);

             var ds = {'unitname':d,'mode':'csv'}
  var d = JSON.stringify(ds);
console.log(d);
    var postUrl = '../app/api/unit.php';
  $http.post(postUrl,d,{
            transformRequest: angular.identity,
            headers: { 'Content-Type': "application/json" }
        }).success(function(data){
       //  console.log(data.type);
              type=data.type,
              title="UnitCreation",
              message=data.response
 toaster.pop(type, title, message);
       
        });


}
CSV File Reader
Directive.js

  
angular.module('MetronicApp').directive('fileReader', function() {
  return {
    scope: {
      fileReader:"="
    },
    link: function(scope, element) {
      $(element).on('change', function(changeEvent) {
        var files = changeEvent.target.files;
        if (files.length) {
          var r = new FileReader();
          r.onload = function(e) {
              var contents = e.target.result;
              scope.$apply(function () {
                scope.fileReader = contents;
                //console.log(scope.fileReader);
               // var s = JSON.stringify(contents)
              // console.log(contents);
              });
          };
          
          r.readAsText(files[0]);

        }

      });
    }
  };
});
View.html

<form role="form" id="form_sample_2" id="container" data-ng-submit="submit1()">
   

     <input type="file" file-reader="fileContent" ng-model="fileContent" class="btn btn-primary" />
    
    <input type="hidden" ng-model="fileContent">
     <button class="btn sbold blue" name="submit" type="submit">Upload</button>

</form>




Angularjs Implement keyboard Shortcut keys

Angularjs Implement keyboard Shortcut keys


Hi Today discussed Angularjs implement keyboard shortcut keys.  Angularjs app submit form and goto another page used keyboard shortcut keys implemented used follows code.

Angularjs Implement keyboard Shortcut keys
Angularjs Implement keyboard Shortcut keys

Angularjs Implement keyboard first bower install or node_modules means npm install and then 

bower install chieffancypants/angular-hotkeys --save
if you used npm node_modules

use this

npm install angular-hotkeys --save

Refer Link: Click Here
Refer Link: Click Here


index.js include lib file.

$scope.submit1 = function(){  //$scope custom    })

  hotkeys.add({

    combo:'alt+s',
    description:'Save Unit Creation',
     allowIn: ['INPUT', 'SELECT', 'TEXTAREA','REQUIRED'],
  callback:function(){
$scope.submit1();

    }
  })

Ionic + Braintree JS integration

Ionic + Braintree JS integration



Hi Today Discussed  Ionic Framework Braintree JS Integration. Ionic Framework.Braintree Payments drop-in into an Ionic mobile app I have them with an ionic modal view. Here follows Code.
Ionic + Braintree JS integration
Ionic + Braintree JS integration

Html Page
<ion-content ng-controller="payController">

        <div ng-show="step == 'signup'">
          <div class="list">
            <label class="item item-input"><input type="text" placeholder="First name" ng-model="customer.firstname"></label>
            <label class="item item-input"><input type="text" placeholder="Last name" ng-model="customer.lastname"></label>
            <label class="item item-input"><input type="text" placeholder="Company" ng-model="customer.company"></label>
            <label class="item item-input"><input type="text" placeholder="email" ng-model="customer.email"></label>
            <label class="item item-input"><input type="text" placeholder="phone" ng-model="customer.phone"></label>
          </div>
          <div class="padding">
            <button class="button button-block button-positive" ng-click="signup(customer)" ng-disabled="!ready">Continue</button>
          </div>
        </div>

        <div ng-show="step == 'verification'">
          <div class="list">
            <label class="item item-input">
              <input type="text" placeholder="Cardholder name" ng-model="card.cardholder">
            </label>
            <label class="item item-input">
              <input type="text" placeholder="Number" ng-model="card.number">
            </label>
            <label class="item item-input">
              <input type="text" placeholder="CVV" ng-model="card.cvv">
            </label>

            <label class="item item-input">
              <span class="input-label">Expire date</span>
              <input type="text" placeholder="mm" ng-model="card.expiration_month">
              <input type="text" placeholder="yy" ng-model="card.expiration_year">
            </label>
          </div>
          <div class="padding">
            <button class="button button-block button-positive" ng-click="saveCard(card)" ng-disabled="!ready">Save</button>
          </div>
        </div>

        <div ng-show="step == 'checkout'">
          <div class="item range">
            <span>€</span>
            <input type="range" ng-model="amount" min="0" max="100">
            <span>{{ amount }}</span>
          </div>
          <div class="padding">
            <button class="button button-block button-positive" ng-click="pay(10)" ng-disabled="!ready">Pay</button>
          </div>
        </div>

        <div ng-show="step == 'done'">
          <p>Transaction completed with transaction id: {{ transactionId }}</p>
        </div>
App.js

 angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})


Services.js


angular
 .module('starter')
 .factory('braintreeService', braintreeFactory);

function braintreeFactory($http) {

 /**
  * Braintree server-side implementation
  * @type string
  */
 var Url = 'Api URL';

 return {

  getClientToken: function(customerId) {
   return $http
    .get(Url + '/Access_token' + (cus_Id ? '/' + cus_Id: ''))
    .then(function(response) {
     if (response.status === 200 && response.data !== undefined) {
      return response.data;
     }

     throw 'Invalid response';
    });
  },

  createCustomer: function(firstName, lastName, company, email, phone, fax, website) {
   var postData = {
    customer: {
     firstName: firstName,
     lastName: lastName,
     company: company,
     email: email,
     phone: phone,
     fax: fax,
     website: website
    }
   };

   return $http
    .post(Url + '/cus', postData)
    .then(function(response) {
     if (response.status === 200 && response.data !== undefined) {
      return response.data;
     }
    });
  },

  createPaymentMethod: function(customerId, nonce) {
   var postData = {
    paymentMethod: {
     customerId: customerId,
     paymentMethodNonce: nonce
    }
   };
   return $http
    .post(Url + '/payment_method', postData)
    .then(function(response) {
     if (response.status === 200 && response.data !== undefined) {
      return response.data;
     }
    });
  },

  sale: function(amount, paymentMethodToken) {
   var postData = {
    transaction: {
     amount: amount,
     paymentMethodToken, paymentMethodToken
    }
   };

   return $http
    .post(Url + '/sale', postData)
    .then(function(response) {
     if (response.status === 200 && response.data !== undefined) {
      return response.data;
     }
    });
  }

 };


};


Controller.js

angular
 .module('starter')
 .controller('payController', payController);

function payController($scope, braintreeService) {
 /**
  * Form steps
  * 1. signup - create customer
  * 2. verification - save & validate card
  * 3. checkout - charge the card
  * 4. done - displays transaction id
  */
 $scope.step = 'signup';

 /**
  * customerId in Braintree
  * reference to credit card in Braintree
  * 
  * These should be persisted for future reference
  */
 $scope.customerId = false;
 $scope.paymentMethodToken = false;
 $scope.amount = 10;

 /**
  * Bypass step forms for testing
  */
 /*$scope.customerId = '';
 $scope.step = 'checkout';
 $scope.paymentMethodToken = '';
 $scope.card = {
  cardholder: 'Michael',
  number:'4111111111111111',
  cvv: 444,
  expiration_month: 10,
  expiration_year: 18
 };*/

 /**
  * Setup Braintree client with clientToken generated on our server
  */
 $scope.ready = false;
 var braintreeClient;
 braintreeService.getClientToken().then(function(clientToken) {
  // braintree.setup(clientToken, "custom", {id: "checkout", enableCORS: true});
  braintreeClient = new braintree.api.Client({clientToken: clientToken, enableCORS: true});
  $scope.ready = true;
 });

 /**
  * Creates braintree customer
  */
 $scope.signup = function(customer) {
  braintreeService
   .createCustomer(customer.firstname, customer.lastname, customer.company, customer.email, customer.phone)
   .then(function(customerId) {
    console.log("customerId " + customerId);
    $scope.customerId = customerId;
    $scope.step = 'verification';
   });
 };

 /**
  * Save card
  */
 $scope.saveCard = function(card) {
  // console.log('tokenizing card', card);
  braintreeClient.tokenizeCard({
   number: card.number,
   cardholderName: card.cardholder,
   expirationMonth: card.expiration_month,
   expirationYear: card.expiration_year,
   cvv: card.cvv
   // billingAddress: {}
  }, function(err, nonce) {
   if (err) {
    throw err;
   }

   braintreeService
    .createPaymentMethod($scope.customerId, nonce)
    .then(function(paymentMethodToken) {
     console.log('paymentMethodToken ' + paymentMethodToken);
     $scope.paymentMethodToken = paymentMethodToken;
     $scope.step = 'checkout';
    });
  })
 };

 $scope.pay = function(amount) {
  braintreeService
   .sale(amount, $scope.paymentMethodToken)
   .then(function(transactionId) {
    $scope.step = 'done';
    $scope.transactionId = transactionId;
    console.log('transactionId ' + transactionId);
   });
 };
};



Angularjs WebCam Take Picture and decode base64

Angularjs WebCam Take Picture and decode base64

Today discussed Angularjs WebCam Take Picture and decode base64 image upload webcam and file upload encrypt blob type image decrypt method and image upload base64 encrypt method convert image decrypt and move folder follows code. try it.

Angularjs WebCam Take Picture and decode base64
Angularjs WebCam Take Picture and decode base64

webcam.html  html page
 <ng-camera capture-message="Cheeeese!"                                                    countdown="3"
      output-height="160"
     output-width="213"
      viewer-height="320"
       viewer-width="426"
          image-format="jpeg"
        jpeg-quality="100"
         action-message="Take picture"
       snapshot="vm.picture"
       flash-fallback-url="/vendors/webcamjs/webcam.swf"
       overlay-url="/overlay.png"
       shutter-url="img/shutter.mp3"></ng-camera>

Controller

(function (angular) {
    'use strict';

    angular.module('camera', []);

})(angular);

angular.module('camera');
app.controller('cameraController', controller);

controller.$inject = ['$scope'];

function controller($scope) {
    /* jshint validthis: true */
    var vm = this;

    vm.picture = false; // Initial state

    $scope.hshow = function (a) {
        alert(a);
    }
}




/* global Webcam */
(function (angular) {
    'use strict';

    angular.module('camera');
    app.directive('ngCamera', directive);

    directive.$inject = ['$q', '$timeout', 'photoManagerClient', '$stateParams'];

    function directive($q, $timeout, photoManagerClient, $stateParams) {
        var clientid = $stateParams.ClientID;
        return {
            'restrict': 'E',
            'scope': {
                'actionMessage': '@',
                'captureMessage': '@',
                'countdown': '@',
                'flashFallbackUrl': '@',
                'overlayUrl': '@',
                'outputHeight': '@',
                'outputWidth': '@',
                'shutterUrl': '@',
                'viewerHeight': '@',
                'viewerWidth': '@',
                'cropHeight': '@',
                'cropWidth': '@',
                'imageFormat': '@',
                'jpegQuality': '@',
                'snapshot': '='
            },

            'template': ['<div class="ng-camera">',
                '<div class="ng-camera-countdown" ng-if="countdown" ng-show="activeCountdown">',
                '<p class="tick">{{countdownText}}</p>',
                '</div>',
                '<div class="ng-camera-stack">',
                '<img class="ng-camera-overlay" ng-if="overlayUrl" ng-show="cameraLive" ng-src="{{snapshot}}" alt="overlay">',
                '<div id="ng-camera-feed"></div>',
                '</div>',
                '<button id="ng-camera-action" ng-click="getSnapshot()">{{actionMessage}}</button>',
                '</div>'].join(''),
            'link': link
        };

        function link(scope, element, attrs) {

            scope.libraryLoaded = false;
            scope.cameraLive = false;
            scope.activeCountdown = false;


            if (scope.viewerHeight === undefined) {
                scope.viewerHeight = 'auto';
            }
            if (scope.viewerWidth === undefined) {
                scope.viewerWidth = 'auto';
            }
            if (scope.outputHeight === undefined) {
                scope.outputHeight = scope.viewerHeight;
            }
            if (scope.outputWidth === undefined) {
                scope.outputWidth = scope.viewerWidth;
            }


            if (scope.cropHeight === undefined || scope.cropWidth === undefined) {
                scope.cropHeight = false;
                scope.cropWith = false;
            }

            Webcam.set({
                width: scope.viewerWidth,
                height: scope.viewerHeight,
                dest_width: scope.outputWidth,
                dest_height: scope.outputHeight,
                crop_width: scope.cropWidth,
                crop_height: scope.cropHeight,
                image_format: scope.imageFormat,
                jpeg_quality: scope.jpegQuality,
                force_flash: false
            });
            if (scope.flashFallbackUrl !== 'undefined') {
                Webcam.setSWFLocation(scope.flashFallbackUrl);
            }
            Webcam.attach('#ng-camera-feed');

            Webcam.on('load', function () {
                console.info('library loaded');
                scope.$apply(function () {
                    scope.libraryLoaded = true;
                });
            });
            Webcam.on('live', function () {
                console.info('camera live');
                scope.$apply(function () {
                    scope.cameraLive = true;
                });
            });
            Webcam.on('error', function (error) {
                console.error('WebcameJS directive ERROR: ', error);
            });

            if (scope.shutterUrl !== undefined) {
                scope.shutter = new Audio();
                scope.shutter.autoplay = false;
                if (navigator.userAgent.match(/Firefox/)) {
                    scope.shutter.src = scope.shutterUrl.split('.')[0] + '.ogg';
                } else {
                    scope.shutter.src = scope.shutterUrl;
                }
            }


            if (scope.countdown !== undefined) {
                scope.countdownTime = parseInt(scope.countdown) * 1000;
                scope.countdownText = parseInt(scope.countdown);
            }
            scope.countdownStart = function () {
                scope.activeCountdown = true;
                scope.countdownPromise = $q.defer();
                scope.countdownTick = setInterval(function () {
                    return scope.$apply(function () {
                        var nextTick;
                        nextTick = parseInt(scope.countdownText) - 1;
                        if (nextTick === 0) {
                            scope.countdownText = scope.captureMessage !== null ? scope.captureMessage : 'GO!';
                            clearInterval(scope.countdownTick);
                            scope.countdownPromise.resolve();
                        } else {
                            scope.countdownText = nextTick;
                        }
                    });
                }, 1000);
            };

            scope.getSnapshot = function () {

                if (scope.countdown !== undefined) {
                    scope.countdownStart();
                    scope.countdownPromise.promise.then(function () {
                        $timeout(function () {
                            scope.activeCountdown = false;
                            scope.countdownText = parseInt(scope.countdown);
                        }, 2000);

                        if (scope.shutterUrl !== undefined) {
                            scope.shutter.play();
                        }

                        Webcam.snap(function (data_uri) {
                            /*   function saveAs(uri, filename) {
                                   var link = document.createElement('a');
                                   if (typeof link.download === 'string') {
                                       console.log();
                                       link.href = uri;
                                       link.download = filename;
   
                                       //Firefox requires the link to be in the body
                                       document.body.appendChild(link);
   
                                       //simulate click
                                       link.click();
   
                                       //remove the link when done
                                       document.body.removeChild(link);
                                   } else {
                                       window.open(uri);
                                   }
   
                               }*/
                            scope.snapshot = data_uri;
                            //  var imageBase64 = data_uri;
                            //  var as = saveAs(imageBase64, 'as.png');
                            //   var image = new Image();
                            //   image.src = data_uri;
                            //  console.log(data_uri);

                            // alert(image);
                            //   var change = decodeBase64(data_uri);
                            // var blob = new Blob([imageBase64], { type: 'image/png' });
                            //  var file = new File([blob], 'imageFileName.png');
                            //  var photos = new File([blob], 'imageFileName.png');
                            var imageBase64 = data_uri;
                            //    var blob = new Blob([decodedImage], { type: 'image/png' });

                            ///now it should work properly
                            //  var photos = new File([blob], 'newname.png');
                            function dataURItoBlob(dataURI) {
                                // convert base64/URLEncoded data component to raw binary data held in a string
                                var byteString;
                                if (dataURI.split(',')[0].indexOf('base64') >= 0)
                                    byteString = atob(dataURI.split(',')[1]);
                                else
                                    byteString = unescape(dataURI.split(',')[1]);

                                // separate out the mime component
                                var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

                                // write the bytes of the string to a typed array
                                var ia = new Uint8Array(byteString.length);
                                for (var i = 0; i < byteString.length; i++) {
                                    ia[i] = byteString.charCodeAt(i);
                                }

                                return new Blob([ia], { type: mimeString });
                            }
                            // var dataURL = data_uri.toDataURL('image/jpeg', 0.5);
                            var blob1 = dataURItoBlob(data_uri);
                            var blob2 = new Blob([blob1], { type: 'image/png' });
                            var blob = new File([blob2], 'image' + clientid + '.png');
                            //  var file = new File([blob], 'imageFileName.png');
                            //  var photos = new File([blob], 'imageFileName.png');
                            //  var fd = new FormData(document.forms[0]);
                            // fd.append("canvasImage", blob);
                            var formData = new FormData();

                            //   angular.forEach(imgData, function (imgData) {
                            //  alert('asdas');
                            //  console.log(imgData);
                            formData.append("canvasImage", blob);
                            //  });
                            return photoManagerClient.save(formData)
                                   .$promise


                        });
                    });
                } else {
                    if (scope.shutterUrl !== undefined) {
                        scope.shutter.play();
                    }

                    Webcam.snap(function (data_uri) {
                        scope.snapshot = data_uri;


                        var Image = scope.snapshot;
                        var st = { 'Image': Image };
                        var ss = JSON.stringify(st);
                        var postUrlna = '../api/Cameraaddimage';
                        $http.post(postUrlna, ss, {
                            transformRequest: angular.identity,
                            headers: { 'Content-Type': "application/json" }
                        }).then(function (result) {

                        });
                        //console.log(data_uri);
                    });
                }
            };

            scope.$on('$destroy', function () {
                Webcam.reset();
            });
        }
    }

})(angular);


Factory Image upload Api

app.factory('photoManager', photoManager);
photoManager.$inject = ['$q', 'photoManagerClient', 'appInfo', '$stateParams'];

function photoManager($q, photoManagerClient, appInfo, $stateParams) {
    var abc = $stateParams.ClientID;
    var service = {
        photos: [],
        load: load,
        upload: upload,
        remove: remove,
        photoExists: photoExists,
        status: {
            uploading: false
        }
    };

    return service;

    function load() {
        service.photos.length = 0;

        return photoManagerClient.query()
                            .$promise
                            .then(function (result) {
                                result.photos
                                        .forEach(function (photo) {
                                            service.photos.push(photo);
                                        });

                                appInfo.setInfo({ message: "photos loaded successfully" });

                                return result.$promise;
                            },
                            function (result) {
                                appInfo.setInfo({ message: "something went wrong: " + result.data.message });
                                return $q.reject(result);
                            })
                            ['finally'](
                            function () {
                                appInfo.setInfo({ busy: false });
                            });
    }

    function upload(photos) {
        console.log(photos);
        var formData = new FormData();

        angular.forEach(photos, function (photo) {
            console.log('photofsdfsdf');
            console.log(photo);
            formData.append(photo.name, photo);
        });
        return photoManagerClient.save(formData)
                                   .$promise
      
    }

    function remove(photo) {
        appInfo.setInfo({ busy: true, message: "deleting photo " + photo.name });

        return photoManagerClient.remove({ fileName: photo.name })
                                    .$promise
                                    .then(function (result) {
                                        //if the photo was deleted successfully remove it from the photos array
                                        var i = service.photos.indexOf(photo);
                                        service.photos.splice(i, 1);

                                        appInfo.setInfo({ message: "photos deleted" });

                                        return result.$promise;
                                    },
                                    function (result) {
                                        appInfo.setInfo({ message: "something went wrong: " + result.data.message });
                                        return $q.reject(result);
                                    })
                                    ['finally'](
                                    function () {
                                        appInfo.setInfo({ busy: false });
                                    });
    }

    function photoExists(photoName) {
        var res = false
        service.photos.forEach(function (photo) {
            if (photo.name === photoName) {
                res = true;
            }
        });

        return res;
    }
}
app.factory('photoManagerClient', photoManagerClient);

photoManagerClient.$inject = ['$resource', '$stateParams'];

function photoManagerClient($resource, $stateParams) {
    var clinetid = $stateParams.ClientID;
    //  alert('dsfsd');
    //sdafdsfds  console.log(clinetid);
    return $resource("../api/photo/:fileName",
           {
               id: "@fileName",
               id1: clinetid,
           },
           {
               'query': { method: 'GET' },
               'save': { method: 'POST', transformRequest: angular.identity, headers: { 'Content-Type': undefined } },
               'remove': { method: 'DELETE', url: '../api/photo/:fileName', params: { name: '@fileName' } }
           });
}

C# Linq Image move Local Folder

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using ss.Controllers.Models;
using ss.Controllers.Photo;
namespace ss.Controllers.Controllers
{
    [RoutePrefix("api/photo")]
    public class PhotoController : ApiController
    {
        private IPhotoManager photoManager;

        public PhotoController()
            : this(new LocalPhotoManager(HttpRuntime.AppDomainAppPath + @"\Customerimage"))
        {
     
        }

        public PhotoController(IPhotoManager photoManager)
        {
            this.photoManager = photoManager;
        }

        // GET: api/Photo
        public async Task<IHttpActionResult> Get()
        {
            var results = await photoManager.Get();
            return Ok(new { photos = results });
        }

        // POST: api/Photo
        public async Task<IHttpActionResult> Post()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                return BadRequest("Unsupported media type");
            }

            try
            {
              //  LaexDataContext lx = new LaexDataContext();
                var photos = await photoManager.Add(Request);
             /*   var a = "DFD";
                var sf = from l in lx.mCustomers where l.ClientID == 10371 select l;
                if (sf.Count() > 0)
                {
                    var de = sf.First();
                    de.NRIC1 = "ZZZ";
                    lx.SubmitChanges();
                }*/
                // string a1 = "update mcustomer set NRIC1='DASD' WHERE ClientID=10371";
                //   var b1 = lx.ExecuteQuery<mCustomer>(a1);
                return Ok(new { Message = "Photos uploaded ok", Photos = photos });
            }
            catch (Exception ex)
            {
                return BadRequest(ex.GetBaseException().Message);
            }

        }

        // DELETE: api/Photo/5
        [HttpDelete]
        [Route("{fileName}")]
        public async Task<IHttpActionResult> Delete(string fileName)
        {
            if (!this.photoManager.FileExists(fileName))
            {
                return NotFound();
            }

            var result = await this.photoManager.Delete(fileName);

            if (result.Successful)
            {
                return Ok(new { message = result.Message });
            }
            else
            {
                return BadRequest(result.Message);
            }
        }
    }
}



Stimulsoft Reports.JS is a platform for generating reports using JavaScript and HTML5. Angularjs

Stimulsoft Reports.JS is a platform for generating reports using JavaScript and HTML5.


Stimulsoft Reports.js is a platform for generating report using javascript and html5. Normally html design and report geneerating and stimulsoft is autometically report generation and connection string your db connection and wrtie query auto function generation report.


DBconnection
dbconnection
Stimulsoft Report is modify design any design easily modifed and watermark and everything is very easy.

View Report
View Report
Include Files:
 <link href="css/demo.css" rel="stylesheet">
 
 <!-- Report Viewer Office2013 style -->
 <link href="css/stimulsoft.viewer.office2013.whiteblue.css" rel="stylesheet">
 
 <!-- Report Designer Office2013 style -->
 <link href="css/stimulsoft.designer.office2013.whiteblue.css" rel="stylesheet">
 
 <!-- Stimusloft Reports.JS -->
 <script src="scripts/stimulsoft.reports.js" type="text/javascript"></script>
 <script src="scripts/stimulsoft.viewer.js" type="text/javascript"></script>
 <script src="scripts/stimulsoft.designer.js" type="text/javascript"></script>

 <!-- Reports -->
 <script src="reports/OnlineStoreSales.js" type="text/javascript"></script>
 <script src="reports/UsersAppleIpad.js" type="text/javascript"></script>
 <script src="reports/SmartphoneBestsellersInQ12015.js" type="text/javascript"></script>
 <script src="reports/SiteStatistics.js" type="text/javascript"></script>
 <script src="reports/HighlightCondition.js" type="text/javascript"></script>
 <script src="reports/Images.js" type="text/javascript"></script>
 <script src="reports/MasterDetail.js" type="text/javascript"></script>
 <script src="reports/MultiColumnList.js" type="text/javascript"></script>
 <script src="reports/SideBySideListWithContainers.js" type="text/javascript"></script>
 <script src="reports/SimpleGroup.js" type="text/javascript"></script>
 <script src="reports/SimpleList.js" type="text/javascript"></script>
 <script src="reports/ParametersSelectingCountry.js" type="text/javascript"></script>

 <!-- Demo data -->


<script>
  var viewer = null;
  var designer = null;
  
  function createViewer() {
   // Specify necessary options for the viewer
   var options = new Stimulsoft.Viewer.StiViewerOptions();
   options.height = "100%";
   options.appearance.scrollbarsMode = true;
   options.toolbar.showDesignButton = true;
   options.toolbar.printDestination = Stimulsoft.Viewer.StiPrintDestination.Direct;
   options.appearance.htmlRenderMode = Stimulsoft.Report.Export.StiHtmlExportMode.Table;

   // Create an instance of the viewer
   viewer = new Stimulsoft.Viewer.StiViewer(options, "StiViewer", false);
   
   // Add the design button event
   viewer.onDesignReport = function (e) {
    this.visible = false;
    if (designer == null) createDesigner();
    designer.visible = true;
    designer.report = e.report;
   };
   
   viewer.renderHtml("viewerContent");
  }
  
  function createDesigner() {
   var options = new Stimulsoft.Designer.StiDesignerOptions();
   options.appearance.fullScreenMode = true;
   options.appearance.htmlRenderMode = Stimulsoft.Report.Export.StiHtmlExportMode.Table;
   
   // Create an instance of the designer
   designer = new Stimulsoft.Designer.StiDesigner(options, "StiDesigner", false);
   
   // Add the exit menu item event
   designer.onExit = function (e) {
    this.visible = false;
    viewer.visible = true;
   }
   
   designer.renderHtml("designerContent");
  }
  
  function setReport(reportObject) {
   // Forcibly show process indicator
   viewer.showProcessIndicator();
   
   // Timeout need for immediate display loading report indicator
   setTimeout(function () {
    // Create a new report instance
    var report = new Stimulsoft.Report.StiReport();
    // Load reports from JSON object
    report.load(reportObject);

    // Remove all connections in report template (they are used in the first place)
    report.dictionary.databases.clear();
    // Registered JSON data specified in the report with same name
    report.regData("Demo", "Demo", Demo);
    // Assign the report to the viewer
    viewer.report = report;
   }, 50);
  }
  
  // Set report button style
  function setReportButton(button) {
   for (var reportName in reportsCollection) {
    var reportButton = document.getElementById(reportName);
    reportButton.isSelected = reportButton == button;
    reportButton.className = reportButton.isSelected ? "ReportButton Selected" : "ReportButton";
   }
  }
  
  // Load first report after the page is loaded
  function onBodyLoad() {
   createViewer();
   selectedButton = document.getElementById("SimpleList");
   onButtonClick(selectedButton, SimpleList);
  }
  
  // Demo Report button events
  // ---
  
  function onButtonClick(button, reportObject) {
   selectedButton.className = "ReportButton";
   button.className = "ReportButton Selected";
   selectedButton = button;
   setReport(reportObject);
  }
  
  function onButtonMouseOver(button) {
   if (button != selectedButton) button.className = "ReportButton Over";
  }
  
  function onButtonMouseOut(button) {
   if (button != selectedButton) button.className = "ReportButton";
  }
 </script>
Html Files
<body onload="onBodyLoad();">
 <div id="designerContent"></div>
 <table class="Main" cellpadding="0" cellspacing="4">
  <tr>
   <td width="150px">
    <table class="LeftPanel" cellpadding="0" cellspacing="0">
     <tr>
      <td height="60px">
       <img style="position: absolute; width: 150px; left: 0px; top: 5px;" src="images/StimulsoftReports.png" />
       <img style="position: absolute; width: 30px; height: 30px; left: 105px; top: 25px;" src="images/Js.png" />
      </td>
     </tr>
     <tr>
      <td height="90%">
       <div class="Buttons">
        <script type="text/javascript">
         // Report id and names for this Demo
         var reportsCollection = {
          "OnlineStoreSales": "Online Store Sales",
          "SimpleList": "Simple List",
          "HighlightCondition": "Highlight Condition",
          "Images": "Images",
          "MasterDetail": "Master-Detail",
          "UsersAppleIpad": "Users Apple Ipad",
          "SmartphoneBestsellersInQ12015": "Smartphone Bestsellers In Q1 2015",
          "MultiColumnList": "Multi-Column List",
          "SimpleGroup": "Simple Group",
          "SiteStatistics": "Site Statistics",
          "ParametersSelectingCountry": "Parameters Selecting Country"
         };
         // Render all report buttons
         for (var reportName in reportsCollection) {
          document.write(
           "<a class=\"ReportButton\" id=\"" + reportName + "\"" + 
           "onmouseover=\"onButtonMouseOver(this)\"" +
           "onmouseout=\"onButtonMouseOut(this)\"" + 
           "onclick=\"onButtonClick(this, " + reportName + ")\">" +
           "<table cellpadding=\"0\" cellspacing=\"0\">" +
           "<tr><td style=\"text-align: center; width: 100%;\"><img src=\"images/" + reportName + ".png\" /></td></tr>" +
           "<tr><td class=\"Caption\">" + reportsCollection[reportName] + "</td></tr>" +
           "</table>" +
           "</a>");
         }
        </script>
       </div>
      </td>
     </tr>
    </table>
   </td>
   <td height="100%" id="viewerContent"></td>
  </tr>
 </table>
</body>
</html>