Formato de fechas al exportar un dataset a XML

Cuando se exporta un dataset a XML, las fechas se formatean según la timezone del equipo donde se está ejecutando la exportación.

Ej, si la fecha es
     2003-04-06T00:00:00

cuando se exporta a XML puede quedar así
     2003-04-06T00:00:00-03:00

En este caso le agregó el GMT -3

Una solución posible es cambiar el DateTimeMode del dataset a Unspecified.
De esta forma, no se incluirá el offset (el -3) en el archivo XML.


System.Data.DataSet data = new DataSet();

// ...

// Iterate the columns and set DataColumn.DateTimeMode
// to DataSetDateTime.Unspecified to remove offset
// when serialized.
foreach (DataTable table in data.Tables)
{
    foreach (DataColumn item in table.Columns)
    {
        // Switching from UnspecifiedLocal to Unspecified
        // is allowed even after the DataSet has rows.
        if (item.DataType == typeof(DateTime) &&
            item.DateTimeMode == DataSetDateTime.UnspecifiedLocal)
        {
            item.DateTimeMode = DataSetDateTime.Unspecified;
        }
    }

}

Fuente: http://blog.scosby.com/post/2013/03/01/Serializing-A-DataSet-With-DateTime-Columns.aspx

Crear un componente con PCB Wizard

http://www.new-wave-concepts.com/files/PWtutor5.pdf


1. Agregar los pads que se necesiten (insert / pad)

2. Ir a Edit / Symbol / Insert Pin y hacer click en el centro de cada pad (esto es lo que permite luego conectar componentes entre si)

3. Ir a View / Coordinates / Origin / Change Origin, y hacer click en la esquina inferior izquierda del componente.

4. Crear con recuadros, circulos, etc, el formato del componente.

5. Seleccionar todo, click derecho, Arrange / Group

6. Hacer click derecho en el componente, ir a Edit / Symbol / Make Symbol, elegir Circuit Symbol, definirle una key (con la que se identificara en el pcb wizard, un nombre y una descripcion)

7. Click derecho en el componente, Symbol / Add to Library, y elegir la libreria en la que se quiere agregar.


CS0103: The name 'Json' does not exist in the current context

Dentro del tag <compilation> agregar lo siguiente:

<assemblies>
            <add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>




Invocar un método por su nombre en C# con Invoke

   Type thisType = this.GetType();

En el caso en que sea un método privado, agregar estos parametros:

   MethodInfo theMethod = thisType.GetMethod("nombre-del-metodo", BindingFlags.NonPublic | BindingFlags.Instance);

Si el método es público:

   MethodInfo theMethod = thisType.GetMethod("nombre-del-metodo");

Para ejecutarlo: (observar que param es el parametro que se le pasa al metodo:

   var msg = (TipoDeDatoQueDevuelveElMetodo)theMethod.Invoke(this, new[] { param });

Ej, si se llama a un actionresult:

   var msg = (TipoDeDatoQueDevuelveElMetodo)theMethod.Invoke(this, new[] { param });


Enviar datos desde javascript hacia un controller con AJAX en MVC

Método #1: Enviar form como JSON y otros parametros

Llamado Ajax

            var f = $("#form_refin").serializeFormJSON();
            var send = { param1: "111", param2: "222", datos: JSON.stringify(f) };
            
            jqxhr2 = $.ajax({
                type: "POST",                
                data: send,
                dataType: "json",
                url: "@Url.Action("Supervision2", "RefinanciacionArrendamiento")",
                beforeSend: function () {
                    //l.start();
                }
            }).fail(function (jqXHR, textStatus) {
                //l.stop();
                alert("Error: " + "Status: " + jqXHR.status + " detalle: " + textStatus + " detalle: " + jqXHR.responseText);
            }).success(function (data) {
                $("#HashSup").val(data);
            });


    (function ($) {
        $.fn.serializeFormJSON = function () {

            var o = {};
            var a = this.serializeArray();
            $.each(a, function () {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };
    })(jQuery);




Controller

using Newtonsoft.Json;
...
...
...

[HttpPost]
public ActionResult Supervision2(string param1, string param2, string datos)
{            

 var refin = JsonConvert.DeserializeObject<RefinanciacionArrendamientoVM>(datos);
}


Método #2: Definir el objeto que se va a enviar manualmente

Llamado Ajax

$("#Modificar").click(function() {
var user = {
Documento: $("#txtDocumento").val(),
Email: $("#txtCorreo").val(),
Nombre: $("#txtNombre").val(),
TipoDoc: $("#drpTipoDoc option:selected").val()
}

jqxhr2 = $.ajax({

type: "POST",
async: false,
data: user,
dataType: "json",
url: "@Url.Action("ModificarUsuarioCreado", "Usuario")",
beforeSend: function () {}
})
.fail(function (jqXHR, textStatus) {})
.success(function (data) {}
);
});


Controller

[HttpPost]
public ActionResult ModificarUsuarioCreado(Usuario user) { ... }


public class Usuario

{
    public string Documento { get; set; }
    public string Email { get; set; }
    public string Nombre { get; set; }
    public string TipoDoc { get; set; }
}


Método #3: Enviar el Modelo completo

De esta forma se puede enviar el modelo desde la vista hacia un controller, cualquiera sea su estructura y complejidad.
Funciona con POST y GET, en este ejemplo se utiliza POST.
*** Tener en cuenta que utilizando este método NO se envían los datos modificados manualmente en el formulario o los datos cargados mediante javascript. Para poder hacer esto, utilizar el método 3 ***

Código en la View

Formulario:

@using Creditos.ViewModels.Liquidaciones
@model RefinanciacionArrendamientoVM
...
...
...    

Llamado Ajax

var model = JSON.parse('@Html.Raw(Json.Encode(Model))');

jqxhr2 = $.ajax({
                type: "POST",
                data: model,
                dataType: "json",
                url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")" 
            }).fail(function (jqXHR, textStatus) {
                $("#arrendContent").html(jqXHR.responseText);
            }).success(function (data) {
                $("#div_mensaje").html(data.MsgError);
            });



Controller

[HttpPost]
public ActionResult Contabilizar(RefinanciacionArrendamientoVM refin) 
...
...
...


Método #4: Enviar el form serializado
De esta forma se pasan todos los datos del formulario (no del modelo, aunque si no se modifican los campos del form, son los mismos)
Este método permite pasar los cambios que se hagan en el formulario (cosa que el método #2 no puede hacer)

Llamado Ajax


jqxhr2 = $.ajax({
        }).fail(function (jqXHR, textStatus) {
            if (data.MsgError == "Refinanciación contabilizada correctamente.") {

    type: "GET",
    data: $('form').serialize(),
    dataType: "json",
    url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")", 
    beforeSend: function () {                    
                  $.blockUI({
                      message: 'Espere por favor...',
                      css: {
                          border: 'none',
                          padding: '15px',
                          backgroundColor: '#000',
                          '-webkit-border-radius': '10px',
                          '-moz-border-radius': '10px',
                          opacity: 0.5,
                          color: '#fff'
                      }
                  });
               }

            $.unblockUI();

            $("#arrendContent").html(jqXHR.responseText);
        }).success(function (data) {
            $.unblockUI();
            $("#div_mensaje").html(data.MsgError);

                $("#btn_contabilizar").attr("disabled", "disabled");

                $("#btn_calcular").attr("disabled", "disabled");
            }                
        });







Cuando se actualizan los datos del modelo en el controller los cambios no se reflejan en la vista

Problema:
Cuando en un action de un controller se modifican datos del modelo y se hace el return View, en la vista no aparecen actualizados dichos datos.

Solución: 
Es necesario hacer ModelState.Remove("nombre-del-atributo")

Por ejemplo:

public ActionResult Prueba(ElModelo m)
{
     m.Nombre = "el nuevo nombre";
     ModelState.Remove("Nombre");
}


Evitar que internet explorer pida confirmación al ejecutar un componente ActiveX

La clase debe implementar la interfaz IObjectSafety.

Para compilarlo:

Ir a prompt de visual studio 2013 (abrirlo como administrador)

Si no hay una strong key, generarla con:
      sn -k keyImpresora.snk

cls
call "%VS120COMNTOOLS%..\Tools\vsvars32.bat"
csc /t:library Impresora.cs /keyfile:keyImpresora.snk
regasm Impresora.dll /tlb:ImpresoraNet.dll /codebase


Código C#

using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Collections.Generic;

namespace X
{
[ComImport()]
[Guid("CB5BDC81-93C1-11CF-8F20-00805F2CD064")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IObjectSafety
{
[PreserveSig()]
int GetInterfaceSafetyOptions(ref Guid riid, out int pdwSupportedOptions, out int pdwEnabledOptions);

[PreserveSig()]
int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions);
}

public enum Estilo
{
Normal,
Bold,
Enlarged,
Condensed
}
public interface IImpresora
{
string Imprimir(string texto, string estilo);
void FormFeed();
void Log(string texto);
string Inicializar(string usuario);
void Agregar(string linea);
void Listar();
}

public class Linea
{
public string Texto {get; set;}
public string Estilo {get; set;}
}

[ProgId("X.Impresora")]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
[ComVisible(true)]
public class Impresora : IObjectSafety
{
bool _fin = false;
string _pathImpresora = "";
List<Linea> lineas;

    private const int INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x00000001;
    private const int INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x00000002;
    private const int S_OK = 0;

    [ComVisible(true)]
    public int GetInterfaceSafetyOptions(ref Guid riid, out int pdwSupportedOptions, out int pdwEnabledOptions)
    {
        pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;
        pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;
        return S_OK;
    }

    [ComVisible(true)]
    public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions)
    {
        return S_OK;
    }

[ComVisible(true)]
public void Agregar(string linea)
{
var l = new Linea();

l.Texto = linea;

lineas.Add(l);
}

[ComVisible(true)]
public void Listar()
{
File.Delete(Environment.GetEnvironmentVariable("TEMP") + "\\outLog.txt");

foreach (var l in lineas)
{
var xx = "";

xx = l.Texto;

xx = xx.Replace((char)13 + "" + (char)10, "");

if (xx.Contains(Convert.ToChar(27) + "(s3B") || xx.Contains(Convert.ToChar(27) + "(s0B"))
{
//evito estas lineas porque hacen bloquear la impresora.
xx = "";
} else
{
xx = xx.Replace( Convert.ToChar(27) + "E" + "", (char)27 + "" + (char)69 + "");
}

Log(xx);
}

EjecutarComando("type %TEMP%\\outLog.txt > " + _pathImpresora);
}

[ComVisible(true)]
public string Inicializar(string usuario)
{
var archivo = @"c:\X_imp\" + usuario + @"\XframePrinter.properties";
var host = "";
var nombreImp = "";


if (File.Exists(archivo))
{
var f = new StreamReader(archivo);
while (!f.EndOfStream)
{
var linea = f.ReadLine();

if (linea.Contains("XframeConnectorService.PrinterDriver.drivers"))
{
var v = linea.Split('=');

host = v[1];
host = host.Substring(0, host.IndexOf(","));

}

if (host != "")
{
if (linea.IndexOf("XframeConnectorService.PrinterDriver." + host + ".port", StringComparison.OrdinalIgnoreCase) >= 0)
{
var v = linea.Split('=');
nombreImp = v[1].Replace("\\", "");
}
}
}
} else
Log("NO EXISTE ARCHIVO DE CONFIG");

var ret = "";

if (host != "" && nombreImp != "")
{
_pathImpresora = @"\\" + host + @"\" + nombreImp;
ret = "OK";
}
else
{
_pathImpresora = "";
ret = "ERROR";
}

if (ret == "OK")
lineas = new List<Linea>();

return ret;
}

private void EjecutarComando(string comando) {
ProcessStartInfo processInfo;
Process proc;
_fin = false;
processInfo = new ProcessStartInfo("cmd.exe", (Convert.ToString("/c ") + comando));
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
processInfo.Verb = "runas";
proc = new Process();
proc.EnableRaisingEvents = true;
proc.StartInfo = processInfo;
proc.OutputDataReceived += OnOutputDataReceived;
proc.Exited += OnProcessExited;
proc.Start();
proc.BeginOutputReadLine();
while (!_fin) {
Thread.Sleep(1);
}

proc.Close();
}


private void OnProcessExited(object sender, EventArgs e) {
_fin = true;
}

private void OnOutputDataReceived(object sender, DataReceivedEventArgs e) {
}

[ComVisible(true)]
public void Log(string texto)
{
var f = new StreamWriter(Environment.GetEnvironmentVariable("TEMP") + "\\outLog.txt", true);

f.WriteLine(texto);

f.Close();
}
}
}

Invocar metodos de un objeto COM desde una página web con javascript - con ejemplo de impresion (call simple ActiveX object installed on the client)

Para compilarlo:

Ir a prompt de visual studio 2013 (abrirlo como administrador)

Si no hay una strong key, generarla con:
      sn -k keyImpresora.snk

cls
call "%VS120COMNTOOLS%..\Tools\vsvars32.bat"
csc /t:library Impresora.cs /keyfile:keyImpresora.snk
regasm Impresora.dll /tlb:ImpresoraNet.dll /codebase


Impresora.cs

using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Collections.Generic;

namespace X
{
public enum Estilo
{
Normal,
Bold,
Enlarged,
Condensed
}
public interface IImpresora
{
string Imprimir(string texto, string estilo);
void FormFeed();
void Log(string texto);
string Inicializar(string usuario);
void Agregar(string linea);
void Listar();
}

public class Linea
{
public string Texto {get; set;}
public string Estilo {get; set;}
}

[ClassInterface(ClassInterfaceType.AutoDual)]
public class Impresora : IImpresora
{
bool _fin = false;
string _pathImpresora = "";
List<Linea> lineas;

public void Agregar(string linea)
{
var l = new Linea();

l.Texto = linea;

lineas.Add(l);
}

public void Listar()
{
var estilo = "normal";
var textoOk = "";

File.Delete("c:\\temp\\outLog.txt");

foreach (var l in lineas)
{
var xx = "";

xx = l.Texto;

xx = xx.Replace((char)13 + "" + (char)10, "");

if (xx.Contains(Convert.ToChar(27) + "(s3B") || xx.Contains(Convert.ToChar(27) + "(s0B"))
{
//evito estas lineas
} else
{
// var xx = l.Texto.Replace( Convert.ToChar(27) + "(s3B", "");
// xx = xx.Replace( Convert.ToChar(27) + "(s0B", "");
xx = xx.Replace( Convert.ToChar(27) + "E" + "", (char)27 + "" + (char)69 + "");
}

Log(xx);
}

EjecutarComando("type c:\\temp\\outLog.txt > " + _pathImpresora);
/*
foreach (var l in lineas)
{
textoOk = "";

for (int i=0; i<l.Texto.Length; i++)
{
if ((int)l.Texto[i] == 12)
{
textoOk += "[FORM FEED]";
i++;
}

if ((int)l.Texto[i] == 27)
{
i++;

if ((int)l.Texto[i] == 69)
{
estilo = "bold";
i++;
} else if ((int)l.Texto[i] == 70)
{
estilo = "normal";
i++;
}
}

textoOk += l.Texto[i];
}

//Log(textoOk + " - " + estilo );
}
*/
}

public string Imprimir(string texto, string estilo)
{
if (estilo == "normal")
ImprimirLinea(texto, Estilo.Normal);

if (estilo == "bold")
ImprimirLinea(texto, Estilo.Bold);

if (estilo == "enlarged")
ImprimirLinea(texto, Estilo.Enlarged);

if (estilo == "condensed")
ImprimirLinea(texto, Estilo.Condensed);

return texto;
}

public void FormFeed()
{
//para que funcione el form feed hay que poner algun caracter antes y despues (en este caso, el signo de menos)
EjecutarComando("echo -" + (char)12 + "- > " + _pathImpresora);
}

public string Inicializar(string usuario)
{
var archivo = @"c:\X_imp\" + usuario + @"\framePrinter.properties";
var host = "";
var nombreImp = "";


if (File.Exists(archivo))
{
var f = new StreamReader(archivo);
while (!f.EndOfStream)
{
var linea = f.ReadLine();

if (linea.Contains("frameConnectorService.PrinterDriver.drivers"))
{
var v = linea.Split('=');

host = v[1];
host = host.Substring(0, host.IndexOf(","));

}

if (host != "")
{
if (linea.IndexOf("frameConnectorService.PrinterDriver." + host + ".port", StringComparison.OrdinalIgnoreCase) >= 0)
{
var v = linea.Split('=');
nombreImp = v[1].Replace("\\", "");
}
}
}
} else
Log("NO EXISTE ARCHIVO DE CONFIG");

var ret = "";

if (host != "" && nombreImp != "")
{
_pathImpresora = @"\\" + host + @"\" + nombreImp;
ret = "OK";
}
else
{
_pathImpresora = "";
ret = "ERROR";
}

if (ret == "OK")
lineas = new List<Linea>();

return ret;
}

private void ImprimirLinea(string texto, Estilo estilo)
{

//(char)27 + (char)15 ---------------- condensado on
//(char)18 --------------------------- condensado off
//(char)27 + (char)87 + (char)49 ----- enlarged on
//(char)27 + (char)87 + (char)48 ----- enlarged off
//(char)27 + (char)69 ---------------- bold on
//(char)27 + (char)70 ---------------- bold off


if (texto.Trim() == "")
{
texto = "(";
estilo = Estilo.Normal;
}
else
texto = " " + texto;

switch (estilo)
{
case Estilo.Normal:
EjecutarComando("echo" + texto + " > " + _pathImpresora);
break;
case Estilo.Bold:
EjecutarComando("echo " + (char)27 + (char)69 + texto + (char)27 + (char)70 + " > " + _pathImpresora);
break;
case Estilo.Enlarged:
EjecutarComando("echo " + (char)27 + (char)87 + (char)49 + texto + (char)27 + (char)87 + (char)48 + " > " + _pathImpresora);
break;
case Estilo.Condensed:
EjecutarComando("echo " + (char)27 + (char)15 + texto + (char)18 + " > " + _pathImpresora);
break;
}
}

private void EjecutarComando(string comando) {
ProcessStartInfo processInfo;
Process proc;
_fin = false;
processInfo = new ProcessStartInfo("cmd.exe", (Convert.ToString("/c ") + comando));
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
processInfo.Verb = "runas";
proc = new Process();
proc.EnableRaisingEvents = true;
proc.StartInfo = processInfo;
proc.OutputDataReceived += OnOutputDataReceived;
proc.Exited += OnProcessExited;
proc.Start();
proc.BeginOutputReadLine();
while (!_fin) {
Thread.Sleep(1);
}

proc.Close();
}
 
private void OnProcessExited(object sender, EventArgs e) {
_fin = true;
}

private void OnOutputDataReceived(object sender, DataReceivedEventArgs e) {
}

public void Log(string texto)
{
var f = new StreamWriter("c:\\temp\\outLog.txt", true);

f.WriteLine(texto);

f.Close();
}
}
}


Version anterior:

Impresora.cs

using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.IO;

namespace X

{
public enum Estilo
{
Normal,
Bold,
Enlarged,
Condensed
}
public interface IImpresora
{
string Imprimir(string texto, string estilo);
void FormFeed();
void Log(string texto);
}

[ClassInterface(ClassInterfaceType.AutoDual)]

public class Impresora : IImpresora
{
bool _fin = false;

public string Imprimir(string texto, string estilo)
{
if (estilo == "normal")
ImprimirLinea(texto, Estilo.Normal);

if (estilo == "bold")

ImprimirLinea(texto, Estilo.Bold);

if (estilo == "enlarged")
ImprimirLinea(texto, Estilo.Enlarged);

if (estilo == "condensed")
ImprimirLinea(texto, Estilo.Condensed);

return texto;
}

public void FormFeed()
{
EjecutarComando("echo " + "ABC" + (char)12 + "ABC" + " > \\\\X00762\\EPSON1");
}

private void ImprimirLinea(string texto, Estilo estilo)
{

//(char)27 + (char)15 ---------------- condensado on
//(char)18 --------------------------- condensado off
//(char)27 + (char)87 + (char)49 ----- enlarged on
//(char)27 + (char)87 + (char)48 ----- enlarged off
//(char)27 + (char)69 ---------------- bold on
//(char)27 + (char)70 ---------------- bold off


if (texto.Trim() == "")
{
texto = "(";
estilo = Estilo.Normal;
}
else
texto = " " + texto;

switch (estilo)
{
case Estilo.Normal: 
EjecutarComando("echo" + texto + " > \\\\X00762\\EPSON1");
break;
case Estilo.Bold: 
EjecutarComando("echo " + (char)27 + (char)69 + texto + (char)27 + (char)70 + " > \\\\X00762\\EPSON1");
break;
case Estilo.Enlarged:
EjecutarComando("echo " + (char)27 + (char)87 + (char)49 + texto + (char)27 + (char)87 + (char)48 + " > \\\\X00762\\EPSON1");
break;
case Estilo.Condensed:
EjecutarComando("echo " + (char)27 + (char)15 + texto + (char)18 + " > \\\\X00762\\EPSON1");
break;
}
}

private void EjecutarComando(string comando) {
ProcessStartInfo processInfo;
Process proc;
_fin = false;
processInfo = new ProcessStartInfo("cmd.exe", (Convert.ToString("/c ") + comando));
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
processInfo.Verb = "runas";
proc = new Process();
proc.EnableRaisingEvents = true;
proc.StartInfo = processInfo;
proc.OutputDataReceived += OnOutputDataReceived;
proc.Exited += OnProcessExited;
proc.Start();
proc.BeginOutputReadLine();
while (!_fin) {
Thread.Sleep(1);
}

proc.Close();
}
  
private void OnProcessExited(object sender, EventArgs e) {
_fin = true;
}

private void OnOutputDataReceived(object sender, DataReceivedEventArgs e) {
}

public void Log(string texto)
{
var f = new StreamWriter("c:\\temp\\outLog.txt", true);

if (texto.IndexOf('\f') >= 0)
f.WriteLine("FORM FEEED!!!!!!");
else
f.WriteLine(texto);

f.Close();
}
}
}

Tester.htm

<html>
<head>
<script language=JavaScript>
var imp = new ActiveXObject('X.Impresora');
alert(imp.Imprimir("Texto PRUEBA"));
</script>
</head>
 <body>
  <h1>Tester.htm</h1>
 </body>
</html>



Fuente: http://forums.asp.net/post/2204437.aspx