Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion CodeGeneration.sln
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,15 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libraries", "Libraries", "{
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Files", "Solution Files", "{3E32806A-8707-4D41-9126-57717DC4C1EE}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
.gitattributes = .gitattributes
.gitignore = .gitignore
README.md = README.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Extensions.Test", "Extensions.Test\Extensions.Test.csproj", "{64EAD5E4-5816-4A94-AF47-7D9A640D8B55}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{587DABEF-E1F1-4A53-90E4-C330A3AC4917}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -42,8 +46,15 @@ Global
{D29742AE-DCD9-4A34-AD67-E3F39FE4443C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D29742AE-DCD9-4A34-AD67-E3F39FE4443C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D29742AE-DCD9-4A34-AD67-E3F39FE4443C}.Release|Any CPU.Build.0 = Release|Any CPU
{64EAD5E4-5816-4A94-AF47-7D9A640D8B55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{64EAD5E4-5816-4A94-AF47-7D9A640D8B55}.Debug|Any CPU.Build.0 = Debug|Any CPU
{64EAD5E4-5816-4A94-AF47-7D9A640D8B55}.Release|Any CPU.ActiveCfg = Release|Any CPU
{64EAD5E4-5816-4A94-AF47-7D9A640D8B55}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{64EAD5E4-5816-4A94-AF47-7D9A640D8B55} = {587DABEF-E1F1-4A53-90E4-C330A3AC4917}
EndGlobalSection
EndGlobal
90 changes: 90 additions & 0 deletions Extensions.Test/Extensions.Test.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{64EAD5E4-5816-4A94-AF47-7D9A640D8B55}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Extensions.Test</RootNamespace>
<AssemblyName>Extensions.Test</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<Choose>
<When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
</ItemGroup>
</When>
<Otherwise>
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework" />
</ItemGroup>
</Otherwise>
</Choose>
<ItemGroup>
<Compile Include="InflectorBehavior.cs" />
<Compile Include="StringExtensionsBehavior.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Extensions\Extensions.csproj">
<Project>{d29742ae-dcd9-4a34-ad67-e3f39fe4443c}</Project>
<Name>Extensions</Name>
</ProjectReference>
</ItemGroup>
<Choose>
<When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<Private>False</Private>
</Reference>
</ItemGroup>
</When>
</Choose>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
21 changes: 21 additions & 0 deletions Extensions.Test/InflectorBehavior.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using HedgehogDevelopment.CodeGeneration.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Extensions.Test
{
[TestClass]
public class InflectorBehavior
{
[TestMethod]
public void CapitalizeShouldOnlyCapitalizeFirstCharacter()
{
Assert.AreEqual("Pagetemplates", "pageTemplates".Capitalize());
}

[TestMethod]
public void CapitalizeShouldPreserveRemainingCharacters()
{
Assert.AreEqual("PageTemplates", "pageTemplates".Capitalize(true));
}
}
}
36 changes: 36 additions & 0 deletions Extensions.Test/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Extensions.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Extensions.Test")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("249ef0fa-7b93-4ed7-857d-b80ecb8d057a")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
53 changes: 53 additions & 0 deletions Extensions.Test/StringExtensionsBehavior.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using HedgehogDevelopment.CodeGeneration.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Extensions.Test
{
[TestClass]
public class StringExtensionsBehavior
{
[TestMethod]
public void AsClassNameShouldNotContainUnderscores()
{
Assert.AreEqual("UserDefined", "User Defined".AsClassName());
Assert.AreEqual("UserDefined", "User_Defined".AsClassName());
}

[TestMethod]
public void AsInterfaceShouldNotContainUnderscores()
{
Assert.AreEqual("IBasePage", "Base Page".AsInterfaceName());
Assert.AreEqual("IBasePage", "Base_Page".AsInterfaceName());
Assert.AreEqual("IBasePage", "IBasePage".AsInterfaceName());
}

[TestMethod]
public void AsNamespaceShouldStripErroneousPeriods()
{
var segments = new string[5] {".My", "Namespace.", "For", "The...Sample..", "Project."};
string ns = segments.AsNamespace();

Assert.AreEqual("My.Namespace.For.The.Sample.Project", ns);
}

[TestMethod]
public void AsNamespaceShouldReturnPascalCased()
{
var segments = new string[6]
{"MyCompany", "MyProject", "sitecore", "templates", "User Defined", "Page Fragments"};
string ns = segments.AsNamespace();

Assert.AreEqual("MyCompany.MyProject.Sitecore.Templates.UserDefined.PageFragments", ns);
}

[TestMethod]
public void AsNamespaceShouldNotContainUnderscores()
{
var segments = new string[6]
{"MyCompany", "MyProject", "sitecore", "templates", "User Defined", "Page Fragments"};
string ns = segments.AsNamespace("");

Assert.AreEqual("MyCompany.MyProject.Sitecore.Templates.UserDefined.PageFragments", ns);
}
}
}
3 changes: 2 additions & 1 deletion Extensions/Extensions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>xcopy "$(TargetDir)*" "%25ProgramFiles%25\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies" /i /d /y /e</PostBuildEvent>
<PostBuildEvent>xcopy "$(TargetDir)*" "%25ProgramFiles%25\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies" /i /d /y /e
xcopy "$(TargetDir)*" "%25ProgramFiles%25\Microsoft Visual Studio 11.0\Common7\IDE\PublicAssemblies" /i /d /y /e</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
Expand Down
12 changes: 12 additions & 0 deletions Extensions/Inflector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,18 @@ public static string Singularize(this string word)
/// <returns><paramref name="word"/> capitalized.</returns>
public static string Capitalize(this string word)
{
return Capitalize(word, false);
}

/// <summary>
/// Capitalizes a word.
/// </summary>
/// <param name="word">The word to be capitalized.</param>
/// <param name="preserveExisting">Flag to determine if remaining characters are reset to lower case</param>
/// <returns><paramref name="word"/> capitalized.</returns>
public static string Capitalize(this string word, bool preserveExisting)
{
if (preserveExisting) return word.Substring(0, 1).ToUpper() + word.Substring(1);
return word.Substring(0, 1).ToUpper() + word.Substring(1).ToLower();
}

Expand Down
45 changes: 29 additions & 16 deletions Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;

namespace HedgehogDevelopment.CodeGeneration.Extensions
{
Expand Down Expand Up @@ -54,13 +55,13 @@ public static string AsInterfaceName(this string word)
{
interfaceWord = string.Concat("I", interfaceWord);
}
return interfaceWord;
return interfaceWord.RemoveUnderscores();
}

public static string AsClassName(this string word)
{
// TitleCase the word
return GetFormattedWord(word, TitleCase);
return GetFormattedWord(word, TitleCase).RemoveUnderscores();
}

public static string AsPropertyName(this string word, bool pluralize = false)
Expand All @@ -86,11 +87,11 @@ public static string AsFieldName(this string word)
/// </summary>
/// <param name="words">The words.</param>
/// <returns></returns>
public static IEnumerable<string> AsValidWords(this IEnumerable<string> words)
public static IEnumerable<string> AsValidWords(this IEnumerable<string> words, string illegalCharReplacement = "")
{
foreach (string word in words)
{
yield return AsValidWord(word);
yield return AsValidWord(word, illegalCharReplacement);
}
}

Expand All @@ -107,21 +108,19 @@ public static IEnumerable<string> AsValidWords(this IEnumerable<string> words)
/// </summary>
/// <param name="word">The word.</param>
/// <returns>A valid word for the specified word.</returns>
public static string AsValidWord(this string word)
public static string AsValidWord(this string word, string illegalCharReplacement = "")
{
string identifier = word;

if (identifier == "*")
{
identifier = "Wildcard";
}
if (identifier == "*") identifier = "Wildcard";
if (String.IsNullOrEmpty(illegalCharReplacement)) identifier = identifier.Replace("_", "");

//identifier = RemoveDiacritics(identifier);

// C# Identifiers - http://msdn.microsoft.com/en-us/library/aa664670(VS.71).aspx
// replace all illegal chars with an '_'
// replace all illegal chars with the value passed in via illegalCharReplacement, default is ""
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Nl}\p{Mn}\p{Mc}\p{Cf}\p{Pc}\p{Lm}]");
identifier = regex.Replace(identifier, "_");
identifier = regex.Replace(identifier, illegalCharReplacement);

//The identifier must start with a character or '_'
if (! (char.IsLetter(identifier, 0) || identifier[0] == '_'))
Expand Down Expand Up @@ -152,23 +151,25 @@ public static string AsValidWord(this string word)
/// </example>
/// <param name="words">The namespace segments.</param>
/// <returns>A valid string in valid namespace format.</returns>
public static string AsNamespace(this IEnumerable<string> words)
public static string AsNamespace(this IEnumerable<string> words, string illegalCharReplacement = "_")
{
List<string> joinedNamespace = new List<string>();
foreach (string segment in words)
{
if (segment != null)
{
// split apart any strings with a '.' and remove any consecutive multiple '.'
string[] segments = segment.Split(new char[1] { '.' }, StringSplitOptions.RemoveEmptyEntries);
// split apart any strings with a '.' and remove any consecutive multiple '.' and
// ensure that the first character is capitalized while preserving the rest
var segments = segment.Split(new char[1] { '.' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Capitalize(true));

// being we are making a namespace, make sure the segments are valid
IEnumerable<string> validSegments = segments.AsValidWords();
IEnumerable<string> validSegments = segments.AsValidWords(illegalCharReplacement);
joinedNamespace.AddRange(validSegments);
}
}
string ns = string.Join(".", joinedNamespace.ToArray());
return ns;
return ns.RemoveUnderscores();
}

/// <summary>
Expand All @@ -191,6 +192,18 @@ private static string RemoveDiacritics(string s)
return stringBuilder.ToString();
}

/// <summary>
/// Replaces any underscores with an empty string, for instance User_Defined becomes UserDefined
/// </summary>
/// <param name="word">The string to replace underscores on.</param>
/// <returns>The string without any underscores.</returns>
public static string RemoveUnderscores(this string word)
{
return !String.IsNullOrEmpty(word)
? word.Replace("_", "")
: word;
}

/// <summary>
/// Tests whether the word conflicts with reserved or language keywords, and if so, attempts to return a
/// valid word that does not conflict. Usually the returned word is only slightly modified to differentiate
Expand Down
Loading