Esempio n. 1
0
        public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit,
                                                  CodeNamespace generatedNamespace,
                                                  CodeTypeDeclaration generatedClass,
                                                  CodeMemberMethod executeMethod)
        {
            base.ProcessGeneratedCode(codeCompileUnit, generatedNamespace, generatedClass, executeMethod);


            // Create the Href wrapper
            CodeTypeMember hrefMethod = new CodeSnippetTypeMember(@"
                // Resolve package relative syntax
                // Also, if it comes from a static embedded resource, change the path accordingly
                public override string Href(string virtualPath, params object[] pathParts) {
                    virtualPath = ApplicationPart.ProcessVirtualPath(GetType().Assembly, VirtualPath, virtualPath);
                    return base.Href(virtualPath, pathParts);
                }");

            generatedClass.Members.Add(hrefMethod);

            Debug.Assert(generatedClass.Name.Length > 0);
            if (!(Char.IsLetter(generatedClass.Name[0]) || generatedClass.Name[0] == '_'))
            {
                generatedClass.Name = '_' + generatedClass.Name;
            }

            // If the generatedClass starts with an underscore, add a ClsCompliant(false) attribute.
            if (generatedClass.Name[0] == '_')
            {
                generatedClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(CLSCompliantAttribute).FullName,
                                                        new CodeAttributeArgument(new CodePrimitiveExpression(false))));
            }
        }
Esempio n. 2
0
        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;
        }
		//construct, given the code provider being used.
		public CompileDirectives(CodeDomProvider codeProvider)
		{
			this.codeProvider = codeProvider;

			if (codeProvider.FileExtension == "cs")
			{
				readonlySnip = new CodeSnippetTypeMember("readonly ");
				isCSharp = true;
			}
			if (codeProvider.FileExtension == "vb")
				readonlySnip = new CodeSnippetTypeMember("ReadOnly ");


			//try and load the directives from the user config.
			try
			{
				//GenericType
				string defaultDiretive = Properties.Settings.Default.DefaultCompilerDirectives.Trim();
				if (defaultDiretive.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Length == 3)
					directives = defaultDiretive.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

				System.Reflection.PropertyInfo[] properties = Properties.Settings.Default.GetType().GetProperties();

				foreach (System.Reflection.PropertyInfo property in properties)
				{
					if (property.PropertyType == typeof(string) && property.Name.EndsWith("CompilerDirectives", StringComparison.InvariantCultureIgnoreCase))
					{
						string directive = property.GetValue(Properties.Settings.Default, null) as string;

						if (directive != null)
						{
							string[] lines = directive.Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
							if (lines.Length == 4)
							{
								if (("*." + codeProvider.FileExtension).Equals(lines[0].Trim(), StringComparison.InvariantCultureIgnoreCase))
								{
									for (int i = 0; i < 3; i++)
									{
										directives[i] = lines[i + 1];
									}
								}
							}
						}
					}
				}

				for (int i = 0; i < directives.Length; i++)
				{
					directives[i] = directives[i].Trim();
				}

				if (directives[0].Contains("{0}") == false)
					throw new Exception("Could not find {0} in directive 0");

			}
			catch (Exception e)
			{
				throw new Exception("Error in user.config file", e);
			}
		}
 public TypescriptSnippetTypeMember(
     CodeSnippetTypeMember member,
     CodeGeneratorOptions options)
 {
     _member = member;
     _options = options;
 }
        /// <summary>
        /// Generates the partial method for an action.
        /// </summary>
        /// <param name = "message">The message.</param>
        /// <param name = "argumentType">Type of the argument.</param>
        /// <returns>The type member.</returns>
        protected override CodeTypeMember GenerateActionPartialMethod(string message, IType argumentType)
        {
            String selector = message;
            String name = GenerateMethodName (selector);

            // Partial method are only possible by using a snippet of code as CodeDom does not handle them
            CodeSnippetTypeMember method = new CodeSnippetTypeMember ("partial void " + name + "(" + argumentType.Name + " sender);" + Environment.NewLine);

            return method;
        }
        /// <summary>
        ///   Generates the partial method for an action.
        /// </summary>
        /// <param name = "message">The message.</param>
        /// <param name = "argumentType">Type of the argument.</param>
        /// <returns>The type member.</returns>
        protected override CodeTypeMember GenerateActionPartialMethod(string message, IType argumentType)
        {
            String selector = message;
            String name = GenerateMethodName (selector);

            // Partial method are only possible by using a snippet of code as CodeDom does not handle them
            String content = String.Format ("Partial Private Sub {0}({1} sender){2}End Sub{2}", name, argumentType.Name, Environment.NewLine);
            CodeSnippetTypeMember method = new CodeSnippetTypeMember (content);

            return method;
        }
Esempio n. 7
0
        public void AddScriptBlock(string source, string uriString, int lineNumber, Location end) {
            CodeSnippetTypeMember scriptSnippet = new CodeSnippetTypeMember(source);
            string fileName = SourceLineInfo.GetFileName(uriString);
            if (lineNumber > 0) {
                scriptSnippet.LinePragma = new CodeLinePragma(fileName, lineNumber);
                scriptUris[fileName] = uriString;
            }
            typeDecl.Members.Add(scriptSnippet);

            this.endUri = uriString;
            this.endLoc = end;
        }
        public static CodeTypeMember CreatePropertyCode(this SAPDataParameter p)
        {
            CodeSnippetTypeMember snippet = new CodeSnippetTypeMember();

            if (p.Comment != null)
            {
                snippet.Comments.Add(new CodeCommentStatement(p.Comment, true));
            }

            snippet.Text = string.Format("public {0} {1} {{get;set;}}", p.Type.ToString(), p.Name);

            return snippet;
        }
Esempio n. 9
0
        public void AddScriptBlock(string source, string uriString, int lineNumber, int endLine, int endPos) {
            CodeSnippetTypeMember scriptSnippet = new CodeSnippetTypeMember(source);
            string fileName = SourceLineInfo.GetFileName(uriString);
            if (lineNumber > 0) {
                scriptSnippet.LinePragma = new CodeLinePragma(fileName, lineNumber);
                scriptFiles.Add(fileName);
            }
            typeDecl.Members.Add(scriptSnippet);

            this.endFileName  = fileName;
            this.endLine      = endLine;
            this.endPos       = endPos;
        }
		private static CodeTypeDeclaration CraeteCodeInterfaceDeclaration(XpidlInterface xpidlInterface, out CodeTypeDeclaration codeConstClassDeclaration)
		{
			// Create interface declaration
			var codeInterfaceDeclaration =
				new CodeTypeDeclaration(xpidlInterface.Name)
				{
					IsInterface = true,
					TypeAttributes = TypeAttributes.Interface | TypeAttributes.NotPublic
				};

			// Set base interface (except of nsISupports)
			if (!String.IsNullOrEmpty(xpidlInterface.BaseName) && !String.Equals(xpidlInterface.BaseName, XpidlType.nsISupports))
			{
				codeInterfaceDeclaration.BaseTypes.Add(xpidlInterface.BaseName);

				var baseInterfaceMembers = new CodeSnippetTypeMember();
				baseInterfaceMembers.Comments.Add(
					new CodeCommentStatement(new CodeComment(String.Format("TODO: declare {0} members here", xpidlInterface.BaseName), false)));

				baseInterfaceMembers.StartDirectives.Add(
					new CodeRegionDirective(CodeRegionMode.Start, String.Format("{0} Members", xpidlInterface.BaseName)));
				baseInterfaceMembers.EndDirectives.Add(
					new CodeRegionDirective(CodeRegionMode.End, null));

				codeInterfaceDeclaration.Members.Add(baseInterfaceMembers);
			}

			// Add [ComImport] attribute
			var comImportAttributeDeclaration =
				new CodeAttributeDeclaration(
					new CodeTypeReference(typeof(ComImportAttribute)));
			codeInterfaceDeclaration.CustomAttributes.Add(comImportAttributeDeclaration);

			// Add [Guid] attribute
			var guidAttributeDeclaration =
				new CodeAttributeDeclaration(
					new CodeTypeReference(typeof(GuidAttribute)),
					new CodeAttributeArgument(new CodePrimitiveExpression(xpidlInterface.Uuid.ToString())));
			codeInterfaceDeclaration.CustomAttributes.Add(guidAttributeDeclaration);

			// Add [InterfaceType] attribute
			var interfaceTypeAttributeDeclaration =
				new CodeAttributeDeclaration(
					new CodeTypeReference(typeof(InterfaceTypeAttribute)),
					new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(ComInterfaceType)), ComInterfaceType.InterfaceIsIUnknown.ToString())));
			codeInterfaceDeclaration.CustomAttributes.Add(interfaceTypeAttributeDeclaration);

			// Create interface members and get separate class for interface constants
			codeConstClassDeclaration = BuildCodeInterfaceDeclaration(codeInterfaceDeclaration, xpidlInterface);
			return codeInterfaceDeclaration;
		}
 internal ObjectFactoryCodeDomTreeGenerator(string outputAssemblyName)
 {
     CodeConstructor constructor;
     this._codeCompileUnit = new System.CodeDom.CodeCompileUnit();
     CodeNamespace namespace2 = new CodeNamespace("__ASP");
     this._codeCompileUnit.Namespaces.Add(namespace2);
     string name = "FastObjectFactory_" + Util.MakeValidTypeNameFromString(outputAssemblyName).ToLower(CultureInfo.InvariantCulture);
     this._factoryClass = new CodeTypeDeclaration(name);
     this._factoryClass.TypeAttributes &= ~TypeAttributes.Public;
     CodeSnippetTypeMember member = new CodeSnippetTypeMember(string.Empty) {
         LinePragma = new CodeLinePragma(@"c:\\dummy.txt", 1)
     };
     this._factoryClass.Members.Add(member);
     constructor = new CodeConstructor {
         Attributes = constructor.Attributes | MemberAttributes.Private
     };
     this._factoryClass.Members.Add(constructor);
     namespace2.Types.Add(this._factoryClass);
 }
Esempio n. 12
0
		public void Constructor0 ()
		{
			CodeSnippetTypeMember cstm = new CodeSnippetTypeMember ();

			Assert.AreEqual (MemberAttributes.Private | MemberAttributes.Final,
				cstm.Attributes, "#1");

			Assert.IsNotNull (cstm.Comments, "#2");
			Assert.AreEqual (0, cstm.Comments.Count, "#3");

			Assert.IsNotNull (cstm.CustomAttributes, "#4");
			Assert.AreEqual (0, cstm.CustomAttributes.Count, "#5");

#if NET_2_0
			Assert.IsNotNull (cstm.StartDirectives, "#6");
			Assert.AreEqual (0, cstm.StartDirectives.Count, "#7");

			Assert.IsNotNull (cstm.EndDirectives, "#8");
			Assert.AreEqual (0, cstm.EndDirectives.Count, "#9");
#endif

			Assert.IsNotNull (cstm.Text, "#10");
			Assert.AreEqual (string.Empty, cstm.Text, "#11");

			Assert.IsNull (cstm.LinePragma, "#12");

			Assert.IsNotNull (cstm.Name, "#13");
			Assert.AreEqual (string.Empty, cstm.Name, "#14");

			Assert.IsNotNull (cstm.UserData, "#15");
			Assert.AreEqual (typeof(ListDictionary), cstm.UserData.GetType (), "#16");
			Assert.AreEqual (0, cstm.UserData.Count, "#17");

			cstm.Name = null;
			Assert.IsNotNull (cstm.Name, "#18");
			Assert.AreEqual (string.Empty, cstm.Name, "#19");

			CodeLinePragma clp = new CodeLinePragma ("mono", 10);
			cstm.LinePragma = clp;
			Assert.IsNotNull (cstm.LinePragma, "#20");
			Assert.AreSame (clp, cstm.LinePragma, "#21");
		}
    internal ObjectFactoryCodeDomTreeGenerator(string outputAssemblyName) {

        _codeCompileUnit = new CodeCompileUnit();

        CodeNamespace sourceDataNamespace = new CodeNamespace(
            BaseCodeDomTreeGenerator.internalAspNamespace);
        _codeCompileUnit.Namespaces.Add(sourceDataNamespace);

        // Make the class name vary based on the assembly (VSWhidbey 363214)
        string factoryClassName = factoryClassNameBase +
            Util.MakeValidTypeNameFromString(outputAssemblyName).ToLower(CultureInfo.InvariantCulture);

        // Create a single class, in which a method will be added for each
        // type that needs to be fast created in this assembly
        _factoryClass = new CodeTypeDeclaration(factoryClassName);

        // Make the class internal (VSWhidbey 363214)
        _factoryClass.TypeAttributes &= ~TypeAttributes.Public;

        // We generate a dummy line pragma, just so it will end with a '#line hidden'
        // and prevent the following generated code from ever being treated as user
        // code.  We need to use this hack because CodeDOM doesn't allow simply generating
        // a '#line hidden'. (VSWhidbey 199384)
        CodeSnippetTypeMember dummySnippet = new CodeSnippetTypeMember(String.Empty);
#if !PLATFORM_UNIX /// Unix file system
        // CORIOLISTODO: Unix file system
        dummySnippet.LinePragma = new CodeLinePragma(@"c:\\dummy.txt", 1);
#else // !PLATFORM_UNIX
        dummySnippet.LinePragma = new CodeLinePragma(@"/dummy.txt", 1);
#endif // !PLATFORM_UNIX
        _factoryClass.Members.Add(dummySnippet);

        // Add a private default ctor to make the class non-instantiatable (VSWhidbey 340829)
        CodeConstructor ctor = new CodeConstructor();
        ctor.Attributes |= MemberAttributes.Private;
        _factoryClass.Members.Add(ctor);

        sourceDataNamespace.Types.Add(_factoryClass);
    }
        internal string GenerateSimpleType(
            XmlSchemaSimpleType type, 
            CodeCompileUnit compileUnit, 
            CodeNamespace mainNamespace, 
            CodeGenerationOptions options, 
            CodeDomProvider codeProvider)
        {
            CodeTypeDeclaration codeClass = CodeDomHelper.CreateClassDeclaration(type);
            mainNamespace.Types.Add(codeClass);

            CodeDomHelper.GenerateXmlTypeAttribute(codeClass, type.QualifiedName.Name, type.QualifiedName.Namespace);

            XmlSchemaSimpleTypeRestriction restriction = type.Content as XmlSchemaSimpleTypeRestriction;

            Type baseType = XsdToClrPrimitive(restriction.BaseTypeName);
            CodeMemberField field = CodeDomHelper.AddField(codeClass, "value", baseType);

            CodeMemberProperty prop = CodeDomHelper.AddPropertyDeclaration(codeClass, field, "Value", baseType);
            CodeDomHelper.AddTextAttribute(prop.CustomAttributes);

            CodeDomHelper.AddCtor(codeClass);
            CodeDomHelper.AddCtor(codeClass, prop);

            // for each facet we support, add validation to the setter
            foreach (object facet in restriction.Facets)
            {
                XmlSchemaLengthFacet length = facet as XmlSchemaLengthFacet;
                if (length != null)
                {
                    int? value = ToInt32(length.Value);
                    if (value.HasValue)
                    {
                        CodeExpression valueLength = CodeDomHelper.Property(CodeDomHelper.Value(), "Length");
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(valueLength, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(value));
                        prop.SetStatements.Add(new CodeConditionStatement(condition, new CodeStatement[] { CodeDomHelper.ThrowFacetViolation("length", value) }, new CodeStatement[0]));
                    }
                    continue;
                }

                XmlSchemaPatternFacet pattern = facet as XmlSchemaPatternFacet;
                if (pattern != null)
                {
                    // TODO: might want ot validate the pattern value here to make sure that it is a valid Regex.
                    if (!string.IsNullOrEmpty(pattern.Value))
                    {
                        CodeExpression patternMatch = 
                            CodeDomHelper.MethodCall( 
                                CodeDomHelper.TypeExpr(typeof(Regex)), "IsMatch", new CodeExpression[] { CodeDomHelper.Value(), CodeDomHelper.Primitive(pattern.Value) });

                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(patternMatch, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(true));
                        prop.SetStatements.Add(new CodeConditionStatement(condition, new CodeStatement[] { CodeDomHelper.ThrowFacetViolation("pattern", pattern.Value) }, new CodeStatement[0]));
                    }
                    continue;
                }

                XmlSchemaMinLengthFacet minLength = facet as XmlSchemaMinLengthFacet;
                if (minLength != null)
                {
                    int? value = ToInt32(minLength.Value);
                    if (value.HasValue)
                    {
                        CodeExpression valueLength = CodeDomHelper.Property(CodeDomHelper.Value(), "Length");
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(valueLength, CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(value));
                        prop.SetStatements.Add(new CodeConditionStatement(condition, new CodeStatement[] { CodeDomHelper.ThrowFacetViolation("minLength", value) }, new CodeStatement[0]));
                    }
                    continue;
                }

                XmlSchemaMaxLengthFacet maxLength = facet as XmlSchemaMaxLengthFacet;
                if (maxLength != null)
                {
                    int? value = ToInt32(maxLength.Value);
                    if (value.HasValue)
                    {
                        CodeExpression valueLength = CodeDomHelper.Property(CodeDomHelper.Value(), "Length");
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(valueLength, CodeBinaryOperatorType.GreaterThan, new CodePrimitiveExpression(value));
                        prop.SetStatements.Add(new CodeConditionStatement(condition, new CodeStatement[] { CodeDomHelper.ThrowFacetViolation("maxLength", value) }, new CodeStatement[0]));
                    }
                    continue;
                }
            }

            //add ToSrting() Overload and implicit and explicit Cast operators for compatibilty woth previously generated code

            CodeMemberMethod toString = CodeDomHelper.MethodDecl(typeof(string), "ToString", MemberAttributes.Public | MemberAttributes.Override);
            toString.Statements.Add(CodeDomHelper.Return(CodeDomHelper.Property("value")));
            codeClass.Members.Add(toString);

            // Unfortunately CodeDom does not support operators, so we have to use CodeSnippet to generate the Cast operators
            // CodeSnippet is not language aware, so we have to use different snippets for different providers
            // this version only support c# syntax
            if (codeProvider is Microsoft.CSharp.CSharpCodeProvider)
            {
                string implicitCast = string.Format("    public static implicit operator {0}({1} x) {{ return new {0}(x); }}", codeClass.Name, baseType.FullName);
                CodeSnippetTypeMember implicitOp = new CodeSnippetTypeMember(implicitCast);
                codeClass.Members.Add(implicitOp);

                string explicitCast = string.Format("    public static explicit operator {1}({0} x) {{ return x.Value; }}", codeClass.Name, baseType.FullName);
                CodeSnippetTypeMember explicitOp = new CodeSnippetTypeMember(explicitCast);
                codeClass.Members.Add(explicitOp);
            }

            return codeClass.Name;
        }
Esempio n. 15
0
        /// <summary>
        /// Generate Cast method in CodeDom and add it in reference class
        /// </summary>
        /// <param name="si">The service interface this grain reference type is being generated for</param>
        /// <param name="isFactory">whether the class being generated is a factory class rather than a grainref implementation</param>
        /// <param name="referenceClass">The class being generated for this grain reference type</param>
        protected override void AddCastMethods(GrainInterfaceData si, bool isFactory, CodeTypeDeclaration referenceClass)
        {
            string castImplCode;
            string checkCode = null;
            if (isFactory)
            {
                castImplCode = string.Format(@"{0}.Cast(grainRef)", si.ReferenceClassName);

                if (si.IsSystemTarget)
                    checkCode = @"if(!((global::Orleans.Runtime.GrainReference)grainRef).IsInitializedSystemTarget)
                        throw new InvalidOperationException(""InvalidCastException cast of a system target grain reference. Must have SystemTargetSilo set to the target silo address"");";
            }
            else
            {
                castImplCode = string.Format(
                    @"({0}) global::Orleans.Runtime.GrainReference.CastInternal(typeof({0}), (global::Orleans.Runtime.GrainReference gr) => {{ return new {1}(gr);}}, grainRef, {2})",
                    si.InterfaceTypeName, // Interface type for references for this grain
                    si.ReferenceClassName, // Concrete class for references for this grain
                    GrainInterfaceData.GetGrainInterfaceId(si.Type));
            }

            var methodImpl = string.Format(@"
            {3} static {0} Cast(global::Orleans.Runtime.IAddressable grainRef)
            {{
                {1}
                return {2};
            }}", si.InterfaceTypeName, checkCode, castImplCode, "public");

            var castMethod = new CodeSnippetTypeMember(methodImpl);
            referenceClass.Members.Add(castMethod);
        }
Esempio n. 16
0
        protected override void AddCreateObjectReferenceMethods(GrainInterfaceData grainInterfaceData, CodeTypeDeclaration factoryClass)
        {
            var fieldImpl = @"
        private static global::Orleans.CodeGeneration.IGrainMethodInvoker methodInvoker;";
            var invokerField = new CodeSnippetTypeMember(fieldImpl);
            factoryClass.Members.Add(invokerField);

            var methodImpl = String.Format(@"
        public async static System.Threading.Tasks.Task<{0}> CreateObjectReference({0} obj)
        {{
            if (methodInvoker == null) methodInvoker = new {2}();
            return {1}.Cast(await global::Orleans.Runtime.GrainReference.CreateObjectReference(obj, methodInvoker));
        }}", grainInterfaceData.TypeName, grainInterfaceData.FactoryClassName, grainInterfaceData.InvokerClassName);
            var createObjectReferenceMethod = new CodeSnippetTypeMember(methodImpl);
            factoryClass.Members.Add(createObjectReferenceMethod);

            methodImpl = String.Format(@"
        public static System.Threading.Tasks.Task DeleteObjectReference({0} reference)
        {{
            return global::Orleans.Runtime.GrainReference.DeleteObjectReference(reference);
        }}",
            grainInterfaceData.TypeName);
            var deleteObjectReferenceMethod = new CodeSnippetTypeMember(methodImpl);
            factoryClass.Members.Add(deleteObjectReferenceMethod);
        }
Esempio n. 17
0
            public CodeCompileUnit GenerateCode(string typeName, string codeBody,
                                       StringCollection imports,
                                       string prefix)
            {
                CodeCompileUnit compileUnit = new CodeCompileUnit();

                CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(typeName);
                typeDecl.IsClass = true;
                typeDecl.TypeAttributes = TypeAttributes.Public;

                // create constructor
                CodeConstructor constructMember = new CodeConstructor();
                constructMember.Attributes = MemberAttributes.Public;
                constructMember.Parameters.Add(new CodeParameterDeclarationExpression("NAnt.Core.Project", "project"));
                constructMember.Parameters.Add(new CodeParameterDeclarationExpression("NAnt.Core.PropertyDictionary", "propDict"));

                constructMember.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("project"));
                constructMember.BaseConstructorArgs.Add(new CodeVariableReferenceExpression ("propDict"));
                typeDecl.Members.Add(constructMember);

                typeDecl.BaseTypes.Add(typeof(FunctionSetBase));

                // add FunctionSet attribute
                CodeAttributeDeclaration attrDecl = new CodeAttributeDeclaration("FunctionSet");
                attrDecl.Arguments.Add(new CodeAttributeArgument(
                    new CodeVariableReferenceExpression("\"" + prefix + "\"")));
                attrDecl.Arguments.Add(new CodeAttributeArgument(
                    new CodeVariableReferenceExpression("\"" + prefix + "\"")));

                typeDecl.CustomAttributes.Add(attrDecl);

                // pump in the user specified code as a snippet
                CodeSnippetTypeMember literalMember =
                    new CodeSnippetTypeMember(codeBody);
                typeDecl.Members.Add( literalMember );

                CodeNamespace nspace = new CodeNamespace();

                //Add default imports
                foreach (string nameSpace in ScriptTask._defaultNamespaces) {
                    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;
            }
        private void AddCodeSnippet(string codeText, int lineNum)
        {
            if (codeText == null || codeText.Trim().Length == 0)
                return;

            CodeSnippetTypeMember snippet = new CodeSnippetTypeMember();
            AddLinePragma(snippet, lineNum);
            snippet.Text = codeText;
            _ccRoot.CodeClass.Members.Add(snippet);
        }
Esempio n. 19
0
 protected override void GenerateSnippetMember(CodeSnippetTypeMember e)
 {
     base.Output.Write(e.Text);
 }
Esempio n. 20
0
		protected override void GenerateSnippetMember (CodeSnippetTypeMember e)
		{
		}
Esempio n. 21
0
		protected override void GenerateSnippetMember (CodeSnippetTypeMember member)
		{
			Output.Write (member.Text);
		}
    /*
     * Build various properties, fields, methods
     */
    protected virtual void BuildMiscClassMembers() {

        // Build the Profile property
        if (NeedProfileProperty)
            BuildProfileProperty();

        // Skip the rest if we're only generating the intermediate class
        if (_sourceDataClass == null)
            return;

        // Build the injected properties from the global.asax <object> tags
        BuildApplicationObjectProperties();
        BuildSessionObjectProperties();

        // Build the injected properties for objects scoped to the page
        BuildPageObjectProperties();

        // Add all the <script runat=server> code blocks
        foreach (ScriptBlockData script in Parser.ScriptList) {

            // Pad the code block so its generated offset matches the aspx
            string code = script.Script;
            code = code.PadLeft(code.Length + script.Column - 1);

            CodeSnippetTypeMember literal = new CodeSnippetTypeMember(code);
            literal.LinePragma = CreateCodeLinePragma(script.VirtualPath, script.Line,
                script.Column, script.Column, script.Script.Length, false);
            _sourceDataClass.Members.Add(literal);
        }
    }
Esempio n. 23
0
 protected override void GenerateSnippetMember(System.CodeDom.CodeSnippetTypeMember e)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Esempio n. 24
0
        /// <summary>
        /// Generates the tracking changes classes.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<CodeTypeDeclaration> GenerateTrackingChangesClasses()
        {
            var classList = new List<CodeTypeDeclaration>();

            classList.Add(CreateObjectsToCollectionProperties("ObjectsOriginalFromCollectionProperties", "Dictionary<string, ObjectList>"));
            classList.Add(CreateObjectsToCollectionProperties("ObjectsAddedToCollectionProperties", "Dictionary<string, ObjectList>"));
            classList.Add(CreateObjectsToCollectionProperties("ObjectsRemovedFromCollectionProperties", "Dictionary<string, ObjectList>"));
            classList.Add(CreateObjectsToCollectionProperties("PropertyValueStatesDictionary", "Dictionary<string, PropertyValueState>"));

            // TrackableCollection
            var trackableCollectionClass = new CodeTypeDeclaration("TrackableCollection")
            {
                IsClass = true,
                IsPartial = false,
                TypeAttributes = TypeAttributes.Public,
            };
            trackableCollectionClass.TypeParameters.Add(new CodeTypeParameter("T"));
            var ctr = new CodeTypeReference("ObservableCollection");
            ctr.TypeArguments.Add("T");

            trackableCollectionClass.BaseTypes.Add(ctr);

            var codeTemplate = new CodeSnippetTypeMember();
            codeTemplate.Text = Resources.TrackableCollection_cs;
            trackableCollectionClass.Members.Add(codeTemplate);
            trackableCollectionClass.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "TrackableCollection class"));
            trackableCollectionClass.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "TrackableCollection"));
            classList.Add(trackableCollectionClass);

            // ObjectChangeTracker class
            var trackableClass = new CodeTypeDeclaration("ObjectChangeTracker")
            {
                IsClass = true,
                IsPartial = false,
                TypeAttributes = TypeAttributes.Public,
            };
            trackableClass.BaseTypes.Add(typeof(INotifyPropertyChanged));
            var cm = new CodeSnippetTypeMember();
            cm.Text = Resources.ObjectChangeTracker_cs;
            trackableClass.Members.Add(cm);
            trackableClass.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Tracking changes class"));
            trackableClass.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "Tracking changes class"));
            classList.Add(trackableClass);

            var notifyTrackableDelegate = new CodeTypeDelegate("NotifyTrackableCollectionChangedEventHandler");
            notifyTrackableDelegate.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "sender"));
            notifyTrackableDelegate.Parameters.Add(new CodeParameterDeclarationExpression("NotifyCollectionChangedEventArgs", "e"));
            notifyTrackableDelegate.Parameters.Add(new CodeParameterDeclarationExpression("system.string", "propertyName"));
            notifyTrackableDelegate.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "NotifyTrackableCollectionChangedEventHandler class"));
            notifyTrackableDelegate.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "NotifyTrackableCollectionChangedEventHandler"));
            classList.Add(notifyTrackableDelegate);

            // enum ObjectState
            var objectStateenum = new CodeTypeDeclaration("ObjectState")
                            {
                                IsEnum = true,
                                TypeAttributes = TypeAttributes.Public
                            };
            // Creates the enum member
            objectStateenum.Members.Add(new CodeMemberField(typeof(int), "Unchanged"));
            objectStateenum.Members.Add(new CodeMemberField(typeof(int), "Added"));
            objectStateenum.Members.Add(new CodeMemberField(typeof(int), "Modified"));
            objectStateenum.Members.Add(new CodeMemberField(typeof(int), "Deleted"));
            objectStateenum.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "ObjectState enum"));
            objectStateenum.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "ObjectState"));
            classList.Add(objectStateenum);


            // ObjectList class
            var ObjectListClass = new CodeTypeDeclaration("ObjectList")
            {
                IsClass = true,
                IsPartial = false,
                TypeAttributes = TypeAttributes.Public,
            };

            ctr = new CodeTypeReference("List");
            ctr.TypeArguments.Add(typeof(object));
            ObjectListClass.BaseTypes.Add(ctr);
            ObjectListClass.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "ObjectList class"));
            ObjectListClass.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "ObjectList"));
            classList.Add(ObjectListClass);

            // ObjectStateChangingEventArgs class
            var objectStateChangingEventArgsClass = new CodeTypeDeclaration("ObjectStateChangingEventArgs")
            {
                IsClass = true,
                IsPartial = false,
                TypeAttributes = TypeAttributes.Public,
            };

            ctr = new CodeTypeReference("EventArgs");
            objectStateChangingEventArgsClass.BaseTypes.Add(ctr);

            codeTemplate = new CodeSnippetTypeMember();
            codeTemplate.Text = Resources.ObjectStateChangingEventArgs_cs;
            objectStateChangingEventArgsClass.Members.Add(codeTemplate);
            objectStateChangingEventArgsClass.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "ObjectStateChangingEventArgs class"));
            objectStateChangingEventArgsClass.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "ObjectStateChangingEventArgs"));
            classList.Add(objectStateChangingEventArgsClass);

            // ObjectChangeTracker class
            var propertyValueStateClass = new CodeTypeDeclaration("PropertyValueState")
            {
                IsClass = true,
                IsPartial = false,
                TypeAttributes = TypeAttributes.Public,
            };
            cm = new CodeSnippetTypeMember();
            cm.Text = Resources.PropertyValueState_cs;
            propertyValueStateClass.Members.Add(cm);
            propertyValueStateClass.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "PropertyValueState class"));
            propertyValueStateClass.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "PropertyValueState class"));
            classList.Add(propertyValueStateClass);

            return classList;
        }
Esempio n. 25
0
        private static CodeTypeDeclaration GenerateEntity(this Entity entity)
        {
            var type = new CodeTypeDeclaration(entity.Name)
            {
                TypeAttributes = TypeAttributes.Public,
                Attributes = MemberAttributes.Public
            };

            foreach (var i in entity.Interfaces.Where(x => !string.IsNullOrEmpty(x.Name)))
            {
                type.BaseTypes.Add(new CodeTypeReference(i.Name.Trim()));
            }

            var properties = new List<MessageProperty>(entity.Properties);

            foreach (var prop in properties.OrderBy(x => x.Optional))
            {
                var camelCased = prop.Name.CamelCased();
                var pascalCased = prop.Name.PascalCased();

                var property = new CodeSnippetTypeMember
                {
                    Text = $"public {prop.Type.SafeTypeName()} {pascalCased} "
                };
                property.Text += "{ get; set; }\n";
                type.Members.Add(property);
            }
            var expression = new Regex(@"\{(.+?)\}", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            if (!string.IsNullOrEmpty(entity.StringFormat))
            {
                var args = new List<CodeExpression>();
                var index = 0;
                foreach (Match match in expression.Matches(entity.StringFormat))
                {
                    entity.StringFormat = entity.StringFormat.Replace(match.ToString(), "{" + index++ + "}");
                    var propertyName = match.Groups[1].Value.PascalCased();
                    args.Add(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), propertyName));
                }

                args.Insert(0, new CodePrimitiveExpression(entity.StringFormat));

                type.Members.Add(new CodeMemberMethod
                {
                    Name = "ToString",
                    ReturnType = new CodeTypeReference(typeof(string)),
                    Attributes = MemberAttributes.Override | MemberAttributes.Public,
                    Statements =
                    {
                        new CodeMethodReturnStatement
                        {
                            Expression =
                                new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof (string)),
                                    "Format", args.ToArray())
                        }
                    }
                });
            }

            type.Members.Add(entity.AddSetPropertiesMethod(SetPropertiesType.Properties));

            return type;
        }
		protected override void GenerateSnippetMember(CodeSnippetTypeMember e)
		{
			Output.WriteLine("[CodeSnippetTypeMember: {0}]", e.ToString());
		}
Esempio n. 27
0
        // Add a new DryadLinqFactory subclass for a type
        internal void AddFactoryClass(Type type)
        {
            Type baseClass = typeof(DryadLinqFactory<>).MakeGenericType(type);
            string baseClassName = TypeSystem.TypeName(baseClass, this.AnonymousTypeToName);
            CodeTypeDeclaration factoryClass = new CodeTypeDeclaration(DryadLinqFactoryClassName(type) + " : " + baseClassName);
            this.m_dryadCodeSpace.Types.Add(factoryClass);
            factoryClass.IsClass = true;
            factoryClass.TypeAttributes = TypeAttributes.Public;

            // Add method MakeReader(IntPtr handle, UInt32 port):
            Type returnType = typeof(DryadLinqRecordReader<>).MakeGenericType(type);
            string returnTypeName = TypeSystem.TypeName(returnType, this.AnonymousTypeToName);
            StringBuilder mb1 = new StringBuilder();
            mb1.AppendLine("        public override " + returnTypeName + " MakeReader(System.IntPtr handle, uint port)");
            mb1.AppendLine("        {");
            mb1.AppendLine("            return new " + DryadReaderClassName(type) +
                           "(Microsoft.Research.DryadLinq.Internal.VertexEnv.MakeBinaryReader(handle, port));");
            mb1.AppendLine("        }");
            CodeTypeMember readerMethod1 = new CodeSnippetTypeMember(mb1.ToString());
            factoryClass.Members.Add(readerMethod1);

            // Add method MakeReader(NativeBlockStream stream):
            StringBuilder mb3 = new StringBuilder();
            mb3.AppendLine("        public override " + returnTypeName +
                           " MakeReader(Microsoft.Research.DryadLinq.Internal.NativeBlockStream stream)");
            mb3.AppendLine("        {");
            mb3.AppendLine("            return new " + DryadReaderClassName(type) +
                           "(Microsoft.Research.DryadLinq.Internal.VertexEnv.MakeBinaryReader(stream));");
            mb3.AppendLine("        }");
            CodeTypeMember readerMethod3 = new CodeSnippetTypeMember(mb3.ToString());
            factoryClass.Members.Add(readerMethod3);
            
            // Add method MakeWriter(IntPtr handle, UInt32 port, Int32 buffSize):
            returnType = typeof(DryadLinqRecordWriter<>).MakeGenericType(type);
            returnTypeName = TypeSystem.TypeName(returnType, this.AnonymousTypeToName);
            StringBuilder mb4 = new StringBuilder();
            mb4.AppendLine("        public override " + returnTypeName + " MakeWriter(System.IntPtr handle, uint port, int buffSize)");
            mb4.AppendLine("        {");
            mb4.AppendLine("            return new " + DryadWriterClassName(type) +
                           "(Microsoft.Research.DryadLinq.Internal.VertexEnv.MakeBinaryWriter(handle, port, buffSize));");
            mb4.AppendLine("        }");
            CodeTypeMember writerMethod1 = new CodeSnippetTypeMember(mb4.ToString());
            factoryClass.Members.Add(writerMethod1);
            
            // Add method MakeWriter(NativeBlockStream stream):
            StringBuilder mb6 = new StringBuilder();
            mb6.AppendLine("        public override " + returnTypeName + " MakeWriter(Microsoft.Research.DryadLinq.Internal.NativeBlockStream stream)");
            mb6.AppendLine("        {");
            mb6.AppendLine("            return new " + DryadWriterClassName(type) +
                           "(Microsoft.Research.DryadLinq.Internal.VertexEnv.MakeBinaryWriter(stream));");
            mb6.AppendLine("        }");
            CodeTypeMember writerMethod3 = new CodeSnippetTypeMember(mb6.ToString());
            factoryClass.Members.Add(writerMethod3);
        }
Esempio n. 28
0
        internal void AddScript(string source, ScriptingLanguage lang, string ns, string fileName, int lineNumber)
        {
            ValidateExtensionNamespace(ns);

            for (ScriptingLanguage langTmp = ScriptingLanguage.JScript; langTmp <= ScriptingLanguage.CSharp; langTmp++)
            {
                Hashtable typeDecls = _typeDeclsByLang[(int)langTmp];
                if (lang == langTmp)
                {
                    CodeTypeDeclaration scriptClass = (CodeTypeDeclaration)typeDecls[ns];
                    if (scriptClass == null)
                    {
                        scriptClass = new CodeTypeDeclaration(GenerateUniqueClassName());
                        scriptClass.TypeAttributes = TypeAttributes.Public;
                        typeDecls.Add(ns, scriptClass);
                    }
                    CodeSnippetTypeMember scriptSnippet = new CodeSnippetTypeMember(source);
                    if (lineNumber > 0)
                    {
                        scriptSnippet.LinePragma = new CodeLinePragma(fileName, lineNumber);
                        _scriptFiles.Add(fileName);
                    }
                    scriptClass.Members.Add(scriptSnippet);
                }
                else if (typeDecls.Contains(ns))
                {
                    throw XsltException.Create(SR.Xslt_ScriptMixedLanguages, ns);
                }
            }
        }
Esempio n. 29
0
			public void Visit (CodeSnippetTypeMember o)
			{
				g.GenerateSnippetMember (o);
			}
Esempio n. 30
0
            public CodeCompileUnit GenerateCode(string typeName, string codeBody,
                ITaskItem[] imports)
            {
                CodeCompileUnit compileUnit = new CodeCompileUnit();

                CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(typeName);
                typeDecl.IsClass = true;
                typeDecl.TypeAttributes = TypeAttributes.Public;

                // pump in the user specified code as a snippet
                CodeSnippetTypeMember literalMember =
                    new CodeSnippetTypeMember(codeBody);
                typeDecl.Members.Add(literalMember);

                CodeNamespace nspace = new CodeNamespace();

                //Add default imports
                foreach (string nameSpace in Script._defaultNamespaces)
                {
                    nspace.Imports.Add(new CodeNamespaceImport(nameSpace));
                }
                if (imports != null)
                {
                    foreach (ITaskItem item in imports)
                    {
                        string nameSpace = item.ItemSpec;
                        nspace.Imports.Add(new CodeNamespaceImport(nameSpace));
                    }
                }
                compileUnit.Namespaces.Add(nspace);
                nspace.Types.Add(typeDecl);

                return compileUnit;
            }
Esempio n. 31
0
		protected abstract void GenerateSnippetMember (CodeSnippetTypeMember m);