Esempio n. 1
0
        /// <summary>
        /// Добавить девайс, который использует уже существующие обмены.
        /// Если хотябы 1 обмен из списка не найденн, то выкидываем Exception.
        /// </summary>
        private async Task AddDeviceOptionWithExiststExchangeOptionsAsync(DeviceOption deviceOption)
        {
            //ПРОВЕРКА ОТСУТСВИЯ УСТРОЙСТВА по имени
            if (await IsExistDeviceAsync(deviceOption.Name))
            {
                throw new OptionHandlerException($"Устройство с таким именем уже существует:  {deviceOption.Name}");
            }

            var exceptionStr = new StringBuilder();

            foreach (var exchangeKey in deviceOption.ExchangeKeys)
            {
                if (!await _exchangeOptionRep.IsExistAsync(exchangeOption => exchangeOption.Key == exchangeKey))
                {
                    exceptionStr.AppendFormat("{0}, ", exchangeKey);
                }
            }

            if (!string.IsNullOrEmpty(exceptionStr.ToString()))
            {
                throw new OptionHandlerException($"Не найденны exchangeKeys:  {exceptionStr}");
            }

            await _deviceOptionRep.AddAsync(deviceOption);
        }
        public DeviceOption ToRRInfo()
        {
            var info = new DeviceOption();

            CopyTo(info);
            return(info);
        }
Esempio n. 3
0
        /// <summary>
        /// Добавить девайс, для которого нужно создать 1 или несколько обменов.
        /// Если хотябы для 1 обмена из списка "exchangeOption", не найденн транспорт, то выкидываем Exception.
        /// Если обмен не существует, добавим его, если существует, то игнорируем добавление.
        /// </summary>
        private async Task AddDeviceOptionWithNewExchangeOptionsAsync(DeviceOption deviceOption, IEnumerable <ExchangeOption> exchangeOptions)
        {
            //ПРОВЕРКА ОТСУТСВИЯ УСТРОЙСТВА по имени
            if (await IsExistDeviceAsync(deviceOption.Name))
            {
                throw new OptionHandlerException($"Устройство с таким именем уже существует:  {deviceOption.Name}");
            }

            var exceptionStr         = new StringBuilder();
            var exchangeExternalKeys = exchangeOptions.Select(exchangeOption => exchangeOption.Key).ToList();

            //ПРОВЕРКА СООТВЕТСТВИЯ exchangeKeys, УКАЗАННОЙ В deviceOption, КЛЮЧАМ ИЗ exchangeOptions
            var diff = exchangeExternalKeys.Except(deviceOption.ExchangeKeys).ToList();

            if (diff.Count > 0)
            {
                throw new OptionHandlerException("Найденно несоответсвие ключей указанных для Device, ключам указанным в exchangeOptions");
            }

            //ПРОВЕРКА НАЛИЧИЯ ОБМЕНОВ УКАЗАННЫХ ДЛЯ УС-ВА В СПИСКЕ НОВЫХ ОБМЕНОВ ИЛИ В СПИСКЕ СУЩЕСТВУЮЩИХ ОБМЕНОВ
            foreach (var exchKey in deviceOption.ExchangeKeys)
            {
                if (exchangeExternalKeys.Contains(exchKey) || _exchangeOptionRep.IsExist(e => e.Key == exchKey))
                {
                    continue;
                }
                exceptionStr.AppendFormat("{0}, ", exchKey);
            }
            if (!string.IsNullOrEmpty(exceptionStr.ToString()))
            {
                throw new OptionHandlerException($"ExchangeKeys указанные для устройства не найденны в списке существующих и добавляемых обменов:  {exceptionStr}");
            }

            //ПРОВЕРКА НАЛИЧИЯ УЖЕ СОЗДАНННОГО ТРАНСПОРТА ДЛЯ КАЖДОГО ОБМЕНА
            foreach (var exchangeOption in exchangeOptions)
            {
                if (!await IsExistTransportAsync(exchangeOption.KeyTransport))
                {
                    exceptionStr.AppendFormat("{0}, ", exchangeOption.KeyTransport);
                }
            }
            if (!string.IsNullOrEmpty(exceptionStr.ToString()))
            {
                throw new OptionHandlerException($"Для ExchangeOption не найденн транспорт по ключу:  {exceptionStr}");
            }

            //ДОБАВИМ ТОЛЬКО НОВЫЕ ОБМЕНЫ К РЕПОЗИТОРИЮ ОБМЕНОВ
            foreach (var exchangeOption in exchangeOptions)
            {
                if (!await _exchangeOptionRep.IsExistAsync(exchOpt => exchOpt.Key == exchangeOption.Key))
                {
                    await _exchangeOptionRep.AddAsync(exchangeOption);
                }
            }

            //ДОБАВИТЬ ДЕВАЙС
            await _deviceOptionRep.AddAsync(deviceOption);
        }
        public void Edit(DeviceOption entity)
        {
            var findItem = GetById(entity.Id);

            if (findItem != null)
            {
                var index = DeviceOptions.IndexOf(findItem);
                DeviceOptions[index] = entity;
            }
        }
Esempio n. 5
0
        private void UpdateUsersAndSites(Instrument settings)
        {
            if (settings.Type == DeviceType.GBPLS)   // GBPlus also has no sites or users.
            {
                return;
            }

            // Set the instrument's users.
            _instCtrlr.SetUsers(settings.Users);
            Master.Instance.SwitchService.Instrument.Users = settings.Users;

            if (settings.Type == DeviceType.MX6 || settings.Type == DeviceType.SC)
            {
                // Calling setUsers on an MX6 instrument (tested with v4.10.02) will clear the active
                // user once the instrument is undocked if it is not reset.  Therefore, the active user
                // must always be set to avoid having to check if the users need to change on the
                // instrument in the first place.
                LogUpdate("ActiveUser", settings.ActiveUser, Master.Instance.SwitchService.Instrument.ActiveUser);
                _instCtrlr.SetActiveUser(settings.ActiveUser);
                Master.Instance.SwitchService.Instrument.ActiveUser = settings.ActiveUser;
            }

            // Set the instrument's sites.
            _instCtrlr.SetSites(settings.Sites);
            Master.Instance.SwitchService.Instrument.Sites = settings.Sites;

            if (settings.Type == DeviceType.MX6 || settings.Type == DeviceType.SC)
            {
                // Calling setSites on an MX6 instrument (tested with v4.10.02) will clear the active
                // site once the instrument is undocked if it is not reset.  Therefore, the active site
                // must always be set to avoid having to check if the sites need to change on the
                // instrument in the first place.
                LogUpdate("ActiveSite", settings.ActiveSite, Master.Instance.SwitchService.Instrument.ActiveSite);
                _instCtrlr.SetActiveSite(settings.ActiveSite);
                Master.Instance.SwitchService.Instrument.ActiveSite = settings.ActiveSite;
            }

            // INS-8548 RHP v7.5 - override the instrument specific "User Security Level" multioption with instrument's Activer User's security level
            if (settings.Type == DeviceType.VPRO)
            {
                if (settings.AccessLevel >= 0)
                {
                    DeviceOption option = settings.Options.Find(op => op.Code.StartsWith("USL") && op.Enabled);
                    if (option != null)
                    {
                        settings.Options.Remove(option);
                        // settings.AccessLevel is a nullable short and input may varry from 0 to 10.
                        // The Multi-option code mapptings are 0->USL0, 1 -> USL1 , and so on til 10->USLA. Hence the conversion ToString("X")
                        settings.Options.Add(new DeviceOption("USL" + (settings.AccessLevel ?? 0).ToString("X"), true));
                        LogUpdate("UserSecurityLevel", settings.AccessLevel, option.Code);
                    }
                }
            }
        }
        /// <summary>
        ///     Applies VertexBuffer over pipeline and into device and outputs the buffer onto the screen.
        /// </summary>
        public void Draw()
        {
            var device        = Drawing.Direct3DDevice;
            var deviceOptions =
                new DeviceOption(device).AddRenderState(RenderState.AlphaBlendEnable, true)
                .AddTexture(0, null)
                .AddPixelShader(null)
                .AddRenderState(RenderState.SourceBlend, RenderState.SourceBlendAlpha)
                .AddRenderState(RenderState.DestinationBlend, RenderState.DestinationBlendAlpha)
                .AddStreamSource(0, buffer, 0, Utilities.SizeOf <Vertex>())
                .AddVertexFormat(VertexFormat.PositionRhw | VertexFormat.Diffuse);

            using (new DeviceOptions(deviceOptions))
            {
                device.DrawPrimitives(PrimitiveType.TriangleFan, 0, Resolution);
            }
        }
Esempio n. 7
0
        public Device(DeviceOption option,
                      IEnumerable <IExchange <TIn> > exchanges,
                      IEventBus eventBus,
                      Func <ProduserOption, Owned <IProduser> > produser4DeviceRespFactory,
                      ProduserOption produser4DeviceOption,
                      ILogger logger)
        {
            Option    = option;
            Exchanges = exchanges.ToList();
            _eventBus = eventBus;
            _logger   = logger;

            var produserOwner = produser4DeviceRespFactory(produser4DeviceOption);

            _produserOwner          = produserOwner;         //можно создать/удалить produser в любое время используя фабрику и Owner
            _produser               = produserOwner.Value;
            TopicName4MessageBroker = null;
        }
Esempio n. 8
0
        /// <summary>
        /// Удалим устройство.
        /// Если ключ обмена уникален, то удалим обмен, если в удаляемом обмене уникальный транспорт, то удалим транспорт.
        /// </summary>
        /// <returns>Возвращает все удаленные объекты (Device + Exchanges + Transport)</returns>
        public async Task <OptionAgregator> RemoveDeviceOptionAsync(DeviceOption deviceOption)
        {
            var deletedOptions = new OptionAgregator
            {
                ExchangeOptions  = new List <ExchangeOption>(),
                DeviceOptions    = new List <DeviceOption>(),
                TransportOptions = new TransportOption
                {
                    TcpIpOptions  = new List <TcpIpOption>(),
                    SerialOptions = new List <SerialOption>(),
                    HttpOptions   = new List <HttpOption>()
                }
            };

            //ПРОВЕРКА УНИКАЛЬНОСТИ ОБМЕНОВ УДАЛЯЕМОГО УСТРОЙСТВА (ЕСЛИ УНИКАЛЬНО ТО УДАЛЯЕМ И ОБМЕН, ЕСЛИ ОБМЕН ИСПОЛЬУЕТ УНИКАЛЬНЫЙ ТРАНСПОРТ, ТО УДАЛЯЕМ И ТРАНСПОРТ)
            var exchangeKeys = (await _deviceOptionRep.ListAsync()).SelectMany(option => option.ExchangeKeys).ToList(); //ключи обменов со всех устройств.

            foreach (var exchangeKey in deviceOption.ExchangeKeys)
            {
                if (exchangeKeys.Count(key => key == exchangeKey) == 1)                                                                          //найден обмен используемый только этим устройством
                {
                    var singleExchOption = await _exchangeOptionRep.GetSingleAsync(exc => exc.Key == exchangeKey);

                    if ((await _exchangeOptionRep.ListAsync()).Count(option => option.KeyTransport.Equals(singleExchOption.KeyTransport)) == 1) //найденн транспорт используемый только этим (удаленным) обменом
                    {
                        await RemoveTransportAsync(singleExchOption.KeyTransport, deletedOptions.TransportOptions);                             //Удалить транспорт
                    }
                    deletedOptions.ExchangeOptions.Add(singleExchOption);
                    await _exchangeOptionRep.DeleteAsync(singleExchOption);                                                                      //Удалить обмен
                }
            }

            //УДАЛИМ УСТРОЙСТВО
            deletedOptions.DeviceOptions.Add(deviceOption);
            await _deviceOptionRep.DeleteAsync(deviceOption);

            return(deletedOptions);
        }
Esempio n. 9
0
        /// <summary>
        ///     Applies VertexBuffer over pipeline and into device and outputs the buffer onto the screen.
        /// </summary>
        public void Draw()
        {
            var device        = Drawing.Direct3DDevice;
            var deviceOptions =
                new DeviceOption(device).AddRenderState(RenderState.AlphaBlendEnable, true)
                .AddTexture(0, null)
                .AddPixelShader(null)
                .AddRenderState(RenderState.SourceBlend, RenderState.SourceBlendAlpha)
                .AddRenderState(RenderState.DestinationBlend, RenderState.DestinationBlendAlpha)
                .AddStreamSource(0, buffer, 0, Utilities.SizeOf <Vertex>())
                .AddVertexFormat(VertexFormat.Diffuse | VertexFormat.PositionRhw);

            if (Smooth)
            {
                deviceOptions.AddRenderState(RenderState.MultisampleAntialias, true);
                deviceOptions.AddRenderState(RenderState.AntialiasedLineEnable, true);
            }

            device.Clear(ClearFlags.Target, new ColorBGRA(255f, 255f, 255f, 255f), 0f, 1);
            using (new DeviceOptions(deviceOptions))
            {
                device.DrawPrimitives(PrimitiveType.LineStrip, 0, Resolution);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Добавить опции для устройства в репозиторий.
        /// Если exchangeOptions и transportOption не указанны, то добавляетя устройство с существующими обменами
        /// Если transportOption не указанн, то добавляетя устройство вместе со списом обменов, на уже существйющем транспорте.
        /// Если указанны все аргументы, то добавляется устройство со спсиком новых обменом и каждый обмен использует новый транспорт.
        /// </summary>
        public async Task <bool> AddDeviceOptionAsync(DeviceOption deviceOption, IEnumerable <ExchangeOption> exchangeOptions = null, TransportOption transportOption = null)
        {
            if (deviceOption == null && exchangeOptions == null && transportOption == null)
            {
                return(false);
            }

            if (deviceOption != null && exchangeOptions == null && transportOption == null)
            {
                await AddDeviceOptionWithExiststExchangeOptionsAsync(deviceOption);
            }
            else
            if (deviceOption != null && exchangeOptions != null && transportOption == null)
            {
                await AddDeviceOptionWithNewExchangeOptionsAsync(deviceOption, exchangeOptions);
            }
            else
            if (deviceOption != null && exchangeOptions != null)
            {
                await AddDeviceOptionWithNewExchangeOptionsAndNewTransportOptionsAsync(deviceOption, exchangeOptions, transportOption);
            }

            return(true);
        }
        public async Task EditAsync(DeviceOption entity)
        {
            await Task.CompletedTask;

            Edit(entity);
        }
        /// <summary>
        ///     Draw a circle directly without instancing a new circle, external drawing method.
        /// </summary>
        /// <param name="position">Position to draw the Circle</param>
        /// <param name="radius">Circle Radius</param>
        /// <param name="rotate">Circle Rotation</param>
        /// <param name="type">Circle Type</param>
        /// <param name="resolution">Circle Resolution</param>
        /// <param name="color">Circle Color</param>
        public static void Draw(Vector2 position,
                                float radius,
                                int rotate,
                                CircleType type,
                                int resolution,
                                ColorBGRA color)
        {
            var vertexVertices = new Vertex[resolution + 2];
            var angle          = rotate * System.Math.PI / 180;
            var x  = position.X;
            var y  = position.Y;
            var pi = (type == CircleType.Full)
                ? System.Math.PI
                : (type == CircleType.Half) ? System.Math.PI / 2 : System.Math.PI / 4;
            var device = Drawing.Direct3DDevice;

            #region Circle

            byte[] b   = { color.R, color.G, color.B, color.A };
            var    bgr = BitConverter.ToInt32(b, 0);

            vertexVertices[0] = new Vertex {
                X = x, Y = y, Z = 0f, Rhw = 1f, Color = bgr
            };

            for (var i = 1; i < vertexVertices.Length; ++i)
            {
                vertexVertices[i] = new Vertex
                {
                    X     = (float)(x - radius * System.Math.Cos(pi * ((i - 1) / (resolution / 2.0f)))),
                    Y     = (float)(y - radius * System.Math.Sin(pi * ((i - 1) / (resolution / 2.0f)))),
                    Z     = 0f,
                    Rhw   = 1f,
                    Color = bgr
                };
            }

            #endregion

            #region Set Angle

            for (var i = 0; i < vertexVertices.Length; ++i)
            {
                vertexVertices[i].X =
                    (float)
                    (x + System.Math.Cos(angle) * (vertexVertices[i].X - x) -
                     System.Math.Sin(angle) * (vertexVertices[i].Y - y));
                vertexVertices[i].Y =
                    (float)
                    (y + System.Math.Sin(angle) * (vertexVertices[i].X - x) -
                     System.Math.Cos(angle) * (vertexVertices[i].Y - y));
            }

            #endregion

            #region Buffer

            var buffer = new VertexBuffer(
                device, vertexVertices.Length * Utilities.SizeOf <Vertex>(), Usage.WriteOnly, VertexFormat.Diffuse,
                Pool.Default);

            var vertices = buffer.Lock(0, vertexVertices.Length * Utilities.SizeOf <Vertex>(), LockFlags.None);
            foreach (var v in vertexVertices)
            {
                vertices.Write(v);
            }
            buffer.Unlock();

            #endregion

            #region Draw

            var deviceOptions =
                new DeviceOption(device).AddRenderState(RenderState.AlphaBlendEnable, true)
                .AddTexture(0, null)
                .AddPixelShader(null)
                .AddRenderState(RenderState.SourceBlend, RenderState.SourceBlendAlpha)
                .AddRenderState(RenderState.DestinationBlend, RenderState.DestinationBlendAlpha)
                .AddStreamSource(0, buffer, 0, Utilities.SizeOf <Vertex>())
                .AddVertexFormat(VertexFormat.PositionRhw | VertexFormat.Diffuse);

            using (new DeviceOptions(deviceOptions))
            {
                device.DrawPrimitives(PrimitiveType.TriangleFan, 0, resolution);
            }

            #endregion

            buffer.Dispose();
        }
        public async Task DeleteAsync(DeviceOption entity)
        {
            await Task.CompletedTask;

            Delete(entity);
        }
 public void Delete(DeviceOption entity)
 {
     DeviceOptions.Remove(entity);
 }
        public async Task AddAsync(DeviceOption entity)
        {
            await Task.CompletedTask;

            Add(entity);
        }
 public void Add(DeviceOption entity)
 {
     entity.Id = CalcMaxId() + 1;
     DeviceOptions.Add(entity);
 }
Esempio n. 17
0
            /// <summary>
            /// tif options for black and white tif devices only.
            /// </summary>
            /// <param name="maxStripSize"></param>
            /// Set the maximum (uncompressed) size of a strip. (non-negative integer; default = 0)
            /// <param name="adjustWidth"></param>
            ///  (0 or 1; default = 1)
            ///  If this option set to 1 then, if the requested page width is close to either A4 (1728 columns) or 
            ///  B4 (2048 columns), set the page width to A4 or B4 respectively.
            /// <returns></returns>
            public static DeviceOption[] tif(int maxStripSize, int adjustWidth)
            {
                DeviceOption MaxStripSize = new DeviceOption("-dMaxStripSize=", maxStripSize.ToString());
                DeviceOption AdjustWidth = new DeviceOption("-dAdjustWidth=", adjustWidth.ToString());

                DeviceOption[] Options = new DeviceOption[2];
                Options.SetValue(MaxStripSize, 0);
                Options.SetValue(AdjustWidth, 0);

                return Options;
            }
Esempio n. 18
0
 /// <summary>
 /// Use DefaultOptions() to return an empty DeviceOptions[] array when the output device used 
 /// has no options, or the defaults are to be used.
 /// </summary>
 /// <returns></returns>
 public static DeviceOption[] DefaultOptions()
 {
     DeviceOption[] Options = new DeviceOption[0];
     return Options;
 }
Esempio n. 19
0
            /// <summary>
            /// jpeg output device option for all jpeg devices. (integer from 0 to 100, default 75)
            /// </summary>
            /// <param name="quality"></param>
            /// Sets the quality level according to the widely used IJG quality scale, which balances the extent of 
            /// compression against the fidelity of the image when reconstituted. Lower values drop more information 
            /// from the image to achieve higher compression, and therefore have lower quality when reconstituted.
            /// <returns></returns>
            public static DeviceOption[] jpg(int quality)
            {
                DeviceOption Quality = new DeviceOption("-dJPEGQ=", quality.ToString());

                DeviceOption[] Options = new DeviceOption[1];
                Options.SetValue(Quality, 0);

                return Options;
            }
Esempio n. 20
0
            /// <summary>
            /// pngalpha output device options (RGB color in the form #RRGGBB, default white = #ffffff)
            /// </summary>
            /// <param name="backgroundColor">
            /// For the pngalpha device only, this sets the suggested background color in the PNG bKGD chunk. 
            /// When a program reading a PNG file does not support alpha transparency, the PNG library converts 
            /// the image using either a background color if supplied by the program or the bKGD chunk. 
            /// One common web browser has this problem, so when using color attributes eg: bgcolor="CCCC00" in a body tag on a web page 
            /// this option would need to be set to "#CCCC00" when creating alpha transparent PNG images for use on the page.
            /// </param>
            /// <returns></returns>
            public static DeviceOption[] pngalpha(string backgroundColor)
            {
                DeviceOption BackgroundColor = new DeviceOption("-dBackgroundColor", "16" + backgroundColor);

                DeviceOption[] Options = new DeviceOption[1];
                Options.SetValue(BackgroundColor, 0);

                return Options;
            }
Esempio n. 21
0
 public Device(DeviceOption option, IEnumerable <IExchange> exchanges, IEventBus eventBus)
 {
     Option    = option;
     Exchanges = exchanges.ToList();
     _eventBus = eventBus;
 }
Esempio n. 22
0
        /// <summary>
        /// Returns the Output Device Option parameters
        /// </summary>
        /// <param name="deviceOptions"></param>
        /// <returns></returns>
        public static List<string> GetDeviceOptionParameters(DeviceOption[] deviceOptions)
        {
            List<string> result = new List<string>();

            for (int counter = 0; counter <= deviceOptions.Length - 1; counter++)
            {
                result.Add(String.Concat(deviceOptions[counter].Option, deviceOptions[counter].Value));
            }

            return result;
        }
Esempio n. 23
0
 /// <summary>
 /// The tiffsep device creates multiple output files.
 /// The device creates a single 32 bit composite CMYK file (tiff32nc format) and multiple tiffgray files. 
 /// A tiffgray file is created for each separation.
 /// See description at:
 /// <see cref="http://ghostscript.com/doc/8.54/Devices.htm#TIFF"/>
 /// </summary>
 /// </summary>
 /// <returns></returns>
 public static DeviceOption[] tiffsep()
 {
     DeviceOption[] Options = new DeviceOption[0];
     return Options;
 }
 public void CopyTo(DeviceOption device_option)
 {
     device_option.option_identifier = option_identifier?.ToRRInfo();
     device_option.suboptions        = suboptions?.Select(x => x?.ToRRInfo()).ToList();
 }
Esempio n. 25
0
        /// <summary>
        /// Добавить девайс, для которого нужно создать 1 или несколько обменов.
        /// Если обмен не существует, добавим его, если существует, то добавим существующий.
        /// Если для нового обменна не существует транспорт, то создадим транспорт.
        /// Если хотябы 1 транспорт в "transportOption" уже существует, то выкидываем Exception.
        /// </summary>
        private async Task AddDeviceOptionWithNewExchangeOptionsAndNewTransportOptionsAsync(DeviceOption deviceOption, IEnumerable <ExchangeOption> exchangeOptions, TransportOption transportOption)
        {
            //ПРОВЕРКА ОТСУТСВИЯ УСТРОЙСТВА по имени
            if (await IsExistDeviceAsync(deviceOption.Name))
            {
                throw new OptionHandlerException($"Устройство с таким именем уже существует:  {deviceOption.Name}");
            }

            var exceptionStr         = new StringBuilder();
            var exchangeExternalKeys = exchangeOptions.Select(exchangeOption => exchangeOption.Key).ToList();

            //ПРОВЕРКА СООТВЕТСТВИЯ exchangeKeys, УКАЗАННОЙ В deviceOption, КЛЮЧАМ ИЗ exchangeOptions
            var diff = exchangeExternalKeys.Except(deviceOption.ExchangeKeys).ToList();

            if (diff.Count > 0)
            {
                throw new OptionHandlerException("Найденно несоответсвие ключей указанных для Device, ключам указанным в exchangeOptions");
            }

            //ПРОВЕРКА НАЛИЧИЯ ОБМЕНОВ УКАЗАННЫХ ДЛЯ УС-ВА В СПИСКЕ НОВЫХ ОБМЕНОВ ИЛИ В СПИСКЕ СУЩЕСТВУЮЩИХ ОБМЕНОВ
            foreach (var exchKey in deviceOption.ExchangeKeys)
            {
                if (exchangeExternalKeys.Contains(exchKey) || _exchangeOptionRep.IsExist(e => e.Key == exchKey))
                {
                    continue;
                }
                exceptionStr.AppendFormat("{0}, ", exchKey);
            }
            if (!string.IsNullOrEmpty(exceptionStr.ToString()))
            {
                throw new OptionHandlerException($"ExchangeKeys указанные для устройства не найденны в списке существующих и добавляемых обменов:  {exceptionStr}");
            }

            //ПРОВЕРКА СООТВЕТСТВИЯ ключей exchangeOptions, указанному транспорту transportOption
            var keysByExchange   = exchangeOptions.Select(option => option.KeyTransport);
            var keysBySp         = transportOption.SerialOptions.Select(option => new KeyTransport(option.Port, TransportType.SerialPort));
            var keysByTcpIp      = transportOption.TcpIpOptions.Select(option => new KeyTransport(option.Name, TransportType.TcpIp));
            var keysByHttp       = transportOption.HttpOptions.Select(option => new KeyTransport(option.Name, TransportType.Http));
            var keysAllTransport = new List <KeyTransport>();

            keysAllTransport.AddRange(keysBySp);
            keysAllTransport.AddRange(keysByTcpIp);
            keysAllTransport.AddRange(keysByHttp);
            var diffKeys = keysByExchange.Except(keysAllTransport).ToList();

            if (diffKeys.Count > 0)
            {
                foreach (var diffKey in diffKeys)
                {
                    exceptionStr.AppendFormat("{0}, ", diffKey);
                }
                throw new OptionHandlerException($"Найденно несоответсвие ключей указанных для Обмненов, ключам указанным для транспорта {exceptionStr}");
            }

            //ПРОВЕРКА ОТСУТСВИЯ ДОБАВЛЯЕМОГО ТРАНСПОРТА ДЛЯ КАЖДОГО ОБМЕНА (по ключу KeyTransport). Добавялем только уникальный обмен.
            foreach (var exchangeOption in exchangeOptions)
            {
                if (await IsExistTransportAsync(exchangeOption.KeyTransport))
                {
                    exceptionStr.AppendFormat("{0}, ", exchangeOption.KeyTransport);
                }
            }
            if (!string.IsNullOrEmpty(exceptionStr.ToString()))
            {
                throw new OptionHandlerException($"Для ExchangeOption УЖЕ СУЩЕСТВУЕТ ТАКОЙ ТРАНСПОРТ:  {exceptionStr}");
            }

            //ДОБАВИТЬ ДЕВАЙС, ОБМЕНЫ, ТРАНСПОРТ
            await _deviceOptionRep.AddAsync(deviceOption);

            await _exchangeOptionRep.AddRangeAsync(exchangeOptions);

            if (transportOption.SerialOptions != null)
            {
                await _serialPortOptionRep.AddRangeAsync(transportOption.SerialOptions);
            }
            if (transportOption.TcpIpOptions != null)
            {
                await _tcpIpOptionRep.AddRangeAsync(transportOption.TcpIpOptions);
            }
            if (transportOption.HttpOptions != null)
            {
                await _httpOptionRep.AddRangeAsync(transportOption.HttpOptions);
            }
        }
Esempio n. 26
0
        public List<string> Convert(OutputDevice outputDevice, DeviceOption[] deviceOptions, string inputFileName, string outputPath, string outputFileName, string temporaryFileFolder, int resolution)
        {
            System.Diagnostics.Debug.WriteLine("GhostScript Convert called, inputFileName=" + inputFileName + " temporaryFileFolder=" + temporaryFileFolder);

            InitializePrivateMembers();

            List<string> outputFilenames = new List<string>();

            // Check if input file is supported
            if (!FileTypeSupported(Path.GetExtension(inputFileName)))
            {
                throw (new GhostScriptException((int)ReturnCode.FileTypeNotSupportedByInterpreter, GhostScript.GetGSErrorMessage((int)ReturnCode.FileTypeNotSupportedByInterpreter)));
            }

            // Construct Ouput Filename Template
            string outputFilenameTemplate = Path.Combine(outputPath, outputFileName);

            if (outputFileName.Trim() == String.Empty)
            {
                // Construct output filename template for multipage document
                string filename = Path.GetFileNameWithoutExtension(inputFileName.Replace("%", "_"));
                //filename = String.Concat(filename,  (filename.EndsWith("_") ? String.Empty : "_"));
                outputFilenameTemplate = Path.Combine(outputPath, String.Concat(filename, "%01d.", GetOutputDeviceFileExtension(outputDevice)));
            }

            // Copy source file and perform processing on the copy
            string temporaryInputFilename = Path.Combine(temporaryFileFolder, String.Concat(Guid.NewGuid().ToString("N"), Path.GetExtension(inputFileName)));

            System.IO.File.Copy(inputFileName, temporaryInputFilename, true);

            // Construct Command Parameters to pass to the GhostScript DLL
            List<string> commandList = new List<string>();
            commandList.Add("convert"); //First parameter is ignored
            commandList.Add("-dSAFER");
            commandList.Add("-dBATCH");
            commandList.Add("-dNOPAUSE");
            commandList.Add("-dCOLORSCREEN");
            commandList.Add("-dDOINTERPOLATE");
            commandList.Add("-dTextAlphaBits=4");
            commandList.Add("-dGraphicsAlphaBits=4");
            commandList.Add("-dUseCIEColor");

            // Specify Output Device
            commandList.Add(GetOutputDeviceParameter(outputDevice));

            // Specify Output Device Options
            commandList.AddRange(GetDeviceOptionParameters(deviceOptions));

            // Specify Resolution
            if (resolution > 0)
            {
                commandList.Add(GetResolutionParameter(resolution));
            }

            // other parameters
            //commandList.Add("-c3000000");
            //commandList.Add("setvmthreshold -f");
            //commandList.Add("-r600");                 // Sets DPI resolution where XRES = YRES
            //commandList.Add("-r300x400");             // Sets DPI resolution (-rXRESxYRES) where XRES and YRES are defferent

            // Specify Output File
            commandList.Add(String.Concat("-sOutputFile=", outputFilenameTemplate));

            // Specify Input File
            commandList.Add(temporaryInputFilename);

            // Convert the command list into a string array
            string[] commandParameters = new string[commandList.Count];
            for (int counter = 0; counter <= commandList.Count - 1; counter++)
            {
                commandParameters[counter] = commandList[counter];
            }

            try
            {
                System.Diagnostics.Debug.WriteLine("GhostScript Convert.CallGSDLL");
                // Call GhostScript DLL
                CallGSDll(commandParameters);

                // Construct the result, listing output files in the output folder in the correct order
                string outputFile = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(outputFilenameTemplate.Replace("%01d", String.Empty)));
                string outputFileExtension = Path.GetExtension(outputFilenameTemplate);
                int counter = 1;
                string outputFileNameCheck = String.Concat(outputFile, counter, outputFileExtension);
                while (System.IO.File.Exists(outputFileNameCheck))
                {
                    // Add ouput file name to result
                    outputFilenames.Add(outputFileNameCheck);

                    // Increment counter, we use this number to check for the next file
                    counter++;

                    // Construct next filename to check
                    outputFileNameCheck = String.Concat(outputFile, counter, outputFileExtension);
                }

                RaiseProcessingCompletedEvent(new ProcessingCompletedEventArgs(_PageCount, outputFilenames));
            }
            finally
            {
                // Delete Temporary Input File
                if (System.IO.File.Exists(temporaryInputFilename))
                {
                    try
                    {
                        System.IO.File.Delete(temporaryInputFilename);
                    }
                    catch
                    {
                        // Ignore error the temporary file cannot be deleted
                    }
                }
            }

            System.Diagnostics.Debug.WriteLine("GhostScript Convert outputFileNameCount = " + outputFilenames.Count.ToString());

            return outputFilenames;
        }
Esempio n. 27
0
            /// <summary>
            /// ps options for writing postscript. (Set to 1, 1.5, 2 or 3, default is 2)
            /// </summary>
            /// <param name="languageLevel"></param>
            /// Set the language level of the generated file. 
            /// Language level 1.5 is language level 1 with color extensions. 
            /// Currently language level 3 generates the same PostScript as 2.
            /// <returns></returns>
            public static DeviceOption[] ps(int languageLevel)
            {
                DeviceOption LanguageLevel = new DeviceOption("-dLanguageLevel=", languageLevel.ToString());

                DeviceOption[] Options = new DeviceOption[1];
                Options.SetValue(LanguageLevel, 0);

                return Options;
            }