Example #1
0
        /// <summary>
        /// Returns a <b>Quadriple Word</b> from this array of bytes starting in <paramref name="start"/>.
        /// </summary>
        /// <param name="data">Target data.</param>
        /// <param name="start">Start byte.</param>
        /// <returns>
        /// A <see cref="T:System.Int64" /> containing the value.
        /// </returns>
        public static long GetQuadrupleWord(this byte[] data, byte start)
        {
            SentinelHelper.ArgumentNull(data);
            SentinelHelper.IsTrue(start + 7 > data.Length);

            return(data.GetDoubleWord(start) | data.GetDoubleWord((byte)(start + 4)) << 32);
        }
Example #2
0
        /// <summary>
        /// Returns the type of axis than represents specified node. Not supported in <c>EPPlus</c> library.
        /// </summary>
        /// <param name="axis"><c>Xml</c> node than represent an axis definition.</param>
        /// <param name="documentHelper">Target xml document helper.</param>
        /// <returns>
        /// A <see cref="KnownAxisType" /> value.
        /// </returns>
        /// <exception cref="T:System.ArgumentNullException">If <paramref name="axis" /> is <c>null</c>.</exception>
        /// <exception cref="T:System.InvalidOperationException">If <paramref name="axis" /> is not an axis.</exception>
        public static KnownAxisType ExtractAxisType(this XmlNode axis, IXmlHelper documentHelper)
        {
            SentinelHelper.ArgumentNull(axis, nameof(axis));
            SentinelHelper.IsFalse(axis.Name.Contains("catAx") || axis.Name.Contains("valAx") || axis.Name.Contains("dateAx"), "Imposible extraer tipo. el nodo no es de tipo eje");

            var idElement = documentHelper.GetXmlNode(axis, "c:axId");
            var valueAttr = idElement.Attributes["val"];

            var value = valueAttr.Value;

            switch (value)
            {
            case "2":
                return(KnownAxisType.PrimaryValueAxis);

            case "3":
                return(KnownAxisType.SecondaryCategoryAxis);

            case "4":
                return(KnownAxisType.SecondaryValueAxis);

            default:
                return(KnownAxisType.PrimaryCategoryAxis);
            }
        }
        /// <summary>
        /// Creates a zip file with specified elements.
        /// </summary>
        /// <param name="elements">Element to zip.</param>
        /// <param name="writer">Writer reference.</param>
        /// <returns>
        /// A <see cref="T:System.String" /> than contains the path to created file.
        /// </returns>
        public static string ToZip(this IDictionary <string, byte[]> elements, IWriter writer)
        {
            SentinelHelper.ArgumentNull(writer);
            SentinelHelper.ArgumentNull(elements);
            SentinelHelper.ArgumentNull(writer.ResponseEx);
            SentinelHelper.ArgumentNull(writer.ResponseEx.ContentDisposition);

            var response = writer.ResponseEx;
            var zipName  = response.ExtractFileName();

            var tempDirectory = FileHelper.TinExportTempDirectory;
            var zipPath       = Path.Combine(tempDirectory, zipName);

            File.Delete(zipPath);

            using (var zip = new ZipFile(zipPath))
            {
                foreach (var element in elements)
                {
                    zip.AddEntry(element.Key, element.Value);
                }

                zip.Save();
            }

            return(zipPath);
        }
Example #4
0
        /// <summary>
        /// Returns stream input as byte array.
        /// </summary>
        /// <param name="stream">Stream to convert.</param>
        /// <param name="closeAfter">if set to <strong>true</strong> close stream after convert it.</param>
        /// <returns>
        /// Array of byte that represent the input stream.
        /// </returns>
        public static byte[] AsByteArray(this Stream stream, bool closeAfter)
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly: iTin.Core, Namespace: iTin.Core, Class: StreamExtensions");
            Logger.Instance.Debug(" Returns stream input as byte array");
            Logger.Instance.Debug($" > Signature: ({typeof(byte[])}) AsByteArray(this {typeof(Stream)}, {typeof(bool)})");

            SentinelHelper.ArgumentNull(stream, nameof(stream));
            Logger.Instance.Debug($"   > stream: {stream.Length} byte(s)");
            Logger.Instance.Debug($"   > closeAfter: {closeAfter}");

            byte[] buffer   = new byte[stream.Length];
            long   position = stream.Position;

            stream.Seek(0L, SeekOrigin.Begin);
            stream.Read(buffer, 0, (int)stream.Length);
            stream.Seek(position, SeekOrigin.Begin);

            if (closeAfter)
            {
                stream.Close();
            }

            Logger.Instance.Debug($"  > Output: {buffer.Length} byte(s) [{buffer[0]} {buffer[1]} {buffer[2]} ...]");

            return(buffer);
        }
        /// <inheritdoc />
        /// <summary>
        /// Gets the property collection for this structure.
        /// </summary>
        /// <param name="properties">Collection of properties of this structure.</param>
        protected override void Parse(SmbiosPropertiesTable properties)
        {
            #region validate parameter/s
            SentinelHelper.ArgumentNull(properties);
            #endregion

            #region values
            properties.Add(DmiProperty.MemoryChannel.ChannelType, GetChannelType(ChannelType));
            properties.Add(DmiProperty.MemoryChannel.MaximunChannelLoad, MaximunChannelLoad);

            byte n = Count;
            if (n != 0x00)
            {
                if (HeaderInfo.Length >= 0x08)
                {
                    byte[] containedElementsArray = new byte[n * 3];
                    Array.Copy(HeaderInfo.RawData, 0x07, containedElementsArray, 0, n * 3);

                    IEnumerable <MemoryChannelElement> containedElements = GetContainedElements(containedElementsArray, n);
                    properties.Add(DmiProperty.MemoryChannel.Devices, new MemoryChannelElementCollection(containedElements));
                }
            }

            #endregion
        }
Example #6
0
        /// <summary>
        /// Returns the current state of the specified bit.
        /// </summary>
        /// <param name="value">Reference value.</param>
        /// <param name="bit">Bit to retrieve.</param>
        /// <returns>
        /// Returns <c>1</c> if specified bit is active; otherwise <c>0</c>.
        /// </returns>
        public static byte GetBit(this ulong value, Bits bit)
        {
            SentinelHelper.IsEnumValid(bit);
            SentinelHelper.IsTrue((byte)bit > 63);

            return(value.GetBit((byte)bit));
        }
        /// <inheritdoc />
        /// <summary>
        /// Gets the property collection for this structure.
        /// </summary>
        /// <param name="properties">Collection of properties of this structure.</param>
        protected override void Parse(SmbiosPropertiesTable properties)
        {
            #region validate parameter/s
            SentinelHelper.ArgumentNull(properties);
            #endregion

            #region versions

            #region 2.0+ - 3.1.1
            properties.Add(DmiProperty.ManagementControllerHostInterface.InterfaceType, GetInterfaceType(InterfaceType));
            #endregion

            #region 3.2+
            if (HeaderInfo.Length >= 0x07)
            {
                properties.Add(DmiProperty.ManagementControllerHostInterface.InterfaceTypeSpecificData, InterfaceTypeSpecificData);
            }

            if (HeaderInfo.Length >= 0x08 + InterfaceTypeSpecificDataLenght)
            {
                properties.Add(DmiProperty.ManagementControllerHostInterface.Protocols, new ManagementControllerHostInterfaceProtocolRecordsCollection(GetProtocolRecords()));
            }
            #endregion

            #endregion
        }
Example #8
0
        /// <summary>
        /// Parse an <see cref="T:System.String" /> and replace the special chars defined in <paramref name="specialChars"/> by a hexadecimal pattern.
        /// </summary>
        /// <param name="value"><see cref="T:System.String" /> to parse</param>
        /// <param name="specialChars">Special chars to replace</param>
        /// <returns>
        /// The parsed string.
        /// </returns>
        /// <remarks>
        /// Analyzes the argument <paramref name="value"/>, replacing <paramref name="specialChars"/> by the pattern '_x####_', where:
        /// ####: Represents ASCII char code in Hexadecimal format
        /// If the argument <paramref name="value"/> does not contain any special characters returns the argument unchanged.
        /// </remarks>
        public static string Parse(string value, IEnumerable <char> specialChars)
        {
            SentinelHelper.ArgumentNull(value);

            if (specialChars == null)
            {
                return(value);
            }

            var parsedField = value;
            var chars       = specialChars.ToList();

            foreach (var specialchar in chars)
            {
                if (!value.StartsWith(specialchar.ToString(CultureInfo.InvariantCulture), StringComparison.Ordinal))
                {
                    continue;
                }

                var charAsString = specialchar.ToString(CultureInfo.InvariantCulture);
                var asciicode    = Encoding.ASCII.GetBytes(charAsString)[0];
                var cleanedfield = value.Replace(charAsString, string.Empty);
                parsedField = $"_x{asciicode.ToString("x4", CultureInfo.InvariantCulture).ToUpper(CultureInfo.InvariantCulture)}_{cleanedfield}";
            }

            return(parsedField);
        }
        /// <inheritdoc />
        /// <summary>
        /// Gets the property collection for this structure.
        /// </summary>
        /// <param name="properties">Collection of properties of this structure.</param>
        protected override void Parse(SmbiosPropertiesTable properties)
        {
            #region validate parameter/s
            SentinelHelper.ArgumentNull(properties);
            #endregion

            #region values
            properties.Add(DmiProperty.MemoryController.ErrorDetectingMethod, GetErrorDetectingMethod(ErrorDetectingMethod));
            properties.Add(DmiProperty.MemoryController.ErrorCorrectingCapabilities, GetErrorCorrectingCapability(ErrorCorrectingCapabilities));
            properties.Add(DmiProperty.MemoryController.SupportedInterleave, GetControllerInterleave(SupportedInterleave));
            properties.Add(DmiProperty.MemoryController.CurrentInterleave, GetControllerInterleave(CurrentInterleave));
            properties.Add(DmiProperty.MemoryController.MaximumMemoryModuleSize, MaximumMemoryModuleSize);
            properties.Add(DmiProperty.MemoryController.SupportedSpeeds, GetControllerSupportedSpeeds(SupportedSpeeds));
            properties.Add(DmiProperty.MemoryController.SupportedMemoryTypes, GetControllerSupportedTypes(SupportedMemoryTypes));
            properties.Add(DmiProperty.MemoryController.MemoryModuleVoltages, GetControllerModuleVoltages(MemoryModuleVoltages));

            byte n = NumberMemorySlots;
            properties.Add(DmiProperty.MemoryController.NumberMemorySlots, n);

            if (n != 0x00)
            {
                int    m = n << 1;
                byte[] containedElementsArray = new byte[m];
                Array.Copy(HeaderInfo.RawData, 0x0f, containedElementsArray, 0, m);

                IEnumerable <int> containedElements = GetContainedMemoryModules(containedElementsArray);
                properties.Add(DmiProperty.MemoryController.ContainedMemoryModules, new MemoryControllerContainedElementCollection(containedElements));

                if (HeaderInfo.Length >= 0x10 + m)
                {
                    properties.Add(DmiProperty.MemoryController.EnabledErrorCorrectingCapabilities, GetErrorCorrectingCapability(HeaderInfo.RawData[0x0f + m]));
                }
            }
            #endregion
        }
Example #10
0
        /// <summary>
        /// Returns a new <see cref="T:iTin.Utilities.Pdf.ComponentModel.OutputResult" /> reference thats represents a one <b>unique zip stream</b> that contains the same entries in <param ref="items"/>
        /// but compressed individually using the name in <param ref="filenames"/>.
        /// </summary>
        /// <param name="items">Items</param>
        /// <param name="filenames">Item filenames.</param>
        /// <returns>
        /// A <see cref="T:iTin.Core.ComponentModel.OutputResult" /> reference that contains action result.
        /// </returns>
        public static OutputResult CreateJoinResult(this IEnumerable <PdfInput> items, IEnumerable <string> filenames)
        {
            IList <PdfInput> elementList = items as IList <PdfInput> ?? items.ToList();

            SentinelHelper.ArgumentNull(elementList, nameof(elementList));

            IList <string> filenameList = filenames as IList <string> ?? filenames.ToList();

            SentinelHelper.ArgumentNull(filenameList, nameof(filenameList));

            try
            {
                Stream zippedStream = elementList.ToStreamEnumerable().AsZipStream(filenameList);
                zippedStream.Position = 0;
                return
                    (OutputResult.CreateSuccessResult(
                         new OutputResultData
                {
                    Zipped = true,
                    Configuration = null,
                    UncompressOutputStream = zippedStream
                }));
            }
            catch (Exception e)
            {
                return(OutputResult.FromException(e));
            }
        }
Example #11
0
        /// <inheritdoc />
        /// <summary>
        /// Gets the property collection for this structure.
        /// </summary>
        /// <param name="properties">Collection of properties of this structure.</param>
        protected override void Parse(SmbiosPropertiesTable properties)
        {
            #region validate parameter/s
            SentinelHelper.ArgumentNull(properties);
            #endregion

            #region values
            properties.Add(DmiProperty.SystemReset.Capabilities.Status, Status);
            properties.Add(DmiProperty.SystemReset.Capabilities.BootOption, GetBootOption(BootOption));
            properties.Add(DmiProperty.SystemReset.Capabilities.BootOptionOnLimit, GetBootOption(BootOptionOnLimit));
            properties.Add(DmiProperty.SystemReset.Capabilities.WatchdogTimer, WatchdogTimer);

            if (ResetCount != 0xffff)
            {
                properties.Add(DmiProperty.SystemReset.ResetCount, ResetCount);
            }

            if (ResetLimit != 0xffff)
            {
                properties.Add(DmiProperty.SystemReset.ResetLimit, ResetLimit);
            }

            if (TimerInterval != 0xffff)
            {
                properties.Add(DmiProperty.SystemReset.TimerInterval, TimerInterval);
            }

            if (TimeOut != 0xffff)
            {
                properties.Add(DmiProperty.SystemReset.Timeout, TimeOut);
            }
            #endregion
        }
        /// <summary>
        /// Returns the current state of the specified bit.
        /// </summary>
        /// <param name="value">Reference value.</param>
        /// <param name="bit">Bit to check.</param>
        /// <returns>
        /// Returns <b>1</b> if specified bit is active; otherwise <b>0</b>.
        /// </returns>
        public static uint GetBit(this uint value, Bits bit)
        {
            SentinelHelper.IsEnumValid(bit);
            SentinelHelper.IsTrue((byte)bit > 31);

            return(value.GetBit((byte)bit));
        }
        /// <summary>
        /// Returns a value indicating whether the specified bit is enabled.
        /// </summary>
        /// <param name="value">Reference value.</param>
        /// <param name="bit">Bit to check.</param>
        /// <returns>
        /// <b>true</b> if specified <paramref name="bit" /> is enabled; otherwise, <b>false</b>.
        /// </returns>
        public static bool CheckBit(this long value, Bits bit)
        {
            SentinelHelper.IsEnumValid(bit);
            SentinelHelper.IsTrue((byte)bit > 63);

            return(value.CheckBit((byte)bit));
        }
Example #14
0
        /// <summary>
        /// Gets a <b>Word</b> from this array of bytes. ( { a, b, n, n + 1, ...}, n ) => (n + 1, n)
        /// </summary>
        /// <param name="data">Target data.</param>
        /// <param name="start">Start byte.</param>
        /// <returns>
        /// A <see cref="T:System.Int32" /> containing the value.
        /// </returns>
        public static int GetWord(this byte[] data, byte start)
        {
            SentinelHelper.ArgumentNull(data);
            SentinelHelper.IsTrue(start + 1 > data.Length);

            return(data[start] | data[start + 1] << 8);
        }
Example #15
0
        /// <summary>
        /// Returns a new <see cref="Image"/> rotated by the specified orientation.
        /// </summary>
        /// <param name="image"><see cref="Image"/> to be rotated.</param>
        /// <param name="style">New orientation.</param>
        /// <returns>
        /// Returns a new <see cref="Image"/> rotated by the specified orientation..
        /// </returns>
        public static Image Flip(this Image image, FlipStyle style)
        {
            SentinelHelper.IsEnumValid(style);

            if (image == null)
            {
                return(null);
            }

            var flipImage = (Image)image.Clone();

            switch (style)
            {
            case FlipStyle.None:
                flipImage.RotateFlip(RotateFlipType.RotateNoneFlipNone);
                break;

            case FlipStyle.X:
                flipImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
                break;

            case FlipStyle.Y:
                flipImage.RotateFlip(RotateFlipType.RotateNoneFlipY);
                break;

            case FlipStyle.XY:
                flipImage.RotateFlip(RotateFlipType.RotateNoneFlipXY);
                break;
            }

            return(flipImage);
        }
Example #16
0
        /// <summary>
        /// Returns a new <see cref="T:System.Drawing.Image"/> with the specified effect.
        /// </summary>
        /// <param name="image">Image object to which the effect is applied.</param>
        /// <param name="effect">Effect type.</param>
        /// <returns>
        /// Returns a new <see cref="T:System.Drawing.Image"/>, result of applying the effect to specified image .
        /// </returns>
        public static Image ApplyEffect(this Image image, KnownEffectType effect)
        {
            SentinelHelper.ArgumentNull(image);

            Image imageWithEffect;

            using (var bmp = new Bitmap(image.Width, image.Height))
            {
                using (var graphics = Graphics.FromImage(bmp))
                {
                    bmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
                    graphics.DrawImage(
                        image,
                        new Rectangle(0, 0, bmp.Width, bmp.Height),
                        0,
                        0,
                        bmp.Width,
                        bmp.Height,
                        GraphicsUnit.Pixel,
                        ImageHelper.GetImageAttributesFromEffect(effect));
                    imageWithEffect = (Image)bmp.Clone();
                }
            }

            return(imageWithEffect);
        }
        /// <summary>
        /// Writes a error comment for specified cell.
        /// </summary>
        /// <param name="cell">Cell to try apply specified comment.</param>
        /// <param name="value">Reference to value information.</param>
        public static void AddErrorComment(this ExcelRangeBase cell, FieldValueInformation value)
        {
            SentinelHelper.ArgumentNull(cell, nameof(cell));
            SentinelHelper.ArgumentNull(value, nameof(value));

            var comment = value.Comment;

            if (comment == null)
            {
                return;
            }

            var showComment = comment.Show == YesNo.Yes;

            if (!showComment)
            {
                return;
            }

            var font         = comment.Font;
            var text         = $"{comment.Text} {value.Value}";
            var autorComment = $"{Environment.MachineName}\\{Environment.UserName}";

            var cellComment = cell.AddComment(text, autorComment);

            cellComment.Font.Size      = font.Size;
            cellComment.Font.FontName  = font.Name;
            cellComment.Font.Color     = font.GetColor();
            cellComment.Font.Bold      = font.Bold == YesNo.Yes;
            cellComment.Font.Italic    = font.Italic == YesNo.Yes;
            cellComment.Font.UnderLine = font.Underline == YesNo.Yes;
        }
Example #18
0
        /// <summary>
        /// Transforms the <strong>XML</strong> input information in another xml defined in the configuration.
        /// </summary>
        /// <param name="inputUri">Contains information to transform.</param>
        /// <param name="settings">Configuration data export.</param>
        /// <exception cref="T:System.IO.FileNotFoundException">Occurs if not found file path.</exception>
        public static void Transform(this Uri inputUri, ExportSettings settings)
        {
            SentinelHelper.ArgumentNull(inputUri);
            SentinelHelper.ArgumentNull(settings);
            SentinelHelper.ArgumentNull(settings.OutputFile, Resources.ErrorMessage.PathNotNull);
            SentinelHelper.ArgumentNull(settings.TransformFile, Resources.ErrorMessage.PathNotNull);

            var input  = inputUri.OriginalString;
            var output = settings.OutputFile.OriginalString;
            var xslt   = settings.TransformFile.OriginalString;

            var existInput = File.Exists(input);

            if (!existInput)
            {
                throw new FileNotFoundException(Resources.ErrorMessage.InputFileNotFound);
            }

            var existXslt = File.Exists(xslt);

            if (!existXslt)
            {
                throw new FileNotFoundException(Resources.ErrorMessage.TransformFileNotFound);
            }

            var transform = new XslCompiledTransform();

            transform.Load(xslt);
            transform.Transform(input, output);
        }
Example #19
0
        /// <summary>
        /// Returns the specified byte.
        /// </summary>
        /// <param name="value">Reference value.</param>
        /// <param name="onebyte">Byte to retrieve.</param>
        /// <returns>
        /// A <see cref="T:System.Byte"/> that contains the result.
        /// </returns>
        public static byte GetByte(this ulong value, Bytes onebyte)
        {
            SentinelHelper.IsEnumValid(onebyte);
            SentinelHelper.IsTrue((byte)onebyte > 7);

            return(value.GetByte((byte)onebyte));
        }
Example #20
0
        /// <summary>
        /// Retrieves <c>Xml</c> content of specified <paramref name="table" /> in a file.
        /// </summary>
        /// <param name="fileName">Target filename</param>
        /// <param name="table">Table to retrieve</param>
        /// <returns>
        /// A collection of <see cref="T:System.Xml.Linq.XElement"/> that contains the table content as <strong>XML</strong>.
        /// </returns>
        protected static IEnumerable <XElement> LoadXmlFromFile(string fileName, string table)
        {
            SentinelHelper.IsTrue(string.IsNullOrEmpty(table));
            SentinelHelper.IsTrue(string.IsNullOrEmpty(fileName));

            IEnumerable <XElement> nodes = null;

            using (var stream = new FileStream(iTin.Core.IO.Path.PathResolver(fileName), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
            {
                var reader   = new XmlTextReader(stream);
                var document = XDocument.Load(reader);
                var root     = document.Root;
                if (root != null)
                {
                    nodes = table == "*"
                        ? root.Elements()
                        : root.Elements(table);
                }

                ////var query = from element in root.Elements()
                ////            group element.Attributes().FirstOrDefault() by element.Name;
                ////var qq = from e in query let c = e.Count() where c > 1 select e.GetEnumerator();
                ////var vvvv = qq.Cast<XAttribute>().ToList();
            }

            return(nodes);
        }
Example #21
0
        public static MemoryStream ToMemoryStream(this Stream stream)
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly: iTin.Core, Namespace: iTin.Core, Class: StreamExtensions");
            Logger.Instance.Debug($" Convert a Stream into {typeof(MemoryStream)}");
            Logger.Instance.Debug($" > Signature: ({typeof(MemoryStream)}) ToMemoryStream(this {typeof(Stream)})");

            SentinelHelper.ArgumentNull(stream, nameof(stream));
            Logger.Instance.Debug($"   > stream: {stream.Length} byte(s)");

            MemoryStream resultStream;
            MemoryStream tempStream = null;

            try
            {
                tempStream = new MemoryStream();
                tempStream.SetLength(stream.Length);
                stream.Read(tempStream.GetBuffer(), 0, (int)stream.Length);
                tempStream.Flush();

                resultStream = tempStream;
                tempStream   = null;
            }
            finally
            {
                tempStream?.Dispose();
            }

            Logger.Instance.Debug($" > Output: {resultStream.Length} byte(s)");

            return(resultStream);
        }
Example #22
0
        /// <summary>
        /// Create or return an element with the specified Prefix, LocalName and NamespaceUri, and adds it to the document in the specified node.
        /// </summary>
        /// <param name="root">The root node of new element.</param>
        /// <param name="prefix">The prefix of the new element.</param>
        /// <param name="localName">The local name of the new element.</param>
        /// <param name="namespaceUri">The namespace URI of the new element.</param>
        /// <returns>
        /// The new <see cref="System.Xml.XmlNode" />.
        /// </returns>
        /// <exception cref="T:System.ArgumentNullException">If <paramref name="root" /> is <c>null</c>.</exception>
        /// <exception cref="T:System.InvalidOperationException">If <paramref name="prefix" /> is empty.</exception>
        /// <exception cref="T:System.InvalidOperationException">If <paramref name="prefix" /> length is less than 1.</exception>
        /// <exception cref="T:System.InvalidOperationException">If <paramref name="localName" /> is empty.</exception>
        /// <exception cref="T:System.InvalidOperationException">If <paramref name="localName" /> length is less than 1.</exception>
        /// <exception cref="T:System.InvalidOperationException">If <paramref name="namespaceUri" /> is empty.</exception>
        /// <exception cref="T:System.InvalidOperationException">If <paramref name="namespaceUri" /> length is less than 1.</exception>
        public static XmlNode CreateOrDefaultAndAppendElementToNode(XmlNode root, string prefix, string localName, string namespaceUri)
        {
            SentinelHelper.ArgumentNull(root);

            SentinelHelper.IsTrue(string.IsNullOrEmpty(prefix), "No puede estar vacio");
            SentinelHelper.IsTrue(prefix.Length < 1, "La longitud minima ha de ser 1");

            SentinelHelper.IsTrue(string.IsNullOrEmpty(localName), "No puede estar vacio");
            SentinelHelper.IsTrue(localName.Length < 1, "La longitud minima ha de ser 1");

            SentinelHelper.IsTrue(string.IsNullOrEmpty(namespaceUri), "No puede estar vacio");
            SentinelHelper.IsTrue(namespaceUri.Length < 1, "La longitud minima ha de ser 1");

            var element = new StringBuilder();

            element.Append(prefix);
            element.Append(":");
            element.Append(localName);

            var exist    = HasElement(root, element.ToString());
            var tempNode = exist ?
                           GetXmlNode(root, element.ToString()) :
                           CreateElement(prefix, localName, namespaceUri);

            if (root == null)
            {
                ChartXml.AppendChild(tempNode);
            }
            else
            {
                root.AppendChild(tempNode);
            }

            return(tempNode);
        }
        /// <summary>
        /// Add a string to the cell.
        /// </summary>
        /// <param name="cell">Current cell.</param>
        /// <param name="value">Reference to <see cref="T:iTin.Export.ComponentModel.FieldValueInformation"/> that contains the information to add.</param>
        /// <returns>
        /// A <see cref="T:Novacode.Cell" /> with text.
        /// </returns>
        public static Cell AppendText(this Cell cell, FieldValueInformation value)
        {
            SentinelHelper.ArgumentNull(cell);

            var style          = value.Style;
            var formattedValue = value.FormattedValue;

            var isNumeric = value.IsNumeric;

            if (isNumeric)
            {
                var isNegative = value.IsNegative;
                if (isNegative)
                {
                    cell.AppendText(formattedValue).AppendNegativeVisualStyle(style);
                }
                else
                {
                    cell.AppendText(formattedValue).AppendVisualStyle(style);
                }
            }
            else
            {
                cell.AppendText(formattedValue).AppendVisualStyle(style);
            }

            return(cell);
        }
Example #24
0
        /// <summary>
        /// Try to get the item in the specified node if exist is returned in the parameter <paramref name="node"/>, otherwise will contain <c>null</c>, if the operation is performed returns <c>true</c>.
        /// </summary>
        /// <param name="root">The root node of new element.</param>
        /// <param name="name">The element name.</param>
        /// <param name="node">The output node.</param>
        /// <returns>
        /// <c>true</c> if exist; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="T:System.ArgumentNullException">If <paramref name="root" /> is <c>null</c>.</exception>
        /// <exception cref="T:System.InvalidOperationException">If <paramref name="name" /> is empty.</exception>
        /// <exception cref="T:System.InvalidOperationException">If <paramref name="name" /> length is less than 3.</exception>
        /// <exception cref="T:System.InvalidOperationException">If <paramref name="name" /> contains white spaces.</exception>
        /// <exception cref="T:System.InvalidOperationException">If <paramref name="name" /> has not correct format.</exception>
        public static bool TryGetElementFrom(XmlNode root, string name, out XmlNode node)
        {
            SentinelHelper.ArgumentNull(root);
            SentinelHelper.IsTrue(name.Length <= 3, "El parametro element debe contener al menos tres caracteres");
            SentinelHelper.IsTrue(string.IsNullOrEmpty(name), "El parametro element no puede estar en blanco");
            SentinelHelper.IsFalse(name.Contains(":"), "El formato no es correcto. Se esperaba prefijo:localname");
            SentinelHelper.IsTrue(name.Contains(" "), "El formato no es correcto. No se permiten espacios en el elemento");

            var exist = HasElement(root, name);

            if (exist)
            {
                node = GetXmlNode(root, name);
            }
            else
            {
                var piece     = name.Split(':');
                var prefix    = piece[0];
                var localName = piece[1];

                node = CreateElement(prefix, localName);
            }

            return(exist);
        }
        /// <summary>
        /// Fills a <see cref="OfficeOpenXml.Drawing.ExcelDrawingBorder"/> object with model data.
        /// </summary>
        /// <param name="border"><see cref="OfficeOpenXml.Drawing.ExcelDrawingBorder"/> object.</param>
        /// <param name="element">Chart element.</param>
        /// <param name="model">Chart border model definition.</param>
        /// <exception cref="T:System.ArgumentNullException">If <paramref name="border" /> is <c>null</c>.</exception>
        /// <exception cref="T:System.ArgumentNullException">If <paramref name="model" /> is <c>null</c>.</exception>
        /// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">The value specified is outside the range of valid values.</exception>
        public static void FormatFromModel(this ExcelDrawingBorder border, KnownChartElement element, ChartBorderModel model)
        {
            SentinelHelper.IsEnumValid(element);
            SentinelHelper.ArgumentNull(model);
            SentinelHelper.ArgumentNull(border);

            if (model.Show == YesNo.Yes)
            {
                border.Fill.Color = model.GetColor();
                border.Width      = model.Width.ToEppBorderWidth();
                border.LineStyle  = model.Style.ToEppLineStyle();
            }

            if (model.Shadow.Show == YesNo.No)
            {
                return;
            }

            var root  = ChartXmlHelper.FromKnownChartElement(element);
            var exist = ChartXmlHelper.TryGetElementFrom(root, "c:spPr", out var shapePropertiesNode);

            shapePropertiesNode.AddEffectContainerNode(model.Shadow);

            if (!exist)
            {
                root.AppendChild(shapePropertiesNode);
            }
        }
        public static MemoryStream ToMemoryStream(this Stream stream)
        {
            SentinelHelper.ArgumentNull(stream);

            MemoryStream resultStream;
            MemoryStream tempStream = null;

            try
            {
                tempStream = new MemoryStream();
                tempStream.SetLength(stream.Length);
                stream.Read(tempStream.GetBuffer(), 0, (int)stream.Length);
                tempStream.Flush();

                resultStream = tempStream;
                tempStream   = null;
            }
            finally
            {
                if (tempStream != null)
                {
                    tempStream.Dispose();
                }
            }

            return(resultStream);
        }
Example #27
0
        /// <summary>
        /// Adds the label alignment to the specified axis. Not supported in <b>EPPlus</b> library.
        /// </summary>
        /// <param name="axis"><b>Xml</b> node than represent an axis definition.</param>
        /// <param name="model">A <see cref="KnownHorizontalAlignment"/> value from model.</param>
        /// <param name="documentHelper">Target xml document helper.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="axis"/> is <b>null</b>.</exception>
        /// <exception cref="InvalidEnumArgumentException">The value specified is outside the range of valid values.</exception>
        /// <exception cref="InvalidOperationException">If <paramref name="axis"/> is not an axis.</exception>
        public static void AddAxisLabelAlignment(this XmlNode axis, KnownHorizontalAlignment model, IXmlHelper documentHelper)
        {
            SentinelHelper.ArgumentNull(axis, nameof(axis));
            SentinelHelper.IsEnumValid(model);
            SentinelHelper.IsFalse(axis.Name.Contains("catAx") || axis.Name.Contains("valAx") || axis.Name.Contains("dateAx"), "Imposible extraer tipo. el nodo no es de tipo eje");

            var axisType = axis.ExtractAxisType(documentHelper);

            switch (axisType)
            {
            case KnownAxisType.PrimaryCategoryAxis:
            case KnownAxisType.SecondaryCategoryAxis:

                var valAttr = documentHelper.CreateAttribute("val");
                valAttr.Value = model.ToEppLabelAlignmentString();

                var lblAlignXmlNode = documentHelper.CreateOrDefaultAndAppendElementToNode(axis, "c:lblAlgn");
                lblAlignXmlNode.Attributes.Append(valAttr);
                break;

            case KnownAxisType.PrimaryValueAxis:
            case KnownAxisType.SecondaryValueAxis:
                break;
            }
        }
Example #28
0
        /// <summary>
        /// Sets the sheet footer from model.
        /// </summary>
        /// <param name="reference">Sheet footer properties.</param>
        /// <param name="section">Footer section model information.</param>
        /// <returns>
        /// An <see cref="ExcelHeaderFooter"/> reference containing the sheet footer section.
        /// </returns>
        private static ExcelHeaderFooter SetSheetFooterSection(this ExcelHeaderFooter reference, XlsxDocumentHeaderFooterSection section)
        {
            SentinelHelper.ArgumentNull(reference, nameof(reference));
            SentinelHelper.ArgumentNull(section, nameof(section));

            if (string.IsNullOrEmpty(section.Text))
            {
                return(reference);
            }

            var footer =
                section.Type == KnownHeaderFooterSectionType.Odd
                    ? reference.OddFooter
                    : reference.EvenFooter;

            var parsedText = OfficeOpenXmlHelper.GetHeaderFooterParsedText(section.Text);

            switch (section.Alignment)
            {
            case KnownHeaderFooterAlignment.Right:
                footer.RightAlignedText = parsedText;
                break;

            case KnownHeaderFooterAlignment.Left:
                footer.LeftAlignedText = parsedText;
                break;

            default:
            case KnownHeaderFooterAlignment.Center:
                footer.CenteredText = parsedText;
                break;
            }

            return(reference);
        }
Example #29
0
        /// <summary>
        /// Saves this stream into a file with name specified by parameter <paramref name="fileName"/>.
        /// You can indicate whether to automatically create the destination path if it does not exist. By default it will try to create the destination path.
        /// The use of the <b>~</b> character is allowed to indicate relative paths, and you can also use <b>UNC</b> path.
        /// </summary>
        /// <param name="stream">Stream to save</param>
        /// <param name="fileName">Destination file path. Absolute or relative (~) paths are allowed</param>
        /// <param name="options">Output save options</param>
        /// <returns>
        /// A <see cref="IResult"/> object that contains the operation result
        /// </returns>
        public static IResult SaveToFile(this NativeIO.Stream stream, string fileName, SaveOptions options = null)
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly:  iTin.Core.IO, Namespace:  iTin.Core.IO, Class: StreamExtensions");
            Logger.Instance.Debug(" Saves this stream into a file with name specified by filename");
            Logger.Instance.Debug($" > Signature: ({typeof(IResult)}) SaveToFile(this {typeof(NativeIO.Stream)}, {typeof(string)})");

            SentinelHelper.ArgumentNull(stream, nameof(stream));
            Logger.Instance.Debug($"   > stream: {stream.Length} bytes");

            SentinelHelper.ArgumentNull(fileName, nameof(fileName));
            Logger.Instance.Debug($"   > fileName: {fileName}");

            try
            {
                IResult saveResult;
                using (var memoryStream = stream as NativeIO.MemoryStream ?? stream.ToMemoryStream())
                {
                    Logger.Instance.Debug(" > Output: Success: True");

                    saveResult = memoryStream.SaveToFile(fileName, options);
                }

                return(saveResult);
            }
            catch (Exception ex)
            {
                Logger.Instance.Error("Error while save stream to file", ex);
                Logger.Instance.Info("  > Output: Success: False");

                return(BooleanResult.FromException(ex));
            }
        }
Example #30
0
        /// <summary>
        /// Gets a <b>Double Word</b> from this array of bytes.
        /// </summary>
        /// <param name="data">Target data.</param>
        /// <param name="start">Start byte.</param>
        /// <returns>
        /// A <see cref="T:System.Int32" /> containing the value.
        /// </returns>
        public static int GetDoubleWord(this byte[] data, byte start)
        {
            SentinelHelper.ArgumentNull(data);
            SentinelHelper.IsTrue(start + 3 > data.Length);

            return(data[start] | data[start + 1] << 8 | data[start + 2] << 16 | data[start + 3] << 24);
        }