Parametros GET en NodeJS y Angular

ver: https://scotch.io/tutorials/use-expressjs-to-get-url-and-post-parameters

Servidor:

var express = require("express"),
    app = express(),
    bodyParser  = require("body-parser"),
    methodOverride = require("method-override"); 
 
  app.use(function (req, res, next) { 
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
  });

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());

var router = express.Router();

router.get('/', function(req, res) {
   res.send("Hello World!");
});

router.get('/abc/:id/:id2/:id3', function(req, res) {
    var datos1 = req.params.id;
    var datos2 = req.params.id2;
    var datos3 = req.params.id3;

    console.log(datos1);
    console.log(datos2);
    console.log(datos3);

    res.send(JSON.stringify("ok")); 
});

app.use(router);

app.listen(8080, function() {
    console.log("Node server running on http://localhost:8080");
});


Cliente:

datos.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class DatosService {

  constructor(public http: Http) { }

  result:any;

  abc(id1: string, id2: string, id3: string) {         
    return this.http.get("http://localhost:8080/abc/" + id1 + "/" + id2 + "/" + id3)     
    .map(res => res.json());       
  }   
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
import { DatosService } from './datos.service';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { ContenidoComponent } from './contenido/contenido.component';

@NgModule({
  declarations: [
    AppComponent,    
    ContenidoComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    FormsModule,
    RouterModule.forRoot([
      {path: 'prueba/:id1/:id2/:id3', component: ContenidoComponent}
    ])          
  ],
  providers: [DatosService],
  bootstrap: [AppComponent]
})
export class AppModule { }


app.component.ts

import { Component } from '@angular/core';
import { DatosService } from './datos.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  datos : any;
  servidor: string;
  idmantis: number;
  archivos: any;

  constructor(private data : DatosService) {}

  abc(id1:string, id2:string, id3:string) {                
    this.data.abc(id1, id2, id3).subscribe((datos) => {    
      
      console.log(datos);              
    });
}


app.component.html

<h1>Pagina principal</h1>

<button (click)='abc(22, 33, 44)'>Prueba parametros</button>

<router-outlet></router-outlet>







ERROR SyntaxError: Unexpected token in JSON

Si se va a devolver un string, usar la funcion de JSON

res.send(JSON.stringify("respuesta"));

Si se manda un objeto, no es necesario hacerlo:

var datos = {nombre: 'pepe', direccion: 'colonia 1010'};
res.send(datos);


Usar mysql con NodeJS y Angular

Servidor:

package.json

{
  "name": "servidor",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "method-override": "^2.3.10",
    "mysql": "^2.15.0"
  }
}

app.js

var express = require("express"),
    app = express(),
    bodyParser  = require("body-parser"),
    methodOverride = require("method-override");

  app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
  });

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());

var router = express.Router();

router.get('/', function(req, res) {
   res.send("Hello World!");
});

router.get('/prueba', function(req, res) {
    var p = [{nombre: 'carlos', apellido: 'russo'},
             {nombre: 'karina', apellido: 'ortiz'}];
 
    res.send(p);
  });

router.get('/sql', function(req, res) {
    var mysql = require('mysql');

    var con = mysql.createConnection({
      host: "Xmantis",
      user: "root",
      password: "p23423423023r2234234rd",
      port: 3360,
      database: "mantis"
    });
   
    con.connect(function(err) {
      if (err) throw err;

      console.log("Connected!");
    });

    con.query(
        'SELECT * FROM X_sector WHERE id > ? and id < ?',[ 4, 20 ],
        function (err, results) {   
            console.log(results);
            res.send(results);
        }
    );     
});

app.use(router);

app.listen(8080, function() {
    console.log("Node server running on http://localhost:8080");
});


Para hacerlo funcionar:

npm install
nodemon app.js (si no esta instalado nodemon, instalarlo con npm install -g nodemon)

y probarlo con:

http://localhost:8080/prueba


Cliente

package.json

{
  "name": "cliente",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.0.0",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "core-js": "^2.4.1",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "^1.6.5",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/language-service": "^5.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.4.2"
  }
}

datos.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class DatosService {

  constructor(public http: Http) { }

  result:any;

  desplegar() {           
    return this.http.get("http://localhost:8080/sql")       
    .map(res => res.json());         
  }       
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

import { HttpModule } from '@angular/http';
import { DatosService } from './datos.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [DatosService],
  bootstrap: [AppComponent]
})
export class AppModule { }


app.component.ts

import { Component } from '@angular/core';
import { DatosService } from './datos.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  datos : any;

  constructor(private data : DatosService) {}

  desplegar() { 
             
    this.data.desplegar().subscribe((posts) => {       
      console.log(posts);       
      this.datos = posts;
    });
  }   
}


app.component.html

<h1>Prueba MySql</h1>

<button (click)='desplegar()'>Click!!</button>

<ul>
  <li *ngFor="let d of datos">{{ d.nombre }}</li>
</ul>




Servidor web en NodeJS

https://carlosazaustre.es/como-crear-una-api-rest-usando-node-js/

******************************
PARA EL SERVIDOR WEB

cd proj
mkdir web1
cd web1
npm init (crea el archivo package.json. Si se indica --yes, no pide ningun dato, asume los default)
cuando pregunte el nombre del main, en lugar de index ponerle app

npm install express --save
npm install method-override --save
npm install body-parser --save

crear un archivo app.js y agregarle este codigo:
(observar que se agrega el access control allow origin para que
se puedan hacer requests desde localhost:4200)

var express = require("express"),
    app = express(),
    bodyParser  = require("body-parser"),
    methodOverride = require("method-override");

  app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
  });

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());

var router = express.Router();

router.get('/', function(req, res) {
   res.send("Hello World!");
});

router.get('/prueba', function(req, res) {
  var p = [{nombre: 'carlos', apellido: 'russo'},
           {nombre: 'karina', apellido: 'ortiz'}];

  res.send(p);
});

app.use(router);

app.listen(8080, function() {
  console.log("Node server running on http://localhost:8080");
});


luego, ejecutar:

node app.js

y queda corriendo el servidor web.


para que no haya que reiniciarlo cada vez que se hace un cambio, instalar nodemon:

npm install -g nodemon

luego iniciar la aplicacion con nodemon app.js, o simplemente nodemon (ya sabe que es app.js
porque se lo indicamos en el ng init)

para probarlo, ir a http://localhost8080
o a http://localhost:8080/prueba


***********************************




Rotar un video que quedo mal grabado con el celular

Si se graba un video en landscape, y el boton de grabacion esta hacia la derecha, todo ok.
Pero si se graba landscape pero con el boton hacia la izquierda, queda mal.

Para solucionarlo:

Ir a Event / Pan and crop
En width dice 1920, debe decir 1080
En height dice 1080, debe decir 1920

** antes de hacer estos cambios, desmarcar la opcion Lock Aspect Ratio ***

Luego rotar el video.

Habilitar CORS en WebApi C# en forma global

En los packages NuGet del sitio WebApi, agregar el package CORS (Microsoft.AspNet.WebApi.Cors)

Luego, en App_Start / WebApiConfig.cs, agregar lo siguiente:

using System.Web.Http.Cors;



var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Retornar JSON en lugar de XML en un servicio WebApi


en App_Start / WebApiConfig.cs agregar en la primera linea:

config.Formatters.JsonFormatter.SupportedMediaTypes
    .Add(new MediaTypeHeaderValue("text/html") );


Fuente: https://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome

Acelerar o desacelerar un video en Sony Vegas


Step 1. To have your video slowed down, you will have to hold down the "Ctrl" key on the keyboard which will increase the length of your clip. By judging the wavy line appearing on the central part of the clip, you will be able to see that speed is modified accordingly.
Step 2. In speeding up the video, you will hold down the "Ctrl" key on the keyboard to shorten the clip's length. Automatically, the speed will be increased. To have the speed reset, you just have to right-click on the video and then proceed to properties and set the playback rate to 1.0.

Como deshabilitar el teclado del notebook

gpedit.msc

Configuracion del equipo / Plantillas administrativas
Sistema / Instalacion de dispositivos / Restricciones de instalacion de dispositivos

Impedir la instalacion de dispositivos que coincidan con cualquiera de estos id de dispositivo

Marcar el radio button "habilitada"

Ir al panel de control, dispositivos y buscar el id del tecaldo

Administrador de dispositivos / teclados / dispositivo de teclado HID

ir a Detalles / en propiedad, elegir ID de hardware

copiar todos los valores

En la pantalla que estaba abierta en el gpedit, elegir "habilitada" y luego click en "mostrar..."

en este cuadro pegar los valores copipados anteriormente, y presionar aceptar

ir a administrador de dispositivos y desinstalar el teclado HID

reiniciar el equipo

Fuente: https://www.youtube.com/watch?v=pAi7SRhAzws