Example #1
0
 private static async Task ProcessDirectory(DirectoryInfo projectDirectory)
 {
     Console.Out.WriteLine($"Analyzing {projectDirectory}...");
     Console.Out.WriteLine(await StyleGenerator.Generate(projectDirectory, Console.Out, true));
     Console.Out.WriteLine($"Analyzing {projectDirectory} complete.");
     Console.Out.WriteLine();
 }
    public static async Task <string> Generate(DirectoryInfo directory, TextWriter writer, bool generateStatistics = false)
    {
        if (directory is null)
        {
            throw new ArgumentNullException(nameof(directory));
        }

        if (writer is null)
        {
            throw new ArgumentNullException(nameof(writer));
        }

        var aggregator = new StyleAggregator();

        await writer.WriteLineAsync($"Analyzing {directory}...").ConfigureAwait(false);

        foreach (var file in directory.EnumerateFiles("*.cs", SearchOption.AllDirectories))
        {
            await writer.WriteLineAsync($"\tAnalyzing {file.FullName}...").ConfigureAwait(false);

            var(unit, model) = StyleGenerator.GetCompilationInformation(file.FullName);
            aggregator       = aggregator.Update(new StyleAggregator().Add(unit, model));
        }

        if (generateStatistics)
        {
            using var statisticsWriter = File.CreateText("statistics.json");
            new JsonSerializer().Serialize(statisticsWriter, aggregator);
        }

        return(aggregator.GenerateConfiguration());
    }
    public static string GenerateFromDocument(FileInfo document, TextWriter writer, bool generateStatistics = false)
    {
        if (document is null)
        {
            throw new ArgumentNullException(nameof(document));
        }

        if (writer is null)
        {
            throw new ArgumentNullException(nameof(writer));
        }

        if (document.Extension.ToUpperInvariant() == ".CS")
        {
            writer.WriteLine($"Analyzing {document.FullName}...");
            var(unit, model) = StyleGenerator.GetCompilationInformation(document.FullName);
            var aggregator = new StyleAggregator().Add(unit, model);

            if (generateStatistics)
            {
                using var statisticsWriter = File.CreateText("statistics.json");
                new JsonSerializer().Serialize(statisticsWriter, aggregator);
            }

            return(aggregator.GenerateConfiguration());
        }

        return(string.Empty);
    }
 public static async Task Main(DirectoryInfo?directory, FileInfo?file, bool generateStatistics = false)
 {
     if (directory is not null)
     {
         await Console.Out.WriteLineAsync(await StyleGenerator.Generate(directory, Console.Out, generateStatistics).ConfigureAwait(false)).ConfigureAwait(false);
     }
     else
     {
         if (file is not null && file.Extension == ".cs")
         {
             await Console.Out.WriteLineAsync(StyleGenerator.GenerateFromDocument(file, Console.Out, generateStatistics)).ConfigureAwait(false);
         }
        void IRequireAfterAxesFinalized.AxesFinalized(IChartRenderContext icrc)
        {
            if (icrc.Type == RenderType.TransformsOnly)
            {
                return;
            }
            var mat   = MatrixSupport.DataArea(CategoryAxis1, CategoryAxis2, icrc.SeriesArea, 4);
            var matmp = MatrixSupport.Multiply(mat.Item1, mat.Item2);

            _trace.Verbose($"{Name} matmp:{matmp} clip:{icrc.SeriesArea}");
            var mt = new MatrixTransform()
            {
                Matrix = matmp
            };

            StyleGenerator?.Reset();
            foreach (var istate in ItemState)
            {
                if (istate.Element.DataContext is GeometryWith2OffsetShim <RectangleGeometry> gs)
                {
                    gs.GeometryTransform = mt;
                }
                else
                {
                    istate.Element.Data.Transform = mt;
                }
                if (StyleGenerator != null)
                {
                    var style = StyleGenerator.For(new Category2StyleContext(CategoryAxis1, CategoryAxis2, this, new double[3] {
                        istate.Value, istate.XValue, (istate as IProvideYValue).YValue
                    }));
                    if (style != null)
                    {
                        istate.Element.Style = style;
                    }
                    else
                    {
                        if (PathStyle != null)
                        {
                            BindTo(this, nameof(PathStyle), istate.Element, FrameworkElement.StyleProperty);
                        }
                    }
                }
            }
            StyleGenerator?.UpdateLegend(new Category2StyleContext(CategoryAxis1, CategoryAxis2, this, new double[0]));
        }
        public static void GenerateFromFile()
        {
            var sourceFile = new FileInfo($"{Guid.NewGuid().ToString("N")}.cs");

            try
            {
                File.WriteAllText(sourceFile.FullName,
                                  @"public static class Test
{
	public static void VarFoo()
	{
		var a = 1;
	}
}");
                using var writer = new StringWriter();
                Assert.That(string.IsNullOrWhiteSpace(StyleGenerator.GenerateFromDocument(sourceFile, writer)), Is.False);
            }
            finally
            {
                File.Delete(sourceFile.FullName);
            }
        }
Example #7
0
        /// <summary>
        /// Saves the document in OOXML format.
        /// </summary>
        private void SaveInOOXML()
        {
            //First create the file if this is a new file
            if (_isNew && _template != null)
            {
                //Create a new file based on the template
                //Read the template stream inot a new document.
                using (_template)
                {
                    using (var documentStream = new MemoryStream((int)_template.Length))
                    {
                        _template.Position = 0L;
                        byte[] buffer = new byte[2048];
                        int    length = buffer.Length;
                        int    size;
                        while ((size = _template.Read(buffer, 0, length)) != 0)
                        {
                            documentStream.Write(buffer, 0, size);
                        }
                        documentStream.Position = 0L;
                        // Modify the document to ensure it is correctly marked as a Document and not Template
                        using (var document = WordprocessingDocument.Open(documentStream, true))
                        {
                            document.ChangeDocumentType(WordprocessingDocumentType.Document);
                        }
                        //Save the stream to a new file.
                        File.WriteAllBytes(Filename, documentStream.ToArray());
                    }
                }
            }
            else if (_isNew && !string.IsNullOrWhiteSpace(_filenameTemplate))
            {
                //Create a new file based on the template
                //Read the file in to a stream.
                using (var templateStream = File.OpenRead(_filenameTemplate))
                {
                    using (var documentStream = new MemoryStream((int)templateStream.Length))
                    {
                        templateStream.Position = 0L;
                        byte[] buffer = new byte[2048];
                        int    length = buffer.Length;
                        int    size;
                        while ((size = templateStream.Read(buffer, 0, length)) != 0)
                        {
                            documentStream.Write(buffer, 0, size);
                        }
                        documentStream.Position = 0L;
                        // Modify the document to ensure it is correctly marked as a Document and not Template
                        using (var document = WordprocessingDocument.Open(documentStream, true))
                        {
                            document.ChangeDocumentType(WordprocessingDocumentType.Document);
                        }
                        //Save the stream to a new file.
                        File.WriteAllBytes(Filename, documentStream.ToArray());
                    }
                }
            }
            else if (_isNew)
            {
                using (var doc = WordprocessingDocument.Create(Filename, WordprocessingDocumentType.Document))
                {
                    var mainPart = doc.AddMainDocumentPart();
                    var document = new Document(
                        new Body());
                    document.Save(mainPart);

                    //Create the styles part.
                    var styleDefinitionsPart = mainPart.AddNewPart <StyleDefinitionsPart>();
                    StyleGenerator.DefaultStyle().Save(styleDefinitionsPart);

                    //Close the document
                    doc.Close();
                }
            }

            using (var doc = WordprocessingDocument.Open(Filename, true))
            {
                try
                {
                    var mainPart = doc.MainDocumentPart;
                    /* Create the contents */
                    var body       = mainPart.Document.Body;
                    var imageCount = 1; //This is a counter for setting the image number.
                    var listCount  = 0; //This is the counter for the number of lists.
                    //Create the list templates
                    var numberingDefinitionsPart = mainPart.NumberingDefinitionsPart ?? mainPart.AddNewPart <NumberingDefinitionsPart>();
                    var numbering = ListGenerator.CreateNumbering(numberingDefinitionsPart);

                    foreach (var paragraph in Paragraphs)
                    {
                        //If this is an image we also need to pass the MainpArt as this is needed to generate the image part
                        var img   = paragraph.Value as Picture;
                        var table = paragraph.Value as Table;
                        var list  = paragraph.Value as List;
                        if (img != null)
                        {
                            foreach (var p in img.GetOOXMLParagraph(mainPart, paragraph.Key, ref imageCount))
                            {
                                body.Append(p);
                            }
                        }
                        else if (table != null)
                        {
                            //Add the table
                            body.Append(table.GetOOXMLTable());
                            //Add an extra paragraph so two following tables will not be concatenated.
                            body.Append(Paragraph.EmptyParagraph());
                        }
                        else if (list != null)
                        {
                            //Add the list
                            listCount++;
                            //Add the reference to the list
                            NumberingInstance numberingInstance = new NumberingInstance {
                                NumberID = listCount
                            };
                            AbstractNumId abstractNumId = new AbstractNumId {
                                Val = list.Type == ListType.Bullet ? 0 : 1
                            };

                            numberingInstance.Append(abstractNumId);
                            numbering.Append(numberingInstance);

                            foreach (var item in list.GetOOXMLList(listCount))
                            {
                                body.Append(item);
                            }
                        }
                        else
                        {
                            //Add the text paragraph(s)
                            foreach (var p in paragraph.Value.GetOOXMLParagraph())
                            {
                                body.Append(p);
                            }
                        }
                    }

                    //All the paragraphs are done.Save the numbering.
                    numbering.Save(numberingDefinitionsPart);

                    //Replace the custom tags.
                    foreach (var customPart in _customParts)
                    {
                        customPart.Replace(mainPart, ref imageCount);
                    }

                    /* Save the results and close */
                    mainPart.Document.Save();
                    doc.Close();
                }
                catch (Exception ex)
                {
                    throw new FileLoadException("An error occured when saving the document", Filename, ex);
                }
            }
        }
        public void Parse(string input)
        {
            bool inStyle = false;
            int strLength = input.Length;
            int lineIndex = 0;
            int lineNo = 0;
            bool inComment = false;
            bool inQuote = false;
            bool inSingleQuote = false;
            bool inDoubleQuote = false;
            char current = '\0';
            char previous = '\0';
            char next = '\0';
            string rule = string.Empty;
            string style = string.Empty;
            string line = string.Empty;

            //int i = 0;
            //while (i < strLength)
            input = input + "\n ";
            for (int i = 0; i < input.Length - 1; i++)
            {
                previous = current;
                current = input[i];
                next = input[i + 1];

                lineIndex++;
                if (current == '\n')
                {
                    if (lineNo == 0)
                    {
                        switch (line)
                        {
                            case "/*Theme*/":
                                generator = StyleGenerator.Theme;
                                break;
                            case "/*Standard*/":
                                generator = StyleGenerator.Standard;
                                break;
                            default:
                                generator = StyleGenerator.Advanced;
                                break;
                        }
                    }

                    if (lineNo == 1)
                    {
                        try
                        {
                            if (line.StartsWith("/*", StringComparison.Ordinal) && line.EndsWith("*/", StringComparison.Ordinal))
                            {
                                hue = int.Parse(line.Substring(2, line.Length - 4));
                            }
                            else
                            {
                                hue = -1;
                            }
                        }
                        catch
                        {
                            hue = -1;
                        }
                    }

                    lineIndex = -1;
                    lineNo++;
                    line = string.Empty;
                    continue;
                }
                else if (current != '\r')
                {
                    line += current.ToString();
                }

                if (current == '/' && next == '*')
                {
                    inComment = true;
                    continue;
                }

                if (current == '/' && previous == '*')
                {
                    inComment = false;
                    continue;
                }

                if (!inQuote && current == '\'')
                {
                    inQuote = inSingleQuote = true;
                }

                if (!inQuote && current == '"')
                {
                    inQuote = inDoubleQuote = true;
                }

                if (inSingleQuote && current == '\'')
                {
                    inQuote = inSingleQuote = false;
                }

                if (inDoubleQuote && current == '"')
                {
                    inQuote = inDoubleQuote = false;
                }

                if (!inComment)
                {
                    if (!inStyle)
                    {
                        if (current == '{')
                        {
                            inStyle = true;
                            rule = rule.Trim(new char[] { ' ', '\t', '\r', '\n' });
                            continue;
                        }

                        if (string.IsNullOrEmpty(rule))
                        {
                            if (current != '\t' && current != ' ')
                            {
                                rule = current.ToString();
                            }
                        }
                        else
                        {
                            rule += current.ToString();
                        }
                    }
                    else
                    {
                        if (!inQuote)
                        {
                            if (current == '}')
                            {
                                inStyle = false;

                                StyleStyle tempStyle = new StyleStyle(rule);
                                tempStyle.Parse(style);
                                styles.Add(rule, tempStyle);

                                style = string.Empty;
                                rule = string.Empty;
                                continue;
                            }
                            else
                            {
                                style += current.ToString();
                            }
                        }
                        else
                        {
                            style += current.ToString();
                        }
                    }
                }

                //i++;
            }
        }
 public CascadingStyleSheet()
 {
     styles = new Dictionary<string, StyleStyle>();
     generator = StyleGenerator.Advanced;
 }