public void FixUpWriteSnippetStatementTest() { var code = " abc zyx"; var stmt = new CodeSnippetStatement(code); WebPageSurrogateControlBuilder.FixUpWriteSnippetStatement(stmt); Assert.AreEqual(code, stmt.Value); code = " this.Write(\"hello\"); "; stmt = new CodeSnippetStatement(code); WebPageSurrogateControlBuilder.FixUpWriteSnippetStatement(stmt); Assert.AreEqual(code, stmt.Value); // @__w.Write case code = " @__w.Write(\"hello\"); "; stmt = new CodeSnippetStatement(code); WebPageSurrogateControlBuilder.FixUpWriteSnippetStatement(stmt); Assert.AreEqual(" WriteLiteral(\"hello\"); ", stmt.Value); // __w.Write case code = " __w.Write(\"hello\"); "; stmt = new CodeSnippetStatement(code); WebPageSurrogateControlBuilder.FixUpWriteSnippetStatement(stmt); Assert.AreEqual(" WriteLiteral(\"hello\"); ", stmt.Value); }
/// <summary> /// Processes the generators. /// </summary> /// <param name="parentClass">The parent class.</param> /// <param name="method">The method.</param> /// <param name="value">The value.</param> /// <param name="baseName">Name of the base.</param> /// <param name="dictionary">The dictionary.</param> /// <returns></returns> public CodeExpression ProcessGenerators(CodeTypeDeclaration parentClass, CodeMemberMethod method, object value, string baseName, ResourceDictionary dictionary = null) { if (value == null) { return(new CodePrimitiveExpression(null)); } IGeneratorValue generator; Type valueType = value.GetType(); CodeExpression valueExpression = null; if (Generators.TryGetValue(valueType, out generator)) { valueExpression = generator.Generate(parentClass, method, value, baseName, dictionary); } else if (valueType.IsEnum) { CodeTypeReferenceExpression typeReference = new CodeTypeReferenceExpression(valueType.Name); valueExpression = new CodeFieldReferenceExpression(typeReference, value.ToString()); } else { valueExpression = new CodePrimitiveExpression("NOT SUPPORTED!"); string errorText = string.Format("Type {0} not supported", valueType.Name); Console.WriteLine(errorText); CodeSnippetStatement error = new CodeSnippetStatement("#error " + errorText); method.Statements.Add(error); } return(valueExpression); }
static CodeStatement _ParseForStatement(_PC pc) { var l = pc.Line; var c = pc.Column; var p = pc.Position; if (ST.forKeyword != pc.SymbolId) { pc.Error("Expecting for"); } pc.Advance(); if (ST.lparen != pc.SymbolId) { pc.Error("Expecting ( in for statement"); } pc.Advance(); var init = _ParseStatement(pc, false); var test = _ParseExpression(pc); if (ST.semi != pc.SymbolId) { pc.Error("Expecting ; in for statement"); } pc.Advance(); CodeStatement inc = null; CodeExpression ince = null; if (ST.rparen != pc.SymbolId) { ince = _ParseExpression(pc); } if (ST.rparen != pc.SymbolId) { pc.Error("Expecting ) in for statement"); } if (null == ince) { inc = new CodeSnippetStatement().SetLoc(pc); } else { var bo = ince as CodeBinaryOperatorExpression; if (null != bo && CodeBinaryOperatorType.Assign == bo.Operator) { // probably not an attach or detach statement but we can't rule it out var ur = bo.UserData.Contains("slang:unresolved"); inc = new CodeAssignStatement(bo.Left, bo.Right).Mark(ince, ur); } else { inc = new CodeExpressionStatement(ince).Mark(ince); } } pc.Advance(); var result = new CodeIterationStatement(init, test, inc).Mark(l, c, p); result.Statements.AddRange(_ParseStatementOrBlock(pc)); return(result); }
/// <summary> /// Generates a wrapper method that takes arguments of the original method. /// </summary> protected virtual CodeTypeMember GetBasicReferenceMethod(MethodInfo methodInfo, CodeTypeParameterCollection genericTypeParam, bool isObserver) { SerializerGenerationManager.RecordTypeToGenerate(methodInfo.ReturnType); foreach (var paramInfo in methodInfo.GetParameters()) { SerializerGenerationManager.RecordTypeToGenerate(paramInfo.ParameterType); } CodeTypeReference returnType; if (!isObserver) { // Method is expected to return either a Task or a grain reference if (!GrainInterfaceData.IsTaskType(methodInfo.ReturnType) && !typeof(IAddressable).IsAssignableFrom(methodInfo.ReturnType)) { throw new InvalidOperationException( string.Format("Unsupported return type {0}. Method Name={1} Declaring Type={2}", methodInfo.ReturnType.FullName, methodInfo.Name, TypeUtils.GetFullName(methodInfo.DeclaringType, language))); } returnType = CreateCodeTypeReference(methodInfo.ReturnType, language); } else { returnType = new CodeTypeReference(typeof(void)); } var referenceMethod = new CodeMemberMethod { Name = methodInfo.Name, ReturnType = returnType }; foreach (var param in methodInfo.GetParameters()) { var paramName = GetParameterName(param); CodeParameterDeclarationExpression p = param.ParameterType.IsGenericType ? new CodeParameterDeclarationExpression( TypeUtils.GetParameterizedTemplateName(param.ParameterType, true, tt => CurrentNamespace != tt.Namespace && !ReferencedNamespaces.Contains(tt.Namespace), language), paramName) : new CodeParameterDeclarationExpression(param.ParameterType, paramName); p.Direction = FieldDirection.In; referenceMethod.Parameters.Add(p); } referenceMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; var pit = new CodeTypeReference(GetGenericTypeName(methodInfo.DeclaringType, type => { }, t => false)); referenceMethod.PrivateImplementationType = pit; var methodImpl = new CodeSnippetStatement(GetBasicMethodImpl(methodInfo)); referenceMethod.Statements.Add(methodImpl); return(referenceMethod); }
public override object Visit(EmptyStatement emptyStatement, object data) { CodeSnippetStatement emptyStmt = new CodeSnippetStatement(); AddStmt(emptyStmt); return(emptyStmt); }
// Generate the CodeDom for our render method internal CodeMemberMethod GenerateRenderMemberMethod(string virtualPath) { Control container = Parent; string physicalPath = HostingEnvironment.MapPath(virtualPath); CodeMemberMethod renderMethod = new CodeMemberMethod(); renderMethod.Name = RenderMethodName; renderMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "__srh")); // REVIEW: we need support for CodeArgumentReferenceExpression, as using a snippet is // not guanranteed to be language agnostic CodeExpression snippetRenderHelper = new CodeArgumentReferenceExpression("__srh"); StringBuilder codeBuilder = new StringBuilder(); // Go through all the children to build the CodeDOM tree for (int controlIndex = 0; controlIndex < container.Controls.Count; controlIndex++) { Control c = container.Controls[controlIndex]; if (!(c is SnippetControl || c is ExpressionSnippetControl)) { // If it's a regular control, generate a call to render it based on its index CodeExpression method = new CodeMethodInvokeExpression(snippetRenderHelper, "RenderControl", new CodePrimitiveExpression(controlIndex)); renderMethod.Statements.Add(new CodeExpressionStatement(method)); continue; } BaseCodeControl codeControl = (BaseCodeControl)c; string code = codeControl.Code; CodeStatement stmt; if (codeControl is SnippetControl) { // If it's a <% code %> block, just append the code as is stmt = new CodeSnippetStatement(code); } else { // If it's a <%= expr %> block, generate a call to render it CodeExpression method = new CodeMethodInvokeExpression(snippetRenderHelper, "Render", new CodeSnippetExpression(code)); stmt = new CodeExpressionStatement(method); } stmt.LinePragma = new CodeLinePragma(physicalPath, codeControl.Line); renderMethod.Statements.Add(stmt); } return(renderMethod); }
public void CodeTryCatchFinallyStatementTest() { CodeStatement cs = new CodeGotoStatement("exit"); CodeCatchClause ccc1 = new CodeCatchClause("ex1", new CodeTypeReference("System.ArgumentException")); CodeCatchClause ccc2 = new CodeCatchClause(null, new CodeTypeReference("System.ApplicationException")); CodeSnippetStatement fin1 = new CodeSnippetStatement("A"); CodeSnippetStatement fin2 = new CodeSnippetStatement("B"); statement = new CodeTryCatchFinallyStatement(new CodeStatement[] { cs }, new CodeCatchClause[] { ccc1, ccc2 }, new CodeStatement[] { fin1, fin2 }); Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, "try {{{0}" + " goto exit;{0}" + "}}{0}" + "catch (System.ArgumentException ex1) {{{0}" + "}}{0}" + "catch (System.ApplicationException ) {{{0}" + "}}{0}" + "finally {{{0}" + #if NET_2_0 "A{0}" + "B{0}" + #else " A{0}" + " B{0}" + #endif "}}{0}", NewLine), Generate(), "#1"); options.ElseOnClosing = true; Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, "try {{{0}" + " goto exit;{0}" + "}} catch (System.ArgumentException ex1) {{{0}" + "}} catch (System.ApplicationException ) {{{0}" + "}} finally {{{0}" + #if NET_2_0 "A{0}" + "B{0}" + #else " A{0}" + " B{0}" + #endif "}}{0}", NewLine), Generate(), "#2"); statement = new CodeTryCatchFinallyStatement(); Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, "try {{{0}" + "}}{0}", NewLine), Generate(), "#3"); options.ElseOnClosing = false; Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, "try {{{0}" + "}}{0}", NewLine), Generate(), "#4"); }
public static String GenerateFullClass(ICollection <String> references, ICollection <String> imports, String CodeNamespace, String className, string methodBody, String method = "Method") { CodeCompileUnit unit = new CodeCompileUnit(); if (references != null) { foreach (var item in references) { unit.ReferencedAssemblies.Add(item); } } CodeNamespace customEntityRoot = new CodeNamespace(CodeNamespace); //Create a namespace unit.Namespaces.Add(customEntityRoot); if (imports != null) { foreach (var item in imports) { customEntityRoot.Imports.Add(new CodeNamespaceImport(item)); } } CodeTypeDeclaration derived = new CodeTypeDeclaration(className); customEntityRoot.Types.Add(derived); CodeConstructor derivedClassConstructor = new CodeConstructor(); derivedClassConstructor.Attributes = MemberAttributes.Public; derived.Members.Add(derivedClassConstructor); CodeMemberMethod derivedMethod = new CodeMemberMethod(); derivedMethod.Attributes = MemberAttributes.Public; derivedMethod.Name = method; derivedMethod.ReturnType = new CodeTypeReference(typeof(void)); CodeSnippetStatement code = new CodeSnippetStatement(methodBody); derivedMethod.Statements.Add(code); derived.Members.Add(derivedMethod); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeGenerator codeGenerator = codeProvider.CreateGenerator(); StringBuilder generatedCode = new StringBuilder(); StringWriter codeWriter = new StringWriter(generatedCode); CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BracingStyle = "C"; codeGenerator.GenerateCodeFromCompileUnit(unit, codeWriter, options); return(generatedCode.ToString()); }
public static CodeSnippetStatement SnippetStatement(string value, CodeDirective[] startDirectives, CodeDirective[] endDirectives, CodeLinePragma linePragma) { var result = new CodeSnippetStatement(value); result.StartDirectives.AddRange(startDirectives); result.EndDirectives.AddRange(endDirectives); result.LinePragma = linePragma; return(result); }
public TypescriptSnippetStatement( IExpressionFactory expressionFactory, CodeSnippetStatement statement, CodeGeneratorOptions options) { _expressionFactory = expressionFactory; _statement = statement; _options = options; }
/// <summary> /// Generates a wrapper method that takes arguments of the original method. /// </summary> protected override CodeTypeMember GetBasicReferenceMethod(MethodInfo methodInfo, CodeTypeParameterCollection genericTypeParam, bool isObserver) { SerializerGenerationManager.RecordTypeToGenerate(methodInfo.ReturnType); foreach (ParameterInfo paramInfo in methodInfo.GetParameters()) { SerializerGenerationManager.RecordTypeToGenerate(paramInfo.ParameterType); } if (!isObserver) { var parameterList = new StringBuilder(); var first = true; foreach (var p in methodInfo.GetParameters()) { if (!first) { parameterList.Append(", "); } first = false; parameterList.AppendFormat("{0} As {1}", p.Name, GetGenericTypeName(p.ParameterType, type => { }, t => false)); } var snippet = new StringBuilder(); snippet.AppendFormat("Public Function {0}({1}) As {2} Implements {3}.{0}", methodInfo.Name, parameterList, GetGenericTypeName(methodInfo.ReturnType, type => { }, t => false), GetGenericTypeName(methodInfo.DeclaringType, type => { }, t => false)) .AppendLine(); snippet.AppendFormat(" {0}", GetBasicMethodImpl(methodInfo)).AppendLine(); snippet.AppendLine(" End Function"); return(new CodeSnippetTypeMember(snippet.ToString())); } var referenceMethod = new CodeMemberMethod { Name = methodInfo.Name, ReturnType = GetReturnTypeReference(methodInfo.ReturnType, SerializeFlag.DeserializeResult) }; foreach (var paramInfo in methodInfo.GetParameters()) { referenceMethod.Parameters.Add(new CodeParameterDeclarationExpression( new CodeTypeReference(paramInfo.ParameterType), GetParameterName(paramInfo))); } referenceMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; var pit = new CodeTypeReference(GetGenericTypeName(methodInfo.DeclaringType, type => { }, t => false)); referenceMethod.PrivateImplementationType = pit; var methodImpl = new CodeSnippetStatement(GetBasicMethodImpl(methodInfo)); referenceMethod.Statements.Add(methodImpl); return(referenceMethod); }
static bool WriteCodeSnippetStatement(CodeSnippetStatement snippetStatement, TextWriter w, CodeGeneratorOptions o) { if (snippetStatement == null) { return(false); } w.WriteLine(IndentLines(snippetStatement.Value, o.IndentString)); return(true); }
protected void GenerateStatement(CodeStatement s) { #if NET_2_0 if (s.StartDirectives.Count > 0) { GenerateDirectives(s.StartDirectives); } #endif if (s.LinePragma != null) { GenerateLinePragmaStart(s.LinePragma); } CodeSnippetStatement snippet = s as CodeSnippetStatement; if (snippet != null) { #if NET_2_0 int indent = Indent; try { Indent = 0; GenerateSnippetStatement(snippet); } finally { Indent = indent; } #else GenerateSnippetStatement(snippet); #endif } else { try { s.Accept(visitor); } catch (NotImplementedException) { throw new ArgumentException("Element type " + s.GetType() + " is not supported.", "s"); } } if (s.LinePragma != null) { GenerateLinePragmaEnd(s.LinePragma); } #if NET_2_0 if (s.EndDirectives.Count > 0) { GenerateDirectives(s.EndDirectives); } #endif }
private CodeMemberMethod creatCodeMethod(string methodName, string statementStr, MemberAttributes memberAttributes = MemberAttributes.Public | MemberAttributes.Final) { CodeMemberMethod method = new CodeMemberMethod(); method.Name = methodName; method.Attributes = memberAttributes; CodeSnippetStatement ass = new CodeSnippetStatement(statementStr); method.Statements.Add(ass); return(method); }
/// <summary> /// body of public PropertyBufferPtr GetProperty(string bufferName, string varNameInShader) /// </summary> /// <param name="method"></param> private void GetPropertyBody(CodeMemberMethod method, DataStructure dataStructure) { foreach (var item in dataStructure.PropertyList) { // if (bufferName == position) var ifStatement = new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression(bufferName), CodeBinaryOperatorType.IdentityEquality, new CodeVariableReferenceExpression(item.NameInModel))); method.Statements.Add(ifStatement); // if (positionBufferPtr != null) var ifStatement2 = new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression(item.BufferPtrName), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null))); ifStatement.TrueStatements.Add(ifStatement2); // using (var buffer = new PropertyBuffer<vec3>(varNameInShader)) var usingBegin = new CodeSnippetStatement(string.Format(" using(var buffer = new PropertyBuffer<{0}>({1}))", item.PropertyType, varNameInShader)); ifStatement2.TrueStatements.Add(usingBegin); ifStatement2.TrueStatements.Add(new CodeSnippetStatement(" {// begin of using")); var create = new CodeSnippetStatement(" buffer.Create();"); ifStatement2.TrueStatements.Add(create); // unsafe { ifStatement2.TrueStatements.Add(new CodeSnippetStatement(" unsafe")); ifStatement2.TrueStatements.Add(new CodeSnippetStatement(" {// begin of unsafe")); // var array = (vec3*)buffer.Header.ToPointer(); ifStatement2.TrueStatements.Add(new CodeSnippetStatement(string.Format(" var array = ({0}*)buffer.Header.ToPointer();", item.PropertyType))); // array[0] = ...;; ifStatement2.TrueStatements.Add(new CodeSnippetStatement(string.Format(" // TODO: set array's values: array[0] = ...;"))); // } ifStatement2.TrueStatements.Add(new CodeSnippetStatement(" }// end of unsafe")); ifStatement2.TrueStatements.Add(new CodeSnippetStatement(string.Format(" {0} = buffer.GetBufferPtr() as PropertyBufferPtr;", item.BufferPtrName))); ifStatement2.TrueStatements.Add(new CodeSnippetStatement(" }// end of using")); ifStatement.TrueStatements.Add(new CodeMethodReturnStatement( new CodeVariableReferenceExpression(item.BufferPtrName))); } // throw new NotImplementedException(); { // This CodeThrowExceptionStatement throws a new System.Exception. var throwException = new CodeThrowExceptionStatement( // codeExpression parameter indicates the exception to throw. // You must use an object create expression to new an exception here. new CodeObjectCreateExpression( // createType parameter inidicates the type of object to create. new CodeTypeReference(typeof(System.ArgumentException)), // parameters parameter indicates the constructor parameters. new CodeExpression[] { new CodePrimitiveExpression(bufferName) })); method.Statements.Add(throwException); } }
public void CodeSnippets() { var snippetStmt = new CodeSnippetStatement("blah"); AssertEqual(snippetStmt, "blah"); var snippetExpr = new CodeSnippetExpression(" blah "); AssertEqual(snippetExpr, " blah "); var snippetCu = new CodeSnippetCompileUnit(); snippetCu.Value = GetEmptyProgramSource(); AssertEqual(snippetCu, GetEmptyProgramSource()); }
/// <summary> /// Adds the code to the method. /// </summary> /// <param name="member1">The member1</param> /// <param name="codeLine">The code line</param> /// <param name="isExpression">Is expression indicator. Default value = false.</param> public static void Method_AddCode(CodeMemberMethod member1, string codeLine, bool isExpression = false) { if (isExpression) { codeLine = codeLine.zSubStr_RemoveStrAtEnd(";"); // It will be added again var code2 = new CodeSnippetExpression(codeLine); member1.Statements.Add(code2); } else { var code1 = new CodeSnippetStatement(codeLine); member1.Statements.Add(code1); } }
private void GenerateSetPropertyMethod(CodeTypeDeclaration file, EAPClass classPom) { CodeMemberMethod method = new CodeMemberMethod(); method.Attributes = MemberAttributes.Public | MemberAttributes.Override; method.Name = "SetProperty"; method.ReturnType = new CodeTypeReference(typeof(void)); method.Parameters.Add(new CodeParameterDeclarationExpression("Property", "property")); List <CodeSnippetStatement> snipets = new List <CodeSnippetStatement>() { new CodeSnippetStatement("\t\t\t\tswitch(property.Id)"), new CodeSnippetStatement("\t\t\t\t{") }; foreach (EAPAttribute att in classPom.Attributes) { if (att.IsListOfReferences == true) { continue; } CodeSnippetStatement css = new CodeSnippetStatement("\t\t\t\t\tcase ModelCode." + att.Code + ":"); CodeSnippetStatement cssProp = new CodeSnippetStatement(); if (att.TypeCode != "" && att.TypeCode.Equals("Enum")) { cssProp = new CodeSnippetStatement("\t\t\t\t\t\t" + att.Name + " = (" + att.MeasurementType + ") property.AsEnum();"); } else if (att.IsReference == true || att.TypeCode.Equals("Class")) { cssProp = new CodeSnippetStatement("\t\t\t\t\t\t" + att.Name + " = property.AsReference();"); } else { cssProp = new CodeSnippetStatement("\t\t\t\t\t\t" + att.Name + " = property." + StringManipulationManager.GetAsMethod(att.MeasurementType)); } CodeSnippetStatement cssBreak = new CodeSnippetStatement("\t\t\t\t\t\tbreak;"); snipets.Add(css); snipets.Add(cssProp); snipets.Add(cssBreak); } CodeSnippetStatement cssDefault = new CodeSnippetStatement("\t\t\t\t\tdefault:"); CodeSnippetStatement cssBase = new CodeSnippetStatement("\t\t\t\t\t\tbase.SetProperty(property);"); CodeSnippetStatement cssBreakDefault = new CodeSnippetStatement("\t\t\t\t\t\tbreak;"); CodeSnippetStatement ccss = new CodeSnippetStatement("\t\t\t\t}"); snipets.Add(cssDefault); snipets.Add(cssBase); snipets.Add(cssBreakDefault); snipets.Add(ccss); foreach (var item in snipets) { method.Statements.Add(item); } file.Members.Add(method); }
public CodeStatement MakeStatement() { var impl = new CodeStatement[_switchStatements.Count + 2]; impl[0] = new CodeSnippetStatement("switch(" + _lexerStateVariable.VariableName + ".CurrentState) {"); for (var i = 0; i < _switchStatements.Count; ++i) { impl[i + 1] = _switchStatements[i]; } impl[_switchStatements.Count + 1] = new CodeSnippetStatement("}"); return(new CodeIterationStatement(new CodeSnippetStatement(), new CodeMethodInvokeExpression(_lexerStateVariable, "ContinueIteration"), new CodeSnippetStatement(), impl)); }
public void CreateCode(Dictionary <string, ExcelToCSharp> dicEc) { if (m_linkMethod != null) { string mainKey = dicEc[m_linkTableName].GetMainKey(); string content = m_linkMethodContent.Replace("{MainKey}", mainKey); CodeSnippetStatement state = new CodeSnippetStatement(content); m_linkMethod.Method.Statements.Add(state); methodList.Add(m_linkMethod); } Create(); }
/// <summary> /// Get属性 /// </summary> /// <param name="inName"></param> public void SetGetName(string inName = "", bool bKeyGet = false) { string s = inName == "" ? property.Name : inName; property.HasGet = true; if (bKeyGet == false) { property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "m_" + Assist.FirstLetterLower(s)))); } else { CodeSnippetStatement state = new CodeSnippetStatement(inName); property.GetStatements.Add(state); } }
private void GenerateRemoveReferencMethod(CodeTypeDeclaration file, EAPClass classPom) { CodeMemberMethod method = new CodeMemberMethod(); method.Attributes = MemberAttributes.Public | MemberAttributes.Override; method.Name = "RemoveReference"; method.ReturnType = new CodeTypeReference(typeof(void)); method.Parameters.Add(new CodeParameterDeclarationExpression("ModelCode", "referenceId")); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(long), "globalId")); CodeSnippetStatement switctS = new CodeSnippetStatement("\t\t\t\tswitch(referenceId)"); CodeSnippetStatement bracket = new CodeSnippetStatement("\t\t\t\t{"); method.Statements.Add(switctS); method.Statements.Add(bracket); foreach (EAPAttribute att in classPom.Attributes) { if (att.IsListOfReferences == true) { CodeSnippetStatement mc = new CodeSnippetStatement("\t\t\t\t\tcase ModelCode." + att.onSameConnectorPairAtt.Code + ":"); CodeSnippetStatement ifSt = new CodeSnippetStatement("\t\t\t\t\t\tif (" + att.Name + ".Contains(globalId))"); CodeSnippetStatement openBr = new CodeSnippetStatement("\t\t\t\t\t\t{"); CodeStatement trueStatement = new CodeSnippetStatement("\t\t\t\t\t\t\t" + att.Name + ".Remove(globalId);"); CodeSnippetStatement closeBrec = new CodeSnippetStatement("\t\t\t\t\t\t}"); CodeSnippetStatement elseSt = new CodeSnippetStatement("\t\t\t\t\t\telse"); CodeSnippetStatement openBrElse = new CodeSnippetStatement("\t\t\t\t\t\t{"); CodeStatement falseStatement = new CodeSnippetStatement("\t\t\t\t\t\t\tCommonTrace.WriteTrace(CommonTrace.TraceWarning, \"Entity(GID = 0x{ 0:x16}) doesn't contain reference 0x{1:x16}.\", this.GlobalId, globalId);"); CodeSnippetStatement closeBrecElse = new CodeSnippetStatement("\t\t\t\t\t\t}"); CodeSnippetStatement breakSnipet = new CodeSnippetStatement("\t\t\t\t\t\tbreak;"); method.Statements.Add(mc); method.Statements.Add(ifSt); method.Statements.Add(openBr); method.Statements.Add(trueStatement); method.Statements.Add(closeBrec); method.Statements.Add(elseSt); method.Statements.Add(openBrElse); method.Statements.Add(falseStatement); method.Statements.Add(closeBrecElse); method.Statements.Add(breakSnipet); } } CodeSnippetStatement defaultS = new CodeSnippetStatement("\t\t\t\t\tdefault:"); CodeSnippetStatement baseS = new CodeSnippetStatement("\t\t\t\t\t\t base.RemoveReference(referenceId, globalId);"); CodeSnippetStatement breakS = new CodeSnippetStatement("\t\t\t\t\t\tbreak;"); CodeSnippetStatement ccss = new CodeSnippetStatement("\t\t\t\t}"); method.Statements.Add(defaultS); method.Statements.Add(baseS); method.Statements.Add(breakS); method.Statements.Add(ccss); file.Members.Add(method); }
public override List <CodeMemberMethod> GenerateMethods(Activity activity, Dictionary <string, string> variables) { var activityMethods = base.GenerateMethods(activity, variables); var invocationCodeCollection = new CodeStatementCollection(); // Add the mapping invocationCodeCollection.AddRange(this.xslBuilder.Build(activity.InputBindings)); // Add the invocation new Timer (timerValue) var code = new CodeSnippetStatement("new Timer(" + activity.Parameters[0].Name + ");"); invocationCodeCollection.Add(code); activityMethods[0].Statements.AddRange(invocationCodeCollection); return(activityMethods); }
private CodeSnippetStatement GetStatementMethod(CodeFunction method, CodeMemberMethod method1, out bool shouldReturn) { shouldReturn = false; string text1; if (method.FunctionKind == vsCMFunction.vsCMFunctionFunction && method.Type.TypeKind != vsCMTypeRef.vsCMTypeRefVoid) { if (!this.IsSupported(method.Type)) { this.DisplayWarning(String.Format(Resource.MethodErrMsg1, method.Type.AsFullName, method.Name)); shouldReturn = true; return(null); } method1.ReturnType = new CodeTypeReference(method.Type.AsFullName); text1 = String.Format(" {0} ", statementReturn); } else { text1 = " "; } text1 += "castFormInstance." + method.Name + "("; bool flag1 = false; foreach (CodeParameter parameter1 in method.Parameters) { if (!this.IsSupported(parameter1.Type)) { this.DisplayWarning(String.Format(Resource.MethodErrMsg2, parameter1.Type.AsFullName, method.Name)); shouldReturn = true; return(null); } CodeParameterDeclarationExpression expression2 = new CodeParameterDeclarationExpression(parameter1.Type.AsFullName, parameter1.Name); method1.Parameters.Add(expression2); if (flag1) { text1 += ", "; } text1 += parameter1.Name; flag1 = true; } text1 = text1 + ")" + statementTerminator; CodeSnippetStatement methodStatement = new CodeSnippetStatement(text1); return(methodStatement); }
public static CodeCompileUnit CreateCompileUnit() { CodeCompileUnit cu = new CodeCompileUnit(); //<Snippet1> // Creates a code expression for a CodeExpressionStatement to contain. CodeExpression invokeExpression = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("Console"), "Write", new CodePrimitiveExpression("Example string")); // Creates a statement using a code expression. CodeExpressionStatement expressionStatement; expressionStatement = new CodeExpressionStatement(invokeExpression); // A C# code generator produces the following source code for the preceeding example code: // Console.Write( "Example string" ); //</Snippet1> //<Snippet2> // Creates a CodeLinePragma that references line 100 of the file "example.cs". CodeLinePragma pragma = new CodeLinePragma("example.cs", 100); //</Snippet2> //<Snippet9> // Creates a CodeSnippetExpression that represents a literal string that // can be used as an expression in a CodeDOM graph. CodeSnippetExpression literalExpression = new CodeSnippetExpression("Literal expression"); //</Snippet9> //<Snippet10> // Creates a statement using a literal string. CodeSnippetStatement literalStatement = new CodeSnippetStatement("Console.Write(\"Test literal statement output\")"); //</Snippet10> //<Snippet11> // Creates a type member using a literal string. CodeSnippetTypeMember literalMember = new CodeSnippetTypeMember("public static void TestMethod() {}"); //</Snippet11> return(cu); }
public void AddDesignTimeHelperStatement(CodeSnippetStatement statement) { if (_designTimeHelperMethod == null) { _designTimeHelperMethod = new CodeMemberMethod() { Name = DesignTimeHelperMethodName, Attributes = MemberAttributes.Private }; _designTimeHelperMethod.Statements.Add( new CodeSnippetStatement(BuildCodeString(cw => cw.WriteDisableUnusedFieldWarningPragma()))); _designTimeHelperMethod.Statements.Add( new CodeSnippetStatement(BuildCodeString(cw => cw.WriteRestoreUnusedFieldWarningPragma()))); GeneratedClass.Members.Insert(0, _designTimeHelperMethod); } _designTimeHelperMethod.Statements.Insert(_designTimeHelperMethod.Statements.Count - 1, statement); }
public void CodeSnippetStatementTest() { CodeSnippetStatement css = new CodeSnippetStatement(); statement = css; Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, "{0}", NewLine), Generate(), "#1"); css.Value = "class"; Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, "class{0}", NewLine), Generate(), "#2"); css.Value = null; Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, "{0}", NewLine), Generate(), "#3"); }
/// <summary> /// Write the State enum to the current state when OnEntry is called by the context. /// </summary> /// <param name="state"></param> /// <param name="onMethod"></param> /// <param name="onEntryExit"></param> private void writeStateEntryStateSetter(StateType state, CodeMemberMethod onMethod, string onEntryExit) { string o = GetStateHierarchicalName(state); string dType = Model.settings.@object[0] .@class; string dTypeInstance = Model.settings.@object[0] .instance; string enumTypeName = StateStore.EnumTypeName; string currentStateEnumPart = StateStore.GetStateEnumHierarchyString(state); string statePropSetterTest = ""; if (state.name != Model.state.name) // state not root state { statePropSetterTest = makeStatePropertySetterStatement(dType, dTypeInstance, enumTypeName, currentStateEnumPart); } //default if state is root if (state.name == StateStore.ParentStateName) { statePropSetterTest = makeStatePropertySetterStatement(dType, dTypeInstance, enumTypeName, StateStore.defaultEntryStateEnum); } if (onEntryExit == "OnEntry" // && state.name != Model.state.name ) { CodeSnippetStatement enumSetterState = new CodeSnippetStatement(statePropSetterTest); //todo add the snippet to the method onMethod.Statements.Add(enumSetterState); } }
public CodeStatementCollection Build(string packageName, IEnumerable <XNode> inputNodes) { this.tab = new Tab(); this.variableDecleration = new Dictionary <string, string>(); var newPackageName = FormatCorrectlyPackageName(packageName); var codeInStringList = this.Build(newPackageName, inputNodes, null); string codeinString = this.GenerateVariableDeclaration() + codeInStringList; // TODO : remove this ugly fix !!! codeinString = MyUglyModification(codeinString); var codeSnippet = new CodeSnippetStatement(codeinString); var codeStatements = new CodeStatementCollection(); codeStatements.Add(codeSnippet); return(codeStatements); }
private CodeTypeMember CreateVisitMethod(string methodName, Type parameterType) { // Declaring a ToString method var visitMethod = new CodeMemberMethod(); visitMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override; visitMethod.Name = methodName; visitMethod.Parameters.Add(new CodeParameterDeclarationExpression(parameterType, "node")); var baseVisitCall = new CodeSnippetStatement($" base.{methodName}(node);"); visitMethod.Statements.Add(baseVisitCall); var addFindingCall = new CodeSnippetStatement($" AddFinding(node, \"{methodName}: {parameterType.Name}\");"); visitMethod.Statements.Add(addFindingCall); return(visitMethod); }
protected virtual void GenerateSnippetStatement(CodeSnippetStatement e) => Output.WriteLine(e.Value);
private void ValidateSnippetStatement(CodeSnippetStatement e) { }
private void GenerateSnippetStatement(CodeSnippetStatement e) { Output.WriteLine(e.Value); }