public static IEnumerable<CodeCommentStatement> ConvertFirstStringToComments(List<Statement> statements) { var nothing = new CodeCommentStatement[0]; if (statements.Count == 0) return nothing; var suiteStmt = statements[0] as SuiteStatement; if (suiteStmt == null) return nothing; var expStm = suiteStmt.stmts[0] as ExpStatement; if (expStm == null) return nothing; var str = expStm.Expression as Str; if (str == null) return nothing; statements.RemoveAt(0); return str.s.Replace("\r\n", "\n").Split('\r', '\n').Select(line => new CodeCommentStatement(" " + line)); }
public void Visit(CodeCommentStatement o) { g.GenerateCommentStatement(o); }
public void Remove(CodeCommentStatement value) { }
public int IndexOf(CodeCommentStatement value) { }
private void ValidateCommentStatement(CodeCommentStatement e) { ValidateComment(e.Comment); }
} //Main() public static void SpitList (TextWriter w, string typeName, ICodeGenerator baseCompiler, string ns) { CodeCommentStatement c = new CodeCommentStatement (string.Format ("List of {0}", typeName)); baseCompiler.GenerateCodeFromStatement (c, w, null); CodeNamespace cnamespace = new CodeNamespace("Microsoft.Samples"); cnamespace.Imports.Add (new CodeNamespaceImport ("System") ); cnamespace.Imports.Add (new CodeNamespaceImport ("System.Collections") ); if (ns != null && ns != "") cnamespace.Imports.Add (new CodeNamespaceImport (ns) ); CodeTypeDeclaration co = new CodeTypeDeclaration (typeName +"List"); co.IsClass = true; cnamespace.Types.Add (co); co.BaseTypes.Add (typeof (CollectionBase) ); co.TypeAttributes = TypeAttributes.Public; //Generates: public <TYPE> this[int index] { // get { // return ((<TYPE>)List[index]); // } // set { // List[index] = value; // } // } CodeMemberProperty cp = new CodeMemberProperty (); cp.Name = "Item"; cp.Attributes = MemberAttributes.Public | MemberAttributes.Final ; cp.Type = new CodeTypeReference(typeName); cp.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference(typeof(int)), "index")); cp.GetStatements.Add (new CodeMethodReturnStatement (new CodeCastExpression (typeName, new CodeIndexerExpression (new CodeFieldReferenceExpression (new CodeThisReferenceExpression(), "List"), new CodeArgumentReferenceExpression ("index"))))); cp.SetStatements.Add (new CodeAssignStatement (new CodeIndexerExpression (new CodeFieldReferenceExpression (new CodeThisReferenceExpression(),"List"), new CodeArgumentReferenceExpression ("index")), new CodeArgumentReferenceExpression ("value"))); co.Members.Add (cp); //Gen: public int Add(<TYPE> value) { // return List.Add(value); // } CodeMemberMethod cm = new CodeMemberMethod (); cm.Name = "Add"; cm.ReturnType = new CodeTypeReference(typeof(int)); cm.Parameters.Add (new CodeParameterDeclarationExpression (typeName, "value")); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final ; cm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeFieldReferenceExpression (new CodeThisReferenceExpression(),"List"), "Add", new CodeArgumentReferenceExpression ("value")))); co.Members.Add (cm); //Gen: public void Insert(int index, <TYPE> value) // { // List.Insert(index, info); // } cm = new CodeMemberMethod (); cm.Name = "Insert"; cm.ReturnType = new CodeTypeReference(typeof(void)); cm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference(typeof(int)), "index")); cm.Parameters.Add (new CodeParameterDeclarationExpression (typeName, "value")); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final ; cm.Statements.Add (new CodeMethodInvokeExpression (new CodeFieldReferenceExpression (new CodeThisReferenceExpression(),"List"), "Insert", new CodeArgumentReferenceExpression ("index"), new CodeArgumentReferenceExpression ("value"))); co.Members.Add (cm); //Gen: public int IndexOf(<TYPE> value) // { // return List.IndexOf(value); // } cm = new CodeMemberMethod (); cm.Name = "IndexOf"; cm.ReturnType = new CodeTypeReference(typeof(int)); cm.Parameters.Add (new CodeParameterDeclarationExpression (typeName, "value")); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final ; cm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeFieldReferenceExpression (new CodeThisReferenceExpression(),"List"), "IndexOf", new CodeExpression [] {new CodeArgumentReferenceExpression ("value")}))); co.Members.Add (cm); //Gen: public bool Contains(<TYPE> value) // { // return List.Contains(value); // } cm = new CodeMemberMethod (); cm.Name = "Contains"; cm.ReturnType = new CodeTypeReference(typeof(bool)); cm.Parameters.Add (new CodeParameterDeclarationExpression (typeName, "value")); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final ; cm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeFieldReferenceExpression (new CodeThisReferenceExpression(),"List"), "Contains", new CodeExpression [] {new CodeArgumentReferenceExpression ("value")}))); co.Members.Add (cm); //Gen: public void Remove(<TYPE> value) // { // List.Remove(value); // } cm = new CodeMemberMethod (); cm.Name = "Remove"; cm.Parameters.Add (new CodeParameterDeclarationExpression (typeName, "value")); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final ; cm.Statements.Add (new CodeMethodInvokeExpression (new CodeFieldReferenceExpression (new CodeThisReferenceExpression(),"List"), "Remove", new CodeExpression [] {new CodeArgumentReferenceExpression ("value")})); co.Members.Add (cm); //Gen: public void CopyTo(<Type>[] array, int index) // { // List.CopyTo(array, index); // } cm = new CodeMemberMethod (); cm.Name = "CopyTo"; cm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference(typeName, 1), "array")); cm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference(typeof(int)), "index")); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final ; cm.Statements.Add (new CodeMethodInvokeExpression (new CodeFieldReferenceExpression (new CodeThisReferenceExpression(),"List"), "CopyTo", new CodeExpression [] {new CodeArgumentReferenceExpression ("array"), new CodeArgumentReferenceExpression ("index")})); co.Members.Add (cm); baseCompiler.GenerateCodeFromNamespace (cnamespace, w, null); } //SpitList()
private void AddPropertyJava(CodeTypeDeclaration ctd, CodeTypeReference ctrfield, CodeCommentStatement propertyComment, string mangledName, CodeFieldReferenceExpression fieldRef, bool isInterface) { var property = new CodeMemberMethod(); mangledName = ToLangCase(mangledName, true); property.Attributes = MemberAttributes.Public | MemberAttributes.Final; property.Name = "get" + mangledName; property.ReturnType = ctrfield; if (!isInterface) { property.Statements.Add(new CodeMethodReturnStatement(fieldRef)); } if (null != propertyComment) { property.Comments.Add(propertyComment); } // Add field property to class ctd.Members.Add(property); if (isInterface) { return; } property = new CodeMemberMethod(); property.Attributes = MemberAttributes.Public | MemberAttributes.Final; property.Name = "set" + mangledName; property.Parameters.Add(new CodeParameterDeclarationExpression(ctrfield, "value")); property.Statements.Add(new CodeAssignStatement(fieldRef, new CodePropertySetValueReferenceExpression())); if (null != propertyComment) { property.Comments.Add(propertyComment); } // Add field property to class ctd.Members.Add(property); }
private void GenerateCommentStatement(CodeCommentStatement e) { GenerateComment(e.Comment); }
private void GenerateParamCommentStatement(string name, CodeCommentStatement comment) { String commentLineStart = " * @param " + name + " "; Output.WriteLine(commentLineStart + comment.Comment.Text); }
/// <summary> /// Adds the setup of the proxy to the stub file, uses a dictionary to store it for use in load tests. /// </summary> /// <param name="proxyType">The type of the proxy.</param> /// <param name="contractType">The type that defines the contract.</param> /// <param name="proxyRef">A reference to the proxy variable.</param> private void GenerateStubProxySetup(Type proxyType, Type contractType, CodeFieldReferenceExpression proxyRef) { // code the static dictionary to store the proxy for each thread CodeMemberField proxyTable = new CodeMemberField(); proxyTable.Attributes = MemberAttributes.Private | MemberAttributes.Static; proxyTable.Type = GetReferencedTypeReference("Dictionary", typeof(int), contractType); proxyTable.Name = GenerateProxyVariableNamePrefix(contractType) + "ProxyTable"; proxyTable.InitExpression = new CodeObjectCreateExpression(proxyTable.Type); this.stubTestType.Members.Add(proxyTable); CodeFieldReferenceExpression proxyTableRef = new CodeFieldReferenceExpression(null, proxyTable.Name); // Need to cast the proxy reference to an ICommunicationObject to get the channel state CodeExpression channelRef = new CodeCastExpression(typeof(ICommunicationObject), proxyRef); // code the setup of the proxy by checking the static dictionary CodeMethodReferenceExpression enterMonitor = new CodeMethodReferenceExpression(GetReferencedTypeReferenceExpression(typeof(System.Threading.Monitor)), "Enter"); this.stubTestInitializer.Statements.Add(new CodeMethodInvokeExpression(enterMonitor, proxyTableRef)); CodeTryCatchFinallyStatement tryStatement = new CodeTryCatchFinallyStatement(); CodeFieldReferenceExpression currentThreadRef = new CodeFieldReferenceExpression(GetReferencedTypeReferenceExpression(typeof(System.Threading.Thread)), "CurrentThread"); CodeFieldReferenceExpression currentThreadIdRef = new CodeFieldReferenceExpression(currentThreadRef, "ManagedThreadId"); CodeMethodInvokeExpression invokeTryGetValue = new CodeMethodInvokeExpression(proxyTableRef, "TryGetValue", currentThreadIdRef, new CodeDirectionExpression(FieldDirection.Out, proxyRef)); tryStatement.TryStatements.Add(invokeTryGetValue); CodeExpression isProxyNull = new CodeBinaryOperatorExpression(proxyRef, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(null)); CodeExpression isProxyFaulted = new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(channelRef, "State"), CodeBinaryOperatorType.ValueEquality, new CodeFieldReferenceExpression(GetReferencedTypeReferenceExpression(typeof(CommunicationState)), "Faulted")); CodeExpression condition = new CodeBinaryOperatorExpression(isProxyNull, CodeBinaryOperatorType.BooleanOr, isProxyFaulted); CodeConditionStatement ifStatement = new CodeConditionStatement(); ifStatement.Condition = condition; CodeCommentStatement commentStatement = new CodeCommentStatement(Messages.UTGenerator_ProxyConstructionComment, false); ifStatement.TrueStatements.Add(commentStatement); if (proxyType == null) { // Get the proxy from the servicefactory ////System.ServiceModel.ChannelFactory<Contracts.IArithmetic> arithmeticFactory = new System.ServiceModel.ChannelFactory<Contracts.IArithmetic>(); ////arithmeticClient = arithmeticFactory.CreateChannel(); CodeTypeReference factoryTypeRef = GetReferencedTypeReference(typeof(ChannelFactory), contractType); CodeVariableDeclarationStatement factoryVariableDecl = new CodeVariableDeclarationStatement(factoryTypeRef, GenerateProxyVariableNamePrefix(contractType) + "Factory", new CodeObjectCreateExpression(factoryTypeRef)); ifStatement.TrueStatements.Add(factoryVariableDecl); ifStatement.TrueStatements.Add(new CodeAssignStatement(proxyRef, new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(null, factoryVariableDecl.Name), "CreateChannel"))); } else { // Just new the proxy ifStatement.TrueStatements.Add(new CodeAssignStatement(proxyRef, new CodeObjectCreateExpression(GetReferencedTypeReference(proxyType)))); } ifStatement.TrueStatements.Add(new CodeMethodInvokeExpression(channelRef, "Open")); CodeAssignStatement assignToTable = new CodeAssignStatement(); assignToTable.Left = new CodeArrayIndexerExpression(proxyTableRef, currentThreadIdRef); assignToTable.Right = proxyRef; ifStatement.TrueStatements.Add(assignToTable); tryStatement.TryStatements.Add(ifStatement); CodeMethodReferenceExpression exitMonitor = new CodeMethodReferenceExpression(GetReferencedTypeReferenceExpression(typeof(System.Threading.Monitor)), "Exit"); tryStatement.FinallyStatements.Add(new CodeMethodInvokeExpression(exitMonitor, proxyTableRef)); this.stubTestInitializer.Statements.Add(tryStatement); }
} //Main() public static void SpitList(TextWriter w, string typeName, ICodeGenerator baseCompiler, string ns) { CodeCommentStatement c = new CodeCommentStatement(string.Format("List of {0}", typeName)); baseCompiler.GenerateCodeFromStatement(c, w, null); CodeNamespace cnamespace = new CodeNamespace("Microsoft.Samples"); cnamespace.Imports.Add(new CodeNamespaceImport("System")); cnamespace.Imports.Add(new CodeNamespaceImport("System.Collections")); if (ns != null && ns != "") { cnamespace.Imports.Add(new CodeNamespaceImport(ns)); } CodeTypeDeclaration co = new CodeTypeDeclaration(typeName + "List"); co.IsClass = true; cnamespace.Types.Add(co); co.BaseTypes.Add(typeof(CollectionBase)); co.TypeAttributes = TypeAttributes.Public; //Generates: public <TYPE> this[int index] { // get { // return ((<TYPE>)List[index]); // } // set { // List[index] = value; // } // } CodeMemberProperty cp = new CodeMemberProperty(); cp.Name = "Item"; cp.Attributes = MemberAttributes.Public | MemberAttributes.Final; cp.Type = new CodeTypeReference(typeName); cp.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "index")); cp.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(typeName, new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "List"), new CodeArgumentReferenceExpression("index"))))); cp.SetStatements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "List"), new CodeArgumentReferenceExpression("index")), new CodeArgumentReferenceExpression("value"))); co.Members.Add(cp); //Gen: public int Add(<TYPE> value) { // return List.Add(value); // } CodeMemberMethod cm = new CodeMemberMethod(); cm.Name = "Add"; cm.ReturnType = new CodeTypeReference(typeof(int)); cm.Parameters.Add(new CodeParameterDeclarationExpression(typeName, "value")); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "List"), "Add", new CodeArgumentReferenceExpression("value")))); co.Members.Add(cm); //Gen: public void Insert(int index, <TYPE> value) // { // List.Insert(index, info); // } cm = new CodeMemberMethod(); cm.Name = "Insert"; cm.ReturnType = new CodeTypeReference(typeof(void)); cm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "index")); cm.Parameters.Add(new CodeParameterDeclarationExpression(typeName, "value")); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cm.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "List"), "Insert", new CodeArgumentReferenceExpression("index"), new CodeArgumentReferenceExpression("value"))); co.Members.Add(cm); //Gen: public int IndexOf(<TYPE> value) // { // return List.IndexOf(value); // } cm = new CodeMemberMethod(); cm.Name = "IndexOf"; cm.ReturnType = new CodeTypeReference(typeof(int)); cm.Parameters.Add(new CodeParameterDeclarationExpression(typeName, "value")); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "List"), "IndexOf", new CodeExpression [] { new CodeArgumentReferenceExpression("value") }))); co.Members.Add(cm); //Gen: public bool Contains(<TYPE> value) // { // return List.Contains(value); // } cm = new CodeMemberMethod(); cm.Name = "Contains"; cm.ReturnType = new CodeTypeReference(typeof(bool)); cm.Parameters.Add(new CodeParameterDeclarationExpression(typeName, "value")); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "List"), "Contains", new CodeExpression [] { new CodeArgumentReferenceExpression("value") }))); co.Members.Add(cm); //Gen: public void Remove(<TYPE> value) // { // List.Remove(value); // } cm = new CodeMemberMethod(); cm.Name = "Remove"; cm.Parameters.Add(new CodeParameterDeclarationExpression(typeName, "value")); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cm.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "List"), "Remove", new CodeExpression [] { new CodeArgumentReferenceExpression("value") })); co.Members.Add(cm); //Gen: public void CopyTo(<Type>[] array, int index) // { // List.CopyTo(array, index); // } cm = new CodeMemberMethod(); cm.Name = "CopyTo"; cm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeName, 1), "array")); cm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "index")); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cm.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "List"), "CopyTo", new CodeExpression [] { new CodeArgumentReferenceExpression("array"), new CodeArgumentReferenceExpression("index") })); co.Members.Add(cm); baseCompiler.GenerateCodeFromNamespace(cnamespace, w, null); } //SpitList()
private static CodeCompileUnit InternalCreate(Dictionary <string, ResourceData> resourceList, string baseName, string generatedCodeNamespace, string resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out string[] unmatchable) { Hashtable hashtable; if (baseName == null) { throw new ArgumentNullException("baseName"); } if (codeProvider == null) { throw new ArgumentNullException("codeProvider"); } ArrayList errors = new ArrayList(0); SortedList list2 = VerifyResourceNames(resourceList, codeProvider, errors, out hashtable); string str = baseName; if (!codeProvider.IsValidIdentifier(str)) { string str2 = VerifyResourceName(str, codeProvider); if (str2 != null) { str = str2; } } if (!codeProvider.IsValidIdentifier(str)) { throw new ArgumentException(Microsoft.Build.Tasks.SR.GetString("InvalidIdentifier", new object[] { str })); } if (!string.IsNullOrEmpty(generatedCodeNamespace) && !codeProvider.IsValidIdentifier(generatedCodeNamespace)) { string str3 = VerifyResourceName(generatedCodeNamespace, codeProvider, true); if (str3 != null) { generatedCodeNamespace = str3; } } CodeCompileUnit e = new CodeCompileUnit(); e.ReferencedAssemblies.Add("System.dll"); e.UserData.Add("AllowLateBound", false); e.UserData.Add("RequireVariableDeclaration", true); CodeNamespace namespace2 = new CodeNamespace(generatedCodeNamespace); namespace2.Imports.Add(new CodeNamespaceImport("System")); e.Namespaces.Add(namespace2); CodeTypeDeclaration declaration = new CodeTypeDeclaration(str); namespace2.Types.Add(declaration); AddGeneratedCodeAttributeforMember(declaration); TypeAttributes attributes = internalClass ? TypeAttributes.AnsiClass : TypeAttributes.Public; declaration.TypeAttributes = attributes; declaration.Comments.Add(new CodeCommentStatement("<summary>", true)); declaration.Comments.Add(new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ClassDocComment"), true)); CodeCommentStatement statement = new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ClassComments1"), true); declaration.Comments.Add(statement); statement = new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ClassComments3"), true); declaration.Comments.Add(statement); declaration.Comments.Add(new CodeCommentStatement("</summary>", true)); CodeTypeReference attributeType = new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute)) { Options = CodeTypeReferenceOptions.GlobalReference }; declaration.CustomAttributes.Add(new CodeAttributeDeclaration(attributeType)); CodeTypeReference reference2 = new CodeTypeReference(typeof(CompilerGeneratedAttribute)) { Options = CodeTypeReferenceOptions.GlobalReference }; declaration.CustomAttributes.Add(new CodeAttributeDeclaration(reference2)); bool useStatic = internalClass || codeProvider.Supports(GeneratorSupport.PublicStaticMembers); bool supportsTryCatch = codeProvider.Supports(GeneratorSupport.TryCatchStatements); EmitBasicClassMembers(declaration, generatedCodeNamespace, baseName, resourcesNamespace, internalClass, useStatic, supportsTryCatch); foreach (DictionaryEntry entry in list2) { string key = (string)entry.Key; string resourceName = (string)hashtable[key]; if (resourceName == null) { resourceName = key; } if (!DefineResourceFetchingProperty(key, resourceName, (ResourceData)entry.Value, declaration, internalClass, useStatic)) { errors.Add(entry.Key); } } unmatchable = (string[])errors.ToArray(typeof(string)); CodeGenerator.ValidateIdentifiers(e); return(e); }
private void CreateEntity(CodeNamespace ns, string fileName) { using (Stream stream = File.OpenRead(fileName)) using (var reader = new JsonTextReader(new StreamReader(stream))) { dynamic input = JObject.Load(reader); var mob = input["minecraft:entity"]; string description = mob.description.identifier; // Generate class for entity string typeName = CodeTypeName(description.Replace("minecraft:", "").Replace(".", "_")); var csClass = new CodeTypeDeclaration(typeName); csClass.Comments.Add(new CodeCommentStatement(description, true)); csClass.BaseTypes.Add(typeof(Entity)); ns.Types.Add(csClass); JObject identifier = mob.description; foreach (var jToken in identifier.Properties()) { Console.WriteLine(jToken); AutoPropertyFromJToken(jToken, csClass); } JObject components = mob.components; foreach (var pair in components) { string componentName = pair.Key; var comment = new CodeCommentStatement(componentName); csClass.Members[0].Comments.Add(comment); if (componentName.StartsWith("minecraft:behavior.")) { string name = CodeTypeName(componentName.Replace("minecraft:behavior.", "").Replace(".", "_")) + "Behavior"; if (!_declaredTypes.TryGetValue(name, out CodeTypeDeclaration csComponentClass)) { csComponentClass = new CodeTypeDeclaration(name); csComponentClass.BaseTypes.Add(typeof(BehaviorBase)); ns.Types.Add(csComponentClass); _declaredTypes.Add(name, csComponentClass); } foreach (JToken jToken in pair.Value) { AutoPropertyFromJToken(jToken, csComponentClass); } } else { string name = CodeTypeName(componentName.Replace("minecraft:", "").Replace(".", "_")) + "Component"; if (!_declaredTypes.TryGetValue(name, out CodeTypeDeclaration csComponentClass)) { csComponentClass = new CodeTypeDeclaration(name); csComponentClass.BaseTypes.Add("ComponentBase"); ns.Types.Add(csComponentClass); _declaredTypes.Add(name, csComponentClass); } foreach (JToken jToken in pair.Value) { AutoPropertyFromJToken(jToken, csComponentClass); } } } } }
static private void AddEvent(Type i, MethodInfo mi, CodeCommentStatement comment) { // public bool OnSomething() // { // foreach (IPlayerActions subscriber in m_playerActionsSubscriberList) // subscriber.OnSomething(); // } CodeMemberMethod cmm = new CodeMemberMethod(); if (comment != null) { cmm.Comments.Add(comment); } cmm.Name = mi.Name; cmm.Attributes = MemberAttributes.Public; ParameterInfo[] parameters = mi.GetParameters(); CodeExpression[] call_parameters = new CodeExpression[parameters.Length]; int index = 0; foreach (ParameterInfo pi in parameters) { CodeParameterDeclarationExpression cpde = new CodeParameterDeclarationExpression(); cpde.Name = pi.Name; cpde.Type = new CodeTypeReference(pi.ParameterType); cmm.Parameters.Add(cpde); call_parameters[index++] = new CodeSnippetExpression(pi.Name); } cmm.ReturnType = new CodeTypeReference(mi.ReturnType); // IEnumerator enumerator = list.GetEnumerator(); CodeAssignStatement cas = new CodeAssignStatement(); cas.Left = new CodeVariableReferenceExpression("IEnumerator e"); CodeVariableReferenceExpression cvre = new CodeVariableReferenceExpression(GetListName(i)); cas.Right = new CodeMethodInvokeExpression(cvre, "GetEnumerator"); cmm.Statements.Add(cas); // Generate a for loop CodeIterationStatement loop = new CodeIterationStatement( new CodeSnippetStatement(""), new CodeMethodInvokeExpression( new CodeVariableReferenceExpression("e"), "MoveNext"), new CodeSnippetStatement("")); // e.Cuurent as loop.Statements.Add(new CodeSnippetStatement(String.Format("{0} sink = e.Current as {0};", i.Name))); loop.Statements.Add(new CodeMethodInvokeExpression( new CodeVariableReferenceExpression("sink"), mi.Name, call_parameters)); cmm.Statements.Add(loop); m_switchboard.Members.Add(cmm); }
public TThis Comment(CodeCommentStatement commentStatment) { _wrappedType.Comments.Add(commentStatment); return(ThisConverter(this)); }
private void GenerateCodeFromCommentState(CodeCommentStatement e, TextWriter w, CodeGeneratorOptions o) { w.WriteLine("#" + e.Comment.Text); }
protected void GenerateStatement(CodeStatement s) { bool handled = false; #if NET_2_0 if (s.StartDirectives.Count > 0) { GenerateDirectives(s.StartDirectives); } #endif if (s.LinePragma != null) { GenerateLinePragmaStart(s.LinePragma); } CodeAssignStatement assign = s as CodeAssignStatement; if (assign != null) { GenerateAssignStatement(assign); handled = true; } CodeAttachEventStatement attach = s as CodeAttachEventStatement; if (attach != null) { GenerateAttachEventStatement(attach); handled = true; } CodeCommentStatement comment = s as CodeCommentStatement; if (comment != null) { GenerateCommentStatement(comment); handled = true; } CodeConditionStatement condition = s as CodeConditionStatement; if (condition != null) { GenerateConditionStatement(condition); handled = true; } CodeExpressionStatement expression = s as CodeExpressionStatement; if (expression != null) { GenerateExpressionStatement(expression); handled = true; } CodeGotoStatement gotostmt = s as CodeGotoStatement; if (gotostmt != null) { GenerateGotoStatement(gotostmt); handled = true; } CodeIterationStatement iteration = s as CodeIterationStatement; if (iteration != null) { GenerateIterationStatement(iteration); handled = true; } CodeLabeledStatement label = s as CodeLabeledStatement; if (label != null) { GenerateLabeledStatement(label); handled = true; } CodeMethodReturnStatement returnstmt = s as CodeMethodReturnStatement; if (returnstmt != null) { GenerateMethodReturnStatement(returnstmt); handled = true; } CodeRemoveEventStatement remove = s as CodeRemoveEventStatement; if (remove != null) { GenerateRemoveEventStatement(remove); handled = true; } 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 handled = true; } CodeThrowExceptionStatement exception = s as CodeThrowExceptionStatement; if (exception != null) { GenerateThrowExceptionStatement(exception); handled = true; } CodeTryCatchFinallyStatement trycatch = s as CodeTryCatchFinallyStatement; if (trycatch != null) { GenerateTryCatchFinallyStatement(trycatch); handled = true; } CodeVariableDeclarationStatement declaration = s as CodeVariableDeclarationStatement; if (declaration != null) { GenerateVariableDeclarationStatement(declaration); handled = true; } if (!handled) { throw new ArgumentException("Element type " + s + " is not supported."); } if (s.LinePragma != null) { GenerateLinePragmaEnd(s.LinePragma); } #if NET_2_0 if (s.EndDirectives.Count > 0) { GenerateDirectives(s.EndDirectives); } #endif }
/// <summary> /// Creates a class declaration /// </summary> /// <param name="schema">record schema</param> /// <param name="ns">namespace</param> /// <returns></returns> protected virtual CodeTypeDeclaration processRecord(Schema schema) { RecordSchema recordSchema = schema as RecordSchema; if (null == recordSchema) { throw new CodeGenException("Unable to cast schema into a record"); } // declare the class var ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(recordSchema.Name)); //@todo implments if (DoJava) { ctd.BaseTypes.Add(SystemObjectStr); ctd.BaseTypes.Add("SpecificRecord"); } else { ctd.BaseTypes.Add("ISpecificRecord"); } var interf = processRecordInterface(schema); ctd.BaseTypes.Add(interf.Name); ctd.Attributes = MemberAttributes.Public; ctd.IsClass = true; ctd.IsPartial = true; createSchemaField(schema, ctd, false, false); // declare Get() to be used by the Writer classes var cmmGet = new CodeMemberMethod(); cmmGet.Name = ToLangCase("Get", !DoJava); cmmGet.Attributes = MemberAttributes.Public; cmmGet.ReturnType = new CodeTypeReference(SystemObjectStr); cmmGet.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos")); StringBuilder getFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n"); // declare Put() to be used by the Reader classes var cmmPut = new CodeMemberMethod(); cmmPut.Name = ToLangCase("Put", !DoJava); cmmPut.Attributes = MemberAttributes.Public; cmmPut.ReturnType = new CodeTypeReference(typeof(void)); cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos")); cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(SystemObjectStr, "fieldValue")); var putFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n"); HashSet <CodeTypeReference> feildRefs = new HashSet <CodeTypeReference>(); foreach (Field field in recordSchema.Fields) { // Determine type of field bool nullibleEnum = false; string baseType = getType(field.Schema, false, ref nullibleEnum, false); var ctrfield = new CodeTypeReference(baseType); // Create field string privFieldName = string.Concat("_", field.Name); if (DoJava) { privFieldName = "m" + privFieldName; } var codeField = new CodeMemberField(ctrfield, privFieldName); codeField.Attributes = MemberAttributes.Private; // Process field documentation if it exist and add to the field CodeCommentStatement propertyComment = null; if (!string.IsNullOrEmpty(field.Documentation)) { propertyComment = createDocComment(field.Documentation); if (null != propertyComment) { codeField.Comments.Add(propertyComment); } } // Add field to class ctd.Members.Add(codeField); // Create reference to the field - this.fieldname var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), privFieldName); var mangledName = CodeGenUtil.Instance.Mangle(field.Name); // Create field property with get and set methods AddProperty(ctd, ctrfield, propertyComment, mangledName, fieldRef, false); string getsetName = mangledName; if (DoJava) { getsetName = privFieldName; } // add to Get() getFieldStmt.Append("\t\t\tcase "); getFieldStmt.Append(field.Pos); getFieldStmt.Append(": return this."); getFieldStmt.Append(getsetName); getFieldStmt.Append(";\n"); // add to Put() putFieldStmt.Append("\t\t\tcase "); putFieldStmt.Append(field.Pos); putFieldStmt.Append(": this."); putFieldStmt.Append(getsetName); feildRefs.Add(ctrfield); if (baseType.EndsWith("long")) { } var castType = baseType; if (DoJava) { castType = getType(field.Schema, true, ref nullibleEnum, false); } if (nullibleEnum) { putFieldStmt.Append(" = fieldValue == null ? ("); putFieldStmt.Append(baseType); putFieldStmt.Append(")null : ("); string type = baseType.Remove(0, 16); // remove System.Nullable< type = type.Remove(type.Length - 1); // remove > putFieldStmt.Append(type); putFieldStmt.Append(")fieldValue; break;\n"); } else { putFieldStmt.Append(" = ("); putFieldStmt.Append(castType); putFieldStmt.Append(")fieldValue; break;\n"); } } // end switch block for Get() getFieldStmt.Append( "\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Get()\");\n\t\t\t}"); var cseGet = new CodeSnippetExpression(getFieldStmt.ToString()); string cs = cseGet.Value; cmmGet.Statements.Add(cseGet); ctd.Members.Add(cmmGet); // end switch block for Put() putFieldStmt.Append( "\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Put()\");\n\t\t\t}"); var csePut = new CodeSnippetExpression(putFieldStmt.ToString()); cmmPut.Statements.Add(csePut); ctd.Members.Add(cmmPut); string nspace = recordSchema.Namespace; if (string.IsNullOrEmpty(nspace)) { throw new CodeGenException("Namespace required for record schema " + recordSchema.Name); } CodeNamespace codens = addNamespace(nspace); codens.Types.Add(ctd); foreach (CodeTypeReference reference in feildRefs) { //codens.Types.Add(reference); } return(ctd); }
public void Statements_AddMultiple_ReturnsExpected() { var catchClause = new CodeCatchClause(); CodeStatement statement1 = new CodeCommentStatement("Value1"); catchClause.Statements.Add(statement1); Assert.Equal(new CodeStatement[] { statement1 }, catchClause.Statements.Cast<CodeStatement>()); CodeStatement statement2 = new CodeCommentStatement("Value1"); catchClause.Statements.Add(statement2); Assert.Equal(new CodeStatement[] { statement1, statement2 }, catchClause.Statements.Cast<CodeStatement>()); }
// CodeCommentStatementCollection public void CodeCommentStatementCollectionExample() { //<Snippet1> //<Snippet2> // Creates an empty CodeCommentStatementCollection. CodeCommentStatementCollection collection = new CodeCommentStatementCollection(); //</Snippet2> //<Snippet3> // Adds a CodeCommentStatement to the collection. collection.Add(new CodeCommentStatement("Test comment")); //</Snippet3> //<Snippet4> // Adds an array of CodeCommentStatement objects to the collection. CodeCommentStatement[] comments = { new CodeCommentStatement("Test comment"), new CodeCommentStatement("Another test comment") }; collection.AddRange(comments); // Adds a collection of CodeCommentStatement objects to the collection. CodeCommentStatementCollection commentsCollection = new CodeCommentStatementCollection(); commentsCollection.Add(new CodeCommentStatement("Test comment")); commentsCollection.Add(new CodeCommentStatement("Another test comment")); collection.AddRange(commentsCollection); //</Snippet4> //<Snippet5> // Tests for the presence of a CodeCommentStatement in the // collection, and retrieves its index if it is found. CodeCommentStatement testComment = new CodeCommentStatement("Test comment"); int itemIndex = -1; if (collection.Contains(testComment)) { itemIndex = collection.IndexOf(testComment); } //</Snippet5> //<Snippet6> // Copies the contents of the collection, beginning at index 0, // to the specified CodeCommentStatement array. // 'comments' is a CodeCommentStatement array. collection.CopyTo(comments, 0); //</Snippet6> //<Snippet7> // Retrieves the count of the items in the collection. int collectionCount = collection.Count; //</Snippet7> //<Snippet8> // Inserts a CodeCommentStatement at index 0 of the collection. collection.Insert(0, new CodeCommentStatement("Test comment")); //</Snippet8> //<Snippet9> // Removes the specified CodeCommentStatement from the collection. CodeCommentStatement comment = new CodeCommentStatement("Test comment"); collection.Remove(comment); //</Snippet9> //<Snippet10> // Removes the CodeCommentStatement at index 0. collection.RemoveAt(0); //</Snippet10> //</Snippet1> }
/// <summary> /// Get return CodeCommentStatement comment /// </summary> /// <param name="text">Return text comment</param> /// <returns>returns return comment statement</returns> internal static CodeCommentStatement GetReturnComment(string text) { var comments = new CodeCommentStatement(string.Format("<returns>{0}</returns>", text), true); return(comments); }
protected virtual void GenerateCommentStatement(CodeCommentStatement e) { if (e.Comment == null) { throw new ArgumentException(SR.Format(SR.Argument_NullComment, nameof(e)), nameof(e)); } GenerateComment(e.Comment); }
/// <summary> /// Get param comment statement /// </summary> /// <param name="paramName">Param Name</param> /// <param name="text">param summary</param> /// <returns>CodeCommentStatement param</returns> internal static CodeCommentStatement GetParamComment(string paramName, string text) { var comments = new CodeCommentStatement(string.Format("<param name=\"{0}\">{1}</param>", paramName, text), true); return(comments); }
public bool Contains(CodeCommentStatement value) { }
// Generate code for comment statements. protected virtual void GenerateCommentStatement (CodeCommentStatement e) { GenerateComment(e.Comment); }
public void Insert(int index, CodeCommentStatement value) { }
private void CreateCommandClass(string className, Command command, List <Parameter> parameters) { Console.WriteLine($"Processing command class {command.Name} [{className}()]"); CreateCompileUnit(out CodeCompileUnit compileUnit, out CodeNamespace codeNamespace, _ezspCommandPackage); CodeTypeDeclaration protocolClass = new CodeTypeDeclaration(className) { IsClass = true, TypeAttributes = System.Reflection.TypeAttributes.Public }; AddNamespaceImport(codeNamespace, _serializerPackage); StringBuilder descriptionStringBuilder = new StringBuilder(); descriptionStringBuilder.AppendLine($"Class to implement the Ember EZSP command \" {command.Name} \"."); if (!string.IsNullOrEmpty(command.Description)) { OutputWithLineBreak(descriptionStringBuilder, "", command.Description); } descriptionStringBuilder.AppendLine(" This class provides methods for processing EZSP commands."); ICodeCommentEntity descriptionCodeCommentEntity = new CodeCommentEntity { Tag = CodeCommentTag.Summary, DocumentationText = descriptionStringBuilder.ToString() }; CodeCommentStatement descriptionCodeComment = CodeCommentHelper.BuildCodeCommentStatement(descriptionCodeCommentEntity, true); protocolClass.Comments.Add(descriptionCodeComment); if (className.EndsWith("Request")) { protocolClass.BaseTypes.Add("EzspFrameRequest"); } else { protocolClass.BaseTypes.Add("EzspFrameResponse"); } codeNamespace.Types.Add(protocolClass); CodeMemberField frameIdCodeMember = CreateCodeConstantMember("FRAME_ID", typeof(int), command.Id); protocolClass.Members.Add(frameIdCodeMember); CreateParameters(codeNamespace, protocolClass, parameters); CreateParameterSetters(parameters, codeNamespace, protocolClass); CreateParameterGetter(parameters, codeNamespace, protocolClass); if (className.EndsWith("Request")) { CreateRequestConstructor(protocolClass); CreateRequestSerializer(parameters, protocolClass); } else { CreateResponseAndHandlerConstructor(parameters, protocolClass); } CreateToStringOverride(className, parameters, protocolClass); GenerateCode(compileUnit, className, "Command/"); }
private static CodeCompileUnit InternalCreate(Dictionary <String, ResourceData> resourceList, String baseName, String generatedCodeNamespace, String resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out String[] unmatchable) { if (baseName == null) { throw new ArgumentNullException("baseName"); } if (codeProvider == null) { throw new ArgumentNullException("codeProvider"); } // Keep a list of errors describing known strings that couldn't be // fixed up (like "4"), as well as listing all duplicate resources that // were fixed up to the same name (like "A B" and "A-B" both going to // "A_B"). ArrayList errors = new ArrayList(0); // Verify the resource names are valid property names, and they don't // conflict. This includes checking for language-specific keywords, // translating spaces to underscores, etc. SortedList cleanedResourceList; Hashtable reverseFixupTable; cleanedResourceList = VerifyResourceNames(resourceList, codeProvider, errors, out reverseFixupTable); // Verify the class name is legal. String className = baseName; // Attempt to fix up class name, and throw an exception if it fails. if (!codeProvider.IsValidIdentifier(className)) { String fixedClassName = VerifyResourceName(className, codeProvider); if (fixedClassName != null) { className = fixedClassName; } } if (!codeProvider.IsValidIdentifier(className)) { throw new ArgumentException(SR.GetString(SR.InvalidIdentifier, className)); } // If we have a namespace, verify the namespace is legal, // attempting to fix it up if needed. if (!String.IsNullOrEmpty(generatedCodeNamespace)) { if (!codeProvider.IsValidIdentifier(generatedCodeNamespace)) { String fixedNamespace = VerifyResourceName(generatedCodeNamespace, codeProvider, true); if (fixedNamespace != null) { generatedCodeNamespace = fixedNamespace; } } // Note we cannot really ensure that the generated code namespace // is a valid identifier, as namespaces can have '.' and '::', but // identifiers cannot. } CodeCompileUnit ccu = new CodeCompileUnit(); ccu.ReferencedAssemblies.Add("System.dll"); ccu.UserData.Add("AllowLateBound", false); ccu.UserData.Add("RequireVariableDeclaration", true); CodeNamespace ns = new CodeNamespace(generatedCodeNamespace); ns.Imports.Add(new CodeNamespaceImport("System")); ccu.Namespaces.Add(ns); // Generate class CodeTypeDeclaration srClass = new CodeTypeDeclaration(className); ns.Types.Add(srClass); AddGeneratedCodeAttributeforMember(srClass); TypeAttributes ta = internalClass ? TypeAttributes.NotPublic : TypeAttributes.Public; //ta |= TypeAttributes.Sealed; srClass.TypeAttributes = ta; srClass.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true)); srClass.Comments.Add(new CodeCommentStatement(SR.GetString(SR.ClassDocComment), true)); CodeCommentStatement comment = new CodeCommentStatement(SR.GetString(SR.ClassComments1), true); srClass.Comments.Add(comment); comment = new CodeCommentStatement(SR.GetString(SR.ClassComments3), true); srClass.Comments.Add(comment); srClass.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true)); CodeTypeReference debuggerAttrib = new CodeTypeReference(typeof(System.Diagnostics.DebuggerNonUserCodeAttribute)); debuggerAttrib.Options = CodeTypeReferenceOptions.GlobalReference; srClass.CustomAttributes.Add(new CodeAttributeDeclaration(debuggerAttrib)); CodeTypeReference compilerGenedAttrib = new CodeTypeReference(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute)); compilerGenedAttrib.Options = CodeTypeReferenceOptions.GlobalReference; srClass.CustomAttributes.Add(new CodeAttributeDeclaration(compilerGenedAttrib)); // Figure out some basic restrictions to the code generation bool useStatic = internalClass || codeProvider.Supports(GeneratorSupport.PublicStaticMembers); bool supportsTryCatch = codeProvider.Supports(GeneratorSupport.TryCatchStatements); EmitBasicClassMembers(srClass, generatedCodeNamespace, baseName, resourcesNamespace, internalClass, useStatic, supportsTryCatch); // Now for each resource, add a property foreach (DictionaryEntry entry in cleanedResourceList) { String propertyName = (String)entry.Key; // The resourceName will be the original value, before fixups, // if any. String resourceName = (String)reverseFixupTable[propertyName]; if (resourceName == null) { resourceName = propertyName; } bool r = DefineResourceFetchingProperty(propertyName, resourceName, (ResourceData)entry.Value, srClass, internalClass, useStatic); if (!r) { errors.Add(entry.Key); } } unmatchable = (String[])errors.ToArray(typeof(String)); // Validate the generated class now CodeGenerator.ValidateIdentifiers(ccu); return(ccu); }
public void AddRange(CodeCommentStatement[] value) {}
protected virtual void GenerateCommentStatement(CodeCommentStatement statement) { GenerateComment(statement.Comment); }
public bool Contains(CodeCommentStatement value) {}
public int VisitComment(CodeCommentStatement codeCommentStatement) { return(0); }
public void CopyTo(CodeCommentStatement[] array, int index) {}
public override void GenerateMethods(IDLInterface idlIntf) { if (idlIntf.Methods != null) // If got methods { bAddNamespace = idlIntf.Methods.Count > 0; foreach (IDLMethod idlMethod in idlIntf.Methods) { // Structs for capturing input/output from method. Udbus.Parsing.CodeTypeDeferredStructHolder paramsHolder = new Udbus.Parsing.CodeTypeDeferredStructHolder(idlMethod.Name + "AsyncParams"); Udbus.Parsing.CodeTypeDeferredStructHolder resultHolder = new Udbus.Parsing.CodeTypeDeferredStructHolder(idlMethod.Name + "AsyncResult"); CodeConstructor constructorResults = new CodeConstructor(); CodeConstructor constructorParams = new CodeConstructor(); constructorResults.Attributes = constructorParams.Attributes = MemberAttributes.Public; // Create Call method. CodeMemberMethod methodCall = new CodeMemberMethod(); methodCall.Name = "Call" + idlMethod.Name; // Actual call to proxy arguments will be added to as we parse IDL arguments. CodeExpressionCollection callParameters = new CodeExpressionCollection(); CodeExpressionCollection callResultArgs = new CodeExpressionCollection(); CodeExpressionCollection interfaceCallArgs = new CodeExpressionCollection(); CodeArgumentReferenceExpression argrefCallData = new CodeArgumentReferenceExpression(dataName); // Event Args string eventName = idlMethod.Name + "EventArgs"; CodeTypeDeclaration typeEvent = new CodeTypeDeclaration(eventName); typeEvent.IsClass = true; typeEvent.TypeAttributes = TypeAttributes.Public; typeEvent.BaseTypes.Add(new CodeTypeReference(typeof(AsyncCompletedEventArgs))); CodeConstructor constructorEventArgs = new CodeConstructor(); eventsDeclarationHolder.Add(typeEvent); CodeExpressionCollection makeEventArgs = new CodeExpressionCollection(); // Event Raiser... string raiserName = "raiser" + idlMethod.Name; CodeTypeReference raiserRef = new CodeTypeReference("AsyncOperationEventRaiser", new CodeTypeReference(eventName)); CodeMemberField fieldRaiser = new CodeMemberField(raiserRef, raiserName); fieldRaiser.InitExpression = new CodeObjectCreateExpression(raiserRef); fieldRaiser.Attributes = MemberAttributes.Private; typeProxy.Members.Add(fieldRaiser); // Event raiser EventCompleted Property - unfortunately CodeMemberEvent is useless here since can't add custom add/remove. // So anything other than CSharp is now a bust. Brilliant. CodeSnippetTypeMember eventRaiser = new CodeSnippetTypeMember(); eventRaiser.Text = string.Format(@" public event System.EventHandler<{0}> {1}Completed {{ add {{ this.{2}.CompletedEvent += value; }} remove {{ this.{2}.CompletedEvent -= value; }} }} ", eventName, idlMethod.Name, raiserName ); // Adding text here. //CodeMemberEvent eventRaiser = new CodeMemberEvent(); //eventRaiser.Attributes = MemberAttributes.Public; //CodeParamDeclaredType declaredType = new CodeParamDeclaredType(typeEvent); //eventRaiser.Type = new CodeTypeReference(CodeBuilderCommon.EventHandlerType.Name, declaredType.CodeType); //eventRaiser.Name = idlMethod.Name + "Completed"; typeProxy.Members.Add(eventRaiser); // Async method. CodeMemberMethod methodAsync = new CodeMemberMethod(); methodAsync.Name = idlMethod.Name + "Async"; methodAsync.Attributes = MemberAttributes.Public; // Straight-forward interface method. CodeMemberMethod methodInterface = new CodeMemberMethod(); methodInterface.Name = idlMethod.Name; methodInterface.Attributes = MemberAttributes.Public; // CodeComment commentMethod = new CodeComment(idlMethod.Name); // method.Comments.Add(new CodeCommentStatement(idlMethod.Name)); CodeExpressionCollection asyncArgs = new CodeExpressionCollection(); Udbus.Parsing.BuildContext context = new Udbus.Parsing.BuildContext(contextDeclarationHolder); foreach (IDLMethodArgument idlMethodArg in idlMethod.Arguments) { CodeCommentStatement commentMethod = new CodeCommentStatement(string.Format("{0} {1} \"{2}\"", idlMethodArg.Direction, idlMethodArg.Name, idlMethodArg.Type)); methodAsync.Comments.Add(commentMethod); methodInterface.Comments.Add(commentMethod); // Parse the type string for the argument, creating required structs as we go, and returning a type for the argument. Udbus.Parsing.IDLArgumentTypeNameBuilderBase nameBuilder = new IDLMethodArgumentTypeNameBuilder(idlIntf, idlMethod); ParamCodeTypeFactory paramtypeHolder = new ParamCodeTypeFactory(CodeTypeFactory.Default, idlMethodArg.Direction == "out" ? FieldDirection.Out : FieldDirection.In); Udbus.Parsing.CodeBuilderHelper.BuildCodeParamType(paramtypeHolder, nameBuilder, idlMethodArg.Type, context); Udbus.Parsing.ICodeParamType paramtype = paramtypeHolder.paramtype; // Arguments. CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(paramtype.CodeType, idlMethodArg.Name); CodeVariableReferenceExpression varrefMethodArg = new CodeVariableReferenceExpression(idlMethodArg.Name); if (idlMethodArg.Direction == "out") // If out argument { // Add to interface parameters. interfaceCallArgs.Add(new CodeDirectionExpression(FieldDirection.Out, varrefMethodArg)); // Put into result holding struct... param.Direction = FieldDirection.Out; methodInterface.Parameters.Add(param); CodeTypeReference argType = CodeBuilderCommon.GetReadOnlyCodeReference(paramtypeHolder.paramtype.CodeType); CodeMemberField fieldResultArg = new CodeMemberField(argType, idlMethodArg.Name); fieldResultArg.Attributes = MemberAttributes.Public; resultHolder.CodeType.Members.Add(fieldResultArg); constructorResults.Parameters.Add(new CodeParameterDeclarationExpression(paramtype.CodeType, idlMethodArg.Name)); CodeFieldReferenceExpression thisArg = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), idlMethodArg.Name ); constructorResults.Statements.Add(new CodeAssignStatement(thisArg, new CodeArgumentReferenceExpression(idlMethodArg.Name))); // Add placeholder variables to call method. methodCall.Statements.Add(new CodeVariableDeclarationStatement(paramtype.CodeType, idlMethodArg.Name)); // Add appropriate parameter in actual call to interface. callParameters.Add(new CodeDirectionExpression(FieldDirection.Out, varrefMethodArg)); // Add appropriate parameter in call to result constructor. callResultArgs.Add(new CodeArgumentReferenceExpression(idlMethodArg.Name)); // Put into event args class... string fieldEventArgName = idlMethodArg.Name + "_"; CodeMemberField fieldEventArg = new CodeMemberField(paramtype.CodeType, fieldEventArgName); fieldEventArg.Attributes = MemberAttributes.Private; typeEvent.Members.Add(fieldEventArg); // Add argument property to EventArgs. CodeMemberProperty propEventArg = new CodeMemberProperty(); propEventArg.Attributes = MemberAttributes.Public | MemberAttributes.Final; propEventArg.Name = idlMethodArg.Name; propEventArg.HasGet = true; propEventArg.Type = paramtype.CodeType; propEventArg.GetStatements.Add(new CodeMethodInvokeExpression(null, "RaiseExceptionIfNecessary")); propEventArg.GetStatements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), fieldEventArgName))); typeEvent.Members.Add(propEventArg); // Add constructor parameter and statement to EventArgs. constructorEventArgs.Parameters.Add(new CodeParameterDeclarationExpression(paramtype.CodeType, idlMethodArg.Name)); constructorEventArgs.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldEventArgName), new CodeArgumentReferenceExpression(idlMethodArg.Name) )); // Add as parameter in call to EventArgs constructor. makeEventArgs.Add(new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression(resultName), idlMethodArg.Name)); } // Ends if out argument else // Else in argument { // Add to interface parameters. interfaceCallArgs.Add(varrefMethodArg); // Put into parameter holding struct. CodeMemberField fieldArg = new CodeMemberField(CodeBuilderCommon.GetReadOnlyCodeReference(paramtype.CodeType), idlMethodArg.Name); fieldArg.Attributes = MemberAttributes.Public; paramsHolder.CodeType.Members.Add(fieldArg); constructorParams.Parameters.Add(new CodeParameterDeclarationExpression(paramtype.CodeType, idlMethodArg.Name)); CodeFieldReferenceExpression thisArg = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), idlMethodArg.Name ); constructorParams.Statements.Add(new CodeAssignStatement(thisArg, new CodeArgumentReferenceExpression(idlMethodArg.Name))); // Add appropriate parameter in actual call to interface. callParameters.Add(new CodeFieldReferenceExpression(argrefCallData, idlMethodArg.Name)); // Add appropriate parameter to async method parameters constructor call. asyncArgs.Add(new CodeArgumentReferenceExpression(idlMethodArg.Name)); // Add parameter to async method. methodAsync.Parameters.Add(param); // Add parameter to interface method. methodInterface.Parameters.Add(param); } // Ends else in argument } // Ends loop over method arguments methodAsync.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState")); // Add method body, then sort out arguments code... CodeFieldReferenceExpression thisRaiser = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), raiserName ); CodeTypeReference typerefResult = null; if (idlMethod.Return != null) // If method has return type { // Add result to Result type. // TODO replace typeof(string) with actual return type. typerefResult = new CodeTypeReference("???"); } CodeTypeReference typerefResults = null; CodeTypeReference typerefParams = null; CodeExpression exprAsyncParamValue = null; string asyncMethodName = "AsyncFuncImpl"; // Default is assuming that function returns something. if (paramsHolder.QuType()) // If got params type { typerefParams = new CodeTypeReference(paramsHolder.CodeType.Name); // Add proxy field to params struct. CodeMemberField memberParamsProxy = new CodeMemberField(new CodeTypeReference("readonly " + genInterfaceName), proxyName); memberParamsProxy.Attributes = MemberAttributes.Public; paramsHolder.CodeType.Members.Insert(0, memberParamsProxy); // TODO: Going to need a using or a fully qualified name. // Add initialisation to constructor constructorParams.Parameters.Insert(0, paramProxy); // Constructor will take proxy as first argument. constructorParams.Statements.Insert(0, assignProxy); paramsHolder.CodeType.TypeAttributes = TypeAttributes.NestedPrivate; paramsHolder.CodeType.IsStruct = true; constructorParams.Attributes = MemberAttributes.Public; paramsHolder.CodeType.Members.Add(constructorParams); typeProxy.Members.Add(paramsHolder.CodeType); asyncArgs.Insert(0, thisProxyFieldRef); exprAsyncParamValue = new CodeObjectCreateExpression(typerefParams, asyncArgs.Cast <CodeExpression>().ToArray()); } // Ends if got params type if (resultHolder.QuType()) // If got results type { typerefResults = new CodeTypeReference(resultHolder.CodeType.Name); methodCall.ReturnType = typerefResults; // Setup call method parameters. if (idlMethod.Return != null) { // Add result field to EventArgs. CodeMemberField fieldResult = new CodeMemberField(typerefResult, resultName); fieldResult.Attributes = MemberAttributes.Private; typeEvent.Members.Insert(0, fieldResult); // Add result property to EventArgs. CodeMemberProperty propResult = new CodeMemberProperty(); propResult.Attributes = MemberAttributes.Public; propResult.Name = resultName; propResult.HasGet = true; propResult.Type = typerefResult; propResult.GetStatements.Add(new CodeMethodInvokeExpression(null, "RaiseExceptionIfNecessary")); propResult.GetStatements.Add(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), resultName)); typeEvent.Members.Add(propResult); // Add suitable parameter as first EventArgs constructor argument. constructorEventArgs.Parameters.Insert(0, new CodeParameterDeclarationExpression(typerefResult, resultName)); // Add statement to initialise result member. CodeFieldReferenceExpression thisArg = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), resultName ); // Include result in parameters to EventArgs in MakeEventArgs statements. makeEventArgs.Insert(0, new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), resultName)); // Add result to Result type. CodeTypeReference typerefReadOnlyResult = CodeBuilderCommon.GetReadOnlyCodeReference(typerefResult); CodeMemberField fieldReadOnlyResult = new CodeMemberField(typerefReadOnlyResult, resultName); fieldResult.Attributes = MemberAttributes.Public; resultHolder.CodeType.Members.Insert(0, fieldReadOnlyResult); // Add suitable parameter as first constructor argument. constructorResults.Parameters.Insert(0, new CodeParameterDeclarationExpression(typerefResult, resultName)); // Add statement to initialise result member. constructorResults.Statements.Insert(0, new CodeAssignStatement(thisArg, new CodeArgumentReferenceExpression(resultName))); } // End if there is a return statement resultHolder.CodeType.TypeAttributes = TypeAttributes.NestedPrivate; resultHolder.CodeType.IsStruct = true; resultHolder.CodeType.Members.Add(constructorResults); typeProxy.Members.Add(resultHolder.CodeType); } // Ends if got results type else // Else no results type { // Absolutely no results (including out parameters) means it's an Action. asyncMethodName = "AsyncActionImpl"; } // Ends else no results type // Time to bite the bullet. CodeTypeReference typerefEvent = new CodeTypeReference(typeEvent.Name); CodeMemberMethod methodMakeEventArgs = new CodeMemberMethod(); methodMakeEventArgs.Name = "Make" + idlMethod.Name + "AsyncEventArgs"; // Add missing parameters to EventArgs... constructorEventArgs.Parameters.Add(CodeBuilderCommon.paramdeclException); constructorEventArgs.Parameters.Add(CodeBuilderCommon.paramdeclCancelled); constructorEventArgs.Parameters.Add(CodeBuilderCommon.paramdeclUserState); // Pass through to base class. constructorEventArgs.BaseConstructorArgs.Add(CodeBuilderCommon.argrefException); constructorEventArgs.BaseConstructorArgs.Add(CodeBuilderCommon.argrefCancelled); constructorEventArgs.BaseConstructorArgs.Add(CodeBuilderCommon.argrefUserState); // Add MakeEventArgs method... // Create MakeEventArgs method. methodMakeEventArgs.Attributes = MemberAttributes.Private | MemberAttributes.Static; if (typerefParams != null) // If got params type { methodMakeEventArgs.Parameters.Add(new CodeParameterDeclarationExpression(typerefParams, dataName)); } else // Else no params type { // The interface will be passed as the first parameter. methodMakeEventArgs.Parameters.Add(paramProxy); } // Ends else no params type if (typerefResults != null) // If got results type { methodMakeEventArgs.Parameters.Add(new CodeParameterDeclarationExpression(typerefResults, resultName)); } methodMakeEventArgs.Parameters.Add(CodeBuilderCommon.paramdeclException); methodMakeEventArgs.Parameters.Add(CodeBuilderCommon.paramdeclCancelled); methodMakeEventArgs.Parameters.Add(CodeBuilderCommon.paramdeclUserState); makeEventArgs.Add(CodeBuilderCommon.argrefException); makeEventArgs.Add(CodeBuilderCommon.argrefCancelled); makeEventArgs.Add(CodeBuilderCommon.argrefUserState); methodMakeEventArgs.Statements.Add(new CodeMethodReturnStatement( new CodeObjectCreateExpression( typerefEvent, makeEventArgs.Cast <CodeExpression>().ToArray() ) )); methodMakeEventArgs.ReturnType = typerefEvent; typeProxy.Members.Add(methodMakeEventArgs); // Setup call method parameters. methodCall.Attributes = MemberAttributes.Private | MemberAttributes.Static; CodeExpression exprProxyRef; //methodCall.ReturnType = new CodeTypeReference(resultHolder.CodeType.Name); if (typerefParams != null) // If passing parameters { methodCall.Parameters.Add(new CodeParameterDeclarationExpression(typerefParams, dataName)); exprProxyRef = new CodeFieldReferenceExpression(argrefCallData, proxyName); } // Ends if passing parameters else // Else just passing proxy { methodCall.Parameters.Add(new CodeParameterDeclarationExpression(genInterfaceName, proxyName)); exprProxyRef = new CodeArgumentReferenceExpression(proxyName); } // Ends else just passing proxy // Add call method body... // Invocation to proxy. CodeMethodReferenceExpression methodProxy = new CodeMethodReferenceExpression(exprProxyRef, idlMethod.Name); CodeMethodInvokeExpression invokeProxy = new CodeMethodInvokeExpression(methodProxy, callParameters.Cast <CodeExpression>().ToArray()); if (idlMethod.Return != null) // If got return type { // TODO - return values. // Add invocation of actual interface method and store result. CodeVariableDeclarationStatement exprResult = new CodeVariableDeclarationStatement(typerefResult, resultName, invokeProxy); methodCall.Statements.Add(exprResult); // Initialise result parameter in Result struct. callResultArgs.Insert(0, new CodeArgumentReferenceExpression(resultName)); } // Ends if got return type else // Else no return type { // Add invocation of actual interface method and ignore result. methodCall.Statements.Add(invokeProxy); } // Ends else no return type if (typerefResults != null) // If got result type { // Create Call return statement. CodeMethodReturnStatement retCall = new CodeMethodReturnStatement( new CodeObjectCreateExpression(typerefResults, callResultArgs.Cast <CodeExpression>().ToArray()) ); methodCall.Statements.Add(retCall); } // Ends if got result type // Add call method to type. typeProxy.Members.Add(methodCall); // Add async method implementation... if (exprAsyncParamValue == null) // If no params { // Just pass the proxy. exprAsyncParamValue = thisProxyFieldRef; } // Ends if no params methodAsync.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(thisRaiser, asyncMethodName) , new CodeArgumentReferenceExpression("userState") , exprAsyncParamValue , new CodeMethodReferenceExpression(null, methodCall.Name) , new CodeMethodReferenceExpression(null, methodMakeEventArgs.Name) )); methodInterface.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(thisProxyFieldRef, idlMethod.Name) , interfaceCallArgs.Cast <CodeExpression>().ToArray() )); // Finish up. typeEvent.Members.Add(constructorEventArgs); constructorEventArgs.Attributes = MemberAttributes.Public; ns.Types.Add(typeEvent); typeProxy.Members.Add(methodAsync); typeProxy.Members.Add(methodInterface); } // Ends loop over methods } // Ends if got methods }
public int IndexOf(CodeCommentStatement value) {}
protected override CodeTypeDeclaration processRecord(Schema schema) { RecordSchema recordSchema = schema as RecordSchema; if (null == recordSchema) { throw new CodeGenException("Unable to cast schema into a record"); } bool isError = recordSchema.Tag == Schema.Type.Error; // declare the class var ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(recordSchema.Name)); ctd.BaseTypes.Add(isError ? "SpecificException" : "ISpecificRecord"); ctd.Attributes = MemberAttributes.Public; ctd.IsClass = true; ctd.IsPartial = true; createSchemaField(schema, ctd, isError); // declare Get() to be used by the Writer classes var cmmGet = new CodeMemberMethod(); cmmGet.Name = "Get"; cmmGet.Attributes = MemberAttributes.Public; cmmGet.ReturnType = new CodeTypeReference("System.Object"); cmmGet.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos")); StringBuilder getFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n"); // declare Put() to be used by the Reader classes var cmmPut = new CodeMemberMethod(); cmmPut.Name = "Put"; cmmPut.Attributes = MemberAttributes.Public; cmmPut.ReturnType = new CodeTypeReference(typeof(void)); cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos")); cmmPut.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "fieldValue")); var putFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n"); if (isError) { cmmGet.Attributes |= MemberAttributes.Override; cmmPut.Attributes |= MemberAttributes.Override; } foreach (Field field in recordSchema.Fields) { // Determine type of field bool nullibleEnum = false; string baseType = getType(field.Schema, false, ref nullibleEnum); var ctrfield = new CodeTypeReference(baseType); // Create field string privFieldName = string.Concat("_", field.Name); var codeField = new CodeMemberField(ctrfield, privFieldName); codeField.Attributes = MemberAttributes.Private; // Process field documentation if it exist and add to the field CodeCommentStatement propertyComment = null; if (!string.IsNullOrEmpty(field.Documentation)) { propertyComment = createDocComment(field.Documentation); if (null != propertyComment) { codeField.Comments.Add(propertyComment); } } // Add field to class ctd.Members.Add(codeField); // Create reference to the field - this.fieldname var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), privFieldName); var mangledName = CodeGenUtil.Instance.Mangle(field.Name); // Create field property with get and set methods var property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public | MemberAttributes.Final; property.Name = mangledName.FirstCharToUpper(); property.Type = ctrfield; property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef)); property.SetStatements.Add(new CodeAssignStatement(fieldRef, new CodePropertySetValueReferenceExpression())); if (null != propertyComment) { property.Comments.Add(propertyComment); } // Add field property to class ctd.Members.Add(property); // add to Get() getFieldStmt.Append("\t\t\tcase "); getFieldStmt.Append(field.Pos); getFieldStmt.Append(": return this."); getFieldStmt.Append(privFieldName); getFieldStmt.Append(";\n"); // add to Put() putFieldStmt.Append("\t\t\tcase "); putFieldStmt.Append(field.Pos); putFieldStmt.Append(": this."); putFieldStmt.Append(privFieldName); if (nullibleEnum) { putFieldStmt.Append(" = fieldValue == null ? ("); putFieldStmt.Append(baseType); putFieldStmt.Append(")null : ("); string type = baseType.Remove(0, 16); // remove System.Nullable< type = type.Remove(type.Length - 1); // remove > putFieldStmt.Append(type); putFieldStmt.Append(")fieldValue; break;\n"); } else { putFieldStmt.Append(" = ("); putFieldStmt.Append(baseType); putFieldStmt.Append(")fieldValue; break;\n"); } } // end switch block for Get() getFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Get()\");\n\t\t\t}"); var cseGet = new CodeSnippetExpression(getFieldStmt.ToString()); cmmGet.Statements.Add(cseGet); ctd.Members.Add(cmmGet); // end switch block for Put() putFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Put()\");\n\t\t\t}"); var csePut = new CodeSnippetExpression(putFieldStmt.ToString()); cmmPut.Statements.Add(csePut); ctd.Members.Add(cmmPut); string nspace = recordSchema.Namespace; if (string.IsNullOrEmpty(nspace)) { throw new CodeGenException("Namespace required for record schema " + recordSchema.Name); } CodeNamespace codens = addNamespace(nspace); codens.Types.Add(ctd); return(ctd); }
public void Insert(int index, CodeCommentStatement value) {}
private void AddProperty(CodeTypeDeclaration ctd, CodeTypeReference ctrfield, CodeCommentStatement propertyComment, string mangledName, CodeFieldReferenceExpression fieldRef, bool isInterface) { if (DoJava) { AddPropertyJava(ctd, ctrfield, propertyComment, mangledName, fieldRef, isInterface); return; } var property = new CodeMemberProperty(); if (!isInterface) { property.Attributes = MemberAttributes.Public | MemberAttributes.Final; } property.Name = mangledName; property.Type = ctrfield; property.HasGet = true; if (isInterface) { property.HasSet = false; } else { property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef)); property.SetStatements.Add(new CodeAssignStatement(fieldRef, new CodePropertySetValueReferenceExpression())); } if (null != propertyComment) { property.Comments.Add(propertyComment); } // Add field property to class ctd.Members.Add(property); }
public void Remove(CodeCommentStatement value) {}
private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, string nameSpace, string baseName, string resourcesNamespace, bool internalClass, bool useStatic, bool supportsTryCatch) { string str; if (resourcesNamespace != null) { if (resourcesNamespace.Length > 0) { str = resourcesNamespace + '.' + baseName; } else { str = baseName; } } else if ((nameSpace != null) && (nameSpace.Length > 0)) { str = nameSpace + '.' + baseName; } else { str = baseName; } CodeCommentStatement statement = new CodeCommentStatement(System.Design.SR.GetString("ClassComments1")); srClass.Comments.Add(statement); statement = new CodeCommentStatement(System.Design.SR.GetString("ClassComments2")); srClass.Comments.Add(statement); statement = new CodeCommentStatement(System.Design.SR.GetString("ClassComments3")); srClass.Comments.Add(statement); statement = new CodeCommentStatement(System.Design.SR.GetString("ClassComments4")); srClass.Comments.Add(statement); CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(SuppressMessageAttribute))) { AttributeType = { Options = CodeTypeReferenceOptions.GlobalReference } }; declaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("Microsoft.Performance"))); declaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("CA1811:AvoidUncalledPrivateCode"))); CodeConstructor constructor = new CodeConstructor(); constructor.CustomAttributes.Add(declaration); if (useStatic || internalClass) { constructor.Attributes = MemberAttributes.FamilyAndAssembly; } else { constructor.Attributes = MemberAttributes.Public; } srClass.Members.Add(constructor); CodeTypeReference type = new CodeTypeReference(typeof(ResourceManager), CodeTypeReferenceOptions.GlobalReference); CodeMemberField field = new CodeMemberField(type, "resourceMan") { Attributes = MemberAttributes.Private }; if (useStatic) { field.Attributes |= MemberAttributes.Static; } srClass.Members.Add(field); CodeTypeReference reference2 = new CodeTypeReference(typeof(CultureInfo), CodeTypeReferenceOptions.GlobalReference); field = new CodeMemberField(reference2, "resourceCulture") { Attributes = MemberAttributes.Private }; if (useStatic) { field.Attributes |= MemberAttributes.Static; } srClass.Members.Add(field); CodeMemberProperty property = new CodeMemberProperty(); srClass.Members.Add(property); property.Name = "ResourceManager"; property.HasGet = true; property.HasSet = false; property.Type = type; if (internalClass) { property.Attributes = MemberAttributes.Assembly; } else { property.Attributes = MemberAttributes.Public; } if (useStatic) { property.Attributes |= MemberAttributes.Static; } CodeTypeReference reference3 = new CodeTypeReference(typeof(EditorBrowsableState)) { Options = CodeTypeReferenceOptions.GlobalReference }; CodeAttributeArgument argument = new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(reference3), "Advanced")); CodeAttributeDeclaration declaration2 = new CodeAttributeDeclaration("System.ComponentModel.EditorBrowsableAttribute", new CodeAttributeArgument[] { argument }) { AttributeType = { Options = CodeTypeReferenceOptions.GlobalReference } }; property.CustomAttributes.Add(declaration2); CodeMemberProperty property2 = new CodeMemberProperty(); srClass.Members.Add(property2); property2.Name = "Culture"; property2.HasGet = true; property2.HasSet = true; property2.Type = reference2; if (internalClass) { property2.Attributes = MemberAttributes.Assembly; } else { property2.Attributes = MemberAttributes.Public; } if (useStatic) { property2.Attributes |= MemberAttributes.Static; } property2.CustomAttributes.Add(declaration2); CodeFieldReferenceExpression left = new CodeFieldReferenceExpression(null, "resourceMan"); CodeMethodReferenceExpression method = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(object)), "ReferenceEquals"); CodeMethodInvokeExpression condition = new CodeMethodInvokeExpression(method, new CodeExpression[] { left, new CodePrimitiveExpression(null) }); CodePropertyReferenceExpression expression4 = new CodePropertyReferenceExpression(new CodeTypeOfExpression(new CodeTypeReference(srClass.Name)), "Assembly"); CodeObjectCreateExpression initExpression = new CodeObjectCreateExpression(type, new CodeExpression[] { new CodePrimitiveExpression(str), expression4 }); CodeStatement[] trueStatements = new CodeStatement[] { new CodeVariableDeclarationStatement(type, "temp", initExpression), new CodeAssignStatement(left, new CodeVariableReferenceExpression("temp")) }; property.GetStatements.Add(new CodeConditionStatement(condition, trueStatements)); property.GetStatements.Add(new CodeMethodReturnStatement(left)); property.Comments.Add(new CodeCommentStatement("<summary>", true)); property.Comments.Add(new CodeCommentStatement(System.Design.SR.GetString("ResMgrPropertyComment"), true)); property.Comments.Add(new CodeCommentStatement("</summary>", true)); CodeFieldReferenceExpression expression = new CodeFieldReferenceExpression(null, "resourceCulture"); property2.GetStatements.Add(new CodeMethodReturnStatement(expression)); CodePropertySetValueReferenceExpression right = new CodePropertySetValueReferenceExpression(); property2.SetStatements.Add(new CodeAssignStatement(expression, right)); property2.Comments.Add(new CodeCommentStatement("<summary>", true)); property2.Comments.Add(new CodeCommentStatement(System.Design.SR.GetString("CulturePropertyComment1"), true)); property2.Comments.Add(new CodeCommentStatement(System.Design.SR.GetString("CulturePropertyComment2"), true)); property2.Comments.Add(new CodeCommentStatement("</summary>", true)); }
public CodeCommentStatementCollection(CodeCommentStatement[] value) {}
public static CodeCompileUnit TestSimpleClassCompileUnit() { CodeCommentStatement docComment = new CodeCommentStatement("this is a doc comment", true); CodeCommentStatement comment = new CodeCommentStatement("this is a comment", false); CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace("Test.Namespace"); CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration("TestClass") { IsClass = true }; classDeclaration.TypeAttributes = (classDeclaration.TypeAttributes & ~TypeAttributes.VisibilityMask) | TypeAttributes.NotPublic; var field1 = new CodeMemberField(typeof(int), "count"); field1.Attributes = (field1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private; var field2 = new CodeMemberField(typeof(int), "increment"); field2.Attributes = (field2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.FamilyAndAssembly; classDeclaration.Members.Add(field1); classDeclaration.Members.Add(field2); var prop1 = new CodeMemberProperty() { Name = "Prop", HasGet = true, HasSet = true, Type = Types.Int, Attributes = MemberAttributes.Public | MemberAttributes.Final }; var prop2 = new CodeMemberProperty() { Name = "Prop2", HasSet = true, Type = Types.Int, Attributes = MemberAttributes.Public }; prop1.GetStatements.Add(new CodeMethodReturnStatement(FieldReferenceExpression.Default("increment"))); prop1.SetStatements.Add( new CodeAssignStatement(FieldReferenceExpression.Default("increment"), new CodePropertySetValueReferenceExpression())); prop2.SetStatements.Add(new CodeThrowExceptionStatement( new CodeObjectCreateExpression(new CodeTypeReference("Exception")))); classDeclaration.Members.Add(prop1); classDeclaration.Members.Add(prop2); var constructor = new CodeConstructor(); constructor.Attributes = (constructor.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Family; constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "count")); constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "increment")); constructor.Statements.Add(new CodeAssignStatement( FieldReferenceExpression.This("count"), new CodeArgumentReferenceExpression("count"))); constructor.Statements.Add(new CodeAssignStatement( FieldReferenceExpression.This("increment"), new CodeArgumentReferenceExpression("increment"))); classDeclaration.Members.Add(constructor); classDeclaration.Attributes = (classDeclaration.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.FamilyOrAssembly; var method = new CodeMemberMethod() { Name = "IncrementAndGet", ReturnType = Types.Int, Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Final }; method.Statements.Add(comment); method.Statements.Add( new CodeOperationAssignmentStatement( FieldReferenceExpression.Default("count"), CodeBinaryOperatorTypeMore.Add, FieldReferenceExpression.Default("increment")).AsAssignStatement()); method.Statements.Add(new CodeMethodReturnStatement(FieldReferenceExpression.Default("count"))); classDeclaration.Members.Add(method); codeNamespace.Types.Add(classDeclaration); compileUnit.Namespaces.Add(codeNamespace); codeNamespace.Comments.Add(comment); codeNamespace.Comments.Add(docComment); classDeclaration.Comments.Add(docComment); classDeclaration.Comments.Add(docComment); method.Comments.Add(comment); return(compileUnit); }
// Methods public int Add(CodeCommentStatement value) {}
internal CodeCommentStatement Comment(string comment) { var c = new CodeCommentStatement(comment); Scope.Add(c); return c; }
private static IList <CodeVariableDeclarationStatement> _TraceCommentStatement(CodeCommentStatement s, CodeStatement t, out bool found) { found = t == s; return(new CodeVariableDeclarationStatement[0]); }
// Methods public int Add(CodeCommentStatement value) { }
public override void Initialize(CodeFileGenerator fileGenerator) { base.Initialize(fileGenerator); //Throw in NUnit base.Namespace.Imports.Add(new CodeNamespaceImport("NUnit.Framework")); //Declare test suite class var testSuitDeclaration = new CodeTypeDeclaration { Name = _testSuiteData.Name + "TestSuite", IsClass = true, }; //Adding text fixture attribute testSuitDeclaration.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference("TestFixture"))); foreach (var scenario in _testSuiteData.Scenarios) { var isMultiinstance = _elementData.IsMultiInstance; var useParameter = !String.IsNullOrEmpty(scenario.CommandData.RelatedTypeName); const string controllerVariableName = "controller"; const string argumentVariableName = "argument"; const string senderVariableName = "sender"; //Setup scenario method var testMethod = new CodeMemberMethod { Name = scenario.Name.Replace(" ", "_"), Attributes = MemberAttributes.Public, }; testMethod.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference("Test"))); //Create controller instance + comment var controllerDeclaractionComment = new CodeCommentStatement("GIVEN: setup your environment here"); var contollerDeclaractionStatement = new CodeVariableDeclarationStatement( new CodeTypeReference(_elementData.NameAsController), controllerVariableName, new CodeObjectCreateExpression(_elementData.NameAsController)); testMethod.Statements.Add(new CodeSnippetStatement("")); testMethod.Statements.Add(controllerDeclaractionComment); testMethod.Statements.Add(contollerDeclaractionStatement); //Create viewmodel if multiinstance if (isMultiinstance) { var viewModelDeclaration = new CodeVariableDeclarationStatement( new CodeTypeReference(_elementData.NameAsViewModel), senderVariableName, new CodeObjectCreateExpression( new CodeTypeReference(_elementData.NameAsViewModel), new CodeSnippetExpression(controllerVariableName))); testMethod.Statements.Add(viewModelDeclaration); } //Create parameter if needed if (useParameter) { CodeVariableDeclarationStatement argumentDeclaration = null; var viewModel = _elementData.OwnerData.GetViewModel(scenario.CommandData.RelatedTypeName); if (viewModel == null) argumentDeclaration = new CodeVariableDeclarationStatement( new CodeTypeReference(scenario.CommandData.RelatedTypeName), argumentVariableName, new CodeDefaultValueExpression(new CodeTypeReference(scenario.CommandData.RelatedTypeName)) ); else argumentDeclaration = new CodeVariableDeclarationStatement( new CodeTypeReference(viewModel.NameAsViewModel), argumentVariableName, new CodeDefaultValueExpression(new CodeTypeReference(viewModel.NameAsViewModel))); testMethod.Statements.Add(argumentDeclaration); } //Create invocation to the controller + comment var commandInvocationComment = new CodeCommentStatement("WHEN: call to the command"); var commandInvocation = new CodeMethodInvokeExpression( new CodeSnippetExpression(controllerVariableName), scenario.CommandData.Name); if(isMultiinstance) commandInvocation.Parameters.Add(new CodeSnippetExpression(senderVariableName)); if(useParameter) commandInvocation.Parameters.Add(new CodeSnippetExpression(argumentVariableName)); testMethod.Statements.Add(new CodeSnippetStatement("")); testMethod.Statements.Add(commandInvocationComment); testMethod.Statements.Add(commandInvocation); //Create template assertion + comment var assertionComment = new CodeCommentStatement("THEN: Assert anything here"); var assertionInvocation = new CodeSnippetExpression("Assert.That(true)"); testMethod.Statements.Add(new CodeSnippetStatement("")); testMethod.Statements.Add(assertionComment); testMethod.Statements.Add(assertionInvocation); testSuitDeclaration.Members.Add(testMethod); } base.Namespace.Types.Add(testSuitDeclaration); }