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

Enviar directo a la impresora desde C# (raw printing)



Código Html

<body>
    <object
        name="Hello World"
        classid="clsid:E86A9038-368D-4e8f-B389-FDEF38935B2F"
        codebase="http://localhost/bin/Debug/Test.ActiveX.dll">
    </object>  

    <script type="text/javascript">    
        var hw = new ActiveXObject("Test.ActiveX.PruebaX");
        
alert( hw.imprimir() );
    </script>    
</body>


Código C#

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Reflection;
using System.Diagnostics; 

namespace PruebaX
{
    [Guid("E86A9038-368D-4e8f-B389-FDEF38935B2F")]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    [ComVisible(true)]
    public interface IHelloWorld
    {
        [DispId(0)]
        string Prueba();
        [DispId(1)]
        string Imprimir();

    }

    [ComVisible(true)]
    [ProgId("Test.ActiveX.PruebaX")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(IHelloWorld))]
    public class HelloWorld : IHelloWorld    
    {
        [ComRegisterFunction()]
        public static void RegisterClass(string key)
        {
            // Strip off HKEY_CLASSES_ROOT\ from the passed key as I don't need it
            StringBuilder sb = new StringBuilder(key);
            sb.Replace(@"HKEY_CLASSES_ROOT\ ", ""); // <-- extra space to preserve prettify only.. not in the real code

            // Open the CLSID\{guid} key for write access
            using (RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(), true))
            {
                // And create the 'Control' key - this allows it to show up in 
                // the ActiveX control container 
                using (RegistryKey ctrl = k.CreateSubKey("Control"))
                {
                    ctrl.Close();
                }

                // Next create the CodeBase entry - needed if not string named and GACced.
                using (RegistryKey inprocServer32 = k.OpenSubKey("InprocServer32", true))
                {
                    inprocServer32.SetValue("CodeBase", Assembly.GetExecutingAssembly().CodeBase);
                    inprocServer32.Close();
                }

                // Finally close the main key
                k.Close();
            }
        }

        public string Prueba()
        {
            return "Prueba";
        }

        public string Imprimir()
        {
            EjecutarComando("dir c:\\temp > " + "\"" + "\\\\X00895\\Brother HL-2270DW series" + "\"");

            return "Impresion enviada";
        }


        private void EjecutarComando(string comando)
        {
            ProcessStartInfo processInfo;
            Process proc;

            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.Start();
            proc.BeginOutputReadLine();
            proc.Close();
        }
    }
}

Delay sign a DLL - Firmar una dll con SN y MsBuild desde linea de comando

call "%VS120COMNTOOLS%..\Tools\vsvars32.bat"

IF NOT EXIST "C:\temp\Generados\outGAC\Signed" mkdir "C:\temp\Generados\outGAC\Signed"

IF EXIST "C:\temp\Generados\outGAC\Signed\LibX.dll" del "C:\temp\Generados\outGAC\Signed\LibX.dll"

msbuild.exe "C:\crusso\X\fuentes\desarrollo\_DLL\LibX\LibX.vbproj" /p:TargetFrameworkVersion=v4.5.1;Configuration=Release /tv:4.0 /t:Rebuild /p:OutDir="C:\temp\Generados\outGAC" /p:PreBuildEvent= /p:PostBuildEvent= /p:SignAssembly=true /p:AssemblyOriginatorKeyFile="c:\crusso\X\fuentes\desarrollo\_KEYSTORE\Desarrollo\keyLibX.snk" /p:DelaySign=true

sn -R "C:\temp\Generados\outGAC\LibX.dll" "c:\crusso\X\fuentes\desarrollo\_KEYSTORE\Desarrollo\keyLibX.snk"

gacutil.exe /i "C:\temp\Generados\outGAC\LibX.dll" /f

Crear un drive USB bootable sin utilizar ningùn software


Step 1: Using DISKPART command


  1. Insert your USB flash drive to your running computer. As the first step, we need to run Command Prompt as administrator. To do this, we need to find cmd by typing 'cmd' in the search box on Windows Start Menu. After search result for 'cmd' appears, right click on it and select "Run as administrator".
  2. Type 'diskpart' on Command Prompt (without quotes) and hit Enter. Wait for a while until the DISKPART program run.
  3. Type 'list disk' to view active disks on your computer and hit Enter. There would be seen that the active disks shown as Disk 0 for hard drive and Disk 1 for your USB flashdrive with its total capacity.
  4. Type 'select disk 1' to determine that disk 1 would be processed in the next step then hit Enter.
  5. Type 'clean' and hit Enter to remove all of data in the drive.
  6. Type 'create partition primary' and hit Enter. Creating a primary partition and further recognized by Windows as 'partition 1'.
  7. Type 'select partition 1' an hit Enter. Choosing the 'partition 1' for setting up it as an active partition.
  8. Type 'active' and hit Enter. Activating current partition.
  9. Type 'format fs=ntfs quick' and hit Enter. Formatting current partition as NTFS file system quickly.
  10. Type 'exit' and hit Enter. Leaving DISKPART program but don't close the Command Prompt instead. We would still need it for next proces

Step 2: create the boot sector

Step 2: Creating Boot Sector

Let us assume that the flash / USB drive is the D: drive and the DVD installer located on drive F :. The first step, we will navigate Command Prompt to set installation DVD as its active directory.
  1. By default, Command Prompt's active directory for Administrator permission is on C:\Windows\System32>. We will navigate Command Prompt to set on DVD (F:) as its active directory. Just type 'f:' then hit Enter, and the active directory changed to F:.
  2. Type 'cd boot' and hit Enter. Active directory changed to F:\boot>.
  3. Type 'bootsect /nt60 d:' and hit Enter. Creating boot sector on D: drive (USB flash drive).
  4. Type 'exit' and hit Enter to close the Command Prompt. Until this step we have made a bootable USB drive sucessfully, and the flash drive is ready to be used as a boot media.

Step 3: Copying Installation Files

xcopy f:\*.* d:\ /E /H /F


Fuente: http://www.instructables.com/id/How-to-Create-a-Bootable-USB-Drive-Without-Using-A/?ALLSTEPS

Desinstalar assembly del GAC de .NET


Ejemplo:

Desinstalar la LibX de la carpeta GAC de .NET:



gacutil /u "LibX,Version=3.0.0.0, Culture=neutral, PublicKeyToken=2ebfdc71997c1f40"

la version a especificar en el gacutil es

        v4.0_3.0.0.0__2ebfdc71997c1f40

y el token:

        v4.0_3.0.0.0__2ebfdc71997c1f40

Post build event para instalar dll en GAC sin modificar el fuente

Para poder publicar una DLL en el GAC, es necesario que esté firmada.
Adicionalmente, para poderla utilizar en fuentes cuyo framework es 4.5.1, es necesario recompilarla en dicha versión.

Dado que no es posible firmar la LibX.dll ni actualizar su framework (porque si se hace habría que recompilar todos los fuentes que la utilicen), se definió un post-build event, que realiza las siguientes acciones:

1. Compilar la librería en la versión framework 4.5.1 (dejando la .dll resultante en una carpeta auxiliar)
2. Firmar la .dll con la clave disponible para dicha librería (el archivo keyLibX.snk en este caso)
3. Instalar la .dll firmada en el GAC, mediante gacutil


Este es el código del post-build event:


call "$(DevEnvDir)..\Tools\vsvars32.bat"

IF NOT EXIST c:\temp\$(TargetName)\OutDir mkdir C:\temp\$(TargetName)\OutDir

IF NOT EXIST c:\temp\$(TargetName)\Signed mkdir C:\temp\$(TargetName)\Signed

IF NOT EXIST $(TargetDir)\Signed mkdir $(TargetDir)\Signed

msbuild.exe $(ProjectPath) /p:TargetFrameworkVersion=v4.5.1;Configuration=Release /tv:4.0 /t:Rebuild /p:OutDir=c:\temp\$(TargetName)\Outdir /p:PreBuildEvent= /p:PostBuildEvent=

ildasm.exe $(TargetPath) /out:$(TargetDir)\Signed\$(TargetName).il

ilasm.exe $(TargetDir)\Signed\$(TargetName).il /dll /key=$(ProjectDir)\keyLibX.snk /output=$(TargetDir)\Signed\$(TargetName).dll

gacutil.exe /i $(TargetDir)\Signed\$(TargetName).dll /f


El objetivo de este post-build event, es lograr que una .dll que no esté firmada y en una versión anterior de framework, llegue al GAC con la versión 4.5.1 de framework, sin modificar el fuente del proyecto para no afectar a los otros desarrollos que la utilizan.



Post build event: The command xxx exited with code 9009

Este error ocurre cuando faltan los seteos de entorno de Visual Studio.
Para solucionarlo, en el post build event agregar como 1ra linea esta sentencia:

call "$(DevEnvDir)..\Tools\vsvars32.bat"

Access Denied. An exception of type 'System.Runtime.InteropServices.COMException' occurred in xxx.dll

Al intentar abrir un archivo excel mediante office interop ocurre este error:

An exception of type 'System.Runtime.InteropServices.COMException' occurred in xxx.dll
Microsoft Excel no puede obtener acceso al archivo aaa.xls

-Crear una carpeta llamada Desktop dentro de esta ruta:

    C:\Windows\System32\config\systemprofile

Si se trata de office 32 bits, crearla en esta ubicación

    C:\Windows\SysWOW64\config\systemprofile

-Agregar permisos a esta carpeta, para el usuario que se configure en el app pool (por ej, X\userconnect)

Adicionalmente, el problema puede darse porque el usuario con el que se está ejecutando el app pool no está configurado en la seguridad de los componentes DCOM.

Para configurarlo, ejecutar dcomcnfg.exe


En las propiedades de Microsoft Excel Application, configurar lo siguiente:




En este caso, el app pool se está ejecutando con el usuario X\userconnect


Permisos de inicio y activación:


Permisos de acceso:


Permisos de configuración:


Identidad:












Buscar una tabla en el modelo edmx

Para localizar una tabla en el diagrama de entidades (edmx):

1. Abrir el .edmx

2. Hacer click en la pestaña "Model Browser"

**Si la pestaña Model Browser no está visible, ir a View / Other Windows / Entity Data Model Browser ***




3. Ubicar la tabla en la lista, y luego hacer click derecho y "Show in Diagram"







Customizar proceso de compilación en Visual Studio (ej para quitar readonly)

Ejemplo:

Quitar atributo readonly de la solucion antes de empezar la compilación:

1. Editar el archivo

C:\Program Files (x86)\MSBuild\12.0\Bin\Microsoft.Common.CurrentVersion.targets

***si no deja modificarlo es porque el usuario no tiene permisos sobre este archivo. Editar las propiedades del archivo, luego ir a seguridad y agregar el usuario con permisos sobre el mismo***

2. Buscar el tag <Target Name="BeforeBuild" /> y sustituirlo por lo siguiente

<Target Name="BeforeBuild">
    <Message Text ="Hello World" />
    <Exec Command="calc.exe" />
</Target>

Esto es un ejemplo, cuando se compile un proyecto de .Net, en el output de la compilación aparecerá el mensaje Hello World, y se abrira la calculadora:

Target "BeforeBuild: (TargetId:3)" in file "C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets" from project "c:\temp\PruebaXX\PruebaXX\PruebaXX.csproj" (target "Build" depends on it):
Task "Message" (TaskId:4)
Task Parameter:Text=Hello World (TaskId:4)
Hello World (TaskId:4)
Done executing task "Message". (TaskId:4)


Ejemplo 2: Quitar atributo Readonly de la solución antes de iniciar la compilación

Editar el archivo

C:\Program Files (x86)\MSBuild\12.0\Bin\Microsoft.Common.CurrentVersion.targets

Sustituir
     <Target Name="BeforeBuild" />  
por
     <Target Name="BeforeBuild">  
<Exec Command="attrib -R $(SolutionDir)*.* /S" />  
     </Target>

Sustituir
     <Target Name="BeforeReBuild" />  
por
     <Target Name="BeforeRebuild">
<Exec Command="attrib -R $(SolutionDir)*.* /S" />
     </Target>

Sustituir
     <Target Name="BeforeCompile" />
por
     <Target Name="BeforeCompile">
<Exec Command="attrib -R $(SolutionDir)*.* /S" />  
     </Target>

Sustituir
     <Target Name="BeforeClean" />
por
     <Target Name="BeforeClean">
<Exec Command="attrib -R $(SolutionDir)*.* /S" />
     </Target>


En este link también hay ejemplos para ejecutar código C# dentro del xml

https://www.universalthread.com/ViewPageArticle.aspx?ID=61