diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..64d3b41 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,17 @@ +; Visual Studio Extension : http://visualstudiogallery.msdn.microsoft.com/c8bccfe2-650c-4b42-bc5c-845e21f96328 +; See http://editorconfig.org/ for more informations +; Top-most EditorConfig file +root = true + +; Windows-style newlines +[*] +end_of_line = CRLF + +; 4-column space indentation +[*.cs] +indent_style = space +indent_size = 4 + +[*.cake] +indent_style = tab +indent_size = 4 \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..20fcc39 --- /dev/null +++ b/.gitignore @@ -0,0 +1,336 @@ + +# Created by https://www.gitignore.io/api/visualstudio + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + + +# End of https://www.gitignore.io/api/visualstudio diff --git a/sortresx/FileProcessor.cs b/sortresx/FileProcessor.cs index 2f71426..1904d65 100644 --- a/sortresx/FileProcessor.cs +++ b/sortresx/FileProcessor.cs @@ -1,60 +1,74 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Xml; namespace Codice.SortResX { public class FileProcessor { + private readonly List _mResourceNameList; + private readonly Dictionary _mResourceNodes; + private readonly XmlDocument _mDoc; + private readonly string _mPath; + + private readonly Dictionary _xpathQuery = new Dictionary + { + {".resx", "data/@name"}, + {".dbml", "*[local-name() != 'ConnectionString']/@Name"} + }; + public FileProcessor(string path) { - mPath = path; - mResourceNameList = new List(); - mResourceNodes = new Dictionary(); - mDoc = new XmlDocument(); + _mPath = path; + _mResourceNameList = new List(); + _mResourceNodes = new Dictionary(); + _mDoc = new XmlDocument(); try { - mDoc.Load(mPath); + _mDoc.Load(_mPath); } catch (XmlException ex) { Console.WriteLine("The XML file is not correct. Message: " + ex.Message); - throw ex; + throw; } } - public void Process() + public bool Process() { - string[] sortedNames; - try { - var xpathQuery = new Dictionary(); - xpathQuery.Add(".resx", "data/@name"); - xpathQuery.Add(".dbml", "*[local-name() != 'ConnectionString']/@Name"); - - string query = null; - if (!xpathQuery.TryGetValue(Path.GetExtension(mPath).ToLowerInvariant(), out query)) + if (!_xpathQuery.TryGetValue(Path.GetExtension(_mPath).ToLowerInvariant(), out var query)) { - Console.WriteLine("Error when processing the file. Unsupported file extension: " + Path.GetExtension(mPath)); - return; + Console.WriteLine("Error when processing the file. Unsupported file extension: " + Path.GetExtension(_mPath)); + return false; } ExtractResources(query); - sortedNames = SortResourceList(); - WriteOrderedResources(sortedNames); + + var shouldSaveSort = TrySortResourceList(out var sortedNames); + if (shouldSaveSort) + { + WriteOrderedResources(sortedNames); + Console.WriteLine("Resx file '{0}' sorted successfully.", _mPath); + return true; + } + + Console.WriteLine("Resx file '{0}' is already sorted. Nothing to do.", _mPath); + return false; } catch (Exception ex) { Console.WriteLine("Error when processing the file. Message: " + ex.Message); - throw ex; + throw; } } void ExtractResources(string query) { - foreach (XmlAttribute attribute in mDoc.DocumentElement.SelectNodes(query)) + foreach (XmlAttribute attribute in _mDoc.DocumentElement.SelectNodes(query)) { var element = attribute.OwnerElement; AddXmlNode(element, attribute); @@ -64,37 +78,33 @@ void ExtractResources(string query) void AddXmlNode(XmlNode node, XmlAttribute attribute) { - if (mResourceNodes.ContainsKey(attribute.Value.ToString())) + if (_mResourceNodes.ContainsKey(attribute.Value)) return; - mResourceNodes.Add(attribute.Value.ToString(), node); - mResourceNameList.Add(attribute.Value.ToString()); + _mResourceNodes.Add(attribute.Value, node); + _mResourceNameList.Add(attribute.Value); } - string[] SortResourceList() + bool TrySortResourceList(out string[]sortedNames) { - string[] names = new string[mResourceNameList.Count]; + string[] names = new string[_mResourceNameList.Count]; - for (int i = 0; i < mResourceNameList.Count; i++) - names[i] = mResourceNameList[i]; + for (int i = 0; i < _mResourceNameList.Count; i++) + names[i] = _mResourceNameList[i]; - Array.Sort(names); - return names; + sortedNames = names.OrderBy(s => s).ToArray(); + + return !sortedNames.SequenceEqual(names); } void WriteOrderedResources(string[] names) { foreach (string key in names) { - mDoc.DocumentElement.AppendChild(mResourceNodes[key]); + _mDoc.DocumentElement.AppendChild(_mResourceNodes[key]); } - mDoc.Save(mPath); + _mDoc.Save(_mPath); } - - private List mResourceNameList = null; - private Dictionary mResourceNodes = null; - private XmlDocument mDoc = null; - private string mPath = null; } } diff --git a/sortresx/Main.cs b/sortresx/Main.cs index 885e4fa..cc1ac35 100644 --- a/sortresx/Main.cs +++ b/sortresx/Main.cs @@ -1,36 +1,83 @@ using System; +using System.ComponentModel; using System.IO; +using System.Linq; +using System.Reflection; namespace Codice.SortResX { class Program { + enum ReturnCodes + { + [Description("Success with file sorted")] + SuccessFileSorted = 0, + [Description("Success but the file didn't need to be sorted")] + SuccessButNothingToSort = 1, + [Description("Help displayed")] + Help = 2, + [Description("Bad arguments passed to the tool")] + BadArguments = 3, + [Description("Error during processing")] + ErrorDuringProcessing = 4, + } + [STAThread] static int Main(string[] args) { - ResourceFileSorter fileSorter = null; - if (args.Length <= 0) - return 1; - - if (!CheckArgs(args[0])) - return 1; - - try - { - fileSorter = new ResourceFileSorter(args[0]); - fileSorter.Sort(); - } - catch (Exception) - { - Console.WriteLine("================================"); - Console.WriteLine("Could not sort resources. Abort."); - } - return 0; + if (args.Length <= 0) + { + PrintUsage(""); + return (int) ReturnCodes.Help; + } + + var filepath = args[0]; + if (!CheckArgs(filepath)) + { + Console.WriteLine("The file specified '{0}' doesn't exist!", filepath); + return (int) ReturnCodes.BadArguments; + } + + try + { + var doneSomethingSuccessfully = new ResourceFileSorter(filepath).Sort(); + return (int) (doneSomethingSuccessfully ? ReturnCodes.SuccessFileSorted : ReturnCodes.SuccessButNothingToSort); + } + catch (Exception) + { + Console.WriteLine("================================"); + Console.WriteLine("Could not sort resources. Abort."); + return (int)ReturnCodes.ErrorDuringProcessing; + } } static void PrintUsage(string argument) { Console.WriteLine("Invalid argument:" + argument + "\nUsage: sortresx file_to_sort"); + Console.WriteLine("Return codes:\n"); + + var myEnumDescriptions = from ReturnCodes n in Enum.GetValues(typeof(ReturnCodes)) + select new {ID = (int) n, Name = GetEnumDescription(n)}; + foreach (var returnCode in myEnumDescriptions) + { + Console.WriteLine(" " + returnCode.Name + ":" + returnCode.ID + "\n"); + } + } + + public static string GetEnumDescription(Enum value) + { + FieldInfo fi = value.GetType().GetField(value.ToString()); + + DescriptionAttribute[] attributes = + (DescriptionAttribute[])fi.GetCustomAttributes( + typeof(DescriptionAttribute), + false); + + if (attributes != null && + attributes.Length > 0) + return attributes[0].Description; + else + return value.ToString(); } static bool CheckArgs(string filepath) @@ -43,17 +90,14 @@ internal class ResourceFileSorter { public ResourceFileSorter(string path) { - mFileProcessor = new FileProcessor(path); + _mFileProcessor = new FileProcessor(path); } - public void Sort() + public bool Sort() { - if (mFileProcessor != null) - { - mFileProcessor.Process(); - } + return _mFileProcessor?.Process() ?? false; } - private FileProcessor mFileProcessor; + private readonly FileProcessor _mFileProcessor; } } \ No newline at end of file diff --git a/sortresx/app.config b/sortresx/app.config new file mode 100644 index 0000000..57c0f2c --- /dev/null +++ b/sortresx/app.config @@ -0,0 +1,3 @@ + + + diff --git a/sortresx/sortresx.csproj b/sortresx/sortresx.csproj index 0c7eb49..1162066 100644 --- a/sortresx/sortresx.csproj +++ b/sortresx/sortresx.csproj @@ -1,5 +1,5 @@  - + Local 7.10.3077 @@ -28,10 +28,11 @@ - v2.0 + v4.0 0.0 + bin\Debug\ @@ -52,6 +53,7 @@ 4 full prompt + false bin\Release\ @@ -72,6 +74,7 @@ 4 none prompt + false @@ -95,6 +98,9 @@ Code + + +