0

I am using T4Scaffolding to create a custom scaffold. I use the following PS code to get a list of all domain objects in my project:

# List of all domain classes. Get all top level files/folders in the project | drill down to Models folder | Enumerate ProjectItems | Where Name ends with .cs | Select name truncating .cs, pluralized name
$domainClasses = (Get-Project "Domain").ProjectItems | Where { $_.Name -eq "Models" } | ForEach { $_.ProjectItems } | Where { $_.Name.EndsWith('.cs') } | Select @{ Name = 'Name'; Expression={ $_.Name.SubString(0,$_.Name.Length - 3) } }, @{ Name = 'Plural'; Expression={ Get-PluralizedWord $_.Name.SubString(0,$_.Name.Length - 3) } } 
if (!$domainClasses) { $domainClasses = @() }

Then I call the Add-ProjectItemViaTemplate method like this:

Add-ProjectItemViaTemplate $outputPath -Template MyTemplate `
  -Model @{ DomainClasses=[Array]$domainClasses } `
  -SuccessMessage "Added Domain output at {0}" `
  -TemplateFolders $TemplateFolders -Project $DomainProjectName -CodeLanguage $CodeLanguage -Force:$Force

I get the following exception when I run the sacffold:

System.Runtime.Serialization.SerializationException: Type 'System.Management.Automation.PSCustomObject' in assembly 'System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.      

The problem seems to be that the $domainClasses variable can't be serialized for some reason. What am I doing wrong?

1 Answers1

0

I tried this a long time ago but it did not work :(

I solved it anyway since I noticed that you can pass an array of string into the T4-template. Since you can pass in a array of strings I built comma-separated strings with the information for each object... Then I did a split(",") inside of the T4-template getting the data back...

Example

#Get regular properties
$properties = @()(Get-ProjectType $ModelType).Children | Where-Object{$_.Kind -eq 4 -and $_.Type.TypeKind -ne 1 } | ForEach{
$p = "$($_.Name),$($_.Type.AsString)"; 
$properties = $properties + $p
}

Then I just pass the $properties array as a regular parameter (the fourth parameter)...

Add-ProjectItemViaTemplate $outputPath -Template ViewModel `
-Model @{   
Namespace = $namespace; 
DataType = [MarshalByRefObject]$foundModelType; 
DataTypeName = $foundModelType.Name; 
Properties = $properties;
Parents = $parents;
Children = $children;
ExtraUsings = $ximports
} `
-SuccessMessage "Added ViewModel for $ModelType {0}" `
-TemplateFolders $TemplateFolders -Project $coreProjectName -CodeLanguage $CodeLanguage -Force:$Force

The in the T4 I just...

<#
//Own properties 
foreach (var property in Model.Properties) {
    var info = property.Split(',');
#>
    public <#= info[1] #> <#= info[0] #> {get;set;}
<#  
}
#>

Not what I prefer to do... But it works

Uffe
  • 2,275
  • 1
  • 13
  • 9