示例#1
0
        /// <summary>
        /// Upgrades the driver.
        /// </summary>
        /// <param name="driver">The driver.</param>
        /// <param name="queueName">Name of the queue.</param>
        public void UpgradeDriver(PrintDeviceDriver driver, string queueName)
        {
            if (driver == null)
            {
                throw new ArgumentNullException("driver");
            }

            DateTime start = DateTime.Now;
            DateTime end   = DateTime.Now;

            InstallStatusData status = _installStatus.Create(queueName);

            lock (_driverLock)
            {
                UpdateStatus("Upgrading print driver... " + driver.Name);
                status.Record("DRIVER UPGRADE START", out start);

                // Upgrade the driver, but do not check to see if the driver is installed,
                // this has already been done.
                DriverInstaller.Upgrade(driver.CreateDetail(), queueName);

                status.Record("DRIVER UPGRADE END", out end);
                status.Record("DRIVER UPGRADE TOTAL", end.Subtract(start));
            }
        }
示例#2
0
 private void inboxDriver_DataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
 {
     if (inboxDriver_DataGridView.SelectedRows.Count > 0 && e.RowIndex >= 0)
     {
         _driver = inboxDriver_DataGridView.SelectedRows[0].DataBoundItem as PrintDeviceDriver;
     }
 }
        private void inboxDriver_Button_Click(object sender, EventArgs e)
        {
            using (InboxDriverSelectionForm form = new InboxDriverSelectionForm())
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    PrintDeviceDriver driver = form.PrintDriver;

                    if (driver != null)
                    {
                        string path = _manager.DriverPackagePaths.Add(Path.GetDirectoryName(driver.InfPath));
                        UpdateDriverPathsComboBox();

                        _manager.AddDriver(driver);

                        driverPackagePath_ComboBox.SelectedItem = path;

                        SelectComboBoxItem
                        (
                            driver.Name,
                            driver.Architecture,
                            driver.Version,
                            Path.GetFileName(driver.InfPath)
                        );
                    }
                }
            }
        }
示例#4
0
 private void inboxDriver_DataGridView_DoubleClick(object sender, EventArgs e)
 {
     if (inboxDriver_DataGridView.SelectedRows.Count > 0 && inboxDriver_DataGridView.SelectedRows[0].Index > 0)
     {
         _driver      = inboxDriver_DataGridView.SelectedRows[0].DataBoundItem as PrintDeviceDriver;
         DialogResult = System.Windows.Forms.DialogResult.OK;
         Close();
     }
 }
示例#5
0
 private void viewInf_Button_Click(object sender, EventArgs e)
 {
     if (inboxDriver_DataGridView.SelectedRows.Count > 0 && inboxDriver_DataGridView.SelectedRows[0].Index > 0)
     {
         _driver = inboxDriver_DataGridView.SelectedRows[0].DataBoundItem as PrintDeviceDriver;
         using (TextDisplayDialog textBox = new TextDisplayDialog(File.ReadAllText(_driver.InfPath), _driver.InfPath))
         {
             textBox.ShowDialog();
         }
     }
 }
        /// <summary>
        /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
        /// </summary>
        /// <param name="obj">An object to compare with this instance.</param>
        /// <returns>
        /// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance is less than <paramref name="obj"/>. Zero This instance is equal to <paramref name="obj"/>. Greater than zero This instance is greater than <paramref name="obj"/>.
        /// </returns>
        /// <exception cref="T:System.ArgumentException">
        ///   <paramref name="obj"/> is not the same type as this instance. </exception>
        public int CompareTo(object obj)
        {
            if (obj == null)
            {
                return(1);
            }

            PrintDeviceDriver item = obj as PrintDeviceDriver;

            string left  = this.Name + this.Architecture.ToString() + this.InfPath + this.Version.ToString();
            string right = item.Name + item.Architecture.ToString() + item.InfPath + item.Version.ToString();

            return(string.Compare(left, right, StringComparison.OrdinalIgnoreCase));
        }
        /// <summary>
        /// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
        /// </summary>
        /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
        /// <returns>
        ///     <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
        /// </returns>
        public override bool Equals(object obj)
        {
            if (Object.ReferenceEquals(obj, null))
            {
                return(false);
            }

            PrintDeviceDriver properties = obj as PrintDeviceDriver;

            return
                (properties.Name.Equals(Name, StringComparison.OrdinalIgnoreCase) &&
                 properties.Architecture == Architecture &&
                 properties.Version.Equals(Version) &&
                 properties.InfPath.Equals(InfPath, StringComparison.OrdinalIgnoreCase));
        }
示例#8
0
        private static string GetDefaultConfigFile(PrintDeviceDriver driver)
        {
            string location = string.IsNullOrEmpty(driver.InfPath) ? string.Empty : Path.GetDirectoryName(driver.InfPath);

            string[] driverConfigFiles = Directory.GetFiles(location, "*.cfg");
            int      count             = driverConfigFiles.Count();

            TraceFactory.Logger.Debug("{0} .cfg file(s) found: {1}".FormatWith(count, location));
            if (count == 1)
            {
                return(Path.GetFileNameWithoutExtension(driverConfigFiles.First()));
            }

            //An invalid number of config files were found.
            throw new InvalidOperationException("{0} driver config files found in {1}".FormatWith(driverConfigFiles.Count(), location));
        }
示例#9
0
        /// <summary>
        /// Adds the specified print driver package to the list of available packages
        /// </summary>
        /// <param name="printDriver">The print driver.</param>
        public void AddDriver(PrintDeviceDriver printDriver)
        {
            if (printDriver == null)
            {
                throw new ArgumentNullException("printDriver");
            }

            _currentDriverKey = "{0} [{1}]".FormatWith(printDriver.Name, printDriver.InfPath);

            if (!_printDrivers.ContainsKey(_currentDriverKey))
            {
                _printDrivers.Add(_currentDriverKey, printDriver);
                _generateNewPropertiesSet = true;
            }

            CurrentDriver = printDriver;
        }
        /// <summary>
        /// Upgrades the specified driver name.
        /// </summary>
        /// <param name="upgradeData">The upgrade data.</param>
        /// <param name="newDriver">The new driver.</param>
        public void Upgrade(SortableBindingList <DriverUpgradeData> upgradeData, PrintDeviceDriver newDriver)
        {
            _queueManager.Reset();

            _upgradeData = upgradeData;
            _newDriver   = newDriver;

            TriggerDataUpdateEvent();

            if (_currentDriverName.Equals(_newDriver.Name, StringComparison.OrdinalIgnoreCase))
            {
                foreach (DriverUpgradeData data in _upgradeData)
                {
                    data.Status             = "Not Monitored";
                    data.StartTimeFormatted = string.Empty;
                    data.EndTimeFormatted   = string.Empty;
                    data.Duration           = string.Empty;
                }

                lock (this)
                {
                    _upgradeThread = new Thread(UpgradeSameVersion);
                    _upgradeThread.Start();
                }
            }
            else
            {
                foreach (DriverUpgradeData data in _upgradeData)
                {
                    data.Status             = string.Empty;
                    data.StartTimeFormatted = string.Empty;
                    data.EndTimeFormatted   = string.Empty;
                    data.Duration           = string.Empty;
                }

                lock (this)
                {
                    _upgradeThread = new Thread(UpgradeToNewVersion);
                    _upgradeThread.Start();
                }
            }
        }
示例#11
0
        /// <summary>
        /// Installs the designated driver.
        /// </summary>
        /// <param name="driver">The driver.</param>
        /// <param name="forceInstall">if set to <c>true</c> then an install is forced.</param>
        public void InstallDriver(PrintDeviceDriver driver, bool forceInstall = false)
        {
            if (driver == null)
            {
                throw new ArgumentNullException("driver");
            }

            DateTime start = DateTime.Now;
            DateTime end   = DateTime.Now;

            InstallStatusData status = _installStatus.Create(driver.Name);

            lock (_driverLock)
            {
                UpdateStatus("Installing print driver... " + driver.Name);
                status.Record("DRIVER INSTALL START", out start);
                DriverInstaller.Install(driver.CreateDetail(), forceInstall);
                status.Record("DRIVER INSTALL END", out end);
                _installedDrivers.Add(driver.Name);
                status.Record("DRIVER INSTALL TOTAL", end.Subtract(start));
            }
        }
示例#12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="InstallerPrintDevice" /> class.
 /// </summary>
 /// <param name="driver">The driver.</param>
 /// <param name="port">The port.</param>
 public InstallerPrintDevice(PrintDeviceDriver driver, TcpIPPortInstaller port)
 {
     Driver    = driver;
     Port      = port;
     QueueName = "{0} ({1})".FormatWith(driver.Name, port.PortName);
 }
示例#13
0
        private void CreatePrintQueue(object state)
        {
            _installThreads.Add(Thread.CurrentThread);

            QueueInstallationData queueData = state as QueueInstallationData;
            InstallStatusData     status    = _installStatus.Create(queueData);

            try
            {
                if (queueData.QueueIsInstalled)
                {
                    // This queue is already installed, so return
                    return;
                }

                if (string.IsNullOrEmpty(queueData.Address))
                {
                    UpdateStatus("NO ADDRESS - SKIPPING");
                    status.Record("NO ADDRESS - SKIPPING");
                    return;
                }

                // Install the initial Print Driver for this queue if needed
                PrintDeviceDriver driver = queueData.Driver;

                InstallDriver(driver);

                DateTime queueInstallStart = DateTime.Now;
                status.Record("NEW ENTRY START", out queueInstallStart);

                TcpIPPortInstaller port = TcpIPPortInstaller.CreateRawPortManager
                                          (
                    queueData.Address,
                    portNumber: queueData.Port,
                    portName: "IP_{0}:{1}".FormatWith(queueData.Address, queueData.Port),
                    snmpEnabled: queueData.SnmpEnabled
                                          );

                queueData.Progress = "Working...";
                UpdateStatus("Installing... " + queueData.QueueName);

                TraceFactory.Logger.Debug("UseConfigurationFile: {0}".FormatWith(queueData.UseConfigurationFile));
                if (!queueData.UseConfigurationFile)
                {
                    // Make sure there are no CFM files sitting in the driver directory
                    RemoveConfigFiles(status);
                    RestoreDriverDefaults(driver, status);
                }

                InstallerPrintDevice printDevice = new InstallerPrintDevice(driver, port);
                printDevice.ConfigFile         = (queueData.UseConfigurationFile) ? queueData.ConfigurationFilePath : string.Empty;
                printDevice.QueueName          = queueData.QueueName;
                printDevice.IsSharedQueue      = queueData.Shared;
                printDevice.IsRenderedOnClient = queueData.ClientRender;

                bool         queueCreated = true;
                StatusRecord record       = new StatusRecord(status);
                while (true)
                {
                    if (!SetupPort(printDevice, record, queueData))
                    {
                        queueCreated = false;
                        break;
                    }

                    if (!InstallQueue(printDevice, record, queueData))
                    {
                        queueCreated = false;
                        break;
                    }

                    if (!SetupClientRendering(printDevice, record, queueData))
                    {
                        queueCreated = false;
                        break;
                    }

                    if (!SetupSharing(printDevice, record, queueData))
                    {
                        queueCreated = false;
                        break;
                    }

                    break;
                }

                DateTime queueInstallEnd = DateTime.Now;
                status.Record("NEW ENTRY END", out queueInstallEnd);
                TimeSpan totalTime = queueInstallEnd.Subtract(queueInstallStart);
                status.Record("NEW ENTRY TOTAL", totalTime);

                if (queueCreated)
                {
                    queueData.Progress = "{0:D2}:{1:D2}.{2:D3}".FormatWith(totalTime.Minutes, totalTime.Seconds, totalTime.Milliseconds);
                    UpdateStatus("1");
                    UpdateStatus("Queue creation complete.");
                }
                else
                {
                    queueData.Progress = "ERROR";
                    UpdateStatus("1");
                    UpdateStatus("Queue creation failed.");
                }

                _threadSemaphore.Release();
            }
            catch (Win32Exception ex)
            {
                status.Record("FAILED: " + ex.Message);
                string message = new Win32Exception(ex.NativeErrorCode).Message;
                UpdateStatus("Queue creation failed: {0}".FormatWith(message));
                FireComplete();
                return;
            }
            finally
            {
                _installThreads.Remove(Thread.CurrentThread);
            }
        }
示例#14
0
        /// <summary>
        /// When a .cfm file is applied to a driver installation, the settings propagate to the .cfg file.  So, even when the .cfm file
        /// is removed from the driver install directory, the settings persist.  To complicate things further, sometimes additional .cfg
        /// files are created which have a higher usage priority during queue creation.  For example, if the default config file is hpcpu140.cfg,
        /// in the driver installation directory there may also be hpcpu140_p6.cfg.  The _p6 file has priority over the original .cfg file
        /// during queue creation.  Therefore, when restoring the original default .cfg file, it is necessary to remove all files that start with
        /// "hpcpu140".
        /// The intent of this method is to copy the original .cfg file from the driver location chosen by the user into the driver installation
        /// directory.  We can't just do a File.Copy here because there may be other files related to the .cfg filename that need to be removed.
        /// So the restore is done in 2 phases - delete and copy.
        /// </summary>
        /// <param name="driver">The driver properties</param>
        /// <param name="status">The install status data</param>
        private static void RestoreDriverDefaults(PrintDeviceDriver driver, InstallStatusData status)
        {
            string defaultConfigFile = GetDefaultConfigFile(driver);

            //Remove all cfg files that match the default .cfg file name.
            foreach (string file in Directory.GetFiles(DriverController.SystemVersion3DriverDirectory, "{0}*.cfg".FormatWith(defaultConfigFile)))
            {
                try
                {
                    TraceFactory.Logger.Debug("Deleting {0}".FormatWith(file));
                    File.Delete(file);
                }
                catch (ArgumentException ex)
                {
                    LogDeleteError(status, file, ex);
                }
                catch (IOException ex)
                {
                    LogDeleteError(status, file, ex);
                }
                catch (UnauthorizedAccessException ex)
                {
                    LogDeleteError(status, file, ex);
                }
                catch (NotSupportedException ex)
                {
                    LogDeleteError(status, file, ex);
                }
            }

            // Copy the original .cfg file over to the driver installation location
            string source      = @"{0}\{1}.cfg".FormatWith(driver.Location, defaultConfigFile);
            string destination = @"{0}\{1}.cfg".FormatWith(DriverController.SystemVersion3DriverDirectory, defaultConfigFile);

            if (!File.Exists(destination))
            {
                try
                {
                    TraceFactory.Logger.Debug("Source: {0}".FormatWith(source));
                    TraceFactory.Logger.Debug("Destination: {0}".FormatWith(destination));
                    File.Copy(source, destination, true);
                }
                catch (ArgumentException ex)
                {
                    LogFileCopyError("CFG", ex);
                    throw;
                }
                catch (IOException ex)
                {
                    LogFileCopyError("CFG", ex);
                    throw;
                }
                catch (UnauthorizedAccessException ex)
                {
                    LogFileCopyError("CFG", ex);
                    throw;
                }
                catch (NotSupportedException ex)
                {
                    LogFileCopyError("CFG", ex);
                    throw;
                }
            }
        }
        /// <summary>
        /// Constructs the queue definitions based on the provided list of printer Ids.
        /// </summary>
        /// <param name="printerIds">The printer ids.</param>
        /// <param name="sourceDriver">The driver.</param>
        /// <param name="currentDriver">The driver.</param>
        /// <param name="description">The additional description.</param>
        /// <param name="queueCount">The queue count.</param>
        /// <returns></returns>
        public Collection <QueueInstallationData> Create
        (
            Collection <string> printerIds,
            PrintDeviceDriver sourceDriver,
            PrintDeviceDriver currentDriver,
            string description,
            int queueCount = 1,
            bool fullName  = true
        )
        {
            Collection <QueueInstallationData> queueData = new Collection <QueueInstallationData>();
            StringBuilder queueName = new StringBuilder();

            if (printerIds.Count == 0)
            {
                return(queueData);
            }

            using (AssetInventoryContext context = DbConnect.AssetInventoryContext())
            {
                foreach (Asset asset in context.Assets.Where(n => printerIds.Contains(n.AssetId)))
                {
                    for (int i = 0; i < queueCount; i++)
                    {
                        QueueInstallationData data = new QueueInstallationData();

                        // Assign the driver install data from a collected list of loaded package data
                        // based on the version.
                        data.Driver = sourceDriver;

                        data.AssetId   = asset.AssetId;
                        data.QueueType = asset.AssetType;
                        data.Shared    = true;

                        queueName.Clear();

                        if (asset.AssetType == "Printer")
                        {
                            Printer printer = (Printer)asset;

                            data.Port         = printer.PortNumber;
                            data.Address      = printer.Address1;
                            data.SnmpEnabled  = true;
                            data.ClientRender = false;
                            data.Shared       = true;
                            data.Description  = printer.Description;

                            queueName.Append(printer.Product);
                            queueName.Append(" ").Append(data.AssetId);

                            if (fullName)
                            {
                                queueName.Append(" ").Append(currentDriver.DriverType);
                                queueName.Append(" ").Append(Regex.Replace(currentDriver.VerifyPdl, @"\s+", " "));
                            }

                            if (!string.IsNullOrEmpty(currentDriver.Release))
                            {
                                queueName.Append(" ").Append(Regex.Replace(currentDriver.Release, @"\s+", " "));
                            }

                            // Append the additional description data if it exists
                            if (!string.IsNullOrEmpty(description))
                            {
                                queueName.Append(" ").Append(Regex.Replace(description, @"\s+", " "));
                            }
                        }
                        else if (asset.AssetType == "VirtualPrinter")
                        {
                            VirtualPrinter virtualPrinter = (VirtualPrinter)asset;

                            //Build a shortened version of the asset ID
                            string        addressCode = asset.AssetId.Split('-')[0];
                            AddressParser assetIP     = new AddressParser(virtualPrinter.Address);

                            data.Port         = virtualPrinter.PortNumber;
                            data.Address      = virtualPrinter.Address;
                            data.SnmpEnabled  = virtualPrinter.SnmpEnabled;
                            data.Description  = "Virtual Printer";
                            data.ClientRender = false;
                            data.Shared       = true;

                            queueName.Append(addressCode);
                            queueName.Append("-").Append(assetIP.GetOctet(2));
                            queueName.Append("-").Append(assetIP.GetOctet(3));
                            queueName.Append(" ").Append(currentDriver.DriverType);
                            queueName.Append(" ").Append(Regex.Replace(currentDriver.VerifyPdl, @"\s+", " "));

                            if (!string.IsNullOrEmpty(currentDriver.Release))
                            {
                                queueName.Append(" ").Append(Regex.Replace(currentDriver.Release, @"\s+", " "));
                            }

                            // Append the additional description data if it exists
                            if (!string.IsNullOrEmpty(description))
                            {
                                queueName.Append(" ").Append(Regex.Replace(description, @"\s+", " "));
                            }
                        }

                        data.Key = queueName.ToString();
                        IncrementQueueIndex(data);

                        if (queueCount > 1)
                        {
                            queueName.Append(" ").Append(_queueIndex[data.Key].ToString("D3"));
                        }

                        data.QueueName = queueName.ToString();
                        queueData.Add(data);
                    }
                }
            }

            return(queueData);
        }
        /// <summary>
        /// Constructs the queue definitions based on user provided configuration.
        /// </summary>
        /// <param name="properties">The driver.</param>
        /// <param name="additionalDescription">The additional description.</param>
        /// <param name="ipStartValue">The start value of the last IP octet.</param>
        /// <param name="ipEndValue">The end value of the last IP octet.</param>
        /// <param name="hostName">The hostname.</param>
        /// <param name="numberOfQueues">The number of queues.</param>
        /// <param name="addressCode">The address code.</param>
        /// <param name="incrementIP">if set to <c>true</c> increment IP octet values.</param>
        /// <param name="enableSnmp">if set to <c>true</c> SNMP will be enable on the port.</param>
        /// <param name="renderOnClient">if set to <c>true</c> the render on client option will be set on the queue.</param>
        /// <param name="shareQueues">if set to <c>true</c> the queue will be shared.</param>
        /// <returns>Collection of QueueInstallationData</returns>
        public Collection <QueueInstallationData> Create
        (
            PrintDeviceDriver properties,
            string additionalDescription,
            int ipStartValue,
            int ipEndValue,
            string hostName,
            int numberOfQueues,
            string addressCode,
            bool incrementIP,
            bool enableSnmp,
            bool renderOnClient,
            bool shareQueues
        )
        {
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }
            if (numberOfQueues < 1)
            {
                throw new ArgumentException("numberOfQueues must be a positive, non-zero integer.");
            }
            if (ipStartValue < 1)
            {
                throw new ArgumentException("ipStartValue must be a positive, non-zero integer.");
            }

            Collection <QueueInstallationData> queueData = new Collection <QueueInstallationData>();
            int             currentIPNumber = ipStartValue;
            FrameworkServer vPrintServer    = null;

            using (AssetInventoryContext context = DbConnect.AssetInventoryContext())
            {
                vPrintServer = context.FrameworkServers.FirstOrDefault(n => n.HostName.StartsWith(hostName));
            }

            AddressParser serverIP  = ParseAddress(vPrintServer);
            StringBuilder queueName = new StringBuilder();

            for (int i = 0; i < numberOfQueues; i++)
            {
                queueName.Clear();

                QueueInstallationData data = new QueueInstallationData();
                data.Driver       = properties;
                data.QueueType    = "VirtualPrinter";
                data.AssetId      = "{0}-{1:D5}".FormatWith(addressCode, currentIPNumber);
                data.Address      = serverIP.Prefix + currentIPNumber.ToString();
                data.SnmpEnabled  = enableSnmp;
                data.ClientRender = renderOnClient;
                data.Shared       = shareQueues;

                queueName.Append(addressCode);
                queueName.Append("-").Append(serverIP.GetOctet(2));
                queueName.Append("-").Append(currentIPNumber.ToString("D3"));
                queueName.Append(" ").Append(properties.DriverType);
                queueName.Append(" ").Append(Regex.Replace(properties.VerifyPdl, @"\s+", " "));

                if (!string.IsNullOrEmpty(properties.Release))
                {
                    queueName.Append(" ").Append(Regex.Replace(properties.Release, @"\s+", " "));
                }

                // Append the additional description data if it exists
                if (!string.IsNullOrEmpty(additionalDescription))
                {
                    queueName.Append(" ").Append(Regex.Replace(additionalDescription, @"\s+", " "));
                }

                // Append a queue index if we're reusing the Virtual Printer for multiple queues
                if (incrementIP == false || numberOfQueues > 255)
                {
                    data.Key = queueName.ToString();
                    IncrementQueueIndex(data);
                    queueName.Append(" ").Append(_queueIndex[data.Key].ToString("D3"));
                }

                data.QueueName = queueName.ToString();
                queueData.Add(data);

                if (currentIPNumber == ipEndValue)
                {
                    //Restart the IP number, don't increment
                    currentIPNumber = ipStartValue;
                }
                else if (incrementIP)
                {
                    currentIPNumber++;
                }
            }

            return(queueData);
        }