protected internal virtual void GenerateMessages(ProjectItem directoryProjectItem, IEnumerable <IMsgFile> messageList, string standardNamespace) { foreach (IMsgFile message in messageList) { ITextTemplatingSession session = _textTemplatingSessionHost.CreateSession(); session[TemplateParameterConstants.RosMessage.ROS_MESSAGE_TYPE_ATTRIBUTE_NAMESPACE] = _rosMessageTypeAttributeNamespace; session[TemplateParameterConstants.RosMessage.ROS_MESSAGE_TYPE_ATTRIBUTE_NAME] = _rosMessageTypeAttributeName; session[TemplateParameterConstants.RosMessage.NAMESPACE_PREFIX] = _defaultNamespace; ISet <string> dependencySet = new HashSet <string>() { standardNamespace }; dependencySet.UnionWith(message.DependencySet.Select(type => type.Namespace)); session[TemplateParameterConstants.RosMessage.DEPENDENCY_LIST] = dependencySet; session[TemplateParameterConstants.RosMessage.NAMESPACE] = message.Type.Namespace; session[TemplateParameterConstants.RosMessage.TYPE] = message.Type.Type; session[TemplateParameterConstants.RosMessage.CONSTANT_FIELD_LIST] = message.ConstantFieldSet.Select(field => Tuple.Create(field.Type.Type, field.FieldName, field.FieldValue)).ToList(); session[TemplateParameterConstants.RosMessage.ARRAY_FIELD_LIST] = message.ArrayFieldSet.Select(field => Tuple.Create(field.Type.Type, field.FieldName, field.ArrayElementCount)).ToList(); session[TemplateParameterConstants.RosMessage.FIELD_LIST] = message.FieldSet.ToDictionary(k => k.FieldName, v => v.Type.Type); TransformTemplateToFile(session, directoryProjectItem, _rosMessageCodeGenerationTemplatePath, _rosMessageCodeGenerationTemplateContent, message.Type.Type); } ; }
/// <summary> /// Process the given template with the given session /// </summary> /// <param name="template"></param> /// <param name="session"></param> /// <returns></returns> public string ProcessTemplateWithSession(FileInfo template, ITextTemplatingSession session) { if (null == template) { throw new ArgumentNullException(nameof(template)); } if (null == session) { throw new ArgumentNullException(nameof(session)); } if (!template.Exists) { throw new FileNotFoundException(template.FullName); } _textTemplatingEngineHost.TemplateFile = template.FullName; _textTemplatingEngineHost.Session = session; string templateContent = File.ReadAllText(template.FullName); Engine engine = new Engine(); string templateOutput = engine.ProcessTemplate(templateContent, _textTemplatingEngineHost); return(templateOutput); }
public bool Equals(ITextTemplatingSession other) { if (other != null) { return(Equals(other.Id)); } return(false); }
private static IEnumerable <ITextTemplatingSession> GetServiceT4Sessions(ITextTemplatingSessionHost host, GeneratedService generatedService) { ITextTemplatingSession session = host.CreateSession(); session["generatedService"] = generatedService; yield return(session); }
public ITextTemplatingSession CreateSession() { if (session == null) { session = new TextTemplatingSession(); } return(session); }
protected internal virtual void GenerateCustomTimePrimitiveType(ProjectItem standardNamespaceDirectoryProjectItem, string standardNamespace) { ITextTemplatingSession session = _textTemplatingSessionHost.CreateSession(); session[TemplateParameterConstants.TimeData.NAMESPACE] = $"{_defaultNamespace}.{standardNamespace}"; session[TemplateParameterConstants.TimeData.TYPE] = RosConstants.MessageTypes.CUSTOM_TIME_PRIMITIVE_TYPE; TransformTemplateToFile(session, standardNamespaceDirectoryProjectItem, _customTimeDataTemplatePath, ReadAllTextFromFile(_customTimeDataTemplatePath), RosConstants.MessageTypes.CUSTOM_TIME_PRIMITIVE_TYPE); }
public void TimeDataTemplate_ShouldCreatesAppropriateType() { //arrange string testNamespace = "testNamespace"; string testType = "testType"; ITextTemplatingSession session = CreateTemplateSession(testNamespace, testType); //act string templateOutput = _templateProcessor.ProcessTemplateWithSession(_template, session); //assert SyntaxTree parsedTemplateOutput = _templateCompiler.ParseTemplateOutput(templateOutput); Assembly compiledAssembly = _templateCompiler.CompileSyntaxTree(parsedTemplateOutput, DefaultCompilationOptions, DefaultReferences, MethodBase.GetCurrentMethod().Name); _templateCompiler.CompilationInfo.Success.Should().BeTrue(); compiledAssembly.Should().NotBeNull(); compiledAssembly.DefinedTypes.Should().NotBeNull(); compiledAssembly.DefinedTypes.Should().HaveCount(1); Type resultType = compiledAssembly.DefinedTypes.First(); resultType.Namespace.Should().Be(testNamespace); resultType.Name.Should().Be(testType); resultType.IsValueType.Should().BeTrue(); MethodInfo equalsMethod = resultType.GetMethod("Equals"); equalsMethod.Should().NotBeNull(); equalsMethod.ReturnType.Should().Be(typeof(Boolean)); equalsMethod.IsPublic.Should().BeTrue(); equalsMethod.IsVirtual.Should().BeTrue(); IEnumerable <MethodInfo> resultMethodCollection = resultType.GetMethods(); resultMethodCollection.Should().NotBeNull(); MethodInfo resultEqualsMethod = resultMethodCollection.FirstOrDefault(member => member.Name == EQUALS_METHOD.Key); resultEqualsMethod.Should().NotBeNull(); resultEqualsMethod.ReturnType.Should().Be(EQUALS_METHOD.Value); IEnumerable <PropertyInfo> resultPropertyCollection = resultType.GetProperties(); resultPropertyCollection.Should().HaveCount(2); PropertyInfo resultSecProperty = resultPropertyCollection.SingleOrDefault(property => property.Name == SEC_PROPERTY.Key); resultSecProperty.Should().NotBeNull(); resultSecProperty.PropertyType.Should().Be(SEC_PROPERTY.Value); PropertyInfo resultNSecProperty = resultPropertyCollection.SingleOrDefault(property => property.Name == NSEC_PROPERTY.Key); resultNSecProperty.Should().NotBeNull(); resultNSecProperty.PropertyType.Should().Be(NSEC_PROPERTY.Value); }
protected override void OnSessionChanged(ITextTemplatingSession oldSession, ITextTemplatingSession newSession) { if (modelBus != null) { foreach (IStatefulAdapterManager manager in modelBus.GetRegisteredAdapterManagers <IStatefulAdapterManager>()) { manager.ClearState(); } } }
public override bool Equals(object obj) { ITextTemplatingSession textTemplatingSession = obj as ITextTemplatingSession; if (textTemplatingSession != null) { return(Equals(textTemplatingSession)); } return(false); }
public override bool Equals(object obj) { ITextTemplatingSession other = obj as ITextTemplatingSession; if (other == null) { return(false); } return(this.Equals(other)); }
private static IEnumerable <ITextTemplatingSession> GetObjectT4Sessions(ITextTemplatingSessionHost host, IEnumerable <GeneratedObject> generatedObjects) { foreach (GeneratedObject generatedObject in generatedObjects) { ITextTemplatingSession session = host.CreateSession(); session["generatedObject"] = generatedObject; yield return(session); } }
protected override void SetStartSession(string sourcePath, string sourceSha256) { ITextTemplatingSession session = SetGeneralSessionValues(sourcePath, sourceSha256); session["ClassNode"] = null; session["MethodNode"] = null; session["PropertyNode"] = null; _requiredUsings = new List <string>(); session["RequiredUsing"] = _requiredUsings; }
protected internal virtual void TransformTemplateToFile(ITextTemplatingSession session, ProjectItem groupDirectoryProjectItem, string templatePath, string templateContent, string typeName) { string directoryPath = _solutionManager.GetProjectItemFullPath(groupDirectoryProjectItem); _textTemplatingSessionHost.Session = session; string transformedTemplate = _textTemplating.ProcessTemplate(templatePath, templateContent); string newFilePath = WriteToFile(directoryPath, typeName, transformedTemplate); _solutionManager.AddFileToDirectoryProjectItem(groupDirectoryProjectItem, newFilePath); }
public void TimeDataTemplate_TypeParameterEmpty_TemplateShouldThrowArgumentException() { //arrange string testNamespace = "testNamespace"; string testType = string.Empty; ITextTemplatingSession session = CreateTemplateSession(testNamespace, testType); //act string templateOutput = _templateProcessor.ProcessTemplateWithSession(_template, session); //assert templateOutput.Should().NotBeNull(); _textTemplatingEngineHost.Errors.Should().HaveCount(1); _textTemplatingEngineHost.Errors.Any(error => error.FileName == _template.FullName && error.ErrorText.Contains(typeof(ArgumentException).Name)).Should().BeTrue(); }
public bool EndErrorSession() { this.errorSessionDepth--; if ((this.errorSessionDepth == 0) && this.transformationSessionImplicitlyCreated) { this.transformationSession = null; this.transformationSessionImplicitlyCreated = false; } bool flag = false; if (this.currentErrors != null) { flag = this.currentErrors.Count > 0; } return(flag); }
public void RosMessageTemplate_MessageTypeIsEmpty_ShouldThrowArgumentException() { //arrange Type rosMessageTypeAttributeType = typeof(RosMessageTypeAttribute); string rosbridgeAttributeNamespace = rosMessageTypeAttributeType.Namespace; string rosbridgeAttributeType = rosMessageTypeAttributeType.Name; string namespacePrefix = "testPrefix"; string testNamespace = "testNamespace"; string testType = string.Empty; IEnumerable <string> testDependencies = new string[] { }; IEnumerable <Tuple <string, string, string> > testConstantFields = new List <Tuple <string, string, string> >() { Tuple.Create("String", "TestFieldName1", "TestValue") }; IEnumerable <Tuple <string, string, int> > testArrayFields = new List <Tuple <string, string, int> >() { Tuple.Create("String", "TestFieldName2", 2) }; IDictionary <string, string> testFields = new Dictionary <string, string>() { { "TestFieldName3", "String" } }; ITextTemplatingSession session = CreateTemplateSession( rosbridgeAttributeNamespace, rosbridgeAttributeType, namespacePrefix, testNamespace, testType, testDependencies, testConstantFields, testArrayFields, testFields); //act string templateOutput = _templateProcessor.ProcessTemplateWithSession(_template, session); //assert templateOutput.Should().NotBeNull(); _textTemplatingEngineHost.Errors.Should().HaveCount(1); _textTemplatingEngineHost.Errors.Any(error => error.FileName == _template.FullName && error.ErrorText.Contains(typeof(ArgumentException).Name)).Should().BeTrue(); }
public void BeginErrorSession() { if (this.errorSessionDepth == 0) { if (this.currentErrors == null) { this.currentErrors = new Dictionary <string, int>(); } else { this.currentErrors.Clear(); } this.errorProvider.Tasks.Clear(); if ((this.transformationSession == null) && !this.transformationSessionImplicitlyCreated) { this.transformationSession = new TextTemplatingSession(); this.transformationSessionImplicitlyCreated = true; } } this.errorSessionDepth++; }
public ITextTemplatingSession SetGeneralSessionValues(string sourcePath, string sourceSha256) { _usedTemplates.Clear(); ITextTemplatingSession session = T4Generator.GetOrCreateSession(); session["FileName"] = Path.GetFileName(sourcePath); session["FilePath"] = sourcePath; session["User"] = Environment.UserName; session["FileSha256"] = sourceSha256; session["Now"] = DateTime.Now.ToString("o"); session["MachineName"] = Environment.MachineName; session["GlobalTag"] = BuilderSettings.GlobalTag; Action <string> log = (s) => Console.Out.WriteLine(s); session["Log"] = log; Action <string> logError = (s) => Console.Error.WriteLine(s); session["LogError"] = logError; Action <string> logDebug = (s) => { if (BuilderSettings.Verbosity > 1) { Console.Out.WriteLine(s); } }; session["LogDebug"] = logDebug; session["ExtraTag"] = null; return(session); }
public ITextTemplatingSession CreateSession() { return Session = new TemplateGeneratorSession(); }
public void RosMessageTemplate_ShouldCreateAppropriateType() { //arrange Type rosMessageTypeAttributeType = typeof(RosMessageTypeAttribute); string rosbridgeAttributeNamespace = rosMessageTypeAttributeType.Namespace; string rosbridgeAttributeType = rosMessageTypeAttributeType.Name; string namespacePrefix = "testPrefix"; string testNamespace = "testNamespace"; string testType = "testType"; IEnumerable <string> testDependencies = new string[] { }; IEnumerable <Tuple <string, string, string> > testConstantFields = new List <Tuple <string, string, string> >() { Tuple.Create("String", "TestFieldName1", "TestValue") }; IEnumerable <Tuple <string, string, int> > testArrayFields = new List <Tuple <string, string, int> >() { Tuple.Create("String", "TestFieldName2", 2) }; IDictionary <string, string> testFields = new Dictionary <string, string>() { { "TestFieldName3", "String" } }; ITextTemplatingSession session = CreateTemplateSession( rosbridgeAttributeNamespace, rosbridgeAttributeType, namespacePrefix, testNamespace, testType, testDependencies, testConstantFields, testArrayFields, testFields); //act string templateOutput = _templateProcessor.ProcessTemplateWithSession(_template, session); //assert SyntaxTree parsedTemplateOutput = _templateCompiler.ParseTemplateOutput(templateOutput); Assembly compiledAssembly = _templateCompiler.CompileSyntaxTree(parsedTemplateOutput, DefaultCompilationOptions, DefaultReferences, MethodBase.GetCurrentMethod().Name); _templateCompiler.CompilationInfo.Success.Should().BeTrue(); compiledAssembly.Should().NotBeNull(); compiledAssembly.DefinedTypes.Should().NotBeNull(); compiledAssembly.DefinedTypes.Should().HaveCount(1); //type check Type resultType = compiledAssembly.DefinedTypes.First(); resultType.Name.Should().Be(testType); resultType.Namespace.Should().Be($"{namespacePrefix}.{testNamespace}"); resultType.IsValueType.Should().BeFalse(); resultType.CustomAttributes.Should().Contain(attribute => attribute.AttributeType == rosMessageTypeAttributeType); MethodInfo equalsMethod = resultType.GetMethod("Equals"); equalsMethod.Should().NotBeNull(); equalsMethod.ReturnType.Should().Be(typeof(Boolean)); equalsMethod.IsPublic.Should().BeTrue(); equalsMethod.IsVirtual.Should().BeTrue(); IEnumerable <FieldInfo> resultConstantFieldCollection = resultType.GetFields().Where(field => field.IsLiteral && !field.IsInitOnly).ToList(); resultConstantFieldCollection.Should().NotBeNull(); resultConstantFieldCollection.Should().HaveCount(1); Tuple <string, string, string> testConstantField = testConstantFields.First(); FieldInfo resultConstantField = resultConstantFieldCollection.SingleOrDefault(field => field.Name == testConstantField.Item2); resultConstantField.Should().NotBeNull(); resultConstantField.FieldType.Name.Should().Be(testConstantField.Item1); IEnumerable <PropertyInfo> resultPropertyCollection = resultType.GetProperties(); resultPropertyCollection.Should().NotBeNull(); resultPropertyCollection.Should().HaveCount(testArrayFields.Count() + testFields.Count); Tuple <string, string, int> testArrayField = testArrayFields.First(); PropertyInfo resultArrayProperty = resultPropertyCollection.SingleOrDefault(property => property.Name == testArrayField.Item2); resultArrayProperty.Should().NotBeNull(); resultArrayProperty.PropertyType.IsArray.Should().BeTrue(); resultArrayProperty.PropertyType.GetElementType().Name.Should().Be(testArrayField.Item1); KeyValuePair <string, string> testField = testFields.FirstOrDefault(); PropertyInfo resultFieldProperty = resultPropertyCollection.SingleOrDefault(property => property.Name == testField.Key); resultFieldProperty.Should().NotBeNull(); resultFieldProperty.PropertyType.Name.Should().Be(testField.Value); //instance check dynamic instantiatedResultType = Activator.CreateInstance(resultType); dynamic resultConstantFieldInstanceValue = resultConstantField.GetValue(instantiatedResultType); testConstantField.Item3.Should().Be(resultConstantFieldInstanceValue); dynamic resultArrayPropertyInstanceValue = resultArrayProperty.GetValue(instantiatedResultType); testArrayField.Item3.Should().Be(resultArrayPropertyInstanceValue.Length); }
public bool Equals(ITextTemplatingSession other) { return(other == this); }
public void RosMessageTemplate_NoFieldsDefined_ShouldCreateAppropriateTypeWithoutFields() { //arrange Type rosMessageTypeAttributeType = typeof(RosMessageTypeAttribute); string rosbridgeAttributeNamespace = rosMessageTypeAttributeType.Namespace; string rosbridgeAttributeType = rosMessageTypeAttributeType.Name; string namespacePrefix = "testPrefix"; string testNamespace = "testNamespace"; string testType = "testType"; IEnumerable <string> testDependencies = new string[] { }; IEnumerable <Tuple <string, string, string> > testConstantFields = new List <Tuple <string, string, string> >(); IEnumerable <Tuple <string, string, int> > testArrayFields = new List <Tuple <string, string, int> >(); IDictionary <string, string> testFields = new Dictionary <string, string>(); ITextTemplatingSession session = CreateTemplateSession( rosbridgeAttributeNamespace, rosbridgeAttributeType, namespacePrefix, testNamespace, testType, testDependencies, testConstantFields, testArrayFields, testFields); //act string templateOutput = _templateProcessor.ProcessTemplateWithSession(_template, session); //assert SyntaxTree parsedTemplateOutput = _templateCompiler.ParseTemplateOutput(templateOutput); Assembly compiledAssembly = _templateCompiler.CompileSyntaxTree(parsedTemplateOutput, DefaultCompilationOptions, DefaultReferences, MethodBase.GetCurrentMethod().Name); _templateCompiler.CompilationInfo.Success.Should().BeTrue(); compiledAssembly.Should().NotBeNull(); compiledAssembly.DefinedTypes.Should().NotBeNull(); compiledAssembly.DefinedTypes.Should().HaveCount(1); //type check Type resultType = compiledAssembly.DefinedTypes.First(); resultType.Name.Should().Be(testType); resultType.Namespace.Should().Be($"{namespacePrefix}.{testNamespace}"); resultType.IsValueType.Should().BeFalse(); resultType.CustomAttributes.Should().Contain(attribute => attribute.AttributeType == rosMessageTypeAttributeType); MethodInfo equalsMethod = resultType.GetMethod("Equals"); equalsMethod.Should().NotBeNull(); equalsMethod.ReturnType.Should().Be(typeof(Boolean)); equalsMethod.IsPublic.Should().BeTrue(); equalsMethod.IsVirtual.Should().BeTrue(); IEnumerable <FieldInfo> resultConstantFieldCollection = resultType.GetFields().Where(field => field.IsLiteral && !field.IsInitOnly).ToList(); resultConstantFieldCollection.Should().NotBeNull(); resultConstantFieldCollection.Should().BeEmpty(); IEnumerable <PropertyInfo> resultPropertyCollection = resultType.GetProperties(); resultPropertyCollection.Should().NotBeNull(); resultPropertyCollection.Should().BeEmpty(); }
protected override void SetStartSession(string sourcePath, string sourceSha256) { ITextTemplatingSession session = SetGeneralSessionValues(sourcePath, sourceSha256); session["Source"] = File.ReadAllText(sourcePath); }
public bool Equals(ITextTemplatingSession other) { return(ReferenceEquals(this, other)); }
public SessionTemplateGenerator() { session = new TextTemplatingSession(); }
/// <summary> /// Returns the current session instance, creating it if necessary. /// </summary> public ITextTemplatingSession GetOrCreateSession() => session ?? (session = CreateSession());
public ITextTemplatingSession CreateSession() { return(Session = new TemplateGeneratorSession()); }
public bool Equals(ITextTemplatingSession other) { return other == this; }
/// <summary> /// Instantiates an object of the generated transformation class from the compiled assembly. /// </summary> private object CreateTextTransformation(string fullClassName, ITextTemplatingEngineHost host, Assembly assembly, ITextTemplatingSession userSession, string baseTypeName) { object obj = null; try { obj = assembly.CreateInstance(fullClassName); if (obj == null) { LogError(Resources.ExceptionInstantiatingTransformationObject, false); return(null); } Type type = obj.GetType(); if (host != null) { try { PropertyInfo property = type.GetProperty("Host"); if (property != null) { property.SetValue(obj, host, null); } else { LogError(string.Format(CultureInfo.CurrentCulture, Resources.HostPropertyNotFound, baseTypeName), false); } } catch (Exception e) { if (Engine.IsCriticalException(e)) { throw; } LogError(string.Format(CultureInfo.CurrentCulture, Resources.ExceptionSettingHost, type.FullName), false); } } try { PropertyInfo mostDerivedProperty = GetMostDerivedProperty(type, "Session"); if (mostDerivedProperty != null) { mostDerivedProperty.SetValue(obj, userSession, null); } } catch (Exception e2) { if (Engine.IsCriticalException(e2)) { throw; } LogError(string.Format(CultureInfo.CurrentCulture, Resources.ExceptionSettingSession, type.FullName), false); } return(obj); } catch (Exception ex) { if (Engine.IsCriticalException(ex)) { (obj as IDisposable)?.Dispose(); throw; } LogError(Resources.ExceptionInstantiatingTransformationObject + string.Format(CultureInfo.CurrentCulture, Resources.Exception, ex), false); } return(null); }
public bool Equals(ITextTemplatingSession other) { return(other != null && other.Id == this.Id); }
public bool Equals(ITextTemplatingSession other) { return ReferenceEquals(this, other); }
private TextTransformation CreateTextTransformation(string fullClassName, ITextTemplatingEngineHost host, Assembly assembly, ITextTemplatingSession userSession) { object obj2 = null; try { obj2 = assembly.CreateInstance(fullClassName); if (obj2 == null) { this.LogError(Resources.ExceptionInstantiatingTransformationObject, false); return(null); } Type transformationType = obj2.GetType(); if (host != null) { try { transformationType.GetProperty("Host").SetValue(obj2, host, null); } catch (Exception exception) { if (Engine.IsCriticalException(exception)) { throw; } this.LogError(string.Format(CultureInfo.CurrentCulture, Resources.ExceptionSettingHost, new object[] { transformationType.FullName }), false); } } try { PropertyInfo mostDerivedProperty = GetMostDerivedProperty(transformationType, "Session"); if (mostDerivedProperty != null) { mostDerivedProperty.SetValue(obj2, userSession, null); } } catch (Exception exception2) { if (Engine.IsCriticalException(exception2)) { throw; } this.LogError(string.Format(CultureInfo.CurrentCulture, Resources.ExceptionSettingSession, new object[] { transformationType.FullName }), false); } return((TextTransformation)obj2); } catch (Exception exception3) { if (Engine.IsCriticalException(exception3)) { IDisposable disposable = obj2 as IDisposable; if (disposable != null) { disposable.Dispose(); } throw; } this.LogError(Resources.ExceptionInstantiatingTransformationObject + string.Format(CultureInfo.CurrentCulture, Resources.Exception, new object[] { exception3.ToString() }), false); } return(null); }
public ITextTemplatingSession CreateSession() { return(Session = new ToolTemplateSession(this)); }