public void Process(CodeTypeDeclaration typeDecl) { for (int i = 0; i < typeDecl.Members.Count; i++) { CodeTypeMember typeMember = typeDecl.Members[i]; if (typeMember is CodeMemberMethod) { CodeMemberMethod memberMethod = (CodeMemberMethod) typeMember; CodeObjectSource source = Utils.GetTypeReferenceSource(memberMethod.ReturnType); if (source.Target == typeof (void) && source.ArrayRanks.Length == 0 && memberMethod.Parameters.Count == 0) { if (StringUtils.CaseInsensitiveEquals(memberMethod.Name, "Class_Initialize")) { CodeConstructor constructor = new CodeConstructor(); constructor.Statements.AddRange(memberMethod.Statements); typeDecl.Members[i] = constructor; } else if (StringUtils.CaseInsensitiveEquals(memberMethod.Name, "Class_Terminate")) { CodeDestructor destructor = new CodeDestructor(); destructor.Statements.AddRange(memberMethod.Statements); typeDecl.Members[i] = destructor; } } } else if (typeMember is CodeTypeDeclaration) { Process((CodeTypeDeclaration) typeMember); } } }
public void AddBodyParameterTest() { var method = new MockMethod() { Name = "Method", Parameters = new Dictionary<string, IParameter>() }; var typeProvider = new DefaultObjectTypeProvider("Schema"); // Confirm that no body parameter is added. var decorator = new RequestConstructorDecorator(typeProvider); CodeConstructor constructor = new CodeConstructor(); method.HasBody = false; decorator.AddBodyParameter(constructor, method); Assert.AreEqual(0, constructor.Parameters.Count); Assert.AreEqual(0, constructor.Statements.Count); // Confirm that a required body parameter is added. method.RequestType = "MySchema"; method.HasBody = true; constructor = new CodeConstructor(); decorator.AddBodyParameter(constructor, method); Assert.AreEqual(1, constructor.Parameters.Count); Assert.AreEqual("body", constructor.Parameters[0].Name); Assert.AreEqual("Schema.MySchema", constructor.Parameters[0].Type.BaseType); Assert.AreEqual(1, constructor.Statements.Count); }
internal CodeConstructor CreateConstructor(String serviceClassName, IResource resource) { var constructor = new CodeConstructor(); // public [ResourceClass]([ServiceClass] service, Google.Apis.Authentication.IAuthenticator authenticator) constructor.Attributes = MemberAttributes.Public; constructor.Parameters.Add( new CodeParameterDeclarationExpression(serviceClassName, ResourceBaseGenerator.ServiceFieldName)); constructor.Parameters.Add( new CodeParameterDeclarationExpression(typeof(Google.Apis.Authentication.IAuthenticator), ResourceClassGenerator.AuthenticatorName)); // this.service = service constructor.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), ResourceBaseGenerator.ServiceFieldName), new CodeArgumentReferenceExpression(ResourceBaseGenerator.ServiceFieldName))); // this.authenticator = authenticator constructor.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), ResourceClassGenerator.AuthenticatorName), new CodeArgumentReferenceExpression(ResourceClassGenerator.AuthenticatorName))); // Initialize subresources constructor.Statements.AddRange(CreateSubresourceCreateStatements(resource)); return constructor; }
protected virtual CodeConstructor CreateServicesConstructor() { CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; constructor.Parameters.Add(new CodeParameterDeclarationExpression(_serviceType, _naming.ToVariableName(_serviceIdentifier))); return constructor; }
/// <summary> /// This is a simple helper method to create a test valid /// CodeObject to be feed into the /// CreateScriptSource(CodeObject content, string id) /// /// However, CodeObject is simply a base class so we probably /// need a specific type of CodeObject but what? /// /// [Bill - has indicate that CodeObject parameter for CreateScriptSource /// does in fact need to be a CodeMemberMethod - Maybe a spec BUG] /// /// Probably need to put this somewhere else maybe put this in: /// ScriptEngineTestHelper.cs /// </summary> /// <returns>A valid CodeObject boxes some kind of CompileUnit</returns> private static CodeObject BuildCountCode() { // Create a new CodeCompileUnit to contain // the program graph. CodeCompileUnit compileUnit = new CodeCompileUnit(); // Declare a new namespace called Samples. CodeNamespace samples = new CodeNamespace("Samples"); // Add the new namespace to the compile unit. compileUnit.Namespaces.Add(samples); // Declare a new code entry point method. CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeConstructor codecon = new CodeConstructor(); // CodeNamespace cns = new CodeNamespace("Test"); CodeTypeDeclaration ctd = new CodeTypeDeclaration("testclass"); ctd.IsClass = true; CodeMemberMethod method = new CodeMemberMethod(); method.Attributes = MemberAttributes.Public | MemberAttributes.Final; method.Name = "AddTenToNumber"; method.ReturnType = new CodeTypeReference("Int32"); method.Parameters.Add(new CodeParameterDeclarationExpression("int", "number")); method.Statements.Add(new CodeSnippetExpression("return number+10")); ctd.Members.Add(method); samples.Types.Add(ctd); // If we return just the method this will not throw exception // on CreateScriptSource // return method; return compileUnit; }
private static CodeConstructor CreateConstructor(string className) { CodeConstructor result = new CodeConstructor(); result.Attributes = MemberAttributes.Public; result.Name = className; return result; }
public override void DeclareCodeType(IDLInterface idlIntf) { // Proxy class. typeProxy = new CodeTypeDeclaration(name + "Proxy"); typeProxy.IsClass = true; typeProxy.TypeAttributes = TypeAttributes.Public; eventsDeclarationHolder = new CodeTypeDeferredNamespaceDeclarationHolderEvents(idlIntf); typeProxy.BaseTypes.Add(genInterfaceName); // Interface field. CodeMemberField memberProxy = new CodeMemberField(genInterfaceName, proxyName); memberProxy.Attributes = MemberAttributes.Private; typeProxy.Members.Add(memberProxy); // TODO: Going to need a using or a fully qualified name. // Constructor. CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; // TODO - use the actual interface type rather than a string. paramProxy = new CodeParameterDeclarationExpression(genInterfaceName, proxyName); constructor.Parameters.Add(paramProxy); thisProxyFieldRef = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), proxyName ); assignProxy = new CodeAssignStatement(thisProxyFieldRef, new CodeArgumentReferenceExpression(proxyName)); constructor.Statements.Add(assignProxy); typeProxy.Members.Add(constructor); declarationHolder = new CodeTypeIgnoredNamespaceDeclarationHolderParams(idlIntf); contextDeclarationHolder = declarationHolder; bAddNamespace = false; }
public void SetTestFixtureSetup(CodeMemberMethod fixtureSetupMethod) { // xUnit uses IUseFixture<T> on the class fixtureSetupMethod.Attributes |= MemberAttributes.Static; _currentFixtureTypeDeclaration = new CodeTypeDeclaration("FixtureData"); _currentTestTypeDeclaration.Members.Add(_currentFixtureTypeDeclaration); var fixtureDataType = CodeDomHelper.CreateNestedTypeReference(_currentTestTypeDeclaration, _currentFixtureTypeDeclaration.Name); var useFixtureType = new CodeTypeReference(IUSEFIXTURE_INTERFACE, fixtureDataType); CodeDomHelper.SetTypeReferenceAsInterface(useFixtureType); _currentTestTypeDeclaration.BaseTypes.Add(useFixtureType); // public void SetFixture(T) { } // explicit interface implementation for generic interfaces does not work with codedom CodeMemberMethod setFixtureMethod = new CodeMemberMethod(); setFixtureMethod.Attributes = MemberAttributes.Public; setFixtureMethod.Name = "SetFixture"; setFixtureMethod.Parameters.Add(new CodeParameterDeclarationExpression(fixtureDataType, "fixtureData")); setFixtureMethod.ImplementationTypes.Add(useFixtureType); _currentTestTypeDeclaration.Members.Add(setFixtureMethod); // public <_currentFixtureTypeDeclaration>() { <fixtureSetupMethod>(); } CodeConstructor ctorMethod = new CodeConstructor(); ctorMethod.Attributes = MemberAttributes.Public; _currentFixtureTypeDeclaration.Members.Add(ctorMethod); ctorMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(new CodeTypeReference(_currentTestTypeDeclaration.Name)), fixtureSetupMethod.Name)); }
/// <summary> /// Generates code from the specified <paramref name="constructor"/>. /// </summary> /// <param name="constructor">Class constructor for which code needs to be generated.</param> /// <param name="type">Type declaration.</param> /// <param name="namespace">Namespace declaration.</param> /// <param name="options">Code generation options.</param> /// <remarks> /// This method is a workaround for <see cref="CodeDomProvider.GenerateCodeFromMember"/> /// not generating constructors properly. /// </remarks> private void GenerateCodeFromConstructor( CodeConstructor constructor, CodeTypeDeclaration type, CodeNamespace @namespace, CodeGeneratorOptions options) { const string StartMarker = "___startMarker___"; const string EndMarker = "___endMarker___"; // Insert marker fields around the target constructor int indexOfMember = type.Members.IndexOf(constructor); type.Members.Insert(indexOfMember + 1, new CodeMemberField(typeof(int), EndMarker)); type.Members.Insert(indexOfMember, new CodeMemberField(typeof(int), StartMarker)); using (StringWriter buffer = new StringWriter(CultureInfo.InvariantCulture)) { // Generate type declaration in verbatim order to preserve placement of marker fields options = options ?? new CodeGeneratorOptions(); options.VerbatimOrder = true; this.LanguageProvider.GenerateCodeFromNamespace(@namespace, buffer, options); // Extract constructor code from the generated type code const string ConstructorCode = "constructor"; Regex regex = new Regex( @"^[^\r\n]*" + StartMarker + @"[^\n]*$" + @"(?<" + ConstructorCode + @">.*)" + @"^[^\r\n]*" + EndMarker + @"[^\n]*$", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.ExplicitCapture); string code = regex.Match(buffer.ToString()).Groups[ConstructorCode].Value; // Write constructor code to the output buffer this.ClassCode.Write(code); } }
protected override void GenerateConstructor(System.CodeDom.CodeConstructor e, System.CodeDom.CodeTypeDeclaration c) { //Output.Write("constructor"); //OutputMethodSignature(e.Attributes, e.ReturnType, "", e.Parameters, false, false); //GenerateBlock(e.Statements); //Output.WriteLine(";"); }
protected override CodeMemberMethod GetInitializeMethod(IDesignerSerializationManager manager, CodeTypeDeclaration typeDecl, object value) { if (manager == null) { throw new ArgumentNullException("manager"); } if (typeDecl == null) { throw new ArgumentNullException("typeDecl"); } if (value == null) { throw new ArgumentNullException("value"); } CodeMemberMethod method = typeDecl.UserData[_initMethodKey] as CodeMemberMethod; if (method == null) { method = new CodeMemberMethod { Name = "InitializeComponent", Attributes = MemberAttributes.Private }; typeDecl.UserData[_initMethodKey] = method; CodeConstructor constructor = new CodeConstructor { Attributes = MemberAttributes.Public }; constructor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "InitializeComponent", new CodeExpression[0])); typeDecl.Members.Add(constructor); } return method; }
public CodeCompileUnit GenerateCode(string typeName, string codeBody, StringCollection imports, string prefix) { var compileUnit = new CodeCompileUnit(); var typeDecl = new CodeTypeDeclaration(typeName); typeDecl.IsClass = true; typeDecl.TypeAttributes = TypeAttributes.Public; // create constructor var constructMember = new CodeConstructor {Attributes = MemberAttributes.Public}; typeDecl.Members.Add(constructMember); // pump in the user specified code as a snippet var literalMember = new CodeSnippetTypeMember(codeBody); typeDecl.Members.Add(literalMember); var nspace = new CodeNamespace(); ////Add default imports //foreach (string nameSpace in ScriptExecuter._namespaces) //{ // nspace.Imports.Add(new CodeNamespaceImport(nameSpace)); //} foreach (string nameSpace in imports) { nspace.Imports.Add(new CodeNamespaceImport(nameSpace)); } compileUnit.Namespaces.Add(nspace); nspace.Types.Add(typeDecl); return compileUnit; }
protected override CodeMemberMethod GetInitializeMethod(IDesignerSerializationManager manager, CodeTypeDeclaration typeDecl, object value) { if (manager == null) throw new ArgumentNullException("manager"); if (typeDecl == null) throw new ArgumentNullException("typeDecl"); if (value == null) throw new ArgumentNullException("value"); CodeMemberMethod method = typeDecl.UserData[_initMethodKey] as CodeMemberMethod; if (method == null) { method = new CodeMemberMethod(); method.Name = _initMethodName; method.Attributes = MemberAttributes.Private; typeDecl.UserData[_initMethodKey] = method; // Now create a ctor that calls this method. CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Public; ctor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), _initMethodName)); typeDecl.Members.Add(ctor); } return method; }
private static void AddConstructor(CodeTypeDeclaration declaration) { CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; constructor.Parameters.Add( new CodeParameterDeclarationExpression( typeof(IDbConnection), "connection")); constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("connection")); constructor.CustomAttributes.Add(new CodeAttributeDeclaration( new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute)) )); constructor.Statements.Add( new CodeAssignStatement( new CodeVariableReferenceExpression(SqlDataContextHelperClassName), new CodeObjectCreateExpression( typeof(SqlDataContextHelperClass), new CodeExpression[] { new CodeThisReferenceExpression() } ) )); declaration.Members.Add(constructor); }
/// <summary> /// Add a constructor to the class. /// </summary> public void AddConstructor() { // Declare the constructor CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public | MemberAttributes.Final; // Add parameters. constructor.Parameters.Add(new CodeParameterDeclarationExpression( typeof(System.Double), "width")); constructor.Parameters.Add(new CodeParameterDeclarationExpression( typeof(System.Double), "height")); // Add field initialization logic CodeFieldReferenceExpression widthReference = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "widthValue"); constructor.Statements.Add(new CodeAssignStatement(widthReference, new CodeArgumentReferenceExpression("width"))); CodeFieldReferenceExpression heightReference = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "heightValue"); constructor.Statements.Add(new CodeAssignStatement(heightReference, new CodeArgumentReferenceExpression("height"))); targetClass.Members.Add(constructor); }
internal CodeConstructor CreateRequiredConstructor(CodeTypeDeclaration resourceClass, IMethod request, bool addOptionalParameters) { var constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; // IRequestProvider service var serviceArg = new CodeParameterDeclarationExpression(typeof(IRequestProvider), ServiceName); constructor.Parameters.Add(serviceArg); // : base(service, "path", "HTTPMETHOD") constructor.BaseConstructorArgs.Add( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression(ServiceName), BaseUriName)); constructor.BaseConstructorArgs.Add(new CodePrimitiveExpression(request.MediaUpload.Simple.Path)); constructor.BaseConstructorArgs.Add(new CodePrimitiveExpression(request.HttpMethod)); // Add all required arguments to the constructor. AddBodyParameter(constructor, request); // Add common upload arguements. constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(StreamParameterName)); constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(ContentTypeParameterName)); AddAuthorizationAssignment(constructor); AddRequestParameters(resourceClass, request, constructor, addOptionalParameters); constructor.Parameters.Add(new CodeParameterDeclarationExpression( new CodeTypeReference(typeof(System.IO.Stream)), StreamParameterName)); constructor.Parameters.Add(new CodeParameterDeclarationExpression( new CodeTypeReference(typeof(System.String)), ContentTypeParameterName)); return constructor; }
public CodeExpression[] Generate(Table table, HardwireCodeGenerationContext generatorContext, CodeTypeMemberCollection members) { string className = "AIDX_" + Guid.NewGuid().ToString("N"); string name = table.Get("name").String; bool setter = table.Get("setter").Boolean; CodeTypeDeclaration classCode = new CodeTypeDeclaration(className); classCode.TypeAttributes = System.Reflection.TypeAttributes.NestedPrivate | System.Reflection.TypeAttributes.Sealed; classCode.BaseTypes.Add(typeof(ArrayMemberDescriptor)); CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Assembly; classCode.Members.Add(ctor); ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(name)); ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(setter)); DynValue vparams = table.Get("params"); if (vparams.Type == DataType.Table) { List<HardwireParameterDescriptor> paramDescs = HardwireParameterDescriptor.LoadDescriptorsFromTable(vparams.Table); ctor.BaseConstructorArgs.Add(new CodeArrayCreateExpression(typeof(ParameterDescriptor), paramDescs.Select(e => e.Expression).ToArray())); } members.Add(classCode); return new CodeExpression[] { new CodeObjectCreateExpression(className) }; }
// Generates a codedom constructor expression and attaches it to the given type. public static void Emit(CodeTypeDeclaration codeTypeDeclaration, Constructor ctor) { // Create the codedom constructor var codeCtor = new CodeConstructor(); codeTypeDeclaration.Members.Add(codeCtor); // Translate accessibility of the constructor MemberAttributes memberAttributes = MemberAttributes.Public; switch (ctor.Accessibility) { case Accessibility.Internal: memberAttributes |= MemberAttributes.FamilyAndAssembly; break; case Accessibility.Private: memberAttributes |= MemberAttributes.Private; break; case Accessibility.Protected: memberAttributes |= MemberAttributes.Family; break; case Accessibility.Public: memberAttributes |= MemberAttributes.Public; break; } codeCtor.Attributes = memberAttributes; // Translate the parameters of the constructor foreach (Expression p in ctor.Parameters) { if (p is SimpleParameter) // ex "int i" codeCtor.Parameters.Add(new CodeParameterDeclarationExpression((p as SimpleParameter).TypeName, (p as SimpleParameter).Name)); if (p is DirectionedParameter) // ex "ref int i" { var codeParameter = new CodeParameterDeclarationExpression((p as DirectionedParameter).TypeName, (p as DirectionedParameter).Name); switch ((p as DirectionedParameter).Direction) { case ParameterDirection.Out: codeParameter.Direction = FieldDirection.Out; break; case ParameterDirection.Ref: codeParameter.Direction = FieldDirection.Ref; break; } codeCtor.Parameters.Add(codeParameter); } } // Add call to a constructor of the base class or another in the same class. foreach (var a in ctor.SubParameters.ChildExpressions) { if (ctor.Sub) codeCtor.ChainedConstructorArgs.Add(CodeDomEmitter.EmitCodeExpression(a)); else codeCtor.BaseConstructorArgs.Add(CodeDomEmitter.EmitCodeExpression(a)); } // Add all the statements in the body of the constructor foreach (var e in ctor.ChildExpressions) codeCtor.Statements.Add(CodeDomEmitter.EmitCodeStatement(e)); }
public CodeConstructor AddConstructor(CodeTypeDeclaration type) { CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public | MemberAttributes.Final; type.Members.Add(constructor); return constructor; }
private void GenerateDefaultConstructor(CodeTypeDeclaration classObject, JsonObject jsonObject) { CodeConstructor constructor = new CodeConstructor(); classObject.Members.Add(constructor); constructor.Attributes = MemberAttributes.Public; CodeAssignStatement statement = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "RootObject"), new CodeObjectCreateExpression(jsonObject.GetType(), new CodeExpression[0])); constructor.Statements.Add(statement); }
public virtual List<ExplorerItem> BuildAssembly(IConnectionInfo cxInfo, AssemblyName assemblyToBuild, ref string nameSpace, ref string typeName) { var unit = new CodeCompileUnit(); var namespace2 = new CodeNamespace(nameSpace); namespace2.Imports.Add(new CodeNamespaceImport("System")); namespace2.Imports.Add(new CodeNamespaceImport("System.Linq")); namespace2.Imports.Add(new CodeNamespaceImport("Sitecore.ContentSearch")); namespace2.Imports.Add(new CodeNamespaceImport("Sitecore.ContentSearch.SearchTypes")); var settings = new SitecoreConnectionSettings(); var mapper = new DriverDataCxSettingsMapper(); mapper.Read(cxInfo, settings); var selectedType = settings.SearchResultType.GetSelectedType(); namespace2.Imports.Add(new CodeNamespaceImport(selectedType.Namespace)); var declaration = new CodeTypeDeclaration(typeName) { IsClass = true, TypeAttributes = TypeAttributes.Public }; namespace2.Types.Add(declaration); unit.Namespaces.Add(namespace2); var constructor = new CodeConstructor { Attributes = MemberAttributes.Public }; this.AddConstructorCode(constructor, settings); declaration.Members.Add(constructor); var indexNames = this.GetIndexNames(cxInfo); var list = new List<ExplorerItem>(); foreach (var str in indexNames) { this.AddIndexAsProperty(str, selectedType, declaration); var item = new ExplorerItem(str, ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { IsEnumerable = false }; item.DragText = this.GetDragText(item, settings); list.Add(item); } var provider = new CSharpCodeProvider(); var options = new CompilerParameters(); var assemblyFilesToReference = this.GetAssemblyFilesToReference(settings); foreach (var str2 in assemblyFilesToReference) { options.ReferencedAssemblies.Add(str2); } options.GenerateInMemory = true; options.OutputAssembly = assemblyToBuild.CodeBase; var results = provider.CompileAssemblyFromDom(options, new CodeCompileUnit[] { unit }); if (results.Errors.Count > 0) { throw new Exception(string.Concat(new object[] { "Cannot compile typed context: ", results.Errors[0].ErrorText, " (line ", results.Errors[0].Line, ")" })); } return list; }
public virtual string Generate(Window window) { window.ReInitialize(InitializeOption.WithCache); var stringBuilder = new StringBuilder(); var stringWriter = new StringWriter(stringBuilder); var cscProvider = new CSharpCodeProvider(); ICodeGenerator codeGenerator = cscProvider.CreateGenerator(stringWriter); var codeGeneratorOptions = new CodeGeneratorOptions {BlankLinesBetweenMembers = false, VerbatimOrder = false}; codeGenerator.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit(string.Format("using {0};", typeof(UIItem).Namespace)), stringWriter, codeGeneratorOptions); codeGenerator.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit(string.Format("using {0};", typeof(Window).Namespace)), stringWriter, codeGeneratorOptions); codeGenerator.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit(string.Format("using {0};", typeof(AppScreen).Namespace)), stringWriter, codeGeneratorOptions); CodeNamespace codeNamespace = null; if (S.IsNotEmpty(options.Namespace)) { codeNamespace = new CodeNamespace(options.Namespace); } var classDefinition = new CodeTypeDeclaration { IsClass = true, IsPartial = true, Name = window.Title.Trim().Replace(" ", string.Empty), TypeAttributes = TypeAttributes.Public }; classDefinition.BaseTypes.Add(typeof (AppScreen)); var constructor = new CodeConstructor {Attributes = MemberAttributes.Family}; classDefinition.Members.Add(constructor); constructor = new CodeConstructor {Attributes = MemberAttributes.Public}; constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Window), "window")); constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof (ScreenRepository), "screenRepository")); constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("window")); constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("screenRepository")); classDefinition.Members.Add(constructor); var visitor = new CodeGenerationVisitor(new WindowCodeGenerationStrategy(options)); window.Visit(visitor); visitor.Generate(classDefinition); if (codeNamespace != null) { codeNamespace.Types.Add(classDefinition); codeGenerator.GenerateCodeFromNamespace(codeNamespace, stringWriter, codeGeneratorOptions); } else { codeGenerator.GenerateCodeFromType(classDefinition, stringWriter, codeGeneratorOptions); } stringWriter.Close(); return stringBuilder.ToString(); }
public void Init() { functionalConstructor = null; staticConstructor = null; hasElementWildCards = false; contentModelExpression = null; if (propertyNameTypeTable != null) { propertyNameTypeTable.Clear(); } }
internal CodeConstructor CreateEmptyConstructor() { // Example: new TestService() : this(NullAuthenticator.Instance) var constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; var nullAuthenticator = new CodeTypeReferenceExpression(typeof(NullAuthenticator)); constructor.ChainedConstructorArgs.Add(new CodeFieldReferenceExpression(nullAuthenticator, "Instance")); return constructor; }
public CodeConstructor Constructor_1() { CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Public; ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(relationInfo.Table.DBTableName)); ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(relationInfo.Table.Fields[0].DBColumnName)); ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(relationInfo.Table.Fields[1].DBColumnName)); ctor.BaseConstructorArgs.Add(new CodeFieldReferenceExpression(null, "theRelationInfo")); return ctor; }
public TypescriptConstructor( IExpressionFactory expressionFactory, IStatementFactory statementFactory, CodeConstructor member, CodeGeneratorOptions options) { _expressionFactory = expressionFactory; _statementFactory = statementFactory; _member = member; _options = options; }
private CodeConstructor GetAnonymousTypeConstructor(CodeTypeDeclaration type) { var data = CodeWriterFilterService.EntityMetadata[type.GetFieldInitalizedValue("EntityLogicalName")]; var constructor = new CodeConstructor { Attributes = System.CodeDom.MemberAttributes.Public, Name = type.Name }; constructor.Comments.AddRange(new[] { new CodeCommentStatement(@"<summary>", true), new CodeCommentStatement(@"Constructor for populating via LINQ queries given a LINQ anonymous type", true), new CodeCommentStatement(@"<param name=""anonymousType"">LINQ anonymous type.</param>",true), new CodeCommentStatement(@"</summary>", true)}); constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof (Object), "anonymousType")); constructor.ChainedConstructorArgs.Add(new CodeSnippetExpression("")); const string indent = " "; // Rather than attempt to do this all through CodeDom, hard code this as C# constructor.Statements.Add(new CodeSnippetStatement(string.Format(indent + "foreach (var p in anonymousType.GetType().GetProperties()){0}" + "{{{0}" + " var value = p.GetValue(anonymousType, null);{0}" + " var name = p.Name.ToLower();{0}{0}" + " if (name.EndsWith(\"enum\") && value.GetType().BaseType == typeof(System.Enum)){0}" + " {{{0}" + " value = new Microsoft.Xrm.Sdk.OptionSetValue((int) value);{0}" + " name = name.Remove(name.Length - \"enum\".Length);{0}" + " }}{0}{0}" + " switch (name){0}" + " {{{0}" + " case \"id\":{0}" + " base.Id = (System.Guid)value;{0}" + " Attributes[\"{1}\"] = base.Id;{0}" + " break;{0}" + " case \"{1}\":{0}" + " var id = (System.Nullable<System.Guid>) value;{0}" + " if(id == null){{ continue; }}{0}" + " base.Id = id.Value;{0}" + " Attributes[name] = base.Id;{0}" + " break;{0}" + " case \"formattedvalues\":{0}" + " // Add Support for FormattedValues{0}" + " FormattedValues.AddRange((Microsoft.Xrm.Sdk.FormattedValueCollection)value);{0}" + " break;{0}" + " default:{0}" + " Attributes[name] = value;{0}" + " break;{0}" + " }}{0}" + "}}", Environment.NewLine + indent, data.PrimaryIdAttribute))); return constructor; }
public CodeDomTypeDefinition(string typeName) { Type = new CodeTypeDeclaration(typeName); Type.IsClass = true; CodeConstructor classConstructor = new CodeConstructor(); classConstructor.Attributes = MemberAttributes.Public; Constructor = classConstructor; Type.Members.Add(Constructor); }
internal FORMALS formals; // optional public CodeMemberMethod ToCodeMemberMethod() { CodeMemberMethod method; if (method_id == "initialize") method = new CodeConstructor(); else method = new CodeMemberMethod(); method.Name = method_id; method.ReturnType = new CodeTypeReference(typeof(object)); method.Parameters.AddRange(formals.ToCodeParameterDeclarationExpressionCollection()); if (method_id == "InitializeComponent") for (Node n = body; n != null; n = n.nd_next) { if (n is ASSIGNMENT) { CodeStatement stmt = null; Node lhs = ((ASSIGNMENT)n).lhs; Node rhs = ((ASSIGNMENT)n).rhs; if (rhs is METHOD_CALL) { METHOD_CALL m = (METHOD_CALL)rhs; if (m.receiver.ToString() == "Interop" && m.method_id == "VariableDeclaration") { Node init = ((ARGS)m.args).parameters; Node type = init.nd_next; stmt = new CodeVariableDeclarationStatement(type.ToString().Replace("::","."), lhs.ToString(), init.ToCodeExpression()); } } if (stmt == null) stmt = ((ASSIGNMENT)n).ToCodeStatement(); method.Statements.Add(stmt); } else if (n is METHOD_CALL) method.Statements.Add(n.ToCodeExpression()); else throw new System.NotImplementedException(n.GetType().ToString()); } else if (body != null) method.Statements.Add(new CodeCommentStatement("Dummy statement so that it doesn't appear empty to the designer")); method.UserData["original_name"] = method.Name; method.UserData["name_location"] = name_location; method.UserData["location"] = this.location; return method; }
public CodeExpression[] Generate(Table table, HardwireCodeGenerationContext generatorContext, CodeTypeMemberCollection members) { string className = "DVAL_" + Guid.NewGuid().ToString("N"); DynValue kval = table.Get("value"); DynValue vtype = table.Get("type"); DynValue vstaticType = table.Get("staticType"); string type = (vtype.Type == DataType.String) ? vtype.String : null; string staticType = (vstaticType.Type == DataType.String) ? vstaticType.String : null; CodeTypeDeclaration classCode = new CodeTypeDeclaration(className); classCode.TypeAttributes = System.Reflection.TypeAttributes.NestedPrivate | System.Reflection.TypeAttributes.Sealed; classCode.BaseTypes.Add(typeof(DynValueMemberDescriptor)); CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Assembly; classCode.Members.Add(ctor); if (type == null) { Table tbl = new Table(null); tbl.Set(1, kval); string str = tbl.Serialize(); ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(table.Get("name").String)); ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(str)); } else if (type == "userdata") { ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(table.Get("name").String)); CodeMemberProperty p = new CodeMemberProperty(); p.Name = "Value"; p.Type = new CodeTypeReference(typeof(DynValue)); p.Attributes = MemberAttributes.Override | MemberAttributes.Public; p.GetStatements.Add( new CodeMethodReturnStatement( new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(UserData)), "CreateStatic", new CodeTypeOfExpression(staticType)))); classCode.Members.Add(p); } members.Add(classCode); return new CodeExpression[] { new CodeObjectCreateExpression(className) }; }
public CodeConstructor Constructor_Raw() { CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Public; ctor.Parameters.Add(new CodeParameterDeclarationExpression("SoodaConstructor", "c")); ctor.BaseConstructorArgs.Add(Arg("c")); ctor.Statements.Add(new CodeCommentStatement("Do not modify this constructor.")); return ctor; }