Implemented VirtualPrinterDriver project

This commit is contained in:
Marco Batzinger 2020-10-19 17:44:50 +02:00
parent f29c84821b
commit 5c87967c3f
125 changed files with 8191 additions and 0 deletions

View file

@ -0,0 +1,15 @@
namespace VirtualPrinter.SetupDriver
{
public static class Defaults
{
/// <summary>
/// The name that appears in the Windows "Printer & Scanner" menu.
/// </summary>
public const string PrinterName = "AMAGNO";
/// <summary>
/// The printer port.
/// </summary>
public const string PrinterPort = "IP_VIRT_PRINTER";
}
}

View file

@ -0,0 +1,125 @@
using System;
using System.IO;
using JetBrains.Annotations;
using VirtualPrinter.Logging;
using VirtualPrinter.Utils;
using static VirtualPrinter.SetupDriver.Windows;
using static VirtualPrinter.SetupDriver.Defaults;
namespace VirtualPrinter.SetupDriver
{
internal class Program
{
private const string InstallCmd = "install";
private const string TestCmd = "test";
private const string ConfigCmd = "config";
private const string UninstallCmd = "uninstall";
private static readonly IVirtualPrinterLogger<Program> Logger = new VirtualPrinterLogger<Program>();
private static void Main([CanBeNull]string[] args)
{
if (args == null || args.Length < 1)
{
NotUseful();
return;
}
switch (args[0])
{
case InstallCmd:
{
if (args.Length < 2)
{
NotUseful();
return;
}
switch (args[1].ToLower())
{
case "xps":
try
{
AddPrinterPort(PrinterPort, "127.0.0.1", 9101);
var isWin7 = Environment.OSVersion.VersionString.Contains("NT 6.1.");
AddPrinter(PrinterName, "Microsoft XPS Document Writer" + (isWin7 ? string.Empty : " v4"), PrinterPort);
}
catch (Exception exception)
{
LogError(exception, "Failed to add xps printer.");
}
break;
case "ps":
try
{
AddPrinterPort(PrinterPort, "127.0.0.1", 9101);
new RegistryRepository().TryGetGhostscriptPath(out var ghostScriptPath);
if (ghostScriptPath == null)
{
throw new ArgumentNullException(nameof(ghostScriptPath), "Ghostscript path could not be found.");
}
AddPrinter(PrinterName, "Ghostscript PDF", PrinterPort, Path.Combine(ghostScriptPath, @"lib\ghostpdf.inf"));
}
catch (Exception exception)
{
LogError(exception, "Failed to add ps printer.");
}
break;
default:
NotUseful();
return;
}
break;
}
case TestCmd: {
TestPrinter(PrinterName);
break;
}
case ConfigCmd: {
try
{
ConfigPrinter(PrinterName);
}
catch (Exception exception)
{
LogError(exception, "Failed to configurate printer {printerName}.", PrinterName);
}
break;
}
case UninstallCmd: {
try
{
DelPrinter(PrinterName);
DelPrinterPort(PrinterPort);
}
catch (Exception exception)
{
LogError(exception, "Failed to uninstall {printerName} on port {printerPort}.", PrinterName, PrinterPort);
}
break;
}
default: {
NotUseful();
break;
}
}
}
private static void NotUseful()
{
var exception = new ArgumentNullException($"Use '{InstallCmd} [PS|XPS]', '{TestCmd}' or '{UninstallCmd}'!");
LogError(exception, "Failed to handle the arguments.");
throw exception;
}
private static void LogError(Exception exception, string message, params object[] args)
{
Logger.Error(exception, message, args);
}
}
}

View file

@ -0,0 +1,21 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("VirtualPrinter.SetupDriver")]
[assembly: AssemblyDescription("The setup for the virtual printer driver")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("12402f90-a2ae-4549-9142-f90650e2082a")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("properties")]

View file

@ -0,0 +1,84 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using VirtualPrinter.Logging;
namespace VirtualPrinter.SetupDriver
{
internal class Shell
{
private static readonly string WinFolder;
private static readonly IVirtualPrinterLogger<Shell> Logger = new VirtualPrinterLogger<Shell>();
static Shell()
{
WinFolder = Environment.GetEnvironmentVariable("windir") ?? @"C:\Windows";
}
[NotNull]
internal static string GetPrintInf()
{
try
{
var winFolder = Environment.GetEnvironmentVariable("windir") ?? @"C:\Windows";
return Path.Combine(winFolder, "inf", "ntprint.inf");
}
catch (Exception exception)
{
LogError(exception, "Cannot get PrintInf");
throw;
}
}
[NotNull]
internal static string GetPrintVbs()
{
try
{
var printScripts = Path.Combine(WinFolder, "System32", "Printing_Admin_Scripts");
return Directory.GetFiles(printScripts, "*port.vbs", SearchOption.AllDirectories).First();
}
catch (Exception exception)
{
LogError(exception, "Cannot get PrintVbs");
throw;
}
}
internal static void Execute([NotNull]string exe, [NotNull]string args)
{
if (exe == null)
{
throw new ArgumentNullException(nameof(exe));
}
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
try
{
Console.WriteLine(exe + " " + args);
using(var proc = Process.Start(exe, args))
{
proc?.WaitForExit();
}
}
catch (Exception exception)
{
LogError(exception, "Cannot execute {exe} with the following args: {args}", exe, args);
}
}
private static void LogError(Exception exception, string message, params object[] args)
{
Logger.Error(exception, message, args);
}
}
}

View file

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{12402F90-A2AE-4549-9142-F90650E2082A}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>VirtualPrinter.SetupDriver</RootNamespace>
<AssemblyName>setupdrv</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\Files\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject>VirtualPrinter.SetupDriver.Program</StartupObject>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
</ItemGroup>
<ItemGroup>
<Compile Include="Defaults.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Shell.cs" />
<Compile Include="Windows.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Common\VirtualPrinter.Logging\VirtualPrinter.Logging.csproj">
<Project>{aa25364d-22d5-44b0-86a5-6fb14c686308}</Project>
<Name>VirtualPrinter.Logging</Name>
</ProjectReference>
<ProjectReference Include="..\..\Common\VirtualPrinter.Utils\VirtualPrinter.Utils.csproj">
<Project>{cd1c8e9d-5335-41ac-b0c0-88fd7c7c55f3}</Project>
<Name>VirtualPrinter.Utils</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="JetBrains.Annotations" Version="2020.1.0" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,93 @@
using System;
using JetBrains.Annotations;
namespace VirtualPrinter.SetupDriver
{
internal static class Windows
{
public static void AddPrinter([NotNull]string name, [NotNull]string model, [NotNull]string port, [CanBeNull]string driver = null)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (port == null)
{
throw new ArgumentNullException(nameof(port));
}
driver = driver ?? Shell.GetPrintInf();
var args = $@"printui.dll,PrintUIEntry /if /b ""{name}"" /f ""{driver}"" /r ""{port}"" /m ""{model}"" /u";
Shell.Execute("rundll32", args);
}
public static void TestPrinter([NotNull]string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
var args = $@"printui.dll,PrintUIEntry /k /n ""{name}""";
Shell.Execute("rundll32", args);
}
public static void ConfigPrinter([NotNull]string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
var args = $@"printui.dll,PrintUIEntry /e /n ""{name}""";
Shell.Execute("rundll32", args);
}
public static void DelPrinter([NotNull]string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
var args = $@"printui.dll,PrintUIEntry /dl /n ""{name}""";
Shell.Execute("rundll32", args);
}
public static void AddPrinterPort([NotNull]string name, [NotNull]string ip, int port, [CanBeNull]string vbs = null)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (ip == null)
{
throw new ArgumentNullException(nameof(ip));
}
vbs = vbs ?? Shell.GetPrintVbs();
var args = $@"""{vbs}"" -a -r {name} -h {ip} -o raw -n {port}";
Shell.Execute("cscript", args);
}
public static void DelPrinterPort([NotNull]string name, [CanBeNull]string vbs = null)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
vbs = vbs ?? Shell.GetPrintVbs();
var args = $@"""{vbs}"" -d -r {name}";
Shell.Execute("cscript", args);
}
}
}