/// <summary> /// <code> /// Write code part for the current model property to test after /// </code> /// </summary> /// <param name="csspProp">Holds CSSPProp information about the current class name and property</param> /// <param name="TypeName">Current model type name</param> /// <param name="TypeNameLower">Current model type name with first letter lowercase</param> /// <param name="sb">StringBuilder holding the text of the file being created</param> private void CreateClass_CSSPAfter_Testing(CSSPProp csspProp, string TypeName, string TypeNameLower, StringBuilder sb) { if (csspProp.IsVirtual || csspProp.IsKey || csspProp.PropName == "ValidationResults") { return; } switch (csspProp.PropType) { case "Int16": case "Int32": case "Int64": case "Boolean": case "Single": case "String": break; case "DateTime": case "DateTimeOffset": { if (csspProp.HasCSSPAfterAttribute) { sb.AppendLine($@" { TypeNameLower } = null;"); sb.AppendLine($@" { TypeNameLower } = GetFilledRandom{ TypeName }("""");"); sb.AppendLine($@" { TypeNameLower }.{ csspProp.PropName } = new DateTime({ ((int)csspProp.Year - 1).ToString() }, 1, 1);"); if (TypeName == "Contact") { sb.AppendLine($@" { TypeNameLower }Service.Add({ TypeNameLower }, AddContactTypeEnum.LoggedIn);"); } else { sb.AppendLine($@" { TypeNameLower }Service.Add({ TypeNameLower });"); } sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes._YearShouldBeBiggerThan_, ""{ csspProp.PropName }"", ""{ csspProp.Year }""), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); } } break; default: { if (csspProp.HasCSSPEnumTypeAttribute) { // nothing for now } else { if (csspProp.PropName.EndsWith("Web") || csspProp.PropName.EndsWith("Report")) { // nothing yet } else { sb.AppendLine($@" //CSSPError: Type not implemented [{ csspProp.PropName }]"); sb.AppendLine(@""); } } } break; } }
/// <summary> /// <code> /// Write code part for the current model property to test enum type /// </code> /// </summary> /// <param name="csspProp">Holds CSSPProp information about the current class name and property</param> /// <param name="TypeName">Current model type name</param> /// <param name="TypeNameLower">Current model type name with first letter lowercase</param> /// <param name="sb">StringBuilder holding the text of the file being created</param> private void CreateClass_CSSPEnumType_Testing(CSSPProp csspProp, string TypeName, string TypeNameLower, StringBuilder sb) { if (csspProp.IsVirtual || csspProp.IsKey || csspProp.PropName == "ValidationResults") { return; } if (csspProp.PropType.EndsWith("Enum")) { if (csspProp.HasCSSPEnumTypeAttribute) { sb.AppendLine($@" { TypeNameLower } = null;"); sb.AppendLine($@" { TypeNameLower } = GetFilledRandom{ TypeName }("""");"); sb.AppendLine($@" { TypeNameLower }.{ csspProp.PropName } = ({ csspProp.PropType })1000000;"); if (TypeName == "Contact") { sb.AppendLine($@" { TypeNameLower }Service.Add({ TypeNameLower }, AddContactTypeEnum.LoggedIn);"); } else { sb.AppendLine($@" { TypeNameLower }Service.Add({ TypeNameLower });"); } sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes._IsRequired, ""{ csspProp.PropName }""), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); sb.AppendLine(@""); } } }
/// <summary> /// <code> /// Write code part for the current model properties to test /// </code> /// </summary> /// <param name="TypeName">Current model type name</param> /// <param name="TypeNameLower">Current model type name with first letter lowercase</param> /// <param name="type">Class type</param> /// <param name="sb">StringBuilder holding the text of the file being created</param> private void GeneratePropertiesTestCode(string TypeName, string TypeNameLower, Type type, StringBuilder sb) { sb.AppendLine(@" #region Tests Generated Properties"); sb.AppendLine(@" [TestMethod]"); sb.AppendLine($@" public void { TypeName }_Properties_Test()"); sb.AppendLine(@" {"); sb.AppendLine(@" foreach (CultureInfo culture in AllowableCulture)"); sb.AppendLine(@" {"); sb.AppendLine(@" ChangeCulture(culture);"); sb.AppendLine(@""); sb.AppendLine(@" using (CSSPDBContext dbTestDB = new CSSPDBContext(DatabaseTypeEnum.SqlServerTestDB))"); sb.AppendLine(@" {"); sb.AppendLine($@" { TypeName }Service { TypeNameLower }Service = new { TypeName }Service(new Query() {{ Lang = culture.TwoLetterISOLanguageName }}, dbTestDB, ContactID);"); sb.AppendLine(@""); sb.AppendLine(@" int count = 0;"); sb.AppendLine(@" if (count == 1)"); sb.AppendLine(@" {"); sb.AppendLine(@" // just so we don't get a warning during compile [The variable 'count' is assigned but its value is never used]"); sb.AppendLine(@" }"); sb.AppendLine(@""); sb.AppendLine($@" count = { TypeNameLower }Service.Get{ TypeName }List().Count();"); sb.AppendLine(@""); sb.AppendLine($@" { TypeName } { TypeNameLower } = GetFilledRandom{ TypeName }("""");"); sb.AppendLine(@""); sb.AppendLine(@" // -------------------------------"); sb.AppendLine(@" // -------------------------------"); sb.AppendLine(@" // Properties testing"); sb.AppendLine(@" // -------------------------------"); sb.AppendLine(@" // -------------------------------"); sb.AppendLine(@""); foreach (PropertyInfo prop in type.GetProperties()) { CSSPProp csspProp = new CSSPProp(); if (!modelsGenerateCodeHelper.FillCSSPProp(prop, csspProp, type)) { return; } sb.AppendLine(@""); sb.AppendLine(@" // -----------------------------------"); if (csspProp.IsKey) { sb.AppendLine(@" // [Key]"); } if (csspProp.IsNullable) { sb.AppendLine(@" // Is Nullable"); } else { sb.AppendLine(@" // Is NOT Nullable"); } if (csspProp.IsVirtual) { sb.AppendLine(@" // [IsVirtual]"); } if (csspProp.HasCompareAttribute) { sb.AppendLine($@" // [Compare(OtherField = { csspProp.OtherField })]"); } if (csspProp.HasCSSPAfterAttribute) { sb.AppendLine($@" // [CSSPAfter(Year = { csspProp.Year })]"); } if (csspProp.HasCSSPAllowNullAttribute) { sb.AppendLine(@" // [CSSPAllowNull]"); } if (csspProp.HasCSSPBiggerAttribute) { sb.AppendLine($@" // [CSSPBigger(OtherField = { csspProp.OtherField })]"); } if (csspProp.HasCSSPEnumTypeAttribute) { sb.AppendLine(@" // [CSSPEnumType]"); } if (csspProp.HasCSSPExistAttribute) { sb.AppendLine($@" // [CSSPExist(ExistTypeName = ""{ csspProp.ExistTypeName }"", ExistPlurial = ""{ csspProp.ExistPlurial }"", ExistFieldID = ""{ csspProp.ExistFieldID }"", AllowableTVtypeList = { String.Join(",", csspProp.AllowableTVTypeList) })]"); } if (csspProp.HasCSSPFillAttribute) { string FillNeedLanguage = (csspProp.FillNeedLanguage ? "true" : "false"); string FillIsList = (csspProp.FillIsList ? "true" : "false"); sb.AppendLine($@" // [CSSPFill(FillTypeName = ""{ csspProp.FillTypeName }"", FillPlurial = ""{ csspProp.FillPlurial }"", FillFieldID = ""{ csspProp.FillFieldID }"", FillEqualField = ""{ csspProp.FillEqualField }"", FillReturnField = ""{ csspProp.FillReturnField }"", FillNeedLanguage = { FillNeedLanguage }, FillIsList = { FillIsList })]"); } if (csspProp.HasDataTypeAttribute) { sb.AppendLine($@" // [DataType(DataType.{ csspProp.dataType.ToString() })]"); } if (csspProp.HasNotMappedAttribute) { sb.AppendLine(@" // [NotMapped]"); } if (csspProp.HasRangeAttribute) { sb.AppendLine($@" // [Range({ csspProp.Min }, { (csspProp.Max == null ? "-1" : csspProp.Max.ToString()) })]"); } if (csspProp.HasStringLengthAttribute) { string MinText = (csspProp.Min == null ? ")" : $", MinimumLength = { csspProp.Min.ToString() }"); sb.AppendLine($@" // [StringLength({ csspProp.Max }{ MinText })]"); } sb.AppendLine($@" // { TypeNameLower }.{ csspProp.PropName } ({ csspProp.PropType })"); sb.AppendLine(@" // -----------------------------------"); sb.AppendLine(@""); if (csspProp.IsVirtual || csspProp.PropName == "ValidationResults") { sb.AppendLine(@" // No testing requied"); continue; } if (csspProp.PropName == "HasErrors") { sb.AppendLine(@" // No testing requied"); continue; } if (csspProp.IsKey) { CreateClass_Key_Testing(csspProp, TypeName, TypeNameLower, sb); } CreateClass_CSSPExist_Testing(csspProp, TypeName, TypeNameLower, sb); CreateClass_CSSPEnumType_Testing(csspProp, TypeName, TypeNameLower, sb); CreateClass_Required_Properties_Testing(csspProp, TypeName, TypeNameLower, sb); CreateClass_CSSPAfter_Testing(csspProp, TypeName, TypeNameLower, sb); CreateClass_Min_And_Max_Properties_Testing(csspProp, TypeName, TypeNameLower, sb); } sb.AppendLine(@" }"); sb.AppendLine(@" }"); sb.AppendLine(@" }"); sb.AppendLine(@" #endregion Tests Generated Properties"); sb.AppendLine(@""); }
/// <summary> /// <code> /// Write code part for the current model property to test required /// </code> /// </summary> /// <param name="csspProp">Holds CSSPProp information about the current class name and property</param> /// <param name="TypeName">Current model type name</param> /// <param name="TypeNameLower">Current model type name with first letter lowercase</param> /// <param name="sb">StringBuilder holding the text of the file being created</param> private void CreateClass_Required_Properties_Testing(CSSPProp csspProp, string TypeName, string TypeNameLower, StringBuilder sb) { if (csspProp.IsVirtual || csspProp.IsKey || csspProp.PropName == "ValidationResults") { return; } switch (csspProp.PropType) { case "Int16": case "Int32": case "Int64": case "Boolean": case "Single": break; case "DateTime": case "DateTimeOffset": { if (!csspProp.IsNullable) { sb.AppendLine($@" { TypeNameLower } = null;"); sb.AppendLine($@" { TypeNameLower } = GetFilledRandom{ TypeName }("""");"); sb.AppendLine($@" { TypeNameLower }.{ csspProp.PropName } = new DateTime();"); if (TypeName == "Contact") { sb.AppendLine($@" { TypeNameLower }Service.Add({ TypeNameLower }, AddContactTypeEnum.LoggedIn);"); } else { sb.AppendLine($@" { TypeNameLower }Service.Add({ TypeNameLower });"); } sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes._IsRequired, ""{ csspProp.PropName }""), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); } } break; case "String": { if (!csspProp.IsNullable) { sb.AppendLine($@" { TypeNameLower } = null;"); sb.AppendLine($@" { TypeNameLower } = GetFilledRandom{ TypeName }(""{ csspProp.PropName }"");"); if (TypeName == "Contact") { sb.AppendLine($@" Assert.AreEqual(false, { TypeNameLower }Service.Add({ TypeNameLower }, AddContactTypeEnum.LoggedIn));"); } else { sb.AppendLine($@" Assert.AreEqual(false, { TypeNameLower }Service.Add({ TypeNameLower }));"); } if (TypeName == "Contact" && csspProp.PropName == "Id") { sb.AppendLine($@" Assert.AreEqual(2, { TypeNameLower }.ValidationResults.Count());"); } else { sb.AppendLine($@" Assert.AreEqual(1, { TypeNameLower }.ValidationResults.Count());"); } sb.AppendLine($@" Assert.IsTrue({ TypeNameLower }.ValidationResults.Where(c => c.ErrorMessage == string.Format(CSSPServicesRes._IsRequired, ""{ csspProp.PropName }"")).Any());"); sb.AppendLine($@" Assert.AreEqual(null, { TypeNameLower }.{ csspProp.PropName });"); sb.AppendLine($@" Assert.AreEqual(count, { TypeNameLower }Service.Get{ TypeName }List().Count());"); sb.AppendLine(@""); } } break; default: { if (csspProp.HasCSSPEnumTypeAttribute) { // nothing for now } else { if (csspProp.PropName.EndsWith("Web") || csspProp.PropName.EndsWith("Report")) { string EndText = csspProp.PropName.EndsWith("Web") ? "Web" : "Report"; sb.AppendLine($@" { TypeNameLower } = null;"); sb.AppendLine($@" { TypeNameLower } = GetFilledRandom{ TypeName }("""");"); sb.AppendLine($@" { TypeNameLower }.{ TypeName }{ EndText } = null;"); sb.AppendLine($@" Assert.IsNull({ TypeNameLower }.{ TypeName }{ EndText });"); sb.AppendLine(@""); sb.AppendLine($@" { TypeNameLower } = null;"); sb.AppendLine($@" { TypeNameLower } = GetFilledRandom{ TypeName }("""");"); sb.AppendLine($@" { TypeNameLower }.{ TypeName }{ EndText } = new { TypeName }{ EndText }();"); sb.AppendLine($@" Assert.IsNotNull({ TypeNameLower }.{ TypeName }{ EndText });"); } else if (csspProp.PropName.EndsWith("Report")) { } else { sb.AppendLine($@" //CSSPError: Type not implemented [{ csspProp.PropName }]"); sb.AppendLine(@""); } } } break; } }
/// <summary> /// <code> /// Write code part for the current model property to test exist /// </code> /// </summary> /// <param name="csspProp">Holds CSSPProp information about the current class name and property</param> /// <param name="TypeName">Current model type name</param> /// <param name="TypeNameLower">Current model type name with first letter lowercase</param> /// <param name="sb">StringBuilder holding the text of the file being created</param> private void CreateClass_CSSPExist_Testing(CSSPProp csspProp, string TypeName, string TypeNameLower, StringBuilder sb) { if (csspProp.IsVirtual || csspProp.IsKey || csspProp.PropName == "ValidationResults") { return; } switch (csspProp.PropType) { case "Int16": case "Int32": case "Int64": case "Boolean": case "Single": { if (csspProp.IsKey) { break; } if (csspProp.HasCSSPExistAttribute) { sb.AppendLine($@" { TypeNameLower } = null;"); sb.AppendLine($@" { TypeNameLower } = GetFilledRandom{ TypeName }("""");"); sb.AppendLine($@" { TypeNameLower }.{ csspProp.PropName } = 0;"); if (TypeName == "Contact") { sb.AppendLine($@" { TypeNameLower }Service.Add({ TypeNameLower }, AddContactTypeEnum.LoggedIn);"); } else { sb.AppendLine($@" { TypeNameLower }Service.Add({ TypeNameLower });"); } sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes.CouldNotFind_With_Equal_, ""{ csspProp.ExistTypeName }"", ""{ csspProp.PropName }"", { TypeNameLower }.{ csspProp.PropName }.ToString()), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); sb.AppendLine(@""); if (csspProp.ExistTypeName == "TVItem") { int TVItemIDNotGoodType = 0; TVItem tvItem = null; tvItem = (from c in dbTestDB.TVItems where !csspProp.AllowableTVTypeList.Contains(c.TVType) select c).FirstOrDefault(); if (tvItem != null) { TVItemIDNotGoodType = tvItem.TVItemID; } sb.AppendLine($@" { TypeNameLower } = null;"); sb.AppendLine($@" { TypeNameLower } = GetFilledRandom{ TypeName }("""");"); sb.AppendLine($@" { TypeNameLower }.{ csspProp.PropName } = { TVItemIDNotGoodType };"); if (TypeName == "Contact") { sb.AppendLine($@" { TypeNameLower }Service.Add({ TypeNameLower }, AddContactTypeEnum.LoggedIn);"); } else { sb.AppendLine($@" { TypeNameLower }Service.Add({ TypeNameLower });"); } sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes._IsNotOfType_, ""{ csspProp.PropName }"", ""{ String.Join(",", csspProp.AllowableTVTypeList) }""), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); sb.AppendLine(@""); } } } break; default: { } break; } }
/// <summary> /// <code> /// Write code part for the current model property to test min and max /// </code> /// </summary> /// <param name="csspProp">Holds CSSPProp information about the current class name and property</param> /// <param name="TypeName">Current model type name</param> /// <param name="TypeNameLower">Current model type name with first letter lowercase</param> /// <param name="sb">StringBuilder holding the text of the file being created</param> private void CreateClass_Min_And_Max_Properties_Testing(CSSPProp csspProp, string TypeName, string TypeNameLower, StringBuilder sb) { if (csspProp.IsVirtual || csspProp.IsKey || csspProp.PropName == "ValidationResults") { return; } switch (csspProp.PropType) { case "Int16": case "Int32": case "Int64": case "Single": case "Double": { //string propTypeTxt = "Int"; string numbExt = ""; if (csspProp.PropType == "Single") { // propTypeTxt = "Float"; numbExt = ".0f"; } else if (csspProp.PropType == "Double") { //propTypeTxt = "Double"; numbExt = ".0D"; } if (csspProp.Min != null) { sb.AppendLine($@" { TypeNameLower } = null;"); sb.AppendLine($@" { TypeNameLower } = GetFilledRandom{ TypeName }("""");"); sb.AppendLine($@" { TypeNameLower }.{ csspProp.PropName } = { (csspProp.Min - 1).ToString() }{ numbExt };"); if (TypeName == "Contact") { sb.AppendLine($@" Assert.AreEqual(false, { TypeNameLower }Service.Add({ TypeNameLower }, AddContactTypeEnum.First));"); } else { sb.AppendLine($@" Assert.AreEqual(false, { TypeNameLower }Service.Add({ TypeNameLower }));"); } if (csspProp.Max != null) { sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes._ValueShouldBeBetween_And_, ""{ csspProp.PropName }"", ""{ csspProp.Min.ToString() }"", ""{ csspProp.Max.ToString() }""), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); } else { sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes._MinValueIs_, ""{ csspProp.PropName }"", ""{ csspProp.Min.ToString() }""), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); } sb.AppendLine($@" Assert.AreEqual(count, { TypeNameLower }Service.Get{ TypeName }List().Count());"); } if (csspProp.Max != null) { sb.AppendLine($@" { TypeNameLower } = null;"); sb.AppendLine($@" { TypeNameLower } = GetFilledRandom{ TypeName }("""");"); sb.AppendLine($@" { TypeNameLower }.{ csspProp.PropName } = { (csspProp.Max + 1).ToString() }{ numbExt };"); if (TypeName == "Contact") { sb.AppendLine($@" Assert.AreEqual(false, { TypeNameLower }Service.Add({ TypeNameLower }, AddContactTypeEnum.First));"); } else { sb.AppendLine($@" Assert.AreEqual(false, { TypeNameLower }Service.Add({ TypeNameLower }));"); } if (csspProp.Min != null) { sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes._ValueShouldBeBetween_And_, ""{ csspProp.PropName }"", ""{ csspProp.Min.ToString() }"", ""{ csspProp.Max.ToString() }""), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); } else { sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes._MaxValueIs_, ""{ csspProp.PropName }"", ""{ csspProp.Max.ToString() }""), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); } sb.AppendLine($@" Assert.AreEqual(count, { TypeNameLower }Service.Get{ TypeName }List().Count());"); } } break; case "Boolean": { // nothing } break; case "DateTime": case "DateTimeOffset": { // nothing } break; case "String": { if (csspProp.Min != null) { sb.AppendLine($@" { TypeNameLower } = null;"); sb.AppendLine($@" { TypeNameLower } = GetFilledRandom{ TypeName }("""");"); if (csspProp.Min - 1 > 0) { sb.AppendLine($@" { TypeNameLower }.{ csspProp.PropName } = GetRandomString("""", { (csspProp.Min - 1).ToString() });"); if (TypeName == "Contact") { sb.AppendLine($@" Assert.AreEqual(false, { TypeNameLower }Service.Add({ TypeNameLower }, AddContactTypeEnum.First));"); } else { sb.AppendLine($@" Assert.AreEqual(false, { TypeNameLower }Service.Add({ TypeNameLower }));"); } if (csspProp.Max != null) { sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes._LengthShouldBeBetween_And_, ""{ csspProp.PropName }"", ""{ csspProp.Min.ToString() }"", ""{ csspProp.Max.ToString() }""), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); } else { sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes._MinLengthIs_, ""{ csspProp.PropName }"", ""{ csspProp.Min.ToString() }""), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); } sb.AppendLine($@" Assert.AreEqual(count, { TypeNameLower }Service.Get{ TypeName }List().Count());"); } } if (csspProp.Max > 0) { sb.AppendLine($@" { TypeNameLower } = null;"); sb.AppendLine($@" { TypeNameLower } = GetFilledRandom{ TypeName }("""");"); sb.AppendLine($@" { TypeNameLower }.{ csspProp.PropName } = GetRandomString("""", { (csspProp.Max + 1).ToString() });"); if (TypeName == "Contact") { sb.AppendLine($@" Assert.AreEqual(false, { TypeNameLower }Service.Add({ TypeNameLower }, AddContactTypeEnum.First));"); } else { sb.AppendLine($@" Assert.AreEqual(false, { TypeNameLower }Service.Add({ TypeNameLower }));"); } if (csspProp.Min != null) { sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes._LengthShouldBeBetween_And_, ""{ csspProp.PropName }"", ""{ csspProp.Min.ToString() }"", ""{ csspProp.Max.ToString() }""), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); } else { sb.AppendLine($@" Assert.AreEqual(string.Format(CSSPServicesRes._MaxLengthIs_, ""{ csspProp.PropName }"", ""{ csspProp.Max.ToString() }""), { TypeNameLower }.ValidationResults.FirstOrDefault().ErrorMessage);"); } sb.AppendLine($@" Assert.AreEqual(count, { TypeNameLower }Service.Get{ TypeName }List().Count());"); } } break; default: { } break; } }
/// <summary> /// Generates: /// C:\CSSPCode\CSSPModels\CSSPModels.Tests\[ModelClassName]TestGenerated.cs file /// /// Requires: /// C:\CSSPCode\CSSPModels\CSSPModels\bin\Debug\CSSPModels.dll /// </summary> public void ModelClassName_TestGenerated() { ClearPermanentEvent(new StatusEventArgs("")); FileInfo fiDLL = new FileInfo(@"C:\CSSPCode\CSSPModels\CSSPModels\bin\Debug\CSSPModels.dll"); if (!fiDLL.Exists) { CSSPErrorEvent(new CSSPErrorEventArgs($"{fiDLL.FullName } does not exist")); return; } var importAssembly = Assembly.LoadFile(fiDLL.FullName); Type[] types = importAssembly.GetTypes(); foreach (Type type in types) { bool ClassNotMapped = false; StringBuilder sb = new StringBuilder(); StatusTempEvent(new StatusEventArgs(type.Name)); Application.DoEvents(); if (SkipType(type)) { continue; } //if (type.Name != "CSSPWQInputParam") //{ // continue; //} foreach (CustomAttributeData customAttributeData in type.CustomAttributes) { if (customAttributeData.AttributeType.Name == "NotMappedAttribute") { ClassNotMapped = true; break; } } sb.AppendLine(@"/*"); sb.AppendLine(@" * Auto generated from the CSSPCodeWriter.proj by clicking on the [[ModelClassName]TestGenerated.cs] button"); sb.AppendLine(@" *"); sb.AppendLine(@" * Do not edit this file."); sb.AppendLine(@" *"); sb.AppendLine(@" */ "); sb.AppendLine(@"using System;"); sb.AppendLine(@"using System.Text;"); sb.AppendLine(@"using Microsoft.VisualStudio.TestTools.UnitTesting;"); sb.AppendLine(@"using System.Linq;"); sb.AppendLine(@"using System.Globalization;"); sb.AppendLine(@"using System.Transactions;"); sb.AppendLine(@"using System.Collections.Generic;"); sb.AppendLine(@"using CSSPModels.Resources;"); sb.AppendLine(@"using Microsoft.EntityFrameworkCore.Metadata;"); sb.AppendLine(@"using System.Reflection;"); sb.AppendLine(@"using CSSPEnums;"); sb.AppendLine(@"using System.ComponentModel.DataAnnotations;"); sb.AppendLine(@""); sb.AppendLine(@"namespace CSSPModels.Tests"); sb.AppendLine(@"{"); sb.AppendLine(@" [TestClass]"); sb.AppendLine($@" public partial class { type.Name }Test"); sb.AppendLine(@" {"); sb.AppendLine(@" #region Variables"); sb.AppendLine(@" #endregion Variables"); sb.AppendLine(@""); sb.AppendLine(@" #region Properties"); sb.AppendLine($@" private { type.Name } { type.Name.Substring(0, 1).ToLower() }{ type.Name.Substring(1) } {{ get; set; }}"); if (!ClassNotMapped) { sb.AppendLine($@" private { type.Name }ExtraA { type.Name.Substring(0, 1).ToLower() }{ type.Name.Substring(1) }ExtraA {{ get; set; }}"); sb.AppendLine($@" private { type.Name }ExtraB { type.Name.Substring(0, 1).ToLower() }{ type.Name.Substring(1) }ExtraB {{ get; set; }}"); } sb.AppendLine(@" #endregion Properties"); sb.AppendLine(@""); sb.AppendLine(@" #region Constructors"); sb.AppendLine($@" public { type.Name }Test()"); sb.AppendLine(@" {"); sb.AppendLine($@" { type.Name.Substring(0, 1).ToLower() }{ type.Name.Substring(1) } = new { type.Name }();"); if (!ClassNotMapped) { sb.AppendLine($@" { type.Name.Substring(0, 1).ToLower() }{ type.Name.Substring(1) }ExtraA = new { type.Name }ExtraA();"); sb.AppendLine($@" { type.Name.Substring(0, 1).ToLower() }{ type.Name.Substring(1) }ExtraB = new { type.Name }ExtraB();"); } sb.AppendLine(@" }"); sb.AppendLine(@" #endregion Constructors"); sb.AppendLine(@""); sb.AppendLine(@" #region Tests Functions public"); List <string> ClassNameList = new List <string>() { type.Name, $"{type.Name }ExtraA", $"{type.Name }ExtraB" }; foreach (string ClassName in ClassNameList) { Type currentType = null; foreach (Type TempType in types) { if (TempType.Name == ClassName) { currentType = TempType; } } if (currentType == null) { continue; } sb.AppendLine(@" [TestMethod]"); sb.AppendLine($@" public void { currentType.Name }_Properties_Test()"); sb.AppendLine(@" {"); StringBuilder sbVar = new StringBuilder(); StringBuilder sbPropNotMapped = new StringBuilder(); foreach (PropertyInfo prop in currentType.GetProperties().ToList()) { if (!ClassNotMapped) { if (!prop.GetGetMethod().IsVirtual&& !prop.Name.Contains("ValidationResults")) { if (prop.CustomAttributes.Where(c => c.AttributeType.Name.Contains("NotMappedAttribute")).Any()) { sbPropNotMapped.Append($@"""{ prop.Name }"", "); } else { sbVar.Append($@"""{ prop.Name }"", "); } } } else { if (!prop.Name.Contains("ValidationResults")) { sbVar.Append($@"""{ prop.Name }"", "); } } } sb.AppendLine($@" List<string> propNameList = new List<string>() {{ { sbVar.ToString() } }}.OrderBy(c => c).ToList();"); sb.AppendLine($@" List<string> propNameNotMappedList = new List<string>() {{ { sbPropNotMapped.ToString() } }}.OrderBy(c => c).ToList();"); sb.AppendLine(@""); if (!ClassNotMapped) { sb.AppendLine(@" int index = 0;"); sb.AppendLine($@" foreach (PropertyInfo propertyInfo in typeof({ currentType.Name }).GetProperties().OrderBy(c => c.Name))"); sb.AppendLine(@" {"); sb.AppendLine(@" if (!propertyInfo.GetGetMethod().IsVirtual"); sb.AppendLine(@" && propertyInfo.Name != ""ValidationResults"""); sb.AppendLine(@" && !propertyInfo.CustomAttributes.Where(c => c.AttributeType.Name.Contains(""NotMappedAttribute"")).Any())"); sb.AppendLine(@" {"); sb.AppendLine(@" Assert.AreEqual(propNameList[index], propertyInfo.Name);"); sb.AppendLine(@" index += 1;"); sb.AppendLine(@" }"); sb.AppendLine(@" }"); sb.AppendLine(@""); sb.AppendLine(@" Assert.AreEqual(propNameList.Count, index);"); sb.AppendLine(@""); sb.AppendLine(@" index = 0;"); sb.AppendLine($@" foreach (PropertyInfo propertyInfo in typeof({ currentType.Name }).GetProperties().Where(c => c.Name != ""ValidationResults"").OrderBy(c => c.Name).ToList())"); sb.AppendLine(@" {"); sb.AppendLine(@" foreach (CustomAttributeData customAttributeData in propertyInfo.CustomAttributes)"); sb.AppendLine(@" {"); sb.AppendLine(@" if (customAttributeData.AttributeType.Name == ""NotMappedAttribute"")"); sb.AppendLine(@" {"); sb.AppendLine(@" Assert.AreEqual(propertyInfo.Name, propNameNotMappedList[index]);"); sb.AppendLine(@" index += 1;"); sb.AppendLine(@" }"); sb.AppendLine(@" }"); sb.AppendLine(@" }"); sb.AppendLine(@""); sb.AppendLine(@" Assert.AreEqual(propNameNotMappedList.Count, index);"); sb.AppendLine(@""); } else { sb.AppendLine(@" int index = 0;"); sb.AppendLine($@" foreach (PropertyInfo propertyInfo in typeof({ currentType.Name }).GetProperties().Where(c => c.Name != ""ValidationResults"").OrderBy(c => c.Name).ToList())"); sb.AppendLine(@" {"); sb.AppendLine(@" Assert.AreEqual(propertyInfo.Name, propNameList[index]);"); sb.AppendLine(@" index += 1;"); sb.AppendLine(@" }"); sb.AppendLine(@""); sb.AppendLine(@" Assert.AreEqual(propNameList.Count, index);"); } sb.AppendLine(@" }"); } if (!ClassNotMapped) { foreach (string ClassName in ClassNameList) { Type currentType = null; foreach (Type TempType in types) { if (TempType.Name == ClassName) { currentType = TempType; } } sb.AppendLine(@" [TestMethod]"); sb.AppendLine($@" public void { currentType.Name }_Navigation_Test()"); sb.AppendLine(@" {"); StringBuilder sbVar2 = new StringBuilder(); StringBuilder sbCollection = new StringBuilder(); foreach (PropertyInfo propertyInfo in currentType.GetProperties()) { if (propertyInfo.GetGetMethod().IsVirtual) { if (propertyInfo.GetGetMethod().ReturnType.Name.StartsWith("ICollection")) { sbCollection.Append($@"""{ propertyInfo.Name }"", "); } else { sbVar2.Append($@"""{ propertyInfo.Name }"", "); } } } sb.AppendLine($@" List<string> foreignNameList = new List<string>() {{ { sbVar2.ToString() } }}.OrderBy(c => c).ToList();"); sb.AppendLine($@" List<string> foreignNameCollectionList = new List<string>() {{ { sbCollection.ToString() } }}.OrderBy(c => c).ToList();"); sb.AppendLine(@""); sb.AppendLine(@" int index = 0;"); sb.AppendLine($@" foreach (PropertyInfo propertyInfo in typeof({ currentType.Name }).GetProperties())"); sb.AppendLine(@" {"); sb.AppendLine(@" if (propertyInfo.GetGetMethod().IsVirtual && !propertyInfo.GetGetMethod().ReturnType.Name.StartsWith(""ICollection""))"); sb.AppendLine(@" {"); sb.AppendLine(@" Assert.IsTrue(foreignNameList.Contains(propertyInfo.Name));"); sb.AppendLine(@" index += 1;"); sb.AppendLine(@" }"); sb.AppendLine(@" }"); sb.AppendLine(@""); sb.AppendLine(@" Assert.AreEqual(foreignNameList.Count, index);"); sb.AppendLine(@""); sb.AppendLine(@" index = 0;"); sb.AppendLine($@" foreach (PropertyInfo propertyInfo in typeof({ currentType.Name }).GetProperties().Where(c => c.Name != ""ValidationResults"").OrderBy(c => c.Name).ToList())"); sb.AppendLine(@" {"); sb.AppendLine(@" if (propertyInfo.GetGetMethod().ReturnType.Name.StartsWith(""ICollection""))"); sb.AppendLine(@" {"); sb.AppendLine(@" Assert.IsTrue(foreignNameCollectionList.Contains(propertyInfo.Name));"); sb.AppendLine(@" index += 1;"); sb.AppendLine(@" }"); sb.AppendLine(@" }"); sb.AppendLine(@""); sb.AppendLine(@" Assert.AreEqual(foreignNameCollectionList.Count, index);"); sb.AppendLine(@""); sb.AppendLine(@" }"); } } foreach (string ClassName in ClassNameList) { Type currentType = null; foreach (Type TempType in types) { if (TempType.Name == ClassName) { currentType = TempType; } } if (currentType == null) { continue; } sb.AppendLine(@" [TestMethod]"); sb.AppendLine($@" public void { currentType.Name }_Has_ValidationResults_Test()"); sb.AppendLine(@" {"); sb.AppendLine($@" Assert.IsTrue(typeof({ currentType.Name }).GetProperties().Where(c => c.Name == ""ValidationResults"").Any());"); sb.AppendLine(@" }"); } foreach (string ClassName in ClassNameList) { Type currentType = null; foreach (Type TempType in types) { if (TempType.Name == ClassName) { currentType = TempType; } } if (currentType == null) { continue; } sb.AppendLine(@" [TestMethod]"); sb.AppendLine($@" public void { currentType.Name }_Every_Property_Has_Get_Set_Test()"); sb.AppendLine(@" {"); int count = 0; // doing properties which are not virtual nor contains 'ValidationResults' foreach (PropertyInfo prop in currentType.GetProperties()) { count += 1; if (!prop.GetGetMethod().IsVirtual&& !prop.Name.Contains("ValidationResults")) { CSSPProp csspProp = new CSSPProp(); if (!FillCSSPProp(prop, csspProp, currentType)) { CSSPErrorEvent(new CSSPErrorEventArgs($"CSSPError while creating code [{ csspProp.CSSPError }]")); return; } switch (csspProp.PropType) { case "Boolean": { if (csspProp.IsList || csspProp.IsIQueryable) { sb.AppendLine($@" List<bool> val{ count.ToString() } = new List<bool>() {{ true, false }};"); } else { sb.AppendLine($@" bool val{ count.ToString() } = true;"); } } break; case "DateTime": case "DateTimeOffset": { if (csspProp.IsList || csspProp.IsIQueryable) { sb.AppendLine($@" List<DateTime> val{ count.ToString() } = new List<DateTime>() {{ new DateTime(2011, 3, 5), new DateTime(2015, 3, 2, 4, 5, 6) }};"); } else { sb.AppendLine($@" DateTime val{ count.ToString() } = new DateTime(2010, 3, 4);"); } } break; case "Int16": case "Int32": case "Int64": { if (csspProp.IsList || csspProp.IsIQueryable) { sb.AppendLine($@" List<int> val{ count.ToString() } = new List<int>() {{ 34, 45, 56 }};"); } else { sb.AppendLine($@" int val{ count.ToString() } = 45;"); } } break; case "Single": { if (csspProp.IsList || csspProp.IsIQueryable) { sb.AppendLine($@" List<float> val{ count.ToString() } = new List<float>() {{ 34.4f, 45.3f, 56.6f }};"); } else { sb.AppendLine($@" float val{ count.ToString() } = 56.0f;"); } } break; case "Double": { if (csspProp.IsList || csspProp.IsIQueryable) { sb.AppendLine($@" List<double> val{ count.ToString() } = new List<double>() {{ 33.2D, 66.4D, 56.4D }};"); } else { sb.AppendLine($@" double val{ count.ToString() } = 87.9D;"); } } break; case "String": { if (csspProp.IsList || csspProp.IsIQueryable) { sb.AppendLine($@" List<string> val{ count.ToString() } = new List<string>() {{ ""testing"", ""Bonjour Allo"" }};"); } else { sb.AppendLine($@" string val{ count.ToString() } = ""Some text"";"); } } break; case "Byte[]": { if (csspProp.IsList || csspProp.IsIQueryable) { sb.AppendLine($@" List<byte[]> val{ count.ToString() } = new List<byte[]>() {{ Encoding.ASCII.GetBytes(new string(' ', 100)), Encoding.ASCII.GetBytes(new string(' ', 100)) }};"); } else { sb.AppendLine($@" byte[] val{ count.ToString() } = new byte[5];"); } } break; case "Type": { if (csspProp.IsList || csspProp.IsIQueryable) { sb.AppendLine($@" List<Type> val{ count.ToString() } = List<Type>() {{ typeof(Address), typeof(TVItem) }};"); } else { sb.AppendLine($@" Type val{ count.ToString() } = typeof({ currentType.Name });"); } } break; default: { if (csspProp.HasCSSPEnumTypeAttribute) { if (csspProp.IsList || csspProp.IsIQueryable) { sb.AppendLine($@" List<{ csspProp.PropType }> val{ count.ToString() } = new List<{ csspProp.PropType }>() {{ new { csspProp.PropType }(), new { csspProp.PropType }() }};"); } else { sb.AppendLine($@" { csspProp.PropType } val{ count.ToString() } = ({ csspProp.PropType })3;"); } } else { if (csspProp.IsList || csspProp.IsIQueryable) { sb.AppendLine($@" List<{ csspProp.PropType }> val{ count.ToString() } = new List<{ csspProp.PropType }>() {{ new { csspProp.PropType }(), new { csspProp.PropType }() }};"); } else { sb.AppendLine($@" { csspProp.PropType } val{ count.ToString() } = new { csspProp.PropType }();"); } } } break; } if (csspProp.IsIQueryable) { sb.AppendLine($@" { currentType.Name.Substring(0, 1).ToLower() }{ currentType.Name.Substring(1) }.{ prop.Name } = val{ count.ToString() } as IQueryable<{ csspProp.PropType }>;"); } else { sb.AppendLine($@" { currentType.Name.Substring(0, 1).ToLower() }{ currentType.Name.Substring(1) }.{ prop.Name } = val{ count.ToString() };"); } sb.AppendLine($@" Assert.AreEqual(val{ count.ToString() }, { currentType.Name.Substring(0, 1).ToLower() }{ currentType.Name.Substring(1) }.{ prop.Name });"); } } // doing properties which are virtual foreach (PropertyInfo prop in currentType.GetProperties()) { count += 1; if (prop.GetGetMethod().IsVirtual) { CSSPProp csspProp = new CSSPProp(); if (!FillCSSPProp(prop, csspProp, currentType)) { CSSPErrorEvent(new CSSPErrorEventArgs($"CSSPError while creating code [{ csspProp.CSSPError }]")); return; } if (csspProp.IsCollection) { sb.AppendLine($@" ICollection<{ csspProp.PropType }> val{ count.ToString() } = new List<{ csspProp.PropType }>();"); } else if (csspProp.IsList || csspProp.IsIQueryable) { sb.AppendLine($@" List<{ csspProp.PropType }> val{ count.ToString() } = new List<{ csspProp.PropType }>();"); } else { sb.AppendLine($@" { csspProp.PropType } val{ count.ToString() } = new { csspProp.PropType }();"); } sb.AppendLine($@" { currentType.Name.Substring(0, 1).ToLower() }{ currentType.Name.Substring(1) }.{ prop.Name } = val{ count.ToString() };"); sb.AppendLine($@" Assert.AreEqual(val{ count.ToString() }, { currentType.Name.Substring(0, 1).ToLower() }{ currentType.Name.Substring(1) }.{ prop.Name });"); } } // doing properties which contains 'ValidationResults' foreach (PropertyInfo prop in currentType.GetProperties()) { count += 1; if (prop.Name.Contains("ValidationResults")) { CSSPProp csspProp = new CSSPProp(); if (!FillCSSPProp(prop, csspProp, currentType)) { CSSPErrorEvent(new CSSPErrorEventArgs($"CSSPError while creating code [{ csspProp.CSSPError }]")); return; } sb.AppendLine($@" IEnumerable<ValidationResult> val{ count.ToString() } = new List<ValidationResult>() {{ new ValidationResult(""First CSSPError Message"") }}.AsEnumerable();"); sb.AppendLine($@" { currentType.Name.Substring(0, 1).ToLower() }{ currentType.Name.Substring(1) }.{ prop.Name } = val{ count.ToString() };"); sb.AppendLine($@" Assert.AreEqual(val{ count.ToString() }, { currentType.Name.Substring(0, 1).ToLower() }{ currentType.Name.Substring(1) }.{ prop.Name });"); } } sb.AppendLine(@" }"); } sb.AppendLine(@" #endregion Tests Functions public"); sb.AppendLine(@" }"); sb.AppendLine(@"}"); FileInfo fiOutput = new FileInfo($@"C:\CSSPCode\CSSPModels\CSSPModels.Tests\{ type.Name }TestGenerated.cs"); using (StreamWriter sw = fiOutput.CreateText()) { sw.Write(sb.ToString()); } StatusPermanentEvent(new StatusEventArgs($"Created [{ fiOutput.FullName }] ...")); } StatusTempEvent(new StatusEventArgs("Done ...")); StatusPermanentEvent(new StatusEventArgs("")); StatusPermanentEvent(new StatusEventArgs("Done ...")); }
/// <summary> /// Compares the fields in the DB and the ones compiled in CSSPModels DLL /// </summary> /// <param name="tableList">List of Table information from the DB</param> /// <param name="typePropList">List of property information from the compiled CSSPModels DLL</param> /// <returns>True if all fields from DB compares with property fields from the compiled CSSPModels DLL</returns> private bool CompareDBAndCSSPModelsDLL(List <Table> tableList, List <TypeProp> typePropList) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Comparing DB Fields name that does not exist in the CSSPModels.DLL"); sb.AppendLine(""); foreach (Table table in tableList.OrderBy(c => c.TableName)) { if (table.TableName.StartsWith("AspNet") || table.TableName.StartsWith("sys")) { continue; } TypeProp typePropExist = (from c in typePropList let t = c.type.Name + c.Plurial where t == table.TableName select c).FirstOrDefault(); if (typePropExist == null) { sb.AppendLine($"{ table.TableName } ---------------- object does not exist for table"); sb.AppendLine("\r\n"); } foreach (Col col in table.colList) { StatusTempEvent(new StatusEventArgs($"{ table.TableName } --- { col.FieldName}")); Application.DoEvents(); TypeProp typeProp = (from c in typePropList where (c.type.Name + c.Plurial) == table.TableName select c).FirstOrDefault(); if (typeProp != null) { // --------------------------------------- // Check if field name exist // --------------------------------------- CSSPProp csspProp = (from c in typeProp.csspPropList where c.PropName == col.FieldName select c).FirstOrDefault(); if (csspProp == null) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- does not exist"); continue; } if (csspProp.IsNullable != col.AllowNull) { string NullOrNot = (col.AllowNull ? "Nullable" : "Not Nullable"); sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should be { NullOrNot }"); continue; } // --------------------------------------- // Check if field types correspond and proper Attributes // --------------------------------------- switch (col.DataType) { case "bit": { if (csspProp.PropType != "Boolean") { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- wrong type It is [{ csspProp.PropType }] should be [Boolean]"); } } break; case "bigint": { if (csspProp.PropType != "Int64") { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- wrong type It is [{ csspProp.PropType }] should be [Int64]"); } if (csspProp.HasCSSPExistAttribute) { if (csspProp.HasRangeAttribute) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should NOT have a Range Attribute"); } } else { if (!csspProp.HasRangeAttribute) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should have a Range Attribute"); } } } break; case "int": { if (csspProp.PropType != "Int32") { if ($"{ col.FieldName }Enum" != csspProp.PropType) { TableFieldEnumException tableFieldEnumException = TableFieldEnumExceptionList.Where(c => c.TableName == table.TableName && c.FieldName == col.FieldName).FirstOrDefault(); if (tableFieldEnumException == null) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- wrong type It is [{ csspProp.PropType }] should be [Int32]"); sb.AppendLine("\r\n"); sb.AppendLine("You might need to add this enumeration type within the FillPublicList() within the ModelsGenerateCodeHelper.cs\r\n"); sb.AppendLine("Suggestion line to add:\r\n"); sb.AppendLine($@"new TableFieldEnumException() {{ TableName = ""{ table.TableName }"", FieldName = ""{ col.FieldName }"", EnumText = ""{ csspProp.PropType }"" }},\r\n"); } else { if (tableFieldEnumException.EnumText != csspProp.PropType) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- wrong type It is [{ csspProp.PropType }] should be [Int32]"); } if (!csspProp.HasCSSPEnumTypeAttribute) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should have a CSSPEnumType Attribute"); } } } else { if (!csspProp.HasCSSPEnumTypeAttribute) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should have a CSSPEnumType Attribute"); } } } else { if (!csspProp.IsKey) { if (csspProp.HasCSSPExistAttribute) { if (csspProp.HasRangeAttribute) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should NOT have a Range Attribute"); } } else { if (!csspProp.HasRangeAttribute) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should have a Range Attribute"); } } if (csspProp.PropName.EndsWith("ID")) { TableFieldIDException tableFieldIDException = TableFieldIDExceptionList.Where(c => c.TableName == table.TableName && c.FieldName == col.FieldName).FirstOrDefault(); if (tableFieldIDException == null) { if (!csspProp.HasCSSPExistAttribute) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should have a CSSPExist Attribute"); } } } } } } break; case "datetime": { if (csspProp.PropType != "DateTime") { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- wrong type It is [{ csspProp.PropType }] should be [DateTime]"); } if (!csspProp.HasCSSPAfterAttribute) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should have a CSSPAfter Attribute"); } if (csspProp.PropName.ToUpper().StartsWith("END")) { if (!csspProp.HasCSSPBiggerAttribute) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should have a CSSPBigger Attribute"); } } } break; case "text": { if (csspProp.PropType != "String") { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- wrong type It is [{ csspProp.PropType }] should be [String]"); } } break; case "nchar": case "nvarchar": { if (csspProp.PropType != "String") { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- wrong type It is [{ csspProp.PropType }] should be [String]"); } if (!csspProp.HasStringLengthAttribute) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should have a StringLength Attribute"); } TableFieldEmail tableFieldEmail = TableFieldEmailList.Where(c => c.TableName == table.TableName && c.FieldName == col.FieldName).FirstOrDefault(); if (tableFieldEmail != null) { if (csspProp.dataType != DataType.EmailAddress) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should have a DataType Attribute set to email"); } } } break; case "float": { if (csspProp.PropType != "Double") { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- wrong type It is [{ csspProp.PropType }] should be [Double]"); } if (!csspProp.HasRangeAttribute) { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- should have a Range Attribute"); } } break; case "varbinary": { // don't know what to check yet } break; default: { sb.AppendLine($"{ table.TableName }\t{ col.FieldName }\t---------------- not implemented [{ col.DataType }]"); } break; } } } } sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine("Comparing CSSPModels.DLL properties that does not exist in DB"); sb.AppendLine(""); foreach (TypeProp typeProp in typePropList.OrderBy(c => c.type.Name)) { if (typeProp.type.CustomAttributes.Where(c => c.AttributeType.FullName.Contains("NotMappedAttribute")).Any()) { continue; } foreach (CSSPProp csspProp in typeProp.csspPropList) { StatusTempEvent(new StatusEventArgs($"{ typeProp.type.Name } --- { csspProp.PropName }")); Application.DoEvents(); if (csspProp.IsVirtual) { continue; } if (csspProp.PropName == "ValidationResults") { continue; } if (csspProp.HasNotMappedAttribute) { continue; } if (SkipType(typeProp.type)) { continue; } string tableName = $"{ typeProp.type.Name }{ typeProp.Plurial }"; Table table = (from c in tableList where c.TableName == tableName select c).FirstOrDefault(); if (table == null) { sb.AppendLine($"{ typeProp.type.Name }\t{ csspProp.PropName }\t---------------- does not exist"); continue; } Col col = (from c in table.colList where c.FieldName == csspProp.PropName select c).FirstOrDefault(); if (col == null) { sb.AppendLine($"{ typeProp.type.Name }\t{ csspProp.PropName }\t---------------- does not exist"); } } } StatusPermanentEvent(new StatusEventArgs(sb.ToString())); return(true); }
/// <summary> /// Load all properties found in CSSPModels Dll in typePropList /// </summary> /// <param name="typePropList">Holds all properties from the compiled CSSPModels DLL</param> /// <returns>True if all properties where gathered without CSSPErrors</returns> private bool LoadCSSPModelsDLLInfo(List <TypeProp> typePropList) { FileInfo fiDLL = new FileInfo(@"C:\CSSPCode\CSSPModels\CSSPModels\bin\Debug\CSSPModels.dll"); if (!fiDLL.Exists) { CSSPErrorEvent(new CSSPErrorEventArgs($"{ fiDLL.FullName } does not exist")); return(false); } try { var importAssembly = Assembly.LoadFile(fiDLL.FullName); Type[] types = importAssembly.GetTypes(); foreach (Type type in types) { TypeProp typeProp = new TypeProp(); typeProp.type = type; typeProp.Plurial = "s"; if (type.Name == "Address") { typeProp.Plurial = "es"; } //if (type.Name == "AddressWeb") //{ // int seflij = 34; //} if (SkipType(type)) { continue; } foreach (PropertyInfo propertyInfo in type.GetProperties()) { if (propertyInfo.GetGetMethod().IsVirtual) { continue; } if (propertyInfo.Name == "ValidationResults") { continue; } CSSPProp csspProp = new CSSPProp(); if (!FillCSSPProp(propertyInfo, csspProp, type)) { CSSPErrorEvent(new CSSPErrorEventArgs($"CSSPError while creating code [{ csspProp.CSSPError }]")); return(false); } typeProp.csspPropList.Add(csspProp); } typePropList.Add(typeProp); } } catch (Exception ex) { CSSPErrorEvent(new CSSPErrorEventArgs(ex.Message)); return(false); } return(true); }
public bool FillCSSPProp(PropertyInfo propInfo, CSSPProp csspProp, Type type) { csspProp.PropName = propInfo.Name; csspProp.IsNullable = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPAllowNullAttribute").Any(); if (propInfo.PropertyType.FullName.StartsWith("System.Nullable")) { csspProp.IsNullable = true; string typeTxt = propInfo.PropertyType.FullName; typeTxt = typeTxt.Substring(typeTxt.IndexOf("[[") + 2); typeTxt = typeTxt.Substring(typeTxt.IndexOf(".") + 1); typeTxt = typeTxt.Substring(0, typeTxt.IndexOf(",")); csspProp.PropType = typeTxt; } else if (propInfo.PropertyType.FullName.StartsWith("System.Collections.Generic.ICollection")) { csspProp.IsCollection = true; string typeTxt = propInfo.PropertyType.FullName; typeTxt = typeTxt.Substring(typeTxt.IndexOf("[") + 2); typeTxt = typeTxt.Substring(typeTxt.IndexOf(".") + 1); typeTxt = typeTxt.Substring(0, typeTxt.IndexOf(",")); csspProp.PropType = typeTxt; } else if (propInfo.PropertyType.FullName.StartsWith("System.Collections.Generic.List")) { csspProp.IsList = true; string typeTxt = propInfo.PropertyType.FullName; typeTxt = typeTxt.Substring(typeTxt.IndexOf("[") + 2); typeTxt = typeTxt.Substring(typeTxt.IndexOf(".") + 1); typeTxt = typeTxt.Substring(0, typeTxt.IndexOf(",")); csspProp.PropType = typeTxt; } else if (propInfo.PropertyType.FullName.StartsWith("System.Linq.IQueryable")) { csspProp.IsIQueryable = true; string typeTxt = propInfo.PropertyType.FullName; typeTxt = typeTxt.Substring(typeTxt.IndexOf("[") + 2); typeTxt = typeTxt.Substring(typeTxt.IndexOf(".") + 1); typeTxt = typeTxt.Substring(0, typeTxt.IndexOf(",")); csspProp.PropType = typeTxt; } else { csspProp.PropType = propInfo.PropertyType.Name.ToString(); } csspProp.IsKey = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "KeyAttribute").Any(); if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "DataTypeAttribute").Any()) { csspProp.HasDataTypeAttribute = true; CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "DataTypeAttribute").First(); DataType dataType = ((DataType)customAttributeData.ConstructorArguments[0].Value); switch (dataType) { case DataType.Custom: case DataType.DateTime: case DataType.Date: case DataType.Time: case DataType.Duration: case DataType.PhoneNumber: case DataType.Currency: case DataType.Text: case DataType.Html: case DataType.MultilineText: { csspProp.CSSPError = $"DataType [{ dataType.ToString() }] is not implemented yet."; return(false); } case DataType.EmailAddress: { csspProp.dataType = ((DataType)customAttributeData.ConstructorArguments[0].Value); csspProp.HasDataTypeAttribute = true; } break; case DataType.Password: case DataType.Url: case DataType.ImageUrl: case DataType.CreditCard: case DataType.PostalCode: case DataType.Upload: { csspProp.CSSPError = $"DataType [{ dataType.ToString() }] is not implemented yet."; return(false); } default: break; } } if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "StringLengthAttribute").Any()) { csspProp.HasStringLengthAttribute = true; if (propInfo.PropertyType != typeof(System.String)) { csspProp.CSSPError = $"Class [{ type.FullName }] { propInfo.Name } should not contain the StringLength Attribute. StringLength Attribute can only be set for System.String"; return(false); } CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "StringLengthAttribute").First(); csspProp.Max = ((int)customAttributeData.ConstructorArguments.ToArray()[0].Value); if (customAttributeData.NamedArguments.ToArray().Count() > 0) { for (int i = 0, count = customAttributeData.NamedArguments.ToArray().Count(); i < count; i++) { if (customAttributeData.NamedArguments.ToArray()[i].MemberName == "MinimumLength") { csspProp.Min = ((int)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } } } } if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "RangeAttribute").Any()) { csspProp.HasRangeAttribute = true; CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "RangeAttribute").First(); if (csspProp.PropType == "Int16" || csspProp.PropType == "Int32" || csspProp.PropType == "Int64") { csspProp.Min = ((int)customAttributeData.ConstructorArguments.ToArray()[0].Value); csspProp.Max = ((int)customAttributeData.ConstructorArguments.ToArray()[1].Value); if (csspProp.Min > csspProp.Max && csspProp.Max == -1) { csspProp.Max = null; } } else if (csspProp.PropType == "Single" || csspProp.PropType == "Double") { csspProp.Min = ((double)customAttributeData.ConstructorArguments.ToArray()[0].Value); csspProp.Max = ((double)customAttributeData.ConstructorArguments.ToArray()[1].Value); if (csspProp.Min > csspProp.Max && csspProp.Max == -1) { csspProp.Max = null; } } else { csspProp.CSSPError = $"Type [{ type.FullName }] Property [{ csspProp.PropName }] of type [{ csspProp.PropType }] should not use RangeAttribute. Only types [Int,Single,Double] can use RangeAttributre"; return(false); } } if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CompareAttribute").Any()) { csspProp.HasCompareAttribute = true; CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CompareAttribute").First(); csspProp.Compare = ((string)customAttributeData.ConstructorArguments.ToArray()[0].Value); } if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPBiggerAttribute").Any()) { csspProp.HasCSSPBiggerAttribute = true; CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPBiggerAttribute").First(); for (int i = 0, count = customAttributeData.NamedArguments.ToArray().Count(); i < count; i++) { if (customAttributeData.NamedArguments.ToArray()[i].MemberName == "OtherField") { csspProp.OtherField = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } } } if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPAfterAttribute").Any()) { csspProp.HasCSSPAfterAttribute = true; if (csspProp.PropType != "DateTime") { csspProp.CSSPError = $"Property [{ csspProp.PropName }] of type [{ csspProp.PropType }] CSSPAfterAttribute should only be user for DateTime Type"; return(false); } CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPAfterAttribute").First(); for (int i = 0, count = customAttributeData.NamedArguments.ToArray().Count(); i < count; i++) { if (customAttributeData.NamedArguments.ToArray()[i].MemberName == "Year") { csspProp.Year = ((int)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } } } if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPExistAttribute").Any()) { csspProp.HasCSSPExistAttribute = true; CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPExistAttribute").First(); for (int i = 0, count = customAttributeData.NamedArguments.ToArray().Count(); i < count; i++) { switch (customAttributeData.NamedArguments.ToArray()[i].MemberName) { case "ExistTypeName": { csspProp.ExistTypeName = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; case "ExistPlurial": { csspProp.ExistPlurial = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; case "ExistFieldID": { csspProp.ExistFieldID = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; case "AllowableTVTypeList": { csspProp.AllowableTVTypeList = new List <TVTypeEnum>(); string tvTypes = (string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value; foreach (string TVType in tvTypes.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList()) { csspProp.AllowableTVTypeList.Add(((TVTypeEnum)int.Parse(TVType))); } } break; default: csspProp.CSSPError = $"Property [{ csspProp.PropName }] of type [{ csspProp.PropType }] --- member name { customAttributeData.NamedArguments.ToArray()[i].MemberName } does not exist for CSSPExistAttribute"; return(false); } } } if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPFillAttribute").Any()) { csspProp.HasCSSPFillAttribute = true; CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPFillAttribute").First(); for (int i = 0, count = customAttributeData.NamedArguments.ToArray().Count(); i < count; i++) { switch (customAttributeData.NamedArguments.ToArray()[i].MemberName) { case "FillTypeName": { csspProp.FillTypeName = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; case "FillPlurial": { csspProp.FillPlurial = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; case "FillFieldID": { csspProp.FillFieldID = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; case "FillEqualField": { csspProp.FillEqualField = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; case "FillReturnField": { csspProp.FillReturnField = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; case "FillNeedLanguage": { csspProp.FillNeedLanguage = ((bool)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; case "FillIsList": { csspProp.FillIsList = ((bool)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; default: csspProp.CSSPError = $"Property [{ csspProp.PropName }] of type [{ csspProp.PropType }] --- member name { customAttributeData.NamedArguments.ToArray()[i].MemberName } does not exist for CSSPExistAttribute"; return(false); } } } if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPEnumTypeTextAttribute").Any()) { csspProp.HasCSSPEnumTypeTextAttribute = true; CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPEnumTypeTextAttribute").First(); for (int i = 0, count = customAttributeData.NamedArguments.ToArray().Count(); i < count; i++) { switch (customAttributeData.NamedArguments.ToArray()[i].MemberName) { case "EnumTypeName": { csspProp.EnumTypeName = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; case "EnumType": { csspProp.EnumType = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; default: csspProp.CSSPError = $"Property [{ csspProp.PropName }] of type [{ csspProp.PropType }] --- member name { customAttributeData.NamedArguments.ToArray()[i].MemberName } does not exist for CSSPExistAttribute"; return(false); } } } csspProp.IsVirtual = propInfo.GetGetMethod().IsVirtual; csspProp.HasCSSPEnumTypeAttribute = propInfo.CustomAttributes.Where(c => c.AttributeType.Name.StartsWith("CSSPEnumTypeAttribute")).Any(); csspProp.HasNotMappedAttribute = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "NotMappedAttribute").Any(); if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPDescriptionENAttribute").Any()) { csspProp.HasCSSPDescriptionENAttribute = true; CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPDescriptionENAttribute").First(); for (int i = 0, count = customAttributeData.NamedArguments.ToArray().Count(); i < count; i++) { switch (customAttributeData.NamedArguments.ToArray()[i].MemberName) { case "DescriptionEN": { csspProp.DescriptionEN = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; default: csspProp.CSSPError = $"Property [{ csspProp.PropName }] of type [{ csspProp.PropType }] --- member name { customAttributeData.NamedArguments.ToArray()[i].MemberName } does not exist for CSSPExistAttribute"; return(false); } } } if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPDescriptionFRAttribute").Any()) { csspProp.HasCSSPDescriptionFRAttribute = true; CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPDescriptionFRAttribute").First(); for (int i = 0, count = customAttributeData.NamedArguments.ToArray().Count(); i < count; i++) { switch (customAttributeData.NamedArguments.ToArray()[i].MemberName) { case "DescriptionFR": { csspProp.DescriptionFR = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; default: csspProp.CSSPError = $"Property [{ csspProp.PropName }] of type [{ csspProp.PropType }] --- member name { customAttributeData.NamedArguments.ToArray()[i].MemberName } does not exist for CSSPExistAttribute"; return(false); } } } if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPDisplayENAttribute").Any()) { csspProp.HasCSSPDisplayENAttribute = true; CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPDisplayENAttribute").First(); for (int i = 0, count = customAttributeData.NamedArguments.ToArray().Count(); i < count; i++) { switch (customAttributeData.NamedArguments.ToArray()[i].MemberName) { case "DisplayEN": { csspProp.DisplayEN = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; default: csspProp.CSSPError = $"Property [{ csspProp.PropName }] of type [{ csspProp.PropType }] --- member name { customAttributeData.NamedArguments.ToArray()[i].MemberName } does not exist for CSSPExistAttribute"; return(false); } } } if (propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPDisplayFRAttribute").Any()) { csspProp.HasCSSPDisplayFRAttribute = true; CustomAttributeData customAttributeData = propInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CSSPDisplayFRAttribute").First(); for (int i = 0, count = customAttributeData.NamedArguments.ToArray().Count(); i < count; i++) { switch (customAttributeData.NamedArguments.ToArray()[i].MemberName) { case "DisplayFR": { csspProp.DisplayFR = ((string)customAttributeData.NamedArguments.ToArray()[i].TypedValue.Value); } break; default: csspProp.CSSPError = $"Property [{ csspProp.PropName }] of type [{ csspProp.PropType }] --- member name { customAttributeData.NamedArguments.ToArray()[i].MemberName } does not exist for CSSPExistAttribute"; return(false); } } } return(true); }
public bool FillDLLTypeInfoList(FileInfo fiDLL, List <DLLTypeInfo> DLLTypeInfoList) { var importAssembly = Assembly.LoadFile(fiDLL.FullName); List <Type> typeList = importAssembly.GetTypes().ToList(); int count = 0; foreach (Type type in typeList) { if (type.Name.StartsWith("<") || type.FullName.StartsWith("CSSPWebAPI.Models")) { continue; } DLLTypeInfo dllTypeInfo = new DLLTypeInfo(); dllTypeInfo.Type = type; dllTypeInfo.Name = type.Name; dllTypeInfo.IsEnum = false; if (type.GetTypeInfo().BaseType == typeof(System.Enum)) { dllTypeInfo.IsEnum = true; } dllTypeInfo.HasNotMappedAttribute = type.CustomAttributes.Where(c => c.AttributeType.Name == "NotMappedAttribute").Any(); foreach (FieldInfo fieldInfo in type.GetFields()) { if (!fieldInfo.FieldType.Name.EndsWith("Enum")) { continue; } DLLFieldInfo dllFieldInfo = new DLLFieldInfo(); dllFieldInfo.FieldInfo = fieldInfo; dllFieldInfo.Name = fieldInfo.Name; dllTypeInfo.FieldInfoList.Add(dllFieldInfo); } foreach (PropertyInfo propertyInfo in type.GetProperties()) { bool CanReadPropertyType = false; try { var PropertyType = propertyInfo.PropertyType; CanReadPropertyType = true; } catch (Exception) { // not used } if (!CanReadPropertyType) { continue; } if (propertyInfo.PropertyType.Name.StartsWith("<")) { continue; } count += 1; if (count % 200 == 0) { StatusTempEvent(new StatusEventArgs($"Reading type file [{ fiDLL.Name }] [{ type.Name }] [{ propertyInfo.Name }]")); } DLLPropertyInfo dllPropertyInfo = new DLLPropertyInfo(); dllPropertyInfo.PropertyInfo = propertyInfo; CSSPProp csspProp = new CSSPProp(); if (!FillCSSPProp(propertyInfo, csspProp, type)) { CSSPErrorEvent(new CSSPErrorEventArgs("CSSPError while filling CSSPProp")); return(false); } dllPropertyInfo.CSSPProp = csspProp; dllTypeInfo.PropertyInfoList.Add(dllPropertyInfo); } foreach (MethodInfo methodInfo in type.GetMethods()) { if (methodInfo.Name.StartsWith("<")) { continue; } count += 1; if (count % 200 == 0) { StatusTempEvent(new StatusEventArgs($"Reading type file [{ fiDLL.Name }] [{ type.Name }] [{ methodInfo.Name }]")); } if (methodInfo.DeclaringType.FullName.StartsWith("CSSP")) { DLLMethodInfo dllMethodInfo = new DLLMethodInfo(); dllMethodInfo.MethodInfo = methodInfo; dllMethodInfo.Name = methodInfo.Name; dllMethodInfo.DeclaringType = methodInfo.DeclaringType; string DeclaringTypeName = methodInfo.DeclaringType.FullName; if (DeclaringTypeName.StartsWith("System.Nullable")) { DeclaringTypeName = DeclaringTypeName.Substring(DeclaringTypeName.IndexOf("[[") + 2); DeclaringTypeName = DeclaringTypeName.Substring(DeclaringTypeName.IndexOf(".") + 1); DeclaringTypeName = DeclaringTypeName.Substring(0, DeclaringTypeName.IndexOf(",")); } dllMethodInfo.DeclaringTypeName = DeclaringTypeName; try { foreach (ParameterInfo parameterInfo in methodInfo.GetParameters()) { DLLParameterInfo dllParameterInfo = new DLLParameterInfo(); dllParameterInfo.ParameterInfo = parameterInfo; dllParameterInfo.Name = parameterInfo.Name; dllMethodInfo.ParameterInfoList.Add(dllParameterInfo); } } catch (Exception) { // nothing } dllTypeInfo.MethodInfoList.Add(dllMethodInfo); } } DLLTypeInfoList.Add(dllTypeInfo); } return(false); }