Example #1
0
        public CoverageSummary GetCoverageSummary()
        {
            TraceLogger.Debug("ReportGeneratorTool.GetCoverageSummary: Generating coverage summary for the coverage files.");

            var summary = new CoverageSummary();

            if (Configuration.CoverageFiles == null)
            {
                return(summary);
            }

            int totalLines   = 0;
            int coveredLines = 0;

            foreach (var assembly in _parserResult.Assemblies)
            {
                foreach (var @class in assembly.Classes)
                {
                    foreach (var file in @class.Files)
                    {
                        totalLines   += file.CoverableLines;
                        coveredLines += file.CoveredLines;
                    }
                }
            }

            summary.AddCoverageStatistics("line", totalLines, coveredLines, CoverageSummary.Priority.Line);

            return(summary);
        }
        public override Task PublishCumulativeTelemetryAsync()
        {
            if (TelemetryCollectionEnabled)
            {
                try
                {
                    lock (_publishLockNode)
                    {
                        var ciEvent = new CustomerIntelligenceEvent
                        {
                            Area       = Area,
                            Feature    = CumulativeTelemetryFeatureName,
                            Properties = _properties.ToDictionary(entry => entry.Key, entry => entry.Value)
                        };

                        // This is to ensure that the single ci event is never fired more than once.
                        _properties.Clear();

                        return(_httpClient.PublishEventsAsync(new[] { ciEvent }));
                    }
                }
                catch (Exception e)
                {
                    TraceLogger.Debug($"TelemetryDataCollector : PublishCumulativeTelemetryAsync : Failed to publish telemetry due to {e}");
                }
            }

            return(Task.CompletedTask);
        }
Example #3
0
        public static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            ParseArgs(args, ToolName);

            InitializeLogger();

            PrintWelcome(ToolName, RevisionResource);

            try
            {
                if (InputFile.Contains("*.ppt"))
                {
                    var files = Directory.GetFiles(InputFile.Replace("*.ppt", ""), "*.ppt");

                    foreach (string file in files)
                    {
                        if (new FileInfo(file).Extension.ToLower().EndsWith("ppt"))
                        {
                            ChoosenOutputFile = null;
                            processFile(file);
                        }
                    }
                }
                else
                {
                    processFile(InputFile);
                }
            }
            catch (FileNotFoundException ex)
            {
                TraceLogger.Error("Could not read input file {0}.", InputFile);
                TraceLogger.Debug(ex.ToString());
            }
            catch (MagicNumberException)
            {
                TraceLogger.Error("Input file {0} is not a valid PowerPoint 97-2007 file.", InputFile);
            }
            catch (InvalidStreamException)
            {
                TraceLogger.Error("Input file {0} is not a valid PowerPoint 97-2007 file.", InputFile);
            }
            catch (InvalidRecordException)
            {
                TraceLogger.Error("Input file {0} is not a valid PowerPoint 97-2007 file.", InputFile);
            }
            catch (StreamNotFoundException)
            {
                TraceLogger.Error("Input file {0} is not a valid PowerPoint 97-2007 file.", InputFile);
            }
            catch (Exception ex)
            {
                TraceLogger.Error("Conversion of file {0} failed.", InputFile);
                TraceLogger.Debug(ex.ToString());
            }

            TraceLogger.Info("End of program");
        }
Example #4
0
        /// <summary>
        /// Stop the watch and log the trace message with the elapsed time.
        /// Additionally also adds the elapsed time to telemetry under the timer name
        /// </summary>
        public void StopAndLog()
        {
            _timer.Stop();

            var telemetryKey = $"{_telemetryArea}.{_telemetryEventName}";

            _telemetry.AddAndAggregate(telemetryKey, _timer.Elapsed.TotalMilliseconds, _telemetryArea);
            TraceLogger.Debug($"PERF : {telemetryKey} : took {_timer.Elapsed.TotalMilliseconds} ms.");
        }
Example #5
0
        public Lbl(IStreamReader reader, RecordType id, ushort length)
            : base(reader, id, length)
        {
            // assert that the correct record type is instantiated
            //Debug.Assert(this.Id == ID);

            ushort flags = reader.ReadUInt16();

            this.fHidden        = Utils.BitmaskToBool(flags, 0x0001);
            this.fFunc          = Utils.BitmaskToBool(flags, 0x0002);
            this.fOB            = Utils.BitmaskToBool(flags, 0x0004);
            this.fProc          = Utils.BitmaskToBool(flags, 0x0008);
            this.fCalcExp       = Utils.BitmaskToBool(flags, 0x0010);
            this.fBuiltin       = Utils.BitmaskToBool(flags, 0x0020);
            this.fGrp           = Utils.BitmaskToByte(flags, 0x0FC0);
            this.fReserved1     = Utils.BitmaskToBool(flags, 0x1000);
            this.fPublished     = Utils.BitmaskToBool(flags, 0x2000);
            this.fWorkbookParam = Utils.BitmaskToBool(flags, 0x4000);
            this.fReserved2     = Utils.BitmaskToBool(flags, 0x8000);

            this.chKey = reader.ReadByte();
            this.cch   = reader.ReadByte();
            this.cce   = reader.ReadUInt16();
            //read 2 reserved bytes
            this.fReserved3 = reader.ReadUInt16();
            this.itab       = reader.ReadUInt16();
            // read 4 reserved bytes
            this.fReserved4 = reader.ReadUInt32();


            if (this.cch > 0)
            {
                _name = new XLUnicodeStringNoCch(reader, this.cch);
            }
            else
            {
                _name = new XLUnicodeStringNoCch();
            }
            long oldStreamPosition = this.Reader.BaseStream.Position;

            try
            {
                _rgce = ExcelHelperClass.getFormulaStack(this.Reader, this.cce);
            }
            catch (Exception ex)
            {
                this.Reader.BaseStream.Seek(oldStreamPosition, System.IO.SeekOrigin.Begin);
                this.Reader.BaseStream.Seek(this.cce, System.IO.SeekOrigin.Current);
                TraceLogger.Error("Formula parse error in intern name");
                TraceLogger.Debug(ex.StackTrace);
            }

            // assert that the correct number of bytes has been read from the stream
            Debug.Assert(this.Offset + this.Length == this.Reader.BaseStream.Position);
        }
Example #6
0
        private ParserResult ParseCoverageFiles(List <string> coverageFiles)
        {
            TraceLogger.Debug("ReportGeneratorTool.ParseCoverageFiles: Parsing coverage files.");

            CoverageReportParser parser = new CoverageReportParser(1, 1, new string[] { }, new DefaultFilter(new string[] { }),
                                                                   new DefaultFilter(new string[] { }),
                                                                   new DefaultFilter(new string[] { }));

            ReadOnlyCollection <string> collection = new ReadOnlyCollection <string>(coverageFiles);

            return(parser.ParseFiles(collection));
        }
Example #7
0
        public ReportGeneratorTool(PublisherConfiguration configuration)
        {
            Configuration = configuration;

            if (Configuration.CoverageFiles == null)
            {
                TraceLogger.Debug("ReportGeneratorTool: No input coverage files to parse.");
                return;
            }

            _parserResult = ParseCoverageFiles(new List <string>(Configuration.CoverageFiles));
        }
Example #8
0
        public void DebugMessageWritesAsTraceInformation()
        {
            string message   = "message";
            string logname   = "logger";
            var    mockTrace = new Mock <ITrace>();

            mockTrace.Setup(x => x.TraceInformation("[{0}] {1} {2}", "DEBUG", logname, message)).Verifiable();
            ITrace trace  = mockTrace.Object;
            ILog   tested = new TraceLogger(logname, trace);

            tested.Debug(message);
            mockTrace.Verify();
        }
Example #9
0
        public void FormattedDebugMessageWritesAsTraceInformation()
        {
            string format    = "message {0}";
            string arg       = "theArg";
            string logname   = "logger";
            var    mockTrace = new Mock <ITrace>();

            mockTrace.Setup(x => x.TraceInformation("[{0}] {1} {2}", "DEBUG", logname, string.Format(format, arg))).Verifiable();
            ITrace trace  = mockTrace.Object;
            ILog   tested = new TraceLogger(logname, trace);

            tested.Debug(format, arg);
            mockTrace.Verify();
        }
Example #10
0
        public void TraceLogger_InstanceTests()
        {
            String logType = $"{GetType().Name}";

            Console.WriteLine($"Starting Test: {logType}");
            TraceLogger tl = new TraceLogger(logType);

            tl.Enabled = true;

            TraceLogger.Debug($"\tPath: {tl.FullPath}");
            TraceLogger.Debug($"\tEnabled: {tl.Enabled}");
            tl.LogMessage(nameof(TraceLogger_InstanceTests), $"\tPath: {tl.FullPath}");
            tl.LogMessageCrLf(nameof(TraceLogger_InstanceTests), $"\tEnabled: {tl.Enabled}");
        }
        protected virtual void GenerateHTMLReport(ICoverageParserTool tool)
        {
            if (_configuration.GenerateHTMLReport)
            {
                try
                {
                    using (new SimpleTimer("Parser", "ReportGeneration", _telemetry))
                    {
                        // Generate report
                        tool.GenerateHTMLReport();

                        // Copy coverage input files to report directory in a unique folder
                        if (Directory.Exists(_configuration.ReportDirectory))
                        {
                            string summaryFilesSubDir;

                            // Create a unique folder
                            do
                            {
                                summaryFilesSubDir = Path.Combine(_configuration.ReportDirectory, "Summary_" + Guid.NewGuid().ToString().Substring(0, 8));
                            } while (Directory.Exists(summaryFilesSubDir));

                            TraceLogger.Debug("Parser.GenerateHTMLReport: Creating summary file directory: " + summaryFilesSubDir);

                            Directory.CreateDirectory(summaryFilesSubDir);

                            // Copy the files
                            foreach (var summaryFile in _configuration.CoverageFiles)
                            {
                                var summaryFileName        = Path.GetFileName(summaryFile);
                                var destinationSummaryFile = Path.Combine(summaryFilesSubDir, summaryFileName);

                                TraceLogger.Debug("Parser.GenerateHTMLReport: Copying summary file " + summaryFile);
                                File.Copy(summaryFile, destinationSummaryFile, true);
                            }
                        }
                        else
                        {
                            TraceLogger.Debug("Parser.GenerateHTMLReport: Directory " + _configuration.ReportDirectory + " doesn't exist, skipping copying of coverage input files.");
                        }
                    }
                }
                catch (Exception e)
                {
                    _telemetry.AddFailure(e);
                    TraceLogger.Error(string.Format(Resources.HTMLReportError, e.Message));
                }
            }
        }
Example #12
0
        public async Task PublishFileCoverage(IList <FileCoverageInfo> coverageInfos, CancellationToken cancellationToken)
        {
            if (coverageInfos.Count == 0)
            {
                return;
            }

            TraceLogger.Info(Resources.PublishingFileCoverage);

            var maxParallelism = Math.Min(Math.Max(Environment.ProcessorCount / 2, 1), coverageInfos.Count);
            var queue          = new ConcurrentQueue <FileCoverageInfo>(coverageInfos);
            var tasks          = new List <Task>();
            var jsonFile       = Path.Combine(_executionContext.TempPath, Guid.NewGuid().ToString() + _executionContext.BuildId.ToString() + ".cjson");

            try
            {
                var fileContent = JsonUtility.ToString(coverageInfos);
                File.WriteAllText(jsonFile, fileContent);

                _executionContext.TelemetryDataCollector.AddOrUpdate("FileCoverageLength", fileContent.Length);

                Dictionary <string, string> metaData = new Dictionary <string, string>();
                using (new SimpleTimer("AzurePipelinesPublisher", "UploadFileCoverage", _executionContext.TelemetryDataCollector))
                {
                    await _logStoreHelper.UploadTestBuildLogAsync(_executionContext.ProjectId, _executionContext.BuildId, TestLogType.Intermediate, jsonFile, metaData, null, true, cancellationToken);
                }
            }
            catch (Exception ex)
            {
                TraceLogger.Error(string.Format(Resources.FailedToUploadFileCoverage, ex));
            }

            try
            {
                // Delete the generated json file
                if (File.Exists(jsonFile))
                {
                    File.Delete(jsonFile);
                }
            }
            catch (Exception)
            {
                TraceLogger.Debug(string.Format("Failed to delete temporary file: {0}", jsonFile));
            }
        }
Example #13
0
        /// <summary>
        /// Extracts the data from the stream
        /// </summary>
        public void extractData()
        {
            BiffHeader   bh;
            StreamWriter sw = null;

            sw = new StreamWriter(Console.OpenStandardOutput());
            try
            {
                while (this.SummaryStream.BaseStream.Position < this.SummaryStream.BaseStream.Length)
                {
                    bh.id     = (RecordType)this.SummaryStream.ReadUInt16();
                    bh.length = this.SummaryStream.ReadUInt16();

                    byte[] buf = new byte[bh.length];
                    if (bh.length != this.SummaryStream.ReadByte())
                    {
                        sw.WriteLine("EOF");
                    }

                    sw.Write("BIFF {0}\t{1}\t", bh.id, bh.length);
                    //Dump(buffer);
                    int count = 0;
                    foreach (byte b in buf)
                    {
                        sw.Write("{0:X02} ", b);
                        count++;
                        if (count % 16 == 0 && count < buf.Length)
                        {
                            sw.Write("\n\t\t\t");
                        }
                    }
                    sw.Write("\n");
                }
            }
            catch (Exception ex)
            {
                TraceLogger.Error(ex.Message);
                TraceLogger.Debug(ex.ToString());
            }
            this.buffer = sw.ToString();
        }
Example #14
0
        public void GenerateHTMLReport()
        {
            TraceLogger.Debug("ReportGeneratorTool.CreateHTMLReportFromParserResult: Creating HTML report.");

            if (!Directory.Exists(Configuration.ReportDirectory))
            {
                Directory.CreateDirectory(Configuration.ReportDirectory);
            }

            // Generate the html report with custom configuration for report generator.
            var reportGeneratorConfig = new ReportConfigurationBuilder().Create(new Dictionary <string, string>()
            {
                { "targetdir", Configuration.ReportDirectory },
                { "sourcedirs", string.IsNullOrEmpty(Configuration.SourceDirectory) ? "" : Configuration.SourceDirectory },
                { "reporttypes", "HtmlInline_AzurePipelines" }
            });

            var generator = new Generator();

            generator.GenerateReport(reportGeneratorConfig, new Settings(), new RiskHotspotsAnalysisThresholds(), _parserResult);
        }
Example #15
0
        public List <FileCoverageInfo> GetFileCoverageInfos()
        {
            TraceLogger.Debug("ReportGeneratorTool.GetFileCoverageInfos: Generating file coverage info from coverage files.");

            List <FileCoverageInfo> fileCoverages = new List <FileCoverageInfo>();

            if (Configuration.CoverageFiles == null)
            {
                return(fileCoverages);
            }

            foreach (var assembly in _parserResult.Assemblies)
            {
                foreach (var @class in assembly.Classes)
                {
                    foreach (var file in @class.Files)
                    {
                        FileCoverageInfo resultFileCoverageInfo = new FileCoverageInfo {
                            FilePath = file.Path, LineCoverageStatus = new Dictionary <uint, CoverageStatus>()
                        };
                        int lineNumber = 0;

                        foreach (var line in file.LineCoverage)
                        {
                            if (line != -1 && lineNumber != 0)
                            {
                                resultFileCoverageInfo.LineCoverageStatus.Add((uint)lineNumber, line == 0 ? CoverageStatus.NotCovered : CoverageStatus.Covered);
                            }
                            ++lineNumber;
                        }

                        fileCoverages.Add(resultFileCoverageInfo);
                    }
                }
            }

            return(fileCoverages);
        }
        /// <inheritdoc />
        public override Task PublishTelemetryAsync(string feature, Dictionary <string, object> properties)
        {
            if (TelemetryCollectionEnabled)
            {
                try
                {
                    var ciEvent = new CustomerIntelligenceEvent
                    {
                        Area       = Area,
                        Feature    = feature,
                        Properties = properties
                    };

                    return(_httpClient.PublishEventsAsync(new[] { ciEvent }));
                }
                catch (Exception e)
                {
                    TraceLogger.Debug($"TelemetryDataCollector : PublishTelemetryAsync : Failed to publish telemetry due to {e}");
                }
            }

            return(Task.CompletedTask);
        }
Example #17
0
        static void Main(string[] args)
        {
            ParseArgs(args, ToolName);

            InitializeLogger();

            PrintWelcome(ToolName, RevisionResource);

            try
            {
                //copy processing file
                var procFile = new ProcessingFile(InputFile);

                //make output file name
                if (ChoosenOutputFile == null)
                {
                    if (InputFile.Contains("."))
                    {
                        ChoosenOutputFile = InputFile.Remove(InputFile.LastIndexOf(".")) + ".xlsx";
                    }
                    else
                    {
                        ChoosenOutputFile = InputFile + ".xlsx";
                    }
                }

                //parse the document
                using (var reader = new StructuredStorageReader(procFile.File.FullName))
                {
                    var xlsDoc = new XlsDocument(reader);

                    var    outType           = Converter.DetectOutputType(xlsDoc);
                    string conformOutputFile = Converter.GetConformFilename(ChoosenOutputFile, outType);
                    using (var spreadx = SpreadsheetDocument.Create(conformOutputFile, outType))
                    {
                        //start time
                        var start = DateTime.Now;
                        TraceLogger.Info("Converting file {0} into {1}", InputFile, conformOutputFile);

                        Converter.Convert(xlsDoc, spreadx);

                        var end  = DateTime.Now;
                        var diff = end.Subtract(start);
                        TraceLogger.Info("Conversion of file {0} finished in {1} seconds", InputFile, diff.TotalSeconds.ToString(CultureInfo.InvariantCulture));
                    }
                }
            }
            catch (ParseException ex)
            {
                TraceLogger.Error("Could not convert {0} because it was created by an unsupported application (Excel 95 or older).", InputFile);
                TraceLogger.Debug(ex.ToString());
            }
            catch (DirectoryNotFoundException ex)
            {
                TraceLogger.Error(ex.Message);
                TraceLogger.Debug(ex.ToString());
            }
            catch (FileNotFoundException ex)
            {
                TraceLogger.Error(ex.Message);
                TraceLogger.Debug(ex.ToString());
            }
            catch (Exception ex)
            {
                TraceLogger.Error("Conversion of file {0} failed.", InputFile);
                TraceLogger.Debug(ex.ToString());
            }
        }
Example #18
0
        public Lbl(IStreamReader reader, RecordType id, ushort length)
            : base(reader, id, length)
        {
            // assert that the correct record type is instantiated
            //Debug.Assert(this.Id == ID);

            ushort flags = reader.ReadUInt16();

            this.fHidden        = Utils.BitmaskToBool(flags, 0x0001);
            this.fFunc          = Utils.BitmaskToBool(flags, 0x0002);
            this.fOB            = Utils.BitmaskToBool(flags, 0x0004);
            this.fProc          = Utils.BitmaskToBool(flags, 0x0008);
            this.fCalcExp       = Utils.BitmaskToBool(flags, 0x0010);
            this.fBuiltin       = Utils.BitmaskToBool(flags, 0x0020);
            this.fGrp           = Utils.BitmaskToByte(flags, 0x0FC0);
            this.fReserved1     = Utils.BitmaskToBool(flags, 0x1000);
            this.fPublished     = Utils.BitmaskToBool(flags, 0x2000);
            this.fWorkbookParam = Utils.BitmaskToBool(flags, 0x4000);
            this.fReserved2     = Utils.BitmaskToBool(flags, 0x8000);

            this.chKey = reader.ReadByte();
            this.cch   = reader.ReadByte();
            this.cce   = reader.ReadUInt16();
            //read 2 reserved bytes
            this.fReserved3 = reader.ReadUInt16();
            this.itab       = reader.ReadUInt16();
            // read 4 reserved bytes
            this.fReserved4 = reader.ReadUInt32();

            //Peek at the fHighByte value to figure out if the Lbl is encrypted or not
            long oldStreamPosition = this.Reader.BaseStream.Position;
            bool fHighByte         = Utils.BitmaskToBool(reader.ReadByte(), 0x0001);

            this.Reader.BaseStream.Seek(oldStreamPosition, System.IO.SeekOrigin.Begin);

            //If a lbl has garbage cce/cch values, ignore reading those values
            if (this.Length != CalculateLength(fHighByte))
            {
                this.RawLblBytes = this.Reader.ReadBytes((int)(this.Length - LblFixedSize));
                _name            = new XLUnicodeStringNoCch();
                _rgce            = new Stack <AbstractPtg>();
                return;
            }


            if (this.cch > 0)
            {
                _name = new XLUnicodeStringNoCch(reader, this.cch);
            }
            else
            {
                _name = new XLUnicodeStringNoCch();
            }
            oldStreamPosition = this.Reader.BaseStream.Position;
            try
            {
                _rgce = ExcelHelperClass.getFormulaStack(this.Reader, this.cce);
            }
            catch (Exception ex)
            {
                this.Reader.BaseStream.Seek(oldStreamPosition, System.IO.SeekOrigin.Begin);
                this.Reader.BaseStream.Seek(this.cce, System.IO.SeekOrigin.Current);
                TraceLogger.Error("Formula parse error in intern name");
                TraceLogger.Debug(ex.StackTrace);
            }

            // assert that the correct number of bytes has been read from the stream
            Debug.Assert(this.Offset + this.Length == this.Reader.BaseStream.Position);
        }
Example #19
0
        public static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            ParseArgs(args, ToolName);

            InitializeLogger();

            PrintWelcome(ToolName);

            if (CreateContextMenuEntry)
            {
                // create context menu entry
                try
                {
                    TraceLogger.Info("Creating context menu entry for ppt2x ...");
                    RegisterForContextMenu(GetContextMenuKey(ContextMenuInputExtension, ContextMenuText));
                    TraceLogger.Info("Succeeded.");
                }
                catch (Exception)
                {
                    TraceLogger.Info("Failed. Sorry :(");
                }
            }
            else
            {
                try
                {
                    if (InputFile.Contains("*.ppt"))
                    {
                        string[] files = Directory.GetFiles(InputFile.Replace("*.ppt", ""), "*.ppt");

                        foreach (String file in files)
                        {
                            if (new FileInfo(file).Extension.ToLower().EndsWith("ppt"))
                            {
                                ChoosenOutputFile = null;
                                processFile(file);
                            }
                        }
                    }
                    else
                    {
                        processFile(InputFile);
                    }
                }
                catch (ZipCreationException ex)
                {
                    TraceLogger.Error("Could not create output file {0}.", ChoosenOutputFile);
                    //TraceLogger.Error("Perhaps the specified outputfile was a directory or contained invalid characters.");
                    TraceLogger.Debug(ex.ToString());
                }
                catch (FileNotFoundException ex)
                {
                    TraceLogger.Error("Could not read input file {0}.", InputFile);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (MagicNumberException)
                {
                    TraceLogger.Error("Input file {0} is not a valid PowerPoint 97-2007 file.", InputFile);
                }
                catch (InvalidStreamException e)
                {
                    TraceLogger.Error("Input file {0} is not a valid PowerPoint 97-2007 file.", InputFile);
                }
                catch (InvalidRecordException)
                {
                    TraceLogger.Error("Input file {0} is not a valid PowerPoint 97-2007 file.", InputFile);
                }
                catch (StreamNotFoundException e)
                {
                    TraceLogger.Error("Input file {0} is not a valid PowerPoint 97-2007 file.", InputFile);
                }
                catch (Exception ex)
                {
                    TraceLogger.Error("Conversion of file {0} failed.", InputFile);
                    TraceLogger.Debug(ex.ToString());
                }
            }

            TraceLogger.Info("End of program");
        }
Example #20
0
        public static void Main(string[] args)
        {
            ParseArgs(args, ToolName);

            InitializeLogger();

            PrintWelcome(ToolName, RevisionResource);

            // convert
            try
            {
                //copy processing file
                var procFile = new ProcessingFile(InputFile);

                //make output file name
                if (ChoosenOutputFile == null)
                {
                    if (InputFile.Contains("."))
                    {
                        ChoosenOutputFile = InputFile.Remove(InputFile.LastIndexOf(".")) + ".docx";
                    }
                    else
                    {
                        ChoosenOutputFile = InputFile + ".docx";
                    }
                }

                //open the reader
                using (var reader = new StructuredStorageReader(procFile.File.FullName))
                {
                    //parse the input document
                    var doc = new WordDocument(reader);

                    //prepare the output document
                    var    outType           = Converter.DetectOutputType(doc);
                    string conformOutputFile = Converter.GetConformFilename(ChoosenOutputFile, outType);
                    var    docx = WordprocessingDocument.Create(conformOutputFile, outType);

                    //start time
                    var start = DateTime.Now;
                    TraceLogger.Info("Converting file {0} into {1}", InputFile, conformOutputFile);

                    //convert the document
                    Converter.Convert(doc, docx);

                    var end  = DateTime.Now;
                    var diff = end.Subtract(start);
                    TraceLogger.Info("Conversion of file {0} finished in {1} seconds", InputFile, diff.TotalSeconds.ToString(CultureInfo.InvariantCulture));
                }
            }
            catch (DirectoryNotFoundException ex)
            {
                TraceLogger.Error(ex.Message);
                TraceLogger.Debug(ex.ToString());
            }
            catch (FileNotFoundException ex)
            {
                TraceLogger.Error(ex.Message);
                TraceLogger.Debug(ex.ToString());
            }
            catch (ReadBytesAmountMismatchException ex)
            {
                TraceLogger.Error("Input file {0} is not a valid Microsoft Word 97-2003 file.", InputFile);
                TraceLogger.Debug(ex.ToString());
            }
            catch (MagicNumberException ex)
            {
                TraceLogger.Error("Input file {0} is not a valid Microsoft Word 97-2003 file.", InputFile);
                TraceLogger.Debug(ex.ToString());
            }
            catch (UnspportedFileVersionException ex)
            {
                TraceLogger.Error("File {0} has been created with a Word version older than Word 97.", InputFile);
                TraceLogger.Debug(ex.ToString());
            }
            catch (ByteParseException ex)
            {
                TraceLogger.Error("Input file {0} is not a valid Microsoft Word 97-2003 file.", InputFile);
                TraceLogger.Debug(ex.ToString());
            }
            catch (MappingException ex)
            {
                TraceLogger.Error("There was an error while converting file {0}: {1}", InputFile, ex.Message);
                TraceLogger.Debug(ex.ToString());
            }
            catch (Exception ex)
            {
                TraceLogger.Error("Conversion of file {0} failed.", InputFile);
                TraceLogger.Debug(ex.ToString());
            }
        }
Example #21
0
        /// <summary>
        /// Extracting the data from the stream
        /// </summary>
        public override void extractData()
        {
            BiffHeader bh, latestbiff;
            BOF        firstBOF = null;

            //try
            //{
            while (this.StreamReader.BaseStream.Position < this.StreamReader.BaseStream.Length)
            {
                bh.id     = (RecordType)this.StreamReader.ReadUInt16();
                bh.length = this.StreamReader.ReadUInt16();

                // TraceLogger.DebugInternal("BIFF {0}\t{1}\t", bh.id, bh.length);
                Console.WriteLine("WORKSHEET-BIFF {0}\t{1}\t", bh.id, bh.length);

                switch (bh.id)
                {
                case RecordType.EOF:
                {
                    this.StreamReader.BaseStream.Seek(0, SeekOrigin.End);
                }
                break;

                case RecordType.BOF:
                {
                    var bof = new BOF(this.StreamReader, bh.id, bh.length);

                    switch (bof.docType)
                    {
                    case BOF.DocumentType.WorkbookGlobals:
                    case BOF.DocumentType.Worksheet:
                        firstBOF = bof;
                        break;

                    case BOF.DocumentType.Chart:
                        // parse chart

                        break;

                    default:
                        this.readUnknownFile();
                        break;
                    }
                }
                break;

                case RecordType.LabelSst:
                {
                    var labelsst = new LabelSst(this.StreamReader, bh.id, bh.length);
                    this.bsd.addLabelSST(labelsst);
                }
                break;

                case RecordType.MulRk:
                {
                    var mulrk = new MulRk(this.StreamReader, bh.id, bh.length);
                    this.bsd.addMULRK(mulrk);
                }
                break;

                case RecordType.Number:
                {
                    var number = new Number(this.StreamReader, bh.id, bh.length);
                    this.bsd.addNUMBER(number);
                }
                break;

                case RecordType.RK:
                {
                    var rk = new RK(this.StreamReader, bh.id, bh.length);
                    this.bsd.addRK(rk);
                }
                break;

                case RecordType.MergeCells:
                {
                    var mergecells = new MergeCells(this.StreamReader, bh.id, bh.length);
                    this.bsd.MERGECELLSData = mergecells;
                }
                break;

                case RecordType.Blank:
                {
                    var blankcell = new Blank(this.StreamReader, bh.id, bh.length);
                    this.bsd.addBLANK(blankcell);
                } break;

                case RecordType.MulBlank:
                {
                    var mulblank = new MulBlank(this.StreamReader, bh.id, bh.length);
                    this.bsd.addMULBLANK(mulblank);
                }
                break;

                case RecordType.Formula:
                {
                    var formula = new Formula(this.StreamReader, bh.id, bh.length);
                    this.bsd.addFORMULA(formula);
                    TraceLogger.DebugInternal(formula.ToString());
                }
                break;

                case RecordType.Array:
                {
                    var array = new ARRAY(this.StreamReader, bh.id, bh.length);
                    this.bsd.addARRAY(array);
                }
                break;

                case RecordType.ShrFmla:
                {
                    var shrfmla = new ShrFmla(this.StreamReader, bh.id, bh.length);
                    this.bsd.addSharedFormula(shrfmla);
                }
                break;

                case RecordType.String:
                {
                    var formulaString = new STRING(this.StreamReader, bh.id, bh.length);
                    this.bsd.addFormulaString(formulaString.value);
                }
                break;

                case RecordType.Row:
                {
                    var row = new Row(this.StreamReader, bh.id, bh.length);
                    this.bsd.addRowData(row);
                }
                break;

                case RecordType.ColInfo:
                {
                    var colinfo = new ColInfo(this.StreamReader, bh.id, bh.length);
                    this.bsd.addColData(colinfo);
                }
                break;

                case RecordType.DefColWidth:
                {
                    var defcolwidth = new DefColWidth(this.StreamReader, bh.id, bh.length);
                    this.bsd.addDefaultColWidth(defcolwidth.cchdefColWidth);
                }
                break;

                case RecordType.DefaultRowHeight:
                {
                    var defrowheigth = new DefaultRowHeight(this.StreamReader, bh.id, bh.length);
                    this.bsd.addDefaultRowData(defrowheigth);
                }
                break;

                case RecordType.LeftMargin:
                {
                    var leftm = new LeftMargin(this.StreamReader, bh.id, bh.length);
                    this.bsd.leftMargin = leftm.value;
                }
                break;

                case RecordType.RightMargin:
                {
                    var rightm = new RightMargin(this.StreamReader, bh.id, bh.length);
                    this.bsd.rightMargin = rightm.value;
                }
                break;

                case RecordType.TopMargin:
                {
                    var topm = new TopMargin(this.StreamReader, bh.id, bh.length);
                    this.bsd.topMargin = topm.value;
                }
                break;

                case RecordType.BottomMargin:
                {
                    var bottomm = new BottomMargin(this.StreamReader, bh.id, bh.length);
                    this.bsd.bottomMargin = bottomm.value;
                }
                break;

                case RecordType.Setup:
                {
                    var setup = new Setup(this.StreamReader, bh.id, bh.length);
                    this.bsd.addSetupData(setup);
                }
                break;

                case RecordType.HLink:
                {
                    long oldStreamPos = this.StreamReader.BaseStream.Position;
                    try
                    {
                        var hlink = new HLink(this.StreamReader, bh.id, bh.length);
                        this.bsd.addHyperLinkData(hlink);
                    }
                    catch (Exception ex)
                    {
                        this.StreamReader.BaseStream.Seek(oldStreamPos, System.IO.SeekOrigin.Begin);
                        this.StreamReader.BaseStream.Seek(bh.length, System.IO.SeekOrigin.Current);
                        TraceLogger.Debug("Link parse error");
                        TraceLogger.Error(ex.StackTrace);
                    }
                }
                break;

                case RecordType.MsoDrawing:
                {
                    // Record header has already been read. Reset position to record beginning.
                    this.StreamReader.BaseStream.Position -= 2 * sizeof(ushort);
                    this.bsd.ObjectsSequence = new ObjectsSequence(this.StreamReader);
                }
                break;

                default:
                {
                    // this else statement is used to read BiffRecords which aren't implemented
                    var buffer = new byte[bh.length];
                    buffer = this.StreamReader.ReadBytes(bh.length);
                }
                break;
                }
                latestbiff = bh;
            }
            //}
            //catch (Exception ex)
            //{
            //    TraceLogger.Error(ex.Message);
            //    TraceLogger.Error(ex.StackTrace);
            //    TraceLogger.Debug(ex.ToString());
            //}
        }
 public override void WriteLine(string message)
 {
     TraceLogger.Debug(message);
 }
Example #23
0
        /// <summary>
        /// Extracts the data from the stream
        /// </summary>
        public override void extractData()
        {
            BiffHeader bh;

            //try
            //{
            while (this.StreamReader.BaseStream.Position < this.StreamReader.BaseStream.Length)
            {
                bh.id     = (RecordType)this.StreamReader.ReadUInt16();
                bh.length = this.StreamReader.ReadUInt16();
                // Debugging output
                TraceLogger.DebugInternal("BIFF {0}\t{1}\t", bh.id, bh.length);

                switch (bh.id)
                {
                case RecordType.BoundSheet8:
                {
                    // Extracts the Boundsheet data
                    BoundSheet8 bs = new BoundSheet8(this.StreamReader, bh.id, bh.length);
                    TraceLogger.DebugInternal(bs.ToString());

                    SheetData sheetData = null;

                    switch (bs.dt)
                    {
                    case BoundSheet8.SheetType.Worksheet:
                        sheetData      = new WorkSheetData();
                        this.oldOffset = this.StreamReader.BaseStream.Position;
                        this.StreamReader.BaseStream.Seek(bs.lbPlyPos, SeekOrigin.Begin);
                        WorksheetExtractor se = new WorksheetExtractor(this.StreamReader, sheetData as WorkSheetData);
                        this.StreamReader.BaseStream.Seek(oldOffset, SeekOrigin.Begin);
                        break;

                    case BoundSheet8.SheetType.Chartsheet:
                        ChartSheetData chartSheetData = new ChartSheetData();

                        this.oldOffset = this.StreamReader.BaseStream.Position;
                        this.StreamReader.BaseStream.Seek(bs.lbPlyPos, SeekOrigin.Begin);
                        chartSheetData.ChartSheetSequence = new ChartSheetSequence(this.StreamReader);
                        this.StreamReader.BaseStream.Seek(oldOffset, SeekOrigin.Begin);

                        sheetData = chartSheetData;
                        break;

                    default:
                        TraceLogger.Info("Unsupported sheet type: {0}", bs.dt);
                        break;
                    }

                    if (sheetData != null)
                    {
                        // add general sheet info
                        sheetData.boundsheetRecord = bs;
                        this.workBookData.addBoundSheetData(sheetData);
                    }
                }
                break;

                case RecordType.Template:
                {
                    this.workBookData.Template = true;
                }
                break;

                case RecordType.SST:
                {
                    /* reads the shared string table biff record and following continue records
                     * creates an array of bytes and then puts that into a memory stream
                     * this all is used to create a longer biffrecord then 8224 bytes. If theres a string
                     * beginning in the SST that is then longer then the 8224 bytes, it continues in the
                     * CONTINUE BiffRecord, so the parser has to read over the SST border.
                     * The problem here is, that the parser has to overread the continue biff record header
                     */
                    //SST sst;
                    //UInt16 length = bh.length;

                    //// save the old offset from this record begin
                    //this.oldOffset = this.StreamReader.BaseStream.Position;
                    //// create a list of bytearrays to store the following continue records
                    //// List<byte[]> byteArrayList = new List<byte[]>();
                    //byte[] buffer = new byte[length];
                    //LinkedList<VirtualStreamReader> vsrList = new LinkedList<VirtualStreamReader>();
                    //buffer = this.StreamReader.ReadBytes((int)length);
                    //// byteArrayList.Add(buffer);

                    //// create a new memory stream and a new virtualstreamreader
                    //MemoryStream bufferstream = new MemoryStream(buffer);
                    //VirtualStreamReader binreader = new VirtualStreamReader(bufferstream);
                    //BiffHeader bh2;
                    //bh2.id = (RecordType)this.StreamReader.ReadUInt16();

                    //while (bh2.id == RecordType.Continue)
                    //{
                    //    bh2.length = (UInt16)(this.StreamReader.ReadUInt16());

                    //    buffer = new byte[bh2.length];

                    //    // create a buffer with the bytes from the records and put that array into the
                    //    // list
                    //    buffer = this.StreamReader.ReadBytes((int)bh2.length);
                    //    // byteArrayList.Add(buffer);

                    //    // create for each continue record a new streamreader !!
                    //    MemoryStream contbufferstream = new MemoryStream(buffer);
                    //    VirtualStreamReader contreader = new VirtualStreamReader(contbufferstream);
                    //    vsrList.AddLast(contreader);


                    //    // take next Biffrecord ID
                    //    bh2.id = (RecordType)this.StreamReader.ReadUInt16();
                    //}
                    //// set the old position of the stream
                    //this.StreamReader.BaseStream.Position = this.oldOffset;

                    SST sst = new SST(this.StreamReader, bh.id, bh.length);
                    //this.StreamReader.BaseStream.Position = this.oldOffset + bh.length;
                    this.workBookData.SstData = sst;
                }
                break;

                case RecordType.EOF:
                {
                    // Reads the end of the internal file !!!
                    this.StreamReader.BaseStream.Seek(0, SeekOrigin.End);
                }
                break;

                case RecordType.ExternSheet:
                {
                    ExternSheet extsheet = new ExternSheet(this.StreamReader, bh.id, bh.length);
                    this.externSheets.Add(extsheet);
                    this.workBookData.addExternSheetData(extsheet);
                }
                break;

                case RecordType.SupBook:
                {
                    SupBook supbook = new SupBook(this.StreamReader, bh.id, bh.length);
                    this.supBooks.Add(supbook);
                    this.workBookData.addSupBookData(supbook);
                }
                break;

                case RecordType.XCT:
                {
                    XCT xct = new XCT(this.StreamReader, bh.id, bh.length);
                    this.XCTList.Add(xct);
                    this.workBookData.addXCT(xct);
                }
                break;

                case RecordType.CRN:
                {
                    CRN crn = new CRN(this.StreamReader, bh.id, bh.length);
                    this.CRNList.Add(crn);
                    this.workBookData.addCRN(crn);
                }
                break;

                case RecordType.ExternName:
                {
                    ExternName externname = new ExternName(this.StreamReader, bh.id, bh.length);
                    this.workBookData.addEXTERNNAME(externname);
                }
                break;

                case RecordType.Format:
                {
                    Format format = new Format(this.StreamReader, bh.id, bh.length);
                    this.workBookData.styleData.addFormatValue(format);
                }
                break;

                case RecordType.XF:
                {
                    XF xf = new XF(this.StreamReader, bh.id, bh.length);
                    this.workBookData.styleData.addXFDataValue(xf);
                }
                break;

                case RecordType.Style:
                {
                    Style style = new Style(this.StreamReader, bh.id, bh.length);
                    this.workBookData.styleData.addStyleValue(style);
                }
                break;

                case RecordType.Font:
                {
                    Font font = new Font(this.StreamReader, bh.id, bh.length);
                    this.workBookData.styleData.addFontData(font);
                }
                break;

                case RecordType.NAME:
                case RecordType.Lbl:
                {
                    Lbl name = new Lbl(this.StreamReader, bh.id, bh.length);
                    this.workBookData.addDefinedName(name);
                }
                break;

                case RecordType.BOF:
                {
                    this.workBookData.BOF = new BOF(this.StreamReader, bh.id, bh.length);
                }
                break;

                case RecordType.CodeName:
                {
                    this.workBookData.CodeName = new CodeName(this.StreamReader, bh.id, bh.length);
                }
                break;

                case RecordType.FilePass:
                {
                    throw new ExtractorException(ExtractorException.FILEENCRYPTED);
                }
                break;

                case RecordType.Palette:
                {
                    Palette palette = new Palette(this.StreamReader, bh.id, bh.length);
                    workBookData.styleData.setColorList(palette.rgbColorList);
                }
                break;

                default:
                {
                    // this else statement is used to read BiffRecords which aren't implemented
                    byte[] buffer = new byte[bh.length];
                    buffer = this.StreamReader.ReadBytes(bh.length);
                    TraceLogger.Debug("Unknown record found. ID {0}", bh.id);
                }
                break;
                }
            }
            //}
            //catch (Exception ex)
            //{
            //    TraceLogger.Error(ex.Message);
            //    TraceLogger.Debug(ex.ToString());
            //}
        }
Example #24
0
        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="reader">Reader to parse the document </param>
        /// <param name="id">BiffRecord ID</param>
        /// <param name="length">The lengt of the biffrecord </param>
        public SST(IStreamReader reader, RecordType id, UInt16 length)
            : base(reader, id, length)
        {
            // assert that the correct record type is instantiated
            Debug.Assert(this.Id == ID);

            this.StringList = new List <string>();
            this.FormatList = new List <StringFormatAssignment>();

            // copy data to a memory stream to cope with Continue records
            using (MemoryStream ms = new MemoryStream())
            {
                List <long> recordBorders = new List <long>();

                byte[] buffer = reader.ReadBytes(length);
                ms.Write(buffer, 0, length);

                while (BiffRecord.GetNextRecordType(reader) == RecordType.Continue)
                {
                    BiffHeader bh;
                    bh.id     = (RecordType)reader.ReadUInt16();
                    bh.length = reader.ReadUInt16();

                    recordBorders.Add(ms.Position);
                    buffer = reader.ReadBytes(bh.length);
                    ms.Write(buffer, 0, bh.length);
                }

                ms.Position = 0;

                VirtualStreamReader sr = new VirtualStreamReader(ms);

                try
                {
                    this.cstTotal  = sr.ReadUInt32();
                    this.cstUnique = sr.ReadUInt32();

                    // run over the different strings
                    // there are x strings where x = cstUnique
                    for (int i = 0; i < this.cstUnique; i++)
                    {
                        XLUnicodeRichExtendedString str = new XLUnicodeRichExtendedString(sr, recordBorders);

                        //// first get the char count of this string
                        //UInt16 cch = sr.ReadUInt16();
                        //// get the grbit mask
                        //Byte grbit = sr.ReadByte();
                        //bool isCompressedString = !Utils.BitmaskToBool((int)grbit, 0x0001);
                        //bool isExtString = Utils.BitmaskToBool((int)grbit, 0x0004);
                        //bool isRichString = Utils.BitmaskToBool((int)grbit, 0x0008);

                        //int cRun = 0;
                        //int cbExtRst = 0;

                        //if (isRichString)
                        //{
                        //    cRun = sr.ReadUInt16();
                        //}

                        //if (isExtString)
                        //{
                        //    cbExtRst = sr.ReadInt32();
                        //}

                        //// read characters from the string
                        //int charcount = 0;
                        //if (isCompressedString)
                        //    charcount = 1;
                        //else
                        //    charcount = 2;

                        //String stringbuffer = "";

                        //// read chars !!!
                        //while (sr.BaseStream.Length < sr.BaseStream.Position + cch * charcount)
                        //{
                        //    ushort currentLength = (ushort)(sr.BaseStream.Length - sr.BaseStream.Position);
                        //    cch -= (ushort)(currentLength / charcount);
                        //    for (int j = 0; j < currentLength / charcount; j++)
                        //    {
                        //        if (isCompressedString)
                        //        {
                        //            stringbuffer += (char)sr.ReadByte();
                        //        }
                        //        else
                        //        {
                        //            stringbuffer += System.BitConverter.ToChar(sr.ReadBytes(2), 0);
                        //        }
                        //    }

                        //    // read compressed/uncompressed byte value
                        //    byte grbit2 = sr.ReadByte();
                        //    if (grbit2 > 0)
                        //        isCompressedString = false;
                        //    else
                        //        isCompressedString = true;
                        //}

                        //for (int j = 0; j < cch; j++)
                        //{
                        //    if (isCompressedString)
                        //    {
                        //        stringbuffer += (char)sr.ReadByte();
                        //    }
                        //    else
                        //    {
                        //        stringbuffer += System.BitConverter.ToChar(sr.ReadBytes(2), 0);
                        //    }
                        //}
                        this.StringList.Add(str.Value);

                        if (str.fRichSt)
                        {
                            foreach (FormatRun formatRun in str.rgRun)
                            {
                                StringFormatAssignment format = new StringFormatAssignment();
                                format.StringNumber = i + 1;

                                format.CharNumber = formatRun.ich;
                                format.FontRecord = formatRun.ifnt;

                                // NOTE: If this value is less than 4, then it specifies a *zero-based* index of a Font record
                                //  in the collection of Font records in the globals substream. If this value is greater than 4,
                                //  then it specifies a *one-based* index of a Font record in the collection of Font records in
                                //  the globals substream.
                                //
                                if (format.FontRecord > 4)
                                {
                                    format.FontRecord--;
                                }

                                if (format.CharNumber < str.Value.Length)
                                {
                                    this.FormatList.Add(format);
                                }
                            }
                        }

                        //// read formatting runs!!
                        //if (isRichString)
                        //{
                        //    int countFormatingRuns = cRun;
                        //    while (sr.BaseStream.Length < sr.BaseStream.Position + countFormatingRuns * 4)
                        //    {
                        //        ushort currentLength = (ushort)(sr.BaseStream.Length - sr.BaseStream.Position);
                        //        countFormatingRuns -= (ushort)(currentLength / 4);
                        //        // get formating data
                        //        for (int j = 0; j < currentLength / 4; j++)
                        //        {
                        //            StringFormatAssignment format = new StringFormatAssignment();
                        //            format.StringNumber = i + 1;

                        //            format.CharNumber = sr.ReadUInt16();
                        //            format.FontRecord = sr.ReadUInt16();

                        //            if (format.CharNumber < stringbuffer.Length)
                        //            {
                        //                this.FormatList.Add(format);
                        //            }
                        //        }
                        //    }
                        //    // get formating data
                        //    for (int j = 0; j < countFormatingRuns; j++)
                        //    {
                        //        StringFormatAssignment format = new StringFormatAssignment();
                        //        format.StringNumber = i + 1;
                        //        format.CharNumber = sr.ReadUInt16();
                        //        format.FontRecord = sr.ReadUInt16();

                        //        if (format.FontRecord > 4)
                        //        {
                        //            format.FontRecord--;
                        //        }

                        //        /// ToDo: Check why some charNumbers are greater then string length
                        //        if (format.CharNumber < stringbuffer.Length)
                        //        {
                        //            this.FormatList.Add(format);
                        //        }
                        //    }
                        //}

                        //if (isExtString)
                        //{
                        //    int cchExtRst = cbExtRst;
                        //    byte[] ExtRst;
                        //    while (sr.BaseStream.Length < sr.BaseStream.Position + cchExtRst)
                        //    {
                        //        ushort currentLength = (ushort)(sr.BaseStream.Length - sr.BaseStream.Position);
                        //        cchExtRst -= (currentLength);
                        //        ExtRst = sr.ReadBytes(currentLength);
                        //    }

                        //    ExtRst = sr.ReadBytes(cchExtRst);
                        //}
                    }
                }
                catch (Exception ex)
                {
                    TraceLogger.Error(ex.Message);
                    TraceLogger.Debug(ex.ToString());
                }
            }
            // assert that the correct number of bytes has been read from the stream
            // Debug.Assert(this.Offset + this.Length == this.Reader.BaseStream.Position);
        }
Example #25
0
        public Formula(IStreamReader reader, RecordType id, ushort length)
            : base(reader, id, length)
        {
            // assert that the correct record type is instantiated
            Debug.Assert(this.Id == ID);
            this.val          = new byte[8];
            this.rw           = reader.ReadUInt16();
            this.col          = reader.ReadUInt16();
            this.ixfe         = reader.ReadUInt16();
            this.boolValueSet = false;

            long oldStreamPosition = this.Reader.BaseStream.Position;

            this.val = reader.ReadBytes(8); // read 8 bytes for the value of the formula
            ProcessFormulaValue();


            this.grbit    = reader.ReadUInt16();
            this.chn      = reader.ReadUInt32(); // this is used for performance reasons only
            this.cce      = reader.ReadUInt16();
            this.ptgStack = new Stack <AbstractPtg>();
            // reader.ReadBytes(this.cce);

            // check always calc mode
            this.fAlwaysCalc = Utils.BitmaskToBool((int)this.grbit, 0x01);

            // check if shared formula
            this.fShrFmla = Utils.BitmaskToBool((int)this.grbit, 0x08);

            // check if this should ignore error checking
            this.fClearErrors = Utils.BitmaskToBool(this.grbit, 0x20);


            oldStreamPosition = this.Reader.BaseStream.Position;
            if (!this.fShrFmla)
            {
                try
                {
                    this.ptgStack = ExcelHelperClass.getFormulaStack(this.Reader, this.cce);

                    List <PtgMemArea> memAreas = this.ptgStack.Where(ptg => ptg is PtgMemArea).Cast <PtgMemArea>().ToList();

                    //Read out the rgce for relevant PtgExtraMem if necessary
                    foreach (var memArea in memAreas)
                    {
                        memArea.ExtraMem = new PtgExtraMem(this.Reader);
                    }
                }
                catch (Exception ex)
                {
                    this.Reader.BaseStream.Seek(oldStreamPosition, System.IO.SeekOrigin.Begin);
                    this.Reader.BaseStream.Seek(this.cce, System.IO.SeekOrigin.Current);
                    TraceLogger.Error("Formula parse error in Row {0} Column {1}", this.rw, this.col);
                    TraceLogger.Debug(ex.StackTrace);
                    TraceLogger.Debug("Inner exception: {0}", ex.InnerException.StackTrace);
                }
            }
            else
            {
                //If the next expression isn't 5 bytes long, it's not a PtgExp shared formula reference...just ignore for now
                if (this.cce != 5)
                {
                    reader.ReadBytes(this.cce);
                }

                //First 8 bits are reserved, must be 1 but we'll ignore them for now
                byte ptg = reader.ReadByte();
                //Next two bytes are the row containing the shared formula
                sharedRow = reader.ReadUInt16();
                //then the col containing the shared formula
                sharedCol = reader.ReadUInt16();
            }


            // assert that the correct number of bytes has been read from the stream
            Debug.Assert(this.Offset + this.Length == this.Reader.BaseStream.Position);
        }
Example #26
0
        /// <summary>
        /// The overload apply method
        /// Creates the Worksheet xml document
        /// </summary>
        /// <param name="bsd">WorkSheetData</param>
        public void Apply(WorkSheetData bsd)
        {
            _xlsContext.CurrentSheet = bsd;
            _writer.WriteStartDocument();
            _writer.WriteStartElement("worksheet", OpenXmlNamespaces.SpreadsheetML);
            //if (bsd.emtpyWorksheet)
            //{
            //    _writer.WriteStartElement("sheetData");
            //    _writer.WriteEndElement();
            //}
            //else
            {
                // default info
                if (bsd.defaultColWidth >= 0 || bsd.defaultRowHeight >= 0)
                {
                    _writer.WriteStartElement("sheetFormatPr");

                    if (bsd.defaultColWidth >= 0)
                    {
                        double colWidht = (double)bsd.defaultColWidth;
                        _writer.WriteAttributeString("defaultColWidth", Convert.ToString(colWidht, CultureInfo.GetCultureInfo("en-US")));
                    }
                    if (bsd.defaultRowHeight >= 0)
                    {
                        TwipsValue tv = new TwipsValue(bsd.defaultRowHeight);
                        _writer.WriteAttributeString("defaultRowHeight", Convert.ToString(tv.ToPoints(), CultureInfo.GetCultureInfo("en-US")));
                    }
                    if (bsd.zeroHeight)
                    {
                        _writer.WriteAttributeString("zeroHeight", "1");
                    }
                    if (bsd.customHeight)
                    {
                        _writer.WriteAttributeString("customHeight", "1");
                    }
                    if (bsd.thickTop)
                    {
                        _writer.WriteAttributeString("thickTop", "1");
                    }
                    if (bsd.thickBottom)
                    {
                        _writer.WriteAttributeString("thickBottom", "1");
                    }

                    _writer.WriteEndElement(); // sheetFormatPr
                }



                // Col info
                if (bsd.colInfoDataTable.Count > 0)
                {
                    _writer.WriteStartElement("cols");
                    foreach (ColumnInfoData col in bsd.colInfoDataTable)
                    {
                        _writer.WriteStartElement("col");
                        // write min and max
                        // booth values are 0 based in the binary format and 1 based in the oxml format
                        // so you have to add 1 to the value!

                        _writer.WriteAttributeString("min", (col.min + 1).ToString());
                        _writer.WriteAttributeString("max", (col.max + 1).ToString());

                        if (col.widht != 0)
                        {
                            double colWidht = (double)col.widht / 256;
                            _writer.WriteAttributeString("width", Convert.ToString(colWidht, CultureInfo.GetCultureInfo("en-US")));
                        }
                        if (col.hidden)
                        {
                            _writer.WriteAttributeString("hidden", "1");
                        }

                        if (col.outlineLevel > 0)
                        {
                            _writer.WriteAttributeString("outlineLevel", col.outlineLevel.ToString());
                        }

                        if (col.customWidth)
                        {
                            _writer.WriteAttributeString("customWidth", "1");
                        }


                        if (col.bestFit)
                        {
                            _writer.WriteAttributeString("bestFit", "1");
                        }

                        if (col.phonetic)
                        {
                            _writer.WriteAttributeString("phonetic", "1");
                        }

                        if (col.style > 15)
                        {
                            _writer.WriteAttributeString("style", Convert.ToString(col.style - this._xlsContext.XlsDoc.WorkBookData.styleData.XFCellStyleDataList.Count, CultureInfo.GetCultureInfo("en-US")));
                        }

                        _writer.WriteEndElement(); // col
                    }


                    _writer.WriteEndElement();
                }
                // End col info

                _writer.WriteStartElement("sheetData");
                //  bsd.rowDataTable.Values
                foreach (RowData row in bsd.rowDataTable.Values)
                {
                    // write row start tag
                    // Row
                    _writer.WriteStartElement("row");
                    // the rowindex from the binary format is zero based, the ooxml format is one based
                    _writer.WriteAttributeString("r", (row.Row + 1).ToString());
                    if (row.height != null)
                    {
                        _writer.WriteAttributeString("ht", Convert.ToString(row.height.ToPoints(), CultureInfo.GetCultureInfo("en-US")));
                        if (row.customHeight)
                        {
                            _writer.WriteAttributeString("customHeight", "1");
                        }
                    }

                    if (row.hidden)
                    {
                        _writer.WriteAttributeString("hidden", "1");
                    }
                    if (row.outlineLevel > 0)
                    {
                        _writer.WriteAttributeString("outlineLevel", row.outlineLevel.ToString());
                    }
                    if (row.collapsed)
                    {
                        _writer.WriteAttributeString("collapsed", "1");
                    }
                    if (row.customFormat)
                    {
                        _writer.WriteAttributeString("customFormat", "1");
                        if (row.style > 15)
                        {
                            _writer.WriteAttributeString("s", (row.style - this._xlsContext.XlsDoc.WorkBookData.styleData.XFCellStyleDataList.Count).ToString());
                        }
                    }
                    if (row.thickBot)
                    {
                        _writer.WriteAttributeString("thickBot", "1");
                    }
                    if (row.thickTop)
                    {
                        _writer.WriteAttributeString("thickTop", "1");
                    }
                    if (row.minSpan + 1 > 0 && row.maxSpan > 0 && row.minSpan + 1 < row.maxSpan)
                    {
                        _writer.WriteAttributeString("spans", (row.minSpan + 1).ToString() + ":" + row.maxSpan.ToString());
                    }

                    row.Cells.Sort();
                    foreach (AbstractCellData cell in row.Cells)
                    {
                        // Col
                        _writer.WriteStartElement("c");
                        _writer.WriteAttributeString("r", ExcelHelperClass.intToABCString((int)cell.Col, (cell.Row + 1).ToString()));

                        if (cell.TemplateID > 15)
                        {
                            _writer.WriteAttributeString("s", (cell.TemplateID - this._xlsContext.XlsDoc.WorkBookData.styleData.XFCellStyleDataList.Count).ToString());
                        }

                        if (cell is StringCell)
                        {
                            _writer.WriteAttributeString("t", "s");
                        }
                        if (cell is FormulaCell)
                        {
                            FormulaCell fcell = (FormulaCell)cell;


                            if (((FormulaCell)cell).calculatedValue is String)
                            {
                                _writer.WriteAttributeString("t", "str");
                            }
                            else if (((FormulaCell)cell).calculatedValue is double)
                            {
                                _writer.WriteAttributeString("t", "n");
                            }
                            else if (((FormulaCell)cell).calculatedValue is byte)
                            {
                                _writer.WriteAttributeString("t", "b");
                            }
                            else if (((FormulaCell)cell).calculatedValue is int)
                            {
                                _writer.WriteAttributeString("t", "e");
                            }


                            // <f>1</f>
                            _writer.WriteStartElement("f");
                            if (!fcell.isSharedFormula)
                            {
                                String value = FormulaInfixMapping.mapFormula(fcell.PtgStack, this._xlsContext);


                                if (fcell.usesArrayRecord)
                                {
                                    _writer.WriteAttributeString("t", "array");
                                    _writer.WriteAttributeString("ref", ExcelHelperClass.intToABCString((int)cell.Col, (cell.Row + 1).ToString()));
                                }
                                if (fcell.alwaysCalculated)
                                {
                                    _writer.WriteAttributeString("ca", "1");
                                }

                                if (value.Equals(""))
                                {
                                    TraceLogger.Debug("Formula Parse Error in Row {0}\t Column {1}\t", cell.Row.ToString(), cell.Col.ToString());
                                }

                                _writer.WriteString(value);
                            }
                            /// If this cell is part of a shared formula
                            ///
                            else
                            {
                                SharedFormulaData sfd = bsd.checkFormulaIsInShared(cell.Row, cell.Col);
                                if (sfd != null)
                                {
                                    // t="shared"
                                    _writer.WriteAttributeString("t", "shared");
                                    //  <f t="shared" ref="C4:C11" si="0">H4+I4-J4</f>
                                    _writer.WriteAttributeString("si", sfd.ID.ToString());
                                    if (sfd.RefCount == 0)
                                    {
                                        /// Write value and reference
                                        _writer.WriteAttributeString("ref", sfd.getOXMLFormatedData());

                                        String value = FormulaInfixMapping.mapFormula(sfd.PtgStack, this._xlsContext, sfd.rwFirst, sfd.colFirst);
                                        _writer.WriteString(value);

                                        sfd.RefCount++;
                                    }
                                }
                                else
                                {
                                    TraceLogger.Debug("Formula Parse Error in Row {0}\t Column {1}\t", cell.Row.ToString(), cell.Col.ToString());
                                }
                            }

                            _writer.WriteEndElement();
                            /// write down calculated value from a formula
                            ///

                            _writer.WriteStartElement("v");

                            if (((FormulaCell)cell).calculatedValue is int)
                            {
                                _writer.WriteString(FormulaInfixMapping.getErrorStringfromCode((int)((FormulaCell)cell).calculatedValue));
                            }
                            else
                            {
                                _writer.WriteString(Convert.ToString(((FormulaCell)cell).calculatedValue, CultureInfo.GetCultureInfo("en-US")));
                            }

                            _writer.WriteEndElement();
                        }
                        else
                        {// Data !!!
                            _writer.WriteElementString("v", cell.getValue());
                        }
                        // add a type to the c element if the formula returns following types

                        _writer.WriteEndElement();  // close cell (c)
                    }


                    _writer.WriteEndElement();  // close row
                }

                // close tags
                _writer.WriteEndElement();      // close sheetData


                // Add the mergecell part
                //
                // - <mergeCells count="2">
                //        <mergeCell ref="B3:C3" />
                //        <mergeCell ref="E3:F4" />
                //     </mergeCells>
                if (bsd.MERGECELLSData != null)
                {
                    _writer.WriteStartElement("mergeCells");
                    _writer.WriteAttributeString("count", bsd.MERGECELLSData.cmcs.ToString());
                    foreach (MergeCellData mcell in bsd.MERGECELLSData.mergeCellDataList)
                    {
                        _writer.WriteStartElement("mergeCell");
                        _writer.WriteAttributeString("ref", mcell.getOXMLFormatedData());
                        _writer.WriteEndElement();
                    }
                    // close mergeCells Tag
                    _writer.WriteEndElement();
                }

                // hyperlinks!

                if (bsd.HyperLinkList.Count != 0)
                {
                    _writer.WriteStartElement("hyperlinks");
                    bool writtenParentElement = false;
                    foreach (HyperlinkData link in bsd.HyperLinkList)
                    {
                        //    Uri url;
                        //    if (link.absolute)
                        //    {

                        //        if (link.url.StartsWith("http", true, CultureInfo.GetCultureInfo("en-US"))
                        //            || link.url.StartsWith("mailto", true, CultureInfo.GetCultureInfo("en-US")))
                        //        {
                        //            url = new Uri(link.url, UriKind.Absolute);

                        //        }
                        //        else
                        //        {
                        //            link.url = "file:///" + link.url;
                        //            url = new Uri(link.url, UriKind.Absolute);
                        //        }

                        //    }
                        //    else
                        //    {

                        //        url = new Uri(link.url, UriKind.Relative);

                        //    }
                        //    try
                        //    {
                        //        if (System.Uri.IsWellFormedUriString(url.LocalPath.ToString(), System.UriKind.Absolute))
                        //        {

                        //if (!writtenParentElement)
                        //{

                        //    writtenParentElement = true;
                        //}
                        string refstring;

                        if (link.colLast == link.colFirst && link.rwLast == link.rwFirst)
                        {
                            refstring = ExcelHelperClass.intToABCString((int)link.colLast, (link.rwLast + 1).ToString());
                        }
                        else
                        {
                            refstring = ExcelHelperClass.intToABCString((int)link.colFirst, (link.rwFirst + 1).ToString()) + ":" + ExcelHelperClass.intToABCString((int)link.colLast, (link.rwLast + 1).ToString());
                        }

                        if (link.url != null)
                        {
                            ExternalRelationship er = this._xlsContext.SpreadDoc.WorkbookPart.GetWorksheetPart().AddExternalRelationship(OpenXmlRelationshipTypes.HyperLink, link.url.Replace(" ", ""));

                            _writer.WriteStartElement("hyperlink");
                            _writer.WriteAttributeString("ref", refstring);
                            _writer.WriteAttributeString("r", "id", OpenXmlNamespaces.Relationships, er.Id.ToString());

                            _writer.WriteEndElement();
                        }
                        else if (link.location != null)
                        {
                            _writer.WriteStartElement("hyperlink");
                            _writer.WriteAttributeString("ref", refstring);
                            _writer.WriteAttributeString("location", link.location);
                            if (link.display != null)
                            {
                                _writer.WriteAttributeString("display", link.display);
                            }
                            _writer.WriteEndElement();
                        }

                        /*           }
                         * }
                         *  catch (Exception ex)
                         *  {
                         *      TraceLogger.DebugInternal(ex.Message.ToString());
                         *      TraceLogger.DebugInternal(ex.StackTrace.ToString());
                         *  }
                         * }*/
                    }
                    _writer.WriteEndElement(); // hyperlinks
                    if (writtenParentElement)
                    {
                    }
                }

                // worksheet margins !!
                if (bsd.leftMargin != null && bsd.topMargin != null &&
                    bsd.rightMargin != null && bsd.bottomMargin != null &&
                    bsd.headerMargin != null && bsd.footerMargin != null)
                {
                    _writer.WriteStartElement("pageMargins");
                    {
                        _writer.WriteAttributeString("left", Convert.ToString(bsd.leftMargin, CultureInfo.GetCultureInfo("en-US")));
                        _writer.WriteAttributeString("right", Convert.ToString(bsd.rightMargin, CultureInfo.GetCultureInfo("en-US")));
                        _writer.WriteAttributeString("top", Convert.ToString(bsd.topMargin, CultureInfo.GetCultureInfo("en-US")));
                        _writer.WriteAttributeString("bottom", Convert.ToString(bsd.bottomMargin, CultureInfo.GetCultureInfo("en-US")));
                        _writer.WriteAttributeString("header", Convert.ToString(bsd.headerMargin, CultureInfo.GetCultureInfo("en-US")));
                        _writer.WriteAttributeString("footer", Convert.ToString(bsd.footerMargin, CultureInfo.GetCultureInfo("en-US")));
                    }
                    _writer.WriteEndElement(); // pageMargins
                }

                // page setup settings
                if (bsd.PageSetup != null)
                {
                    _writer.WriteStartElement("pageSetup");

                    if (!bsd.PageSetup.fNoPls && bsd.PageSetup.iPaperSize > 0 && bsd.PageSetup.iPaperSize < 255)
                    {
                        _writer.WriteAttributeString("paperSize", bsd.PageSetup.iPaperSize.ToString());
                    }
                    if (bsd.PageSetup.iScale >= 10 && bsd.PageSetup.iScale <= 400)
                    {
                        _writer.WriteAttributeString("scale", bsd.PageSetup.iScale.ToString());
                    }
                    _writer.WriteAttributeString("firstPageNumber", bsd.PageSetup.iPageStart.ToString());
                    _writer.WriteAttributeString("fitToWidth", bsd.PageSetup.iFitWidth.ToString());
                    _writer.WriteAttributeString("fitToHeight", bsd.PageSetup.iFitHeight.ToString());

                    if (bsd.PageSetup.fLeftToRight)
                    {
                        _writer.WriteAttributeString("pageOrder", "overThenDown");
                    }

                    if (!bsd.PageSetup.fNoOrient)
                    {
                        if (bsd.PageSetup.fPortrait)
                        {
                            _writer.WriteAttributeString("orientation", "portrait");
                        }
                        else
                        {
                            _writer.WriteAttributeString("orientation", "landscape");
                        }
                    }

                    //10 <attribute name="usePrinterDefaults" type="xsd:boolean" use="optional" default="true"/>

                    if (bsd.PageSetup.fNoColor)
                    {
                        _writer.WriteAttributeString("blackAndWhite", "1");
                    }
                    if (bsd.PageSetup.fDraft)
                    {
                        _writer.WriteAttributeString("draft", "1");
                    }

                    if (bsd.PageSetup.fNotes)
                    {
                        if (bsd.PageSetup.fEndNotes)
                        {
                            _writer.WriteAttributeString("cellComments", "atEnd");
                        }
                        else
                        {
                            _writer.WriteAttributeString("cellComments", "asDisplayed");
                        }
                    }
                    if (bsd.PageSetup.fUsePage)
                    {
                        _writer.WriteAttributeString("useFirstPageNumber", "1");
                    }

                    switch (bsd.PageSetup.iErrors)
                    {
                    case 0x00: _writer.WriteAttributeString("errors", "displayed"); break;

                    case 0x01: _writer.WriteAttributeString("errors", "blank"); break;

                    case 0x02: _writer.WriteAttributeString("errors", "dash"); break;

                    case 0x03: _writer.WriteAttributeString("errors", "NA"); break;

                    default: _writer.WriteAttributeString("errors", "displayed"); break;
                    }

                    _writer.WriteAttributeString("horizontalDpi", bsd.PageSetup.iRes.ToString());
                    _writer.WriteAttributeString("verticalDpi", bsd.PageSetup.iVRes.ToString());
                    if (!bsd.PageSetup.fNoPls)
                    {
                        _writer.WriteAttributeString("copies", bsd.PageSetup.iCopies.ToString());
                    }

                    _writer.WriteEndElement();
                }

                // embedded drawings (charts etc)
                if (bsd.ObjectsSequence != null)
                {
                    _writer.WriteStartElement(Sml.Sheet.ElDrawing, Sml.Ns);
                    {
                        _writer.WriteAttributeString("r", "id", OpenXmlNamespaces.Relationships, this._worksheetPart.DrawingsPart.RelIdToString);
                        bsd.ObjectsSequence.Convert(new DrawingMapping(this._xlsContext, this._worksheetPart.DrawingsPart, false));
                    }
                    _writer.WriteEndElement();
                }
            }

            _writer.WriteEndElement();      // close worksheet
            _writer.WriteEndDocument();

            // close writer
            _writer.Flush();
        }
Example #27
0
        internal void SetPropertyValue(string propertyName, object value)
        {
            TraceLogger.Debug($"SetProperty[{GetObjType.FullName}.{propertyName}]={value} ({value?.GetType().Name})");
            PropertyInfo pi = this.GetObjType.GetProperty(propertyName);

            if (pi != null)
            {
                this.TL.LogMessage(propertyName + " Set", "SET " + propertyName + " - .NET");
                try
                {
                    this.TL.LogMessage(propertyName + " Set", "  " + value.ToString());
                    pi.SetValue(this.GetLateBoundObject, value, (object[])null);
                    return;
                }
                catch (TargetInvocationException ex)
                {
                    this.SetTargetInvocationExceptionHandler(propertyName, (Exception)ex);
                }
                catch (Exception ex)
                {
                    this.TL.LogMessageCrLf("Exception", ex.ToString());
                    throw;
                }
            }
            if (this.IsComObject)
            {
                this.TL.LogMessage(propertyName + " Set", "SET " + propertyName + " - COM");
                try
                {
                    this.TL.LogMessage(propertyName + " Set", "  " + value.ToString());
                    this.GetObjType.InvokeMember(propertyName, BindingFlags.SetProperty, (Binder)null, this.GetLateBoundObject, new object[] { value }, CultureInfo.InvariantCulture);
                    return;
                }
                catch (COMException ex)
                {
                    this.TL.LogMessageCrLf("COMException", ex.ToString());
                    if (ex.ErrorCode == int.Parse("80020006", NumberStyles.HexNumber, (IFormatProvider)CultureInfo.InvariantCulture))
                    {
                        this.TL.LogMessageCrLf(propertyName + " Set", "  Throwing PropertyNotImplementedException: " + this._strProgId + " " + propertyName);
                        throw new PropertyNotImplementedException(this._strProgId + " " + propertyName, true, (Exception)ex);
                    }
                    this.TL.LogMessageCrLf(propertyName + " Set", "  Re-throwing exception");
                    throw;
                }
                catch (TargetInvocationException ex)
                {
                    this.TL.LogMessageCrLf("TargetInvocationException", ex.ToString());
                    if (ex.InnerException is COMException)
                    {
                        string message   = ex.InnerException.Message;
                        int    errorCode = ((ExternalException)ex.InnerException).ErrorCode;
                        if (errorCode == int.Parse("80040400", NumberStyles.HexNumber, (IFormatProvider)CultureInfo.InvariantCulture))
                        {
                            this.TL.LogMessageCrLf(propertyName + " Set", "  Translating COM not implemented exception to PropertyNotImplementedException: " + this._strProgId + " " + propertyName);
                            throw new PropertyNotImplementedException(this._strProgId + " " + propertyName, true, (Exception)ex);
                        }
                        this.TL.LogMessageCrLf(propertyName + " Set", "COM Exception so throwing inner exception: '" + message + "' '0x" + string.Format("{0:x8}", (object)errorCode) + "'");
                        throw new DriverAccessCOMException(message, errorCode, (Exception)ex);
                    }
                    this.SetTargetInvocationExceptionHandler(propertyName, (Exception)ex);
                }
                catch (Exception ex)
                {
                    this.TL.LogMessageCrLf("Exception", ex.ToString());
                    throw;
                }
            }
            this.TL.LogMessage("PropertySet", "  The object is neither a .NET object nor a COM object!");
            throw new PropertyNotImplementedException(this._strProgId + " " + propertyName, true);
        }
Example #28
0
        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="reader">Reader to parse the document </param>
        /// <param name="id">BiffRecord ID</param>
        /// <param name="length">The lengt of the biffrecord </param>
        public SST(IStreamReader binreader, RecordType id, ushort length, LinkedList <VirtualStreamReader> contstreamlist)
            : base(binreader, id, length)
        {
            // assert that the correct record type is instantiated
            Debug.Assert(this.Id == ID);
            this.contStreamlist = contstreamlist;
            this.StringList     = new List <string>();
            this.FormatList     = new List <StringFormatAssignment>();
            var buffer = new byte[length];
            int counti = 0;

            this.cstTotal  = (uint)this.Reader.ReadUInt32();
            this.cstUnique = this.Reader.ReadUInt32();

            try
            {
                // run over the different strings
                // there are x strings where x = cstUnique
                for (int i = 0; i < this.cstUnique; i++)
                {
                    counti++;
                    if (this.Reader.BaseStream.Position == this.Reader.BaseStream.Length)
                    {
                        this.switchStream();
                    }
                    // first get the char count of this string
                    ushort cch = this.Reader.ReadUInt16();
                    // get the grbit mask
                    byte grbit = this.Reader.ReadByte();
                    bool isCompressedString = false;
                    bool isExtString        = false;
                    bool isRichString       = false;

                    int cRun     = 0;
                    int cbExtRst = 0;

                    // demask the grbit
                    isCompressedString = !Utils.BitmaskToBool((int)grbit, 0x0001);
                    isExtString        = Utils.BitmaskToBool((int)grbit, 0x0004);
                    isRichString       = Utils.BitmaskToBool((int)grbit, 0x0008);



                    if (isRichString)
                    {
                        cRun = this.Reader.ReadUInt16();
                    }

                    if (isExtString)
                    {
                        cbExtRst = this.Reader.ReadInt32();
                    }

                    // switch stream
                    if (this.Reader.BaseStream.Position == this.Reader.BaseStream.Length)
                    {
                        this.switchStream();
                    }


                    // read characters from the string
                    int charcount = 0;
                    if (isCompressedString)
                    {
                        charcount = 1;
                    }
                    else
                    {
                        charcount = 2;
                    }
                    string stringbuffer = "";
                    // read chars !!!
                    while (this.Reader.BaseStream.Length < this.Reader.BaseStream.Position + cch * charcount)
                    {
                        ushort currentLength = (ushort)(this.Reader.BaseStream.Length - this.Reader.BaseStream.Position);
                        cch -= (ushort)(currentLength / charcount);
                        for (int j = 0; j < currentLength / charcount; j++)
                        {
                            if (isCompressedString)
                            {
                                stringbuffer += (char)this.Reader.ReadByte();
                            }
                            else
                            {
                                stringbuffer += System.BitConverter.ToChar(this.Reader.ReadBytes(2), 0);
                            }
                        }
                        // switch to next stream !!
                        this.switchStream();
                        // read compressed/uncompressed byte value
                        byte grbit2 = this.Reader.ReadByte();
                        if (grbit2 > 0)
                        {
                            isCompressedString = false;
                        }
                        else
                        {
                            isCompressedString = true;
                        }
                    }

                    for (int j = 0; j < cch; j++)
                    {
                        if (isCompressedString)
                        {
                            stringbuffer += (char)this.Reader.ReadByte();
                        }
                        else
                        {
                            stringbuffer += System.BitConverter.ToChar(this.Reader.ReadBytes(2), 0);
                        }
                    }
                    this.StringList.Add(stringbuffer);

                    // read formatting runs!!
                    if (isRichString)
                    {
                        int countFormatingRuns = cRun;
                        while (this.Reader.BaseStream.Length < this.Reader.BaseStream.Position + countFormatingRuns * 4)
                        {
                            ushort currentLength = (ushort)(this.Reader.BaseStream.Length - this.Reader.BaseStream.Position);
                            countFormatingRuns -= (ushort)(currentLength / 4);
                            // get formating data
                            for (int j = 0; j < currentLength / 4; j++)
                            {
                                var format = new StringFormatAssignment();
                                format.StringNumber = counti;
                                format.CharNumber   = this.Reader.ReadUInt16();



                                format.FontRecord = this.Reader.ReadUInt16();
                                if (format.CharNumber < stringbuffer.Length)
                                {
                                    this.FormatList.Add(format);
                                }
                            }
                            // switch to next stream !!
                            this.switchStream();
                            // read compressed/uncompressed byte value
                            // this.Reader.ReadByte();
                        }
                        // get formating data
                        for (int j = 0; j < countFormatingRuns; j++)
                        {
                            var format = new StringFormatAssignment();
                            format.StringNumber = counti;
                            format.CharNumber   = this.Reader.ReadUInt16();
                            format.FontRecord   = this.Reader.ReadUInt16();

                            if (format.FontRecord > 4)
                            {
                                format.FontRecord--;
                            }

                            /// ToDo: Check why some charNumbers are greater then string length
                            if (format.CharNumber < stringbuffer.Length)
                            {
                                this.FormatList.Add(format);
                            }
                        }
                    }

                    if (isExtString)
                    {
                        int    cchExtRst = cbExtRst;
                        byte[] ExtRst;
                        while (this.Reader.BaseStream.Length < this.Reader.BaseStream.Position + cchExtRst)
                        {
                            ushort currentLength = (ushort)(this.Reader.BaseStream.Length - this.Reader.BaseStream.Position);
                            cchExtRst -= (currentLength);
                            ExtRst     = this.Reader.ReadBytes(currentLength);
                            // switch to next stream !!
                            this.switchStream();
                            // read compressed/uncompressed byte value
                            // this.Reader.ReadByte();
                        }

                        ExtRst = this.Reader.ReadBytes(cchExtRst);
                    }
                }
            }
            catch (Exception ex)
            {
                TraceLogger.Error(ex.Message);
                TraceLogger.Debug(ex.ToString());
            }

            // assert that the correct number of bytes has been read from the stream
            // Debug.Assert(this.Offset + this.Length == this.Reader.BaseStream.Position);
        }
Example #29
0
        public Formula(IStreamReader reader, RecordType id, ushort length)
            : base(reader, id, length)
        {
            // assert that the correct record type is instantiated
            Debug.Assert(this.Id == ID);
            this.val          = new byte[8];
            this.rw           = reader.ReadUInt16();
            this.col          = reader.ReadUInt16();
            this.ixfe         = reader.ReadUInt16();
            this.boolValueSet = false;

            long oldStreamPosition = this.Reader.BaseStream.Position;

            this.val = reader.ReadBytes(8); // read 8 bytes for the value of the formular
            if (this.val[6] == 0xFF && this.val[7] == 0xFF)
            {
                // this value is a string, an error or a boolean value
                byte firstOffset = this.val[0];
                if (firstOffset == 1)
                {
                    // this is a boolean value
                    this.boolValue    = this.val[2];
                    this.boolValueSet = true;
                }
                if (firstOffset == 2)
                {
                    // this is a error value
                    this.errorValue = (int)this.val[2];
                }
            }
            else
            {
                this.Reader.BaseStream.Seek(oldStreamPosition, System.IO.SeekOrigin.Begin);
                this.calculatedValue = reader.ReadDouble();
            }


            this.grbit    = reader.ReadUInt16();
            this.chn      = reader.ReadUInt32(); // this is used for performance reasons only
            this.cce      = reader.ReadUInt16();
            this.ptgStack = new Stack <AbstractPtg>();
            // reader.ReadBytes(this.cce);

            // check always calc mode
            this.fAlwaysCalc = Utils.BitmaskToBool((int)this.grbit, 0x01);

            // check if shared formula
            this.fShrFmla = Utils.BitmaskToBool((int)this.grbit, 0x08);



            oldStreamPosition = this.Reader.BaseStream.Position;
            if (!this.fShrFmla)
            {
                try
                {
                    this.ptgStack = ExcelHelperClass.getFormulaStack(this.Reader, this.cce);
                }
                catch (Exception ex)
                {
                    this.Reader.BaseStream.Seek(oldStreamPosition, System.IO.SeekOrigin.Begin);
                    this.Reader.BaseStream.Seek(this.cce, System.IO.SeekOrigin.Current);
                    TraceLogger.Error("Formula parse error in Row {0} Column {1}", this.rw, this.col);
                    TraceLogger.Debug(ex.StackTrace);
                    TraceLogger.Debug("Inner exception: {0}", ex.InnerException.StackTrace);
                }
            }
            else
            {
                reader.ReadBytes(this.cce);
            }


            // assert that the correct number of bytes has been read from the stream
            Debug.Assert(this.Offset + this.Length == this.Reader.BaseStream.Position);
        }
Example #30
0
        internal object ExecMethod(string methodName, params object[] parms)
        {
            string methSig = "null";

            if (parms != null)
            {
                methSig = String.Join(", ", parms);
            }
            methSig = $"{methodName}({methSig})";
            TraceLogger.Debug($"ExecMethod=> {methSig}");
            this.TL.LogMessage(methodName, "Start");
            MethodInfo method = this.GetObjType.GetMethod(methodName);

            if (method != null)
            {
                try
                {
                    foreach (object parm in parms)
                    {
                        this.TL.LogMessage(methodName, "  Parameter: " + parm.ToString());
                    }
                    this.TL.LogMessage(methodName, "  Calling " + methodName);
                    object obj = method.Invoke(this.GetLateBoundObject, parms);
                    if (obj == null)
                    {
                        this.TL.LogMessage(methodName, "  Successfully called method, no return value");
                    }
                    else
                    {
                        this.TL.LogMessage(methodName, "  " + obj.ToString());
                    }
                    return(obj);
                }
                catch (TargetInvocationException ex)
                {
                    this.MethodTargetInvocationExceptionHandler(methodName, (Exception)ex);
                }
                catch (Exception ex)
                {
                    this.TL.LogMessageCrLf("Exception", ex.ToString());
                    throw;
                }
            }
            if (this.IsComObject)
            {
                try
                {
                    foreach (object parm in parms)
                    {
                        this.TL.LogMessage(methodName, "  Parameter: " + parm.ToString());
                    }
                    this.TL.LogMessage(methodName, "  Calling " + methodName + " - it is a COM object");
                    object obj = this.GetObjType.InvokeMember(methodName, BindingFlags.InvokeMethod, (Binder)null, this.GetLateBoundObject, parms, CultureInfo.InvariantCulture);
                    if (obj == null)
                    {
                        this.TL.LogMessage(methodName, "  Successfully called method, no return value");
                    }
                    else
                    {
                        this.TL.LogMessage(methodName, "  " + obj.ToString());
                    }
                    return(obj);
                }
                catch (COMException ex)
                {
                    this.TL.LogMessageCrLf("COMException", ex.ToString());
                    if (ex.ErrorCode == int.Parse("80020006", NumberStyles.HexNumber, (IFormatProvider)CultureInfo.InvariantCulture))
                    {
                        this.TL.LogMessageCrLf(methodName, "  Throwing MethodNotImplementedException: " + this._strProgId + " " + methodName);
                        throw new MethodNotImplementedException(this._strProgId + " " + methodName);
                    }
                    this.TL.LogMessageCrLf(methodName, "Re-throwing exception");
                    throw;
                }
                catch (TargetInvocationException ex)
                {
                    this.TL.LogMessageCrLf("TargetInvocationException", ex.ToString());
                    if (ex.InnerException is COMException)
                    {
                        string message   = ex.InnerException.Message;
                        int    errorCode = ((ExternalException)ex.InnerException).ErrorCode;
                        if (errorCode == int.Parse("80040400", NumberStyles.HexNumber, (IFormatProvider)CultureInfo.InvariantCulture))
                        {
                            this.TL.LogMessageCrLf(methodName, "  Translating COM not implemented exception to MethodNotImplementedException: " + this._strProgId + " " + methodName);
                            throw new MethodNotImplementedException(this._strProgId + " " + methodName, (Exception)ex);
                        }
                        this.TL.LogMessageCrLf(methodName, "  COM Exception so throwing inner exception: '" + message + "' '0x" + string.Format("{0:x8}", (object)errorCode) + "'");
                        throw new DriverAccessCOMException(message, errorCode, (Exception)ex);
                    }
                    this.MethodTargetInvocationExceptionHandler(methodName, (Exception)ex);
                }
                catch (Exception ex)
                {
                    this.TL.LogMessageCrLf("Exception", ex.ToString());
                    throw;
                }
            }
            this.TL.LogMessage(methodName, "  is neither a .NET object nor a COM object!");
            throw new MethodNotImplementedException(this._strProgId + " " + methodName);
        }