CORS en llamados Ajax (Cross Origin Resource Sharing) en jQuery

Cuando se realiza un llamado Ajax desde una página html (o .vm, o .aspx, etc), en realidad se está realizando una llamada CORS (Cross Origin Resource Sharing).

Esto es porque la invocación se realiza desde el equipo del usuario hacia un servidor (por ejemplo Xdesa).

Por defecto, y por cuestiones de seguridad, los llamados CORS no están habilitados, y si se realizan se genera una excepción con el texto "No Transport".

Para habilitar ejecuciones CORS, a partir de la versión 1.4.1 de jQuery es necesario realizar esta configuración:

    jQuery.support.cors = true;

La versión previa a 1.4.1 (inclusive), no requiere este setting.

Error 0019: Each type name in a schema must be unique

Este error ocurre en Data Entity Framework cuando quedan versiones antiguas de las .dll's.
Es necesario borrar las .dll's de la carpeta dll de los siguientes proyectos:

                        DAL
                        Persistencia

Luego, recompilar DAL y Persistencia y luego la solución que las utilice.


Referencia: http://realnero.blogspot.com/2010/04/entity-framework-error-0019.html

Sitio de IIS solicita usuario y password

Si un sitio web de IIS solicita usuario y password:

-Tener en cuenta que los sitios deben ser publicados dentro del Default Web Site

-Verificar que el sitio tenga su propio application pool

-Verificar que el usuario del application pool sea

                              .\usr_X

-Verificar que la configuración de Authentication para el sitio coincida con la siguiente:


Unable to load the specified metadata resource

Unable to load the specified metadata resource

Este error ocurre cuando las rutas de Entity Framework definidas en el web.config no coinciden con las que contiene el ensamblado:

Los archivos involucrados en este problema son:

                      .csdl
                      .msl
                      .ssdl

Para averiguar qué rutas está utilizando la aplicación, se debe ir a la carpeta bin del sitio publicado, y analizar con reflection la .dll que corresponda al nombre del sitio (en este ejemplo, el sitio se llama CobTercerosWeb, por lo cual analizaremos el archivo CobTercerosWeb.dll)

Abrir el archivo con la aplicación ILSpy

Abrir la carpeta Resources


Los nombres de los archivos que allí aparecen deben coincidir con los que se referencien en el web.config (o app.config) de la aplicación.

En este caso, el problema radica en que la configuración establecida en el web.config difiere de la ubicación real de los archivos de recursos.

El archivo Web.config contiene lo siguiente:

    <add name="cexofflineEntities" connectionString="metadata=res://*/CexOfflineEntities.csdl|res://*/CexOfflineEntities.ssdl|res://*/CexOfflineEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=Xdesa;initial catalog=cexoffline;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

Mientras que los nombres de los archivos en el ensamblado son estos:

  • ModelCexOffline.csdl
  • ModelCexOffline.msl
  • ModelCexOffline.ssdl
Hay dos posibles soluciones:

1. En este caso, la solución es cambiar en el web.config los nombres CexOfflineEntities por ModelCexOffline.

2. Volver a crear el .edmx en el proyecto pero con los nombres correctos.

Dado que uBuilder adapta los strings de conexión dependiendo del destino de la publicación, la opción 2 es la que debe adoptarse.



Fuente: http://www.ozkary.com/2012/10/unable-to-load-specified-metadata.html
Aplicación ILSpy: http://ilspy.net/

Interfaz para Ambiloop looper con Arduino / controlar click, short hold y long hold sin debounce

Interfaz para ambiloop con Arduino

Dos botones. Se detectan click, short hold, long hold, controlando debounce.

Click del boton1: cambia de track
Click del boton2: comienza / detiene grabación en el track actual
Short hold del boton2: borra el track actual
Long hold del boton2: borra todos los tracks, y selecciona el track 1


#define CLICK 1
#define SHORT 2
#define LONG 3
#define IDLE 0

const int buttonPin = 4;    
int buttonState;           
int lastButtonState = LOW; 

const int button2Pin = 5;    
int button2State;           
int lastButton2State = LOW; 

int estadoBoton1;
int estadoBoton2;

long lastDebounceTime = 0;
long debounceDelay = 30;  
long tiempoIni, tiempoFin;
bool boton1ON, short1ON, long1ON;

long lastDebounceTime2 = 0;
long debounceDelay2 = 30;  
long tiempoIni2, tiempoFin2;
bool boton2ON, short2ON, long2ON;

String tracks[8] = {"1", "2", "3", "4", "5", "6", "7", "8"};
int trackActual = 0;

void setup() {
  pinMode(buttonPin, INPUT);
  boton1ON = false;
  short1ON = false;
  long1ON = false;    
  estadoBoton1 = IDLE;
  estadoBoton2 = IDLE;
}

void loop() {
  bool boton1 = ValidarBoton1();
  bool boton2 = ValidarBoton2();
  
  switch (estadoBoton1)
  {
    case CLICK: 
      trackActual++;
      if (trackActual > 8)
        trackActual = 1;
        
      Keyboard.print(tracks[trackActual-1]);
      estadoBoton1 = IDLE;
      break;
  }

  switch (estadoBoton2)
  {
    case CLICK: 
      Keyboard.print("r"); 
      estadoBoton2 = IDLE; 
      break;
    case SHORT: 
      Keyboard.print("e"); 
      estadoBoton2 = IDLE;
      break;
    case LONG: 
      Keyboard.print("1e2e3e4e5e6e7e8e1 ");
      trackActual = 1;
      estadoBoton2 = IDLE;
      break;   
  }  
}

bool ValidarBoton1()
{
  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  } 
  
  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;

      if (buttonState == HIGH) {          
        tiempoIni = millis();

        while (buttonState == HIGH)
        {
          buttonState = digitalRead(buttonPin);
          delay(1);
        }
        tiempoFin = millis();

        if (tiempoFin - tiempoIni > 1500)
          estadoBoton1 = LONG;  
        else if (tiempoFin - tiempoIni > 500)
          estadoBoton1 = SHORT;
        else 
          estadoBoton1 = CLICK;
      }
    }
  }
  
  lastButtonState = reading;
}  

bool ValidarBoton2()
{
  int reading2 = digitalRead(button2Pin);

  if (reading2 != lastButton2State) {
    lastDebounceTime2 = millis();
  } 
  
  if ((millis() - lastDebounceTime2) > debounceDelay2) {
    if (reading2 != button2State) {
      button2State = reading2;

      if (button2State == HIGH) {          
        tiempoIni2 = millis();

        while (button2State == HIGH)
        {
          button2State = digitalRead(button2Pin);
          delay(1);
        }
        tiempoFin2 = millis();
        
        if (tiempoFin2 - tiempoIni2 > 1500)
          estadoBoton2 = LONG;  
        else if (tiempoFin2 - tiempoIni2 > 500)
          estadoBoton2 = SHORT;
        else 
          estadoBoton2 = CLICK;
      }
    }
  }
  
  lastButton2State = reading2;
}  

Arduino Leonardo keyboard



Fuentes:
https://www.arduino.cc/en/Tutorial/KeyboardMessage
https://www.arduino.cc/en/Tutorial/Debounce




const int buttonPin = 4;  
int ledState = HIGH;      
int buttonState;          
int lastButtonState = LOW;

long lastDebounceTime = 0;
long debounceDelay = 50;  

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledState);
}

void loop() {
  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }
 
  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
     
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }
 
  if (ledState == HIGH)
  {
    Keyboard.print("1");
    ledState = LOW;
  }
 
  lastButtonState = reading;
}


Acceder a elementos de XML con XPath

IMPORTANTE:
Agregar este using:

using System.Xml.XPath;

XDocument xmlDoc;
xmlDoc = XDocument.Load("Data.xml");


/* coleccion de elementos dentro de un determinado path */

var destinos = xmlDoc.XPathSelectElements("publicador/configuracion/destinos/web");
foreach (var dest in destinos.Elements("destino"))
{
   Console.WriteLine(dest.Value);
}



/* coleccion de elementos cuyo valor contiene un texto específico */

var x = xmlDoc.XPathSelectElement("publicador/aplicaciones/aplicacion/nombre[text()='abc']");



Ejecutar un stored procedure con XML como parametro en Sql Server



Tabla

USE [base]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Empresa](
[Id] [numeric](18, 0) NOT NULL,
[Nombre] [varchar](50) NULL,
[Direccion] [varchar](50) NULL,
 CONSTRAINT [PK_Empresa] PRIMARY KEY CLUSTERED 
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


Stored procedure

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE Prueba
@DatosXml XML
AS
BEGIN
SET NOCOUNT ON;

insert into Empresa (Id, Nombre, Direccion)
SELECT
  Pers.value('(Id)[1]', 'int') as 'Id',
  Pers.value('(Nombre)[1]', 'Varchar(50)') as 'Nombre',
  Pers.value('(Direccion)[1]', 'varchar(50)') as 'Direccion'
FROM
  @DatosXml.nodes('/Empresa/Persona') as EMP(Pers)
END
GO


Ejecucion

exec Prueba @DatosXml = '<Empresa> <Persona> <Id>1</Id> <Nombre>Pedro</Nombre> <Direccion>Dir 1</Direccion> </Persona> <Persona> <Id>2</Id> <Nombre>Juan</Nombre> <Direccion>Dir 2</Direccion> </Persona> </Empresa>'

No se puede hacer debug, no entra en los metodos o no se detiene en los breakpoints

PASO 1:

1) Eliminar el archivo .suo
2) hacer clean del proyecto y luego arrancarlo con F10

PASO 2:

Tools / Options / Debugging / Symbols
En "Cache symbols in this directory" agregar el path del archivo .pdb de la solucion.

Ej:
C:\<ruta>\bin\Debug

PASO 3:

1) make sure all projects are using the same Framework (this is crucial!)

2) in Tools/Options>Debugging>General make sure "Enable Just My Code (Managed Only) is NOT ticked

3) in Tools/Options>Debugging>Symbols clear any cached symbols, untick and delete all folder locations under the "Symbols file (.pdb) locations" listbox except the default "Microsoft Symbol Servers" but still untick it too. Also delete any static paths in the "Cache symbols in this directory" textbox. Click the "Empty Symbols Cache" button. Finally make sure the "Only specified modules" radio button is ticked.

4) in the Build/Configuration Manager menu for all projects make sure the configuration is in Debug mode.

PASO 4:

1) Reiniciar el App Pool en el IIS

2) Eliminar el archivo .suo

3) SI SE ESTA HACIENDO DEBUG DE UNA LIBRERIA, NO TENER EL FUENTE ABIERTO!! dejar que lo abra el debugger cuando llegue al breakpoint


PASO 5:

1) Abrir el archive de registro (RegEdit)

2) Buscar la llave HKEY_LOCALMACHINE -> SOFTWARE -> Microsoft -> Internet Explorer -> Main

3) Agregar la clave "Dword" llamada "TabProcGrowth" y asígnale el valor "0"


PASO 6:

Primero ejecutar la aplicacion.
Luego ir a Debug / Windows / Modules

elegir el assembly que corresponda al sitio (ej, RetWeb.dll)
Click derecho, y seleccionar "Symbol Load Information"

Start debugging, as soon as you've arrived at a breakpoint or used Debug > Break All, use Debug > Windows > Modules. You'll see a list of all the assemblies that are loaded into the process. Locate the one you want to get debug info for. Right-click it and select Symbol Load Information. You'll get a dialog that lists all the directories where it looked for the .pdb file for the assembly. Verify that list against the actual .pdb location. Make sure it doesn't find an old one.

In normal projects, the assembly and its .pdb file should always have been copied by the IDE into the same folder as your .exe. The bin\Debug folder of your project. Make sure you remove one from the GAC if you've been playing with it


WaveEngine: mover un sprite

Recordar que los recursos (wpk) se generan con la utilidad Assets Exporter.
Luego, en visual studio, hay que marcar en las propiedades "Copy if newer"

MyScene.cs

#region Using Statements
using System;
using WaveEngine.Common;
using WaveEngine.Common.Graphics;
using WaveEngine.Common.Math;
using WaveEngine.Components.Cameras;
using WaveEngine.Components.Graphics2D;
using WaveEngine.Components.Graphics3D;
using WaveEngine.Framework;
using WaveEngine.Framework.Graphics;
using WaveEngine.Framework.Resources;
using WaveEngine.Framework.Services;
#endregion

namespace Prueba1_MovimProject
{
    public class MyScene : Scene
    {
        protected override void CreateScene()
        {            
            var camera2D = new FixedCamera2D("Camera2D") { BackgroundColor = Color.Black };
            EntityManager.Add(camera2D);

            Entity player = new Entity()
                    .AddComponent(new Transform2D())
                    .AddComponent(new Sprite("Content/ship.wpk"))
                    .AddComponent(new SpriteRenderer(DefaultLayers.Opaque))
                    .AddComponent(new PlayerBehavior());

            EntityManager.Add(player);
        }

        protected override void Start()
        {
            base.Start();

            // This method is called after the CreateScene and Initialize methods and before the first Update.
        }
    }
}


PlayerBehavior.cs

using System;
using WaveEngine.Common.Input;
using WaveEngine.Framework;
using WaveEngine.Framework.Graphics;
using WaveEngine.Framework.Services;

namespace Prueba1_MovimProject
{
    class PlayerBehavior : Behavior
    {
        [RequiredComponent]
        private Transform2D playerData;

        protected override void Update(TimeSpan gameTime)
        {
            if ((WaveServices.Input.KeyboardState.Up == ButtonState.Pressed))
            {
                playerData.Y -= 5;

            }

            if ((WaveServices.Input.KeyboardState.Down == ButtonState.Pressed))
            {
                playerData.Y += 5;

            }

            if ((WaveServices.Input.KeyboardState.Left== ButtonState.Pressed))
            {
                playerData.X -= 5;

            }

            if ((WaveServices.Input.KeyboardState.Right == ButtonState.Pressed))
            {
                playerData.X += 5;

            }
        }
    }
}


Unipolar Steppers con L298 y Arduino






Conexiones:

Stepper:

Blanco y negro: unirlos y no conectarlos a nada
Amarillo: MOTORA- (del L298)
Rojo: MOTORA+ (del L298)
Naranja: MOTORB- (del L298)
Azul: MOTORB+ (del L298)

ENA: Digital 2 de Arduino
IN1: Digital 3
IN2: Digital 4

ENB: Digital 5
IN3: Digital 6
IN4: Digital 7

VMS: Power del L298: 14v (pero puede ser hasta 35v)

Todas las GND juntas! como siempre!

Codigo arduino:


#include <Stepper.h>
const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 3,4,6,7);          
void setup() {
   myStepper.setSpeed(150);
   int ENA=2;//connected to Arduino's port 2
   int ENB=5;//connected to Arduino's port 5
 
   digitalWrite(ENA,HIGH);//enablae motorA
   digitalWrite(ENB,HIGH);//enable motorB
}
void loop() {
  //horario
  myStepper.step(stepsPerRevolution);
  delay(500);

  // antihorario
  myStepper.step(-stepsPerRevolution);
  delay(500);
}







Cambiar la vista de todas las carpetas en windows

Para cambiar la vista predeterminada en todas las carpetas de windows (por ejemplo, para agregar la columna Descripcion)

1. Abrir la carpeta (ej, c:\windows\microsoft.net\assembly)

2. Sobre cualquier columna, click derecho / Mas... / y elegir la columna (por ejemplo, Descripcion del archivo)

3. Apretar "Alt", luego Herramientas / Opciones de carpeta

4. En la ficha Ver, presionar "Aplicar a las carpetas"

int b=2;

void main()
{
   int j=2;
   j++;
   i++;
}