public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.Null)
            {
                JObject jObject = JObject.Load(reader);
                object  result;
                if (objectType == typeof(Message))
                {
                    JToken token       = jObject[nameof(MessageType)];
                    var    messageType = (MessageType)Enum.Parse(typeof(MessageType), token.ToString());
                    switch (messageType)
                    {
                    case MessageType.Progress:
                        result = new ProgressMessage();
                        break;

                    case MessageType.Error:
                        result = new ErrorMessage();
                        break;

                    case MessageType.Result:
                        result = new StatisticsMessage();
                        break;

                    default:
                        throw new NotImplementedException($"{token} message type is not supported");
                    }
                }
                else if (objectType == typeof(LanguageStatistics))
                {
                    JToken   token    = jObject[nameof(Language)];
                    Language language = LanguageUtils.ParseLanguages(token.ToString()).FirstOrDefault();
                    if (language == Language.CSharp)
                    {
                        result = new CSharpStatistics();
                    }
                    else if (language == Language.Java)
                    {
                        result = new JavaStatistics();
                    }
                    else if (language == Language.Php)
                    {
                        result = new PhpStatistics();
                    }
                    else
                    {
                        throw new NotImplementedException($"{token} language is not supported");
                    }
                }
                else
                {
                    throw new FormatException("Invalid JSON");
                }

                serializer.Populate(jObject.CreateReader(), result);
                return(result);
            }

            return(null);
        }
Example #2
0
        private void CollectCSharpStatistics(CSharpStatistics csharpStatistics, string filePath)
        {
            try
            {
                var fileData  = File.ReadAllText(filePath);
                var fileName  = Path.GetFileName(filePath).ToLowerInvariant();
                var extension = Path.GetExtension(fileName).ToLowerInvariant();
                if (extension == ".sln")
                {
                    var solutionFile = Microsoft.Build.Construction.SolutionFile.Parse(filePath);
                    var solution     = new CSharpSolution();
                    csharpStatistics.Solutions.Add(solution);
                    solution.Name = Path.GetFileNameWithoutExtension(filePath);
                    foreach (var project in solutionFile.ProjectsInOrder)
                    {
                        CSharpProject csharpProject = new CSharpProject();
                        csharpProject.Name         = project.ProjectName;
                        csharpProject.GUID         = project.ProjectGuid;
                        csharpProject.RelativePath = project.RelativePath;

                        var guidInd = fileData.IndexOf(csharpProject.GUID);
                        var lineInd = fileData.LastIndexOfAny(new char[] { '\r', '\n' }, guidInd);
                        if (lineInd == -1)
                        {
                            lineInd = 0;
                        }
                        fileData.IndexOf(')', lineInd);
                        int    projectTypeGuidStartInd = lineInd + "Project(\"".Length + 1;
                        int    projectTypeGuidEndInd   = fileData.IndexOf("\")", lineInd);
                        string projectTypeGuid         = fileData.Substring(projectTypeGuidStartInd, projectTypeGuidEndInd - projectTypeGuidStartInd);

                        string projectType;
                        if (CSharpGuidTypes.TryGetValue(projectTypeGuid, out projectType))
                        {
                            csharpProject.ProjectType = projectType;
                        }

                        var projectPath = Path.Combine(Path.GetDirectoryName(filePath), csharpProject.RelativePath);
                        CollectCSharpProjectStatistics(csharpStatistics, csharpProject, projectPath);
                        solution.Projects.Add(csharpProject);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger?.LogInfo(new ErrorMessage(ex.ToString()));
            }
        }
Example #3
0
        private void CollectCSharpProjectStatistics(CSharpStatistics csharpStatistics, CSharpProject csharpProject, string projectPath)
        {
            try
            {
                var doc = XDocument.Load(projectPath);
                var ns  = doc.Root.Name.NamespaceName == "" ? "" : "{" + doc.Root.Name.NamespaceName + "}";

                var frameworkVersions = doc.Element(XName.Get($"{ns}Project"))?.Elements(XName.Get($"{ns}PropertyGroup"))
                                        .SelectMany(elem => elem.Elements(XName.Get($"{ns}TargetFrameworkVersion"))
                                                    .Select(elem2 => elem2.Value));

                if (frameworkVersions != null)
                {
                    csharpProject.FrameworkVersion = frameworkVersions.First();
                }

                var references = doc.Element(XName.Get($"{ns}Project"))?.Elements(XName.Get($"{ns}ItemGroup"))
                                 .SelectMany(elem => elem.Elements(XName.Get($"{ns}Reference"))
                                             .Select(elem2 => elem2.Attribute(XName.Get($"Include"))?.Value));

                if (references != null)
                {
                    csharpProject.References = references.ToList();
                }

                var projectFiles = new List <string>();
                projectFiles.AddRange(GetProjectFiles(doc, "Compile"));
                projectFiles.AddRange(GetProjectFiles(doc, "None"));
                projectFiles.AddRange(GetProjectFiles(doc, "Content"));
                projectFiles.AddRange(GetProjectFiles(doc, "EmbeddedResource"));
                projectFiles.AddRange(GetProjectFiles(doc, "Page"));
                projectFiles.AddRange(GetProjectFiles(doc, "Resource"));

                csharpProject.FilesCount     = projectFiles.Count;
                csharpStatistics.FilesCount += projectFiles.Count;
                string fileDir = Path.GetDirectoryName(projectPath);
                foreach (var projectFile in projectFiles)
                {
                    CollectCSharpFileStatistics(csharpStatistics, csharpProject, Path.Combine(fileDir, projectFile));
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex);
            }
        }
Example #4
0
        public StatisticsMessage CollectStatistics(string directoryPath, int startInd = 0, int length = 0)
        {
            IEnumerable <string> fileNames = Enumerable.Empty <string>();

            if (Directory.Exists(directoryPath))
            {
                fileNames = Directory.GetFiles(directoryPath, "*.*", SearchOption.AllDirectories);
                if (startInd != 0)
                {
                    fileNames = fileNames.Skip(startInd);
                }
                if (length != 0)
                {
                    fileNames = fileNames.Take(length);
                }
            }
            else
            {
                fileNames = new string[] { directoryPath };
            }
            int totalFilesCount = fileNames.Count();

            var phpStatistics    = new PhpStatistics();
            var javaStatistics   = new JavaStatistics();
            var csharpStatistics = new CSharpStatistics();

            int processedCount = 0;

            if (!Multithreading)
            {
                foreach (var filePath in fileNames)
                {
                    CollectStatistics(phpStatistics, javaStatistics, csharpStatistics, filePath, totalFilesCount, ref processedCount);
                }
            }
            else
            {
                var options = new ParallelOptions {
                    MaxDegreeOfParallelism = Environment.ProcessorCount
                };
                Parallel.ForEach(fileNames, options, filePath =>
                {
                    Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
                    CollectStatistics(phpStatistics, javaStatistics, csharpStatistics, filePath, totalFilesCount, ref processedCount);
                });
            }

            var result = new StatisticsMessage
            {
                Id                 = Guid.NewGuid().ToString(),
                ErrorCount         = Logger?.ErrorCount ?? 0,
                LanguageStatistics = new List <LanguageStatistics>()
                {
                    phpStatistics,
                    javaStatistics,
                    csharpStatistics
                }
            };

            return(result);
        }
Example #5
0
        private void CollectCSharpFileStatistics(CSharpStatistics csharpStatistics, CSharpProject csharpProject, string filePath)
        {
            try
            {
                var fileData  = File.ReadAllText(filePath);
                var fileName  = Path.GetFileName(filePath).ToLowerInvariant();
                var extension = Path.GetExtension(fileName).ToLowerInvariant();

                if (extension == ".cs" || extension == ".aspx" || extension == ".cshtml" || extension == ".ashx" || extension == ".ascx")
                {
                    int linesCount = 0;
                    int filesCount = 0;
                    switch (extension)
                    {
                    case ".cs":
                        linesCount = CalculateCSharpLinesCount(fileData);
                        filesCount = 1;
                        csharpStatistics.CsFilesCount += 1;
                        csharpStatistics.CsLinesCount += linesCount;
                        csharpProject.CsFilesCount    += 1;
                        csharpProject.CsLinesCount    += linesCount;
                        break;

                    case ".aspx":
                        linesCount = CalculateXmlLinesCount(fileData);
                        filesCount = 1;
                        csharpStatistics.AspxFilesCount += 1;
                        csharpStatistics.AspxLinesCount += linesCount;
                        csharpProject.AspxFilesCount    += 1;
                        csharpProject.AspxLinesCount    += linesCount;
                        break;

                    case ".cshtml":
                        linesCount = CalculateXmlLinesCount(fileData);
                        filesCount = 1;
                        csharpStatistics.CsHtmlFilesCount += 1;
                        csharpStatistics.CsLinesCount     += linesCount;
                        csharpProject.CsHtmlFilesCount    += 1;
                        csharpProject.CsHtmlLinesCount    += linesCount;
                        break;

                    case ".ashx":
                        linesCount = CalculateXmlLinesCount(fileData);
                        filesCount = 1;
                        csharpStatistics.AshxFilesCount += 1;
                        csharpStatistics.AshxLinesCount += linesCount;
                        csharpProject.AshxFilesCount    += 1;
                        csharpProject.AshxLinesCount    += linesCount;
                        break;

                    case ".ascx":
                        linesCount = CalculateXmlLinesCount(fileData);
                        filesCount = 1;
                        csharpStatistics.AscxFilesCount += 1;
                        csharpStatistics.AscxLinesCount += linesCount;
                        csharpProject.AscxFilesCount    += 1;
                        csharpProject.AscxLinesCount    += linesCount;
                        break;
                    }
                    csharpProject.SourceFilesCount    += filesCount;
                    csharpStatistics.LinesCount       += linesCount;
                    csharpStatistics.SourceFilesCount += filesCount;
                }
                else if (fileName == "packages.config")
                {
                    var doc          = XDocument.Load(filePath);
                    var ns           = doc.Root.Name.NamespaceName == "" ? "" : "{" + doc.Root.Name.NamespaceName + "}";
                    var dependencies = doc.Element(XName.Get($"{ns}packages"))?.Elements()
                                       .Select(elem =>
                                               elem.Attribute(XName.Get($"{ns}id"))?.Value + "-" + elem.Attribute(XName.Get($"{ns}version"))?.Value);
                    if (dependencies != null)
                    {
                        csharpProject.Dependencies = dependencies.ToList();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex);
            }
        }
Example #6
0
 private void CollectStatistics(PhpStatistics phpStatistics, JavaStatistics javaStatistics, CSharpStatistics csharpStatistics, string filePath, int totalFilesCount, ref int processedCount)
 {
     CollectPhpStatistics(phpStatistics, filePath);
     CollectJavaStatistics(javaStatistics, filePath);
     CollectCSharpStatistics(csharpStatistics, filePath);
     Interlocked.Increment(ref processedCount);
     Logger?.LogInfo(new ProgressMessage(processedCount, totalFilesCount)
     {
         LastFileName = filePath
     });
 }