コード例 #1
0
		public void Ctor(string name, CodeExpression value)
		{
			if (string.IsNullOrEmpty(name))
			{
				var argument1 = new CodeAttributeArgument(value);
				Assert.Empty(argument1.Name);
				Assert.Equal(value, argument1.Value);
			}
			var argument2 = new CodeAttributeArgument(name, value);
			Assert.Equal(name ?? string.Empty, argument2.Name);
			Assert.Equal(value, argument2.Value);
		}
コード例 #2
0
		public void Ctor_String(string name, CodeAttributeArgument[] arguments)
		{
			if (arguments.Length == 0)
			{
				var declaration1 = new CodeAttributeDeclaration(name);
				Assert.Equal(name ?? string.Empty, declaration1.Name);
				Assert.Empty(declaration1.Arguments);
				Assert.Equal(new CodeTypeReference(name).BaseType, declaration1.AttributeType.BaseType);
			}
			var declaration2 = new CodeAttributeDeclaration(name, arguments);
			Assert.Equal(name ?? string.Empty, declaration2.Name);
			Assert.Equal(arguments, declaration2.Arguments.Cast<CodeAttributeArgument>());
			Assert.Equal(new CodeTypeReference(name).BaseType, declaration2.AttributeType.BaseType);
		}
コード例 #3
0
		public void Ctor_CodeTypeReference(CodeTypeReference attributeType, CodeAttributeArgument[] arguments)
		{
			if (arguments == null || arguments.Length == 0)
			{
				var declaration1 = new CodeAttributeDeclaration(attributeType);
				Assert.Equal(attributeType?.BaseType ?? string.Empty, declaration1.Name);
				Assert.Equal(attributeType, declaration1.AttributeType);
				Assert.Empty(declaration1.Arguments);
			}
			var declaration2 = new CodeAttributeDeclaration(attributeType, arguments);
			Assert.Equal(attributeType?.BaseType ?? string.Empty, declaration2.Name);
			Assert.Equal(attributeType, declaration2.AttributeType);
			Assert.Equal(arguments ?? new CodeAttributeArgument[0], declaration2.Arguments.Cast<CodeAttributeArgument>());
		}
	// Methods
	public int Add(CodeAttributeArgument value) {}
	public void Remove(CodeAttributeArgument value) {}
コード例 #6
0
		public void Value_Set_Get_ReturnsExpected(CodeExpression value)
		{
			var argument = new CodeAttributeArgument();
			argument.Value = value;
			Assert.Equal(value, argument.Value);
		}
コード例 #7
0
		public void Arguments_AddMultiple_ReturnsExpected()
		{
			var declaration = new CodeAttributeDeclaration();

			CodeAttributeArgument argument1 = new CodeAttributeArgument(new CodePrimitiveExpression("Value1"));
			declaration.Arguments.Add(argument1);
			Assert.Equal(new CodeAttributeArgument[] { argument1 }, declaration.Arguments.Cast<CodeAttributeArgument>());

			CodeAttributeArgument argument2 = new CodeAttributeArgument(new CodePrimitiveExpression("Value2"));
			declaration.Arguments.Add(argument2);
			Assert.Equal(new CodeAttributeArgument[] { argument1, argument2 }, declaration.Arguments.Cast<CodeAttributeArgument>());
		}
コード例 #8
0
        public static List <string> GetAttributes(CodeTypeDeclaration ctd, List <string> usingDirectives)
        {
            List <string> custom = new List <string>();

            try
            {
                foreach (CodeAttributeDeclaration cd in ctd.CustomAttributes)
                {
                    string ca = "[";
                    ca = ca + Format.UsingDirectiveReduction(cd.Name, usingDirectives);
                    if (cd.Arguments.Count > 0)
                    {
                        ca = ca + "(";
                        for (int i = 0; i < cd.Arguments.Count; i++)
                        {
                            CodeAttributeArgument aa = cd.Arguments[i];
                            if (aa.Value.GetType() == typeof(CodePrimitiveExpression))
                            {
                                CodePrimitiveExpression pe = (CodePrimitiveExpression)aa.Value;
                                string prefix = "";
                                if (pe.Value.ToString().Contains("http"))
                                {
                                    prefix = "Namespace=";
                                }
                                if (i == cd.Arguments.Count - 1)
                                {
                                    ca = ca + prefix + "\"" + pe.Value + "\"";
                                }
                                else
                                {
                                    ca = ca + prefix + "\"" + pe.Value + "\", ";
                                }
                            }
                            else if (aa.Value.GetType() == typeof(CodeTypeOfExpression))
                            {
                                CodeTypeOfExpression te = (CodeTypeOfExpression)aa.Value;
                                ca = ca + "typeof(" + te.Type.BaseType + ")";
                            }
                            else
                            {
                            }
                        }
                        ca = ca + ")";
                    }
                    else
                    {
                        ca = ca + "()";
                    }
                    ca = ca + "]";
                    custom.Add(ca);
                }
            }
            catch (Exception ae)
            {
                string strError = ae.ToString();
                if (ae.InnerException != null)
                {
                    strError = ae.InnerException.Message.ToString();
                }
            }

            return(custom);
        }
コード例 #9
0
 public VsBindingSourceAttributeValueProvider(CodeAttributeArgument customAttributeArgument)
 {
     this.customAttributeArgument = customAttributeArgument;
 }
コード例 #10
0
        /// <summary>
        /// Generates the metadata class for the given object (entity or complex object)
        /// </summary>
        /// <param name="codeGenContext">The context to use to generate code.</param>
        /// <param name="optionalSuffix">If not null, optional suffix to class name and namespace</param>
        /// <param name="type">The type of the object for which to generate the metadata class.</param>
        /// <returns><c>true</c> means at least some code was generated.</returns>
        public bool GenerateMetadataClass(CodeGenContext codeGenContext, string optionalSuffix, Type type)
        {
            // If already have a buddy class, bypass all this logic
            // Use soft dependency (string name) to avoid static dependency on DataAnnotations.
            // We do this because this wizard must run from the GAC, and DataAnnotations will not necessarily be in the GAC too.
            Type buddyClassType = TypeUtilities.GetAssociatedMetadataType(type);

            if (buddyClassType != null)
            {
                return(false);
            }

            string className      = type.Name;
            string classNamespace = type.Namespace;

            bool addSuffix = !string.IsNullOrEmpty(optionalSuffix);

            if (addSuffix)
            {
                className      += optionalSuffix;
                classNamespace += optionalSuffix;
            }

            // Every object could have a unique namespace (odd, but true)
            // So we logically create a new namespace for each object.  Those
            // sharing a namespace will reuse the CodeNamespace.
            // We allow the caller to specify in case it needs to override that
            // namespace.  Unit testing is such a scenario
            CodeNamespace codeNamespace = codeGenContext.GetOrGenNamespace(classNamespace);

            // If we redirected to a different namespace than the object, import the real object's namespace
            if (addSuffix)
            {
                CodeGenUtilities.AddImportIfNeeded(codeNamespace, type.Namespace);
            }

            // Name of buddy class is $objectClassName$Metadata (e.g. Orders --> OrdersMetadata)
            string buddyClassName = className + "Metadata";

            // We use the full outer.inner type naming convention for VB because they cannot resolve it otherwise.
            // C# can currently resolve it due to a bug in the compiler, but it is safer to use the legal syntax here.
            string fullBuddyClassName = className + "." + buddyClassName;

            CodeTypeDeclaration objectClass = null;

            // public class $objectType$ { }
            objectClass                = CodeGenUtilities.CreateTypeDeclaration(className, classNamespace);
            objectClass.IsPartial      = true;
            objectClass.TypeAttributes = TypeAttributes.Public;

            // Add explanatory comments about what the [MetadataTypeAttribute] does
            objectClass.Comments.Add(new CodeCommentStatement(String.Format(CultureInfo.CurrentCulture, Resources.BusinessLogicClass_Entity_Partial_Class_Remarks, buddyClassName, className), false));

            // [MetadataType(typeof($objectType$.$objectType$_Metadata))]
            CodeAttributeDeclaration attr = CodeGenUtilities.CreateAttributeDeclaration(BusinessLogicClassConstants.MetadataTypeAttributeTypeName);

            CodeAttributeArgument attrArg = new CodeAttributeArgument(new CodeTypeOfExpression(fullBuddyClassName));

            attr.Arguments.Add(attrArg);
            objectClass.CustomAttributes.Add(attr);

            // public sealed class $objectType$_Metadata { }
            // (note: cannot set 'static' modified from CodeDom.)
            CodeTypeDeclaration buddyClass = CodeGenUtilities.CreateTypeDeclaration(buddyClassName, classNamespace);

            // Both VB and C# use a friend/public buddy class.  A private buddy class does not
            // compile in VB, and it compiles in C# only due to a bug.
            buddyClass.TypeAttributes = TypeAttributes.Sealed | TypeAttributes.NestedAssembly;
            bool generatedProperty = false;

            // Generate a developer comment describing what this class does
            buddyClass.Comments.Add(new CodeCommentStatement(String.Format(CultureInfo.CurrentCulture, Resources.Buddy_Class_Remarks, type.Name)));

            // Add a language-specific example
            string explanation = codeGenContext.IsCSharp ? Resources.Buddy_Class_Remarks_CSharp : Resources.Buddy_Class_Remarks_VB;

            buddyClass.Comments.Add(new CodeCommentStatement(explanation, false));

            // Generate a private ctor to make it impossible to instantiate this class
            CodeConstructor ctor = new CodeConstructor();

            ctor.Attributes = MemberAttributes.Private;
            ctor.Comments.Add(new CodeCommentStatement(Resources.BusinessLogicClass_Private_Ctor_Comment));
            buddyClass.Members.Add(ctor);

            // Sort by name order for baseline predictability
            foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).OrderBy(p => p.Name))
            {
                // CodeDom does not support auto-implemented properties, so we will generate fields and then transform them into properties
                Type propType = propertyInfo.PropertyType;
                if (propType.IsVisible && propertyInfo.GetGetMethod() != null && this.CanGeneratePropertyOfType(propType))
                {
                    // Add an import for this property type's namespace if needed
                    CodeGenUtilities.AddImportIfNeeded(codeNamespace, propertyInfo.PropertyType.Namespace);

                    CodeSnippetTypeMember property = CodeGenUtilities.CreateAutomaticPropertyDeclaration(codeGenContext, buddyClass, propertyInfo, !string.IsNullOrEmpty(codeNamespace.Name) /* insideNamespace */);

                    buddyClass.Members.Add(property);
                    generatedProperty = true;
                }
            }

            // Don't generate anything if the buddy class is empty
            if (generatedProperty)
            {
                // Add the partial object class to the namespace
                codeNamespace.Types.Add(objectClass);

                // Add the metadata class as a nested class inside the partial object class
                objectClass.Members.Add(buddyClass);
            }

            // false if no properties were generated, indicating no code should be emitted
            return(generatedProperty);
        }
 public bool Contains(CodeAttributeArgument value)
 {
 }
 // Methods
 public int Add(CodeAttributeArgument value)
 {
 }
 public void Ctor_NullObjectInArguments_ThrowsArgumentNullException()
 {
     CodeAttributeArgument[] arguments = new CodeAttributeArgument[] { null };
     AssertExtensions.Throws <ArgumentNullException>("value", () => new CodeAttributeDeclaration("name", arguments));
     AssertExtensions.Throws <ArgumentNullException>("value", () => new CodeAttributeDeclaration(new CodeTypeReference(), arguments));
 }
コード例 #14
0
        private void CreateServiceType()
        {
            // We can create the service type(s) only if we have one or more service
            // contract.
            if (code.ServiceContracts.Count > 0)
            {
                // Take a reference to the first ServiceContract available.
                // IMPORTANT!:(Currently we only support single service type)
                // May be want to support multiple service contracts in the next version.
                CodeTypeExtension srvContract = code.ServiceContracts[0];
                // Notify if srvContract is null. This would mean that we have constructed a bad
                // GeneratedCode instance from our CodeFactory.
                Debug.Assert(srvContract != null, "Generated service contract could not be null.");

                // Construct the service type name by removing the leading "I" character from
                // the service contract name that was added for generation of the interface.
                string srvTypeName = srvContract.ExtendedObject.Name.Substring(1);

                // Create a new instance of CodeTypeDeclaration type representing the service type.
                CodeTypeDeclaration srvType = new CodeTypeDeclaration(srvTypeName);

                // Also wrap the CodeTypeDeclaration in an extension.
                CodeTypeExtension typeExt = new CodeTypeExtension(srvType);

                // This class.
                srvType.IsClass = true;

                switch (options.MethodImplementation)
                {
                case MethodImplementation.PartialClassMethodCalls:
                    // The service type is partial so that the implementation methods can be written in separate file.
                    srvType.IsPartial = true;
                    break;

                case MethodImplementation.AbstractMethods:
                    // The service type is abstract so that the operation methods can be made abstract.
                    srvType.TypeAttributes |= TypeAttributes.Abstract;
                    break;
                }

                // And this implements the service contract interface.
                if (code.CodeLanguauge == CodeLanguage.VisualBasic)
                {
                    srvType.Members.Add(new CodeSnippetTypeMember("Implements " + srvContract.ExtendedObject.Name));
                }
                else
                {
                    srvType.BaseTypes.Add(new CodeTypeReference(srvContract.ExtendedObject.Name));
                }

                // Now itterate the srvContractObject.Members and add each and every method in
                // the service contract type to the new type being created.
                foreach (CodeTypeMemberExtension methodExtension in srvContract.Methods)
                {
                    // Get a referece to the actual CodeMemberMethod object extended
                    // by ext.
                    CodeMemberMethod method = methodExtension.ExtendedObject as CodeMemberMethod;

                    // Create a new CodeMemeberMethod and copy the attributes.
                    CodeMemberMethod newMethod = new CodeMemberMethod();
                    newMethod.Name = method.Name;

                    // Implemented method has to be public.
                    newMethod.Attributes = MemberAttributes.Public;

                    // Notify that this member is implementing a method in the service contract.
                    if (code.CodeLanguauge == CodeLanguage.VisualBasic)
                    {
                        newMethod.ImplementationTypes.Add(new CodeTypeReference(srvContract.ExtendedObject.Name));
                    }
                    else
                    {
                        newMethod.ImplementationTypes.Add(srvType.BaseTypes[0]);
                    }

                    // Add all parametes to the newly created method.
                    foreach (CodeParameterDeclarationExpression cpde in method.Parameters)
                    {
                        newMethod.Parameters.Add(cpde);
                    }

                    // Set the return type.
                    newMethod.ReturnType = method.ReturnType;

                    switch (options.MethodImplementation)
                    {
                    case MethodImplementation.PartialClassMethodCalls:
                    {
                        // Gather the parameters from the operation to pass into the implementation method.
                        IEnumerable <CodeArgumentReferenceExpression> parameters = newMethod.Parameters
                                                                                   .OfType <CodeParameterDeclarationExpression>()
                                                                                   .Select(p => new CodeArgumentReferenceExpression(p.Name));

                        // Create an expression to invoke the implementation method.
                        CodeMethodInvokeExpression methodInvocation = new CodeMethodInvokeExpression(null, newMethod.Name + "Implementation", parameters.ToArray());

                        // Check if the method has a return type.
                        if (newMethod.ReturnType.BaseType != "System.Void")
                        {
                            // Make sure the call to the implementation method is returned.
                            CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement(methodInvocation);
                            newMethod.Statements.Add(returnStatement);
                        }
                        else
                        {
                            // Add the call to the implementation method without a return.
                            newMethod.Statements.Add(methodInvocation);
                        }
                    }
                    break;

                    case MethodImplementation.NotImplementedException:
                    {
                        // Create a new code statement to throw NotImplementedExcption.
                        CodeThrowExceptionStatement niex = new CodeThrowExceptionStatement(
                            new CodeObjectCreateExpression(
                                new CodeTypeReference(typeof(NotImplementedException)), new CodeExpression[] { })
                            );

                        // Add it to the statements collection in the new method.
                        newMethod.Statements.Add(niex);
                    }
                    break;

                    case MethodImplementation.AbstractMethods:
                    {
                        // No statement is required for the abstract methods.
                        newMethod.Attributes |= MemberAttributes.Abstract;
                        break;
                    }
                    }

                    // Wrap the CodeMemberMethod in an extension. This could be useful for other extensions.
                    CodeTypeMemberExtension newMethodExt = new CodeTypeMemberExtension(newMethod, typeExt);
                    srvType.Members.Add(newMethodExt);
                }

                // Add the ServiceBehaviorAttribute attribute.
                CodeAttributeDeclaration serviceBehaviorAttribute = new CodeAttributeDeclaration(
                    new CodeTypeReference(typeof(ServiceBehaviorAttribute)));

                if (!string.IsNullOrEmpty(options.InstanceContextMode))
                {
                    CodeTypeReferenceExpression  instanceContextModeEnum     = new CodeTypeReferenceExpression(typeof(InstanceContextMode));
                    CodeFieldReferenceExpression instanceContextModeValue    = new CodeFieldReferenceExpression(instanceContextModeEnum, options.InstanceContextMode);
                    CodeAttributeArgument        instanceContextModeArgument = new CodeAttributeArgument("InstanceContextMode", instanceContextModeValue);
                    serviceBehaviorAttribute.Arguments.Add(instanceContextModeArgument);
                }

                if (!string.IsNullOrEmpty(options.ConcurrencyMode))
                {
                    CodeTypeReferenceExpression  concurrencyModeEnum     = new CodeTypeReferenceExpression(typeof(ConcurrencyMode));
                    CodeFieldReferenceExpression concurrencyModeValue    = new CodeFieldReferenceExpression(concurrencyModeEnum, options.ConcurrencyMode);
                    CodeAttributeArgument        concurrencyModeArgument = new CodeAttributeArgument("ConcurrencyMode", concurrencyModeValue);
                    serviceBehaviorAttribute.Arguments.Add(concurrencyModeArgument);
                }

                if (!options.UseSynchronizationContext)
                {
                    CodeAttributeArgument useSynchronizationContextAttribute = new CodeAttributeArgument("UseSynchronizationContext", new CodePrimitiveExpression(false));
                    serviceBehaviorAttribute.Arguments.Add(useSynchronizationContextAttribute);
                }

                typeExt.AddAttribute(serviceBehaviorAttribute);

                this.serviceTypeName = srvType.Name;
                // Finally add the newly created type to the code being generated.
                code.ServiceTypes.Add(typeExt);
            }
        }
	public CodeAttributeDeclaration(CodeTypeReference attributeType, CodeAttributeArgument[] arguments) {}
	public CodeAttributeDeclaration(string name, CodeAttributeArgument[] arguments) {}
コード例 #17
0
ファイル: CodeValidator.cs プロジェクト: Corillian/corefx
 private void ValidateAttributeArgument(CodeAttributeArgument arg)
 {
     if (!string.IsNullOrEmpty(arg.Name))
     {
         ValidateIdentifier(arg, nameof(arg.Name), arg.Name);
     }
     ValidateExpression(arg.Value);
 }
コード例 #18
0
ファイル: MfSvcImporter.cs プロジェクト: weimingtom/miniclr
        /// <summary>
        /// Add an interface method to a service interface.
        /// </summary>
        /// <param name="operation">A sericce operation.</param>
        /// <param name="action">A service action</param>
        /// <param name="codeType">A CodeTypeDeclaration object used to store this interface definition.</param>
        private void AddServiceOperationToInterface(Operation operation, string action, CodeTypeDeclaration codeType)
        {
            // Add method
            CodeMemberMethod codeMethod = new CodeMemberMethod();

            codeMethod.Name = operation.Name;

            // Find request and response element or type name that defines the interface method and return types
            string inputElementName  = null;
            string inputTypeName     = null;
            string outputElementName = null;
            string outputTypeName    = null;

            foreach (Message message in m_svcDesc.Messages)
            {
                if (operation.Messages.Input != null && operation.Messages.Input.Message.Name == message.Name)
                {
                    inputElementName = CodeGenUtils.GetMessageElementName(m_svcDesc, message);
                    inputTypeName    = CodeGenUtils.GetMessageTypeName(m_svcDesc, message);
                }
                else if (operation.Messages.Output != null && operation.Messages.Output.Message.Name == message.Name)
                {
                    outputElementName = CodeGenUtils.GetMessageElementName(m_svcDesc, message);
                    outputTypeName    = CodeGenUtils.GetMessageTypeName(m_svcDesc, message);
                }
            }

            // If this is an event add event (notification) prototype
            if (operation.Messages.Flow == OperationFlow.Notification)
            {
                codeMethod.ReturnType = new CodeTypeReference(typeof(void));
                if (outputTypeName != null)
                {
                    codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(outputTypeName, "resp"));
                }
            }
            // Else add request/response prototype
            else
            {
                if (operation.Messages.Flow != OperationFlow.RequestResponse || outputTypeName == null)
                {
                    codeMethod.ReturnType = new CodeTypeReference(typeof(void));
                }
                else
                {
                    codeMethod.ReturnType = new CodeTypeReference(outputTypeName);
                }

                if (inputTypeName != null)
                {
                    codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(inputTypeName, "req"));
                }
            }

            // Create OperationContract custom attribute
            CodeAttributeDeclaration codeAttrDecl = new CodeAttributeDeclaration("OperationContract");
            CodeAttributeArgument    codeAttr     = new CodeAttributeArgument("Action", new CodePrimitiveExpression(action));

            codeAttrDecl.Arguments.Add(codeAttr);
            if (operation.Messages.Flow == OperationFlow.OneWay)
            {
                codeAttr = new CodeAttributeArgument("IsOneWay", new CodePrimitiveExpression(true));
                codeAttrDecl.Arguments.Add(codeAttr);
            }
            codeMethod.CustomAttributes.Add(codeAttrDecl);
            codeMethod.Attributes = MemberAttributes.Public;
            codeType.Members.Add(codeMethod);
        }
 private static CodeAttributeDeclaration CreateEditorBrowsableAttribute(EditorBrowsableState editorBrowsableState)
 {
     CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(EditorBrowsableAttribute)));
     CodeTypeReferenceExpression targetObject = new CodeTypeReferenceExpression(typeof(EditorBrowsableState));
     CodeAttributeArgument argument = new CodeAttributeArgument(new CodeFieldReferenceExpression(targetObject, editorBrowsableState.ToString()));
     declaration.Arguments.Add(argument);
     return declaration;
 }
 public int IndexOf(CodeAttributeArgument value)
 {
 }
コード例 #21
0
        private static void BuildStandardMethod(
            CodeTypeDeclaration declaration,
            string methodName,
            string rpcMethodName,
            Type[] argTypes,
            string[] argNames,
            Type returnType,
            Type implementationType)
        {
            CodeMemberMethod cmm = new CodeMemberMethod();

            // set the attributes and name

            // normal, unqualified type names are public
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;

            cmm.ImplementationTypes.Add(implementationType);

            cmm.Name = methodName;

            // set the return type
            CodeTypeReference ctrReturn = new CodeTypeReference(returnType);

            cmm.ReturnType = ctrReturn;

            MakeParameterList(cmm, argTypes, argNames);

            // add an XmlRpcMethod attribute to the type
            CodeAttributeDeclaration cad = new CodeAttributeDeclaration();

            cad.Name = typeof(XmlRpcMethodAttribute).FullName;

            CodeAttributeArgument   caa = new CodeAttributeArgument();
            CodePrimitiveExpression cpe = new CodePrimitiveExpression(rpcMethodName);

            caa.Value = cpe;

            cad.Arguments.Add(caa);

            cmm.CustomAttributes.Add(cad);

            // generate the method body:

            // if non-void return, declared locals for processing return value
            if (returnType != typeof(void))
            {
                // add some local variables
                MakeTempVariable(cmm, typeof(System.Object));
                MakeReturnVariable(cmm, returnType);
            }

            MakeTempParameterArray(cmm, argTypes, argNames);

            // construct a call to the base Invoke method
            CodeThisReferenceExpression ctre = new CodeThisReferenceExpression();

            CodeMethodReferenceExpression cmre = new CodeMethodReferenceExpression(ctre, "Invoke");

            CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression();

            cmie.Method = cmre;
            cmie.Parameters.Add(new CodePrimitiveExpression(methodName));
            cmie.Parameters.Add(new CodeVariableReferenceExpression(DEFAULT_ARR));

            if (returnType != typeof(void))
            {
                // assign the result to tempRetVal
                CodeAssignStatement casTemp = new CodeAssignStatement();
                casTemp.Left  = new CodeVariableReferenceExpression(DEFAULT_TEMP);
                casTemp.Right = cmie;

                cmm.Statements.Add(casTemp);
            }
            else
            {
                // discard return type
                cmm.Statements.Add(cmie);
            }

            MakeReturnStatement(cmm, returnType);

            // add the finished method to the type
            declaration.Members.Add(cmm);
        }
 public void Insert(int index, CodeAttributeArgument value)
 {
 }
コード例 #23
0
ファイル: WriteCodeFragment.cs プロジェクト: yazici/msbuild
        private string GenerateCode(out string extension)
        {
            extension = null;
            bool haveGeneratedContent = false;

            CodeDomProvider provider;

            try
            {
                provider = CodeDomProvider.CreateProvider(Language);
            }
            catch (SystemException e) when
#if FEATURE_SYSTEM_CONFIGURATION
                (e is ConfigurationException || e is SecurityException)
#else
            (e.GetType().Name == "ConfigurationErrorsException") //TODO: catch specific exception type once it is public https://github.com/dotnet/corefx/issues/40456
#endif
            {
                Log.LogErrorWithCodeFromResources("WriteCodeFragment.CouldNotCreateProvider", Language, e.Message);
                return(null);
            }

            extension = provider.FileExtension;

            var unit = new CodeCompileUnit();

            var globalNamespace = new CodeNamespace();
            unit.Namespaces.Add(globalNamespace);

            // Declare authorship. Unfortunately CodeDOM puts this comment after the attributes.
            string comment = ResourceUtilities.GetResourceString("WriteCodeFragment.Comment");
            globalNamespace.Comments.Add(new CodeCommentStatement(comment));

            if (AssemblyAttributes == null)
            {
                return(String.Empty);
            }

            // For convenience, bring in the namespaces, where many assembly attributes lie
            globalNamespace.Imports.Add(new CodeNamespaceImport("System"));
            globalNamespace.Imports.Add(new CodeNamespaceImport("System.Reflection"));

            foreach (ITaskItem attributeItem in AssemblyAttributes)
            {
                var attribute = new CodeAttributeDeclaration(new CodeTypeReference(attributeItem.ItemSpec));

                // Some attributes only allow positional constructor arguments, or the user may just prefer them.
                // To set those, use metadata names like "_Parameter1", "_Parameter2" etc.
                // If a parameter index is skipped, it's an error.
                IDictionary customMetadata = attributeItem.CloneCustomMetadata();

                var orderedParameters = new List <CodeAttributeArgument>(new CodeAttributeArgument[customMetadata.Count + 1] /* max possible slots needed */);
                var namedParameters   = new List <CodeAttributeArgument>();

                foreach (DictionaryEntry entry in customMetadata)
                {
                    string name  = (string)entry.Key;
                    string value = (string)entry.Value;

                    if (name.StartsWith("_Parameter", StringComparison.OrdinalIgnoreCase))
                    {
                        if (!Int32.TryParse(name.Substring("_Parameter".Length), out int index))
                        {
                            Log.LogErrorWithCodeFromResources("General.InvalidValue", name, "WriteCodeFragment");
                            return(null);
                        }

                        if (index > orderedParameters.Count || index < 1)
                        {
                            Log.LogErrorWithCodeFromResources("WriteCodeFragment.SkippedNumberedParameter", index);
                            return(null);
                        }

                        // "_Parameter01" and "_Parameter1" would overwrite each other
                        orderedParameters[index - 1] = new CodeAttributeArgument(String.Empty, new CodePrimitiveExpression(value));
                    }
                    else
                    {
                        namedParameters.Add(new CodeAttributeArgument(name, new CodePrimitiveExpression(value)));
                    }
                }

                bool encounteredNull = false;
                for (int i = 0; i < orderedParameters.Count; i++)
                {
                    if (orderedParameters[i] == null)
                    {
                        // All subsequent args should be null, else a slot was missed
                        encounteredNull = true;
                        continue;
                    }

                    if (encounteredNull)
                    {
                        Log.LogErrorWithCodeFromResources("WriteCodeFragment.SkippedNumberedParameter", i + 1 /* back to 1 based */);
                        return(null);
                    }

                    attribute.Arguments.Add(orderedParameters[i]);
                }

                foreach (CodeAttributeArgument namedParameter in namedParameters)
                {
                    attribute.Arguments.Add(namedParameter);
                }

                unit.AssemblyCustomAttributes.Add(attribute);
                haveGeneratedContent = true;
            }

            var generatedCode = new StringBuilder();
            using (var writer = new StringWriter(generatedCode, CultureInfo.CurrentCulture))
            {
                provider.GenerateCodeFromCompileUnit(unit, writer, new CodeGeneratorOptions());
            }

            string code = generatedCode.ToString();

            // If we just generated infrastructure, don't bother returning anything
            // as there's no point writing the file
            return(haveGeneratedContent ? code : String.Empty);
        }
    }
 public void Remove(CodeAttributeArgument value)
 {
 }
	public bool Contains(CodeAttributeArgument value) {}
	public int IndexOf(CodeAttributeArgument value) {}
コード例 #27
0
        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;
            }
            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(Microsoft.Build.Tasks.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(Microsoft.Build.Tasks.SR.GetString("CulturePropertyComment1"), true));
            property2.Comments.Add(new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("CulturePropertyComment2"), true));
            property2.Comments.Add(new CodeCommentStatement("</summary>", true));
        }
コード例 #28
0
		public void Name_Set_Get_ReturnsExpected(string value)
		{
			var argument = new CodeAttributeArgument();
			argument.Name = value;
			Assert.Equal(value ?? string.Empty, argument.Name);
		}
	public void CopyTo(CodeAttributeArgument[] array, int index) {}
コード例 #30
0
ファイル: XmlCodeExporter.cs プロジェクト: Potapy4/dotnet-wcf
        private CodeAttributeArgument[] GetDefaultValueArguments(PrimitiveMapping mapping, object value, out CodeExpression initExpression)
        {
            initExpression = null;
            if (value == null)
            {
                return(null);
            }

            CodeExpression valueExpression = null;
            CodeExpression typeofValue     = null;
            Type           type            = value.GetType();

            CodeAttributeArgument[] arguments = null;

            if (mapping is EnumMapping)
            {
#if DEBUG
                // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
                if (value.GetType() != typeof(string))
                {
                    throw new InvalidOperationException(string.Format(ResXml.XmlInternalErrorDetails, "Invalid enumeration type " + value.GetType().Name));
                }
#endif

                if (((EnumMapping)mapping).IsFlags)
                {
                    string[] values = ((string)value).Split(null);
                    for (int i = 0; i < values.Length; i++)
                    {
                        if (values[i].Length == 0)
                        {
                            continue;
                        }
                        CodeExpression enumRef = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(mapping.TypeDesc.FullName), values[i]);
                        if (valueExpression != null)
                        {
                            valueExpression = new CodeBinaryOperatorExpression(valueExpression, CodeBinaryOperatorType.BitwiseOr, enumRef);
                        }
                        else
                        {
                            valueExpression = enumRef;
                        }
                    }
                }
                else
                {
                    valueExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(mapping.TypeDesc.FullName), (string)value);
                }
                initExpression = valueExpression;
                arguments      = new CodeAttributeArgument[] { new CodeAttributeArgument(valueExpression) };
            }
            else if (type == typeof(bool) ||
                     type == typeof(Int32) ||
                     type == typeof(string) ||
                     type == typeof(double))
            {
                initExpression = valueExpression = new CodePrimitiveExpression(value);
                arguments      = new CodeAttributeArgument[] { new CodeAttributeArgument(valueExpression) };
            }
            else if (type == typeof(Int16) ||
                     type == typeof(Int64) ||
                     type == typeof(float) ||
                     type == typeof(byte) ||
                     type == typeof(decimal))
            {
                valueExpression = new CodePrimitiveExpression(Convert.ToString(value, NumberFormatInfo.InvariantInfo));
                typeofValue     = new CodeTypeOfExpression(type.FullName);
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeCastExpression(type.FullName, new CodePrimitiveExpression(value));
            }
            else if (type == typeof(sbyte) ||
                     type == typeof(UInt16) ||
                     type == typeof(UInt32) ||
                     type == typeof(UInt64))
            {
                // need to promote the non-CLS complient types

                value = PromoteType(type, value);

                valueExpression = new CodePrimitiveExpression(Convert.ToString(value, NumberFormatInfo.InvariantInfo));
                typeofValue     = new CodeTypeOfExpression(type.FullName);
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeCastExpression(type.FullName, new CodePrimitiveExpression(value));
            }
            else if (type == typeof(DateTime))
            {
                DateTime dt = (DateTime)value;
                string   dtString;
                long     ticks;
                if (mapping.TypeDesc.FormatterName == "Date")
                {
                    dtString = XmlCustomFormatter.FromDate(dt);
                    ticks    = (new DateTime(dt.Year, dt.Month, dt.Day)).Ticks;
                }
                else if (mapping.TypeDesc.FormatterName == "Time")
                {
                    dtString = XmlCustomFormatter.FromDateTime(dt);
                    ticks    = dt.Ticks;
                }
                else
                {
                    dtString = XmlCustomFormatter.FromDateTime(dt);
                    ticks    = dt.Ticks;
                }
                valueExpression = new CodePrimitiveExpression(dtString);
                typeofValue     = new CodeTypeOfExpression(type.FullName);
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeObjectCreateExpression(new CodeTypeReference(typeof(DateTime)), new CodeExpression[] { new CodePrimitiveExpression(ticks) });
            }
            else if (type == typeof(Guid))
            {
                valueExpression = new CodePrimitiveExpression(Convert.ToString(value, NumberFormatInfo.InvariantInfo));
                typeofValue     = new CodeTypeOfExpression(type.FullName);
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeObjectCreateExpression(new CodeTypeReference(typeof(Guid)), new CodeExpression[] { valueExpression });
            }
            if (mapping.TypeDesc.FullName != type.ToString() && !(mapping is EnumMapping))
            {
                // generate cast
                initExpression = new CodeCastExpression(mapping.TypeDesc.FullName, initExpression);
            }
            return(arguments);
        }
	public void Insert(int index, CodeAttributeArgument value) {}
コード例 #32
0
 internal ShellCodeAttributeArgument(CodeAttributeArgument argument) : base(argument as CodeElement)
 {
     _argument = argument;
 }
	public CodeAttributeArgumentCollection(CodeAttributeArgument[] value) {}
コード例 #34
0
 private void OutputAttributeArgument(CodeAttributeArgument arg)
 {
     if (arg.Name != null && arg.Name.Length > 0)
     {
         OutputIdentifier(arg.Name);
         Output.Write("=");
     }
     ((ICodeGenerator)this).GenerateCodeFromExpression(arg.Value, output.InnerWriter, options);
 }
コード例 #35
0
ファイル: MfSvcImporter.cs プロジェクト: weimingtom/miniclr
        /// <summary>
        /// CreateSourceFiles - Parse Wsdl Schema and generate DataContract, DataContractSerializer types,
        /// HostedServices and Client Proxies.
        /// </summary>
        /// <remarks>Currently only generates C# source files.</remarks>
        /// <param name="contractFilename">The name of a contract source code (.cs) file.</param>
        /// <param name="hostedServiceFilename">The name of a hosted service source code (.cs) file.</param>
        /// <param name="clientProxyFilename">The name of a client proxy source code (.cs) file.</param>
        /// <param name="targetPlatform">Specifies the target runtime platform.</param>
        public void CreateSourceFiles(string contractFilename, string hostedServiceFilename, string clientProxyFilename, TargetPlatform targetPlatform)
        {
            m_platform = targetPlatform;

            Logger.WriteLine("", LogLevel.Normal);
            Logger.WriteLine("Generating contract source: " + contractFilename + "...", LogLevel.Normal);

            if (contractFilename == null)
            {
                throw new ArgumentNullException("codeFilename", "You must pass a valid code filename.");
            }

            if (m_svcDesc.Types == null)
            {
                throw new Exception("No wsdl types found.");
            }

            string path = Path.GetDirectoryName(contractFilename).Trim();

            if (!string.IsNullOrEmpty(path) && !Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // Create code file stream
            FileStream   dcStream       = new FileStream(contractFilename, FileMode.Create, FileAccess.Write, FileShare.None);
            StreamWriter dcStreamWriter = new StreamWriter(dcStream);

            // Write the auto generated header
            dcStreamWriter.Write(AutoGenTextHeader.Message);

            try
            {
                // Set up data contract code generator
                CSharpCodeProvider   cSharpCP       = new CSharpCodeProvider();
                ICodeGenerator       codeGen        = cSharpCP.CreateGenerator(dcStreamWriter);
                CodeGeneratorOptions codeGenOptions = new CodeGeneratorOptions();
                codeGenOptions.BracingStyle = "C";

                // Cobble up a valid .net namespace. Turn any progression that's not a-z or A-Z to a single '.'
                string targetNamespaceName = CodeGenUtils.GenerateDotNetNamespace(m_svcDesc.TargetNamespace);

                // For some reason we have to force schemas to compile. Though it was suppose to automatically. Huh!
                foreach (XmlSchema schema in m_svcDesc.Types.Schemas)
                {
                    XmlSchemaSet schemaSet = new XmlSchemaSet();
                    schemaSet.Add(schema);
                    schemaSet.Compile();
                }

                // Create new code namespace
                CodeNamespace targetNamespace = new CodeNamespace(targetNamespaceName);

                // Add data contract using directives
                CodeSnippetCompileUnit compileUnit = new CodeSnippetCompileUnit("using System;");
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using System.Xml;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                if (m_platform == TargetPlatform.MicroFramework)
                {
                    compileUnit.Value = "using System.Ext;";
                    codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                    compileUnit.Value = "using System.Ext.Xml;";
                    codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                }
                compileUnit.Value = "using Ws.ServiceModel;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using Ws.Services.Mtom;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using Ws.Services.Serialization;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlElement = Ws.Services.Xml.WsXmlNode;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlAttribute = Ws.Services.Xml.WsXmlAttribute;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlConvert = Ws.Services.Serialization.WsXmlConvert;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Namespaces.Add(targetNamespace);
                m_dcCodeGen.CodeNamespaces = compileUnit.Namespaces;

                Logger.WriteLine("", LogLevel.Normal);

                // Create HostedServices and ClientProxies collections
                HostedServices hostedServices = new HostedServices(targetNamespaceName);
                ClientProxies  clientProxies  = new ClientProxies(targetNamespaceName);

                // For each PortType process
                foreach (PortType portType in m_svcDesc.PortTypes)
                {
                    // For each operation in the port type:
                    // Get input and output message parts.
                    // If the message part is a simple type:
                    //   Build HostedService operation.
                    // Else if the message part is an element:
                    //   Find elements in Schema
                    //   If element type is native xml type:
                    //     Build HostedService operation.
                    //   Else if element references a simple or complex type:
                    //     If simpleType is base xml type with restrictions:
                    //       Build HostedService operation.
                    //     Else
                    //       Build DataContract and DataContractSerializer.
                    //       Build HostedService Operation.
                    //

                    // Create instance of a HostedService to hold the port type details
                    HostedService hostedService = new HostedService(portType.Name, m_svcDesc.TargetNamespace, m_platform);

                    // Create instance of ClientProxyGenerator
                    ClientProxy clientProxy = new ClientProxy(portType.Name, m_platform);

                    // Create service contract interface
                    CodeTypeDeclaration      serviceCodeType = new CodeTypeDeclaration("I" + portType.Name);
                    CodeAttributeArgument    codeAttr        = new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(m_svcDesc.TargetNamespace));
                    CodeAttributeDeclaration codeAttrDecl    = new CodeAttributeDeclaration("ServiceContract", codeAttr);
                    serviceCodeType.CustomAttributes.Add(codeAttrDecl);

                    // Check for Policy assertions. If found add policy assertion attributes. Policy assertion attributes
                    // are required to regenerate policy assertions when converting a service to Wsdl.
                    List <PolicyAssertion> policyAssertions = GetPolicyAssertions();
                    bool OptimizedMimeEncoded = false;
                    foreach (PolicyAssertion assert in policyAssertions)
                    {
                        serviceCodeType.CustomAttributes.Add(CreatePolicyAssertions(assert.Name, assert.Namespace.ToString(), assert.PolicyID));

                        // if Optimized Mime assertion id found set a processing flag
                        if (assert.Name == "OptimizedMimeSerialization")
                        {
                            OptimizedMimeEncoded = true;
                        }
                    }

                    // Add type declaration
                    serviceCodeType.TypeAttributes = TypeAttributes.Public;
                    serviceCodeType.IsInterface    = true;

                    // Create service contract callback client interface
                    CodeTypeDeclaration serviceCallbackCodeType = new CodeTypeDeclaration("I" + portType.Name + "Callback");

                    // Add type declaration
                    serviceCallbackCodeType.TypeAttributes = TypeAttributes.Public;
                    serviceCallbackCodeType.IsInterface    = true;

                    // If the binding contains a ref to Mtom encoding type set the Mtom flag
                    if (OptimizedMimeEncoded)
                    {
                        m_dcCodeGen.EncodingType   = MessageEncodingType.Mtom;
                        hostedService.EncodingType = MessageEncodingType.Mtom;
                        clientProxy.EncodingType   = MessageEncodingType.Mtom;
                    }

                    // Step through port operations, get method names and parse elements.
                    for (int pt_index = 0; pt_index < portType.Operations.Count; ++pt_index)
                    {
                        Operation operation     = portType.Operations[pt_index];
                        string    operationName = operation.Name;

                        string inputMessageName  = null;
                        string outputMessageName = null;
                        MessagePartCollection inputMessageParts  = null;
                        MessagePartCollection outputMessageParts = null;
                        string inAction  = null;
                        string outAction = null;
                        GetAction(portType, operation, m_svcDesc.TargetNamespace, ref inAction, ref outAction);

                        // Oneway request port type
                        if (operation.Messages.Flow == OperationFlow.OneWay)
                        {
                            OperationInput input = operation.Messages.Input;
                            inputMessageName = input.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }
                        // Twoway request/response pattern
                        else if (operation.Messages.Flow == OperationFlow.RequestResponse)
                        {
                            OperationInput input = operation.Messages.Input;
                            inputMessageName = input.Message.Name;
                            OperationOutput output = operation.Messages.Output;
                            outputMessageName = output.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }
                        // Event pattern
                        else if (operation.Messages.Flow == OperationFlow.Notification)
                        {
                            OperationOutput output = operation.Messages.Output;
                            outputMessageName = output.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }

                        // Find input and output message parts collection in messages collection
                        // and store for later.
                        foreach (Message message in m_svcDesc.Messages)
                        {
                            if (inputMessageName != null)
                            {
                                if (message.Name == inputMessageName)
                                {
                                    inputMessageParts = message.Parts;

                                    // Add operation for HostedService code generation
                                    hostedService.Messages.Add(message);

                                    // Add Message to ClientProxy generator for later
                                    clientProxy.Messages.Add(message);
                                }
                            }

                            if (outputMessageName != null)
                            {
                                if (message.Name == outputMessageName)
                                {
                                    outputMessageParts = message.Parts;

                                    // Add operation for HostedService code generation
                                    hostedService.Messages.Add(message);

                                    // Add Message to ClientProxy generator for later
                                    clientProxy.Messages.Add(message);
                                }
                            }
                        }

                        try
                        {
                            // Try to generate Data Contracts and DataContractSerializers
                            GenerateTypeContracts(operation, inputMessageParts, outputMessageParts);

                            // If operation flow is notification (event) add OperationContract to ServiceContractCallback
                            // else add OperationContract to ServiceContract
                            if (operation.Messages.Flow == OperationFlow.Notification)
                            {
                                AddServiceOperationToInterface(operation, outAction, serviceCallbackCodeType);
                            }
                            else
                            {
                                AddServiceOperationToInterface(operation, inAction, serviceCodeType);
                            }
                        }
                        catch (Exception e)
                        {
                            dcStreamWriter.Close();
                            File.Delete(contractFilename);
                            Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal);
                            return;
                        }
                    }

                    // Add serviceCodeType Service Contract interface to namespace
                    // A serviceCodeType is added even if the wsdl only contains notifications. In that case
                    // the contract will be empty but the ServiceContract attribute and CallbackContract argument
                    // will be used to point to the notification or callback contract interace
                    targetNamespace.Types.Add(serviceCodeType);

                    // If service contract callback type contains members add callback contract to namespace
                    // and add CallbackContract reference attribute to serviceCodeType contract.
                    if (serviceCallbackCodeType.Members.Count > 0)
                    {
                        // Add the callback argument to the service description attribute
                        CodeAttributeArgument callbackArg = new CodeAttributeArgument("CallbackContract",
                                                                                      new CodeTypeOfExpression(serviceCallbackCodeType.Name)
                                                                                      );
                        serviceCodeType.CustomAttributes[0].Arguments.Add(callbackArg);

                        // Add the callback interface to namespace
                        targetNamespace.Types.Add(serviceCallbackCodeType);
                    }

                    // If the hosted service has opeations add to Hosted Services collection for Code Gen
                    if (hostedService.ServiceOperations.Count > 0)
                    {
                        hostedServices.Add(hostedService);
                    }

                    // If the client Proxy service has opeations add to client proxy collection for Code Gen
                    if (clientProxy.ServiceOperations.Count > 0)
                    {
                        clientProxies.Add(clientProxy);
                    }
                }

                // MOD: 12-02-08 Added code to handle multiple type namespaces
                // Generate contract source file
                foreach (CodeNamespace codeNamespace in compileUnit.Namespaces)
                {
                    codeGen.GenerateCodeFromNamespace(codeNamespace, dcStreamWriter, codeGenOptions);
                }
                dcStreamWriter.Flush();
                dcStreamWriter.Close();

                // Generate Hosted Service code
                Logger.WriteLine("Generating Hosted Service source: " + hostedServiceFilename + "...", LogLevel.Normal);
                HostedServiceGenerator hsGen = new HostedServiceGenerator();
                hsGen.GenerateCode(hostedServiceFilename, hostedServices);

                // Generate Client proxy code
                Logger.WriteLine("Generating Client Proxy source: " + clientProxyFilename + "...", LogLevel.Normal);
                ClientProxyGenerator cpGen = new ClientProxyGenerator();
                cpGen.GenerateCode(clientProxyFilename, clientProxies);
            }
            catch (Exception e)
            {
                dcStreamWriter.Close();
                File.Delete(contractFilename);
                Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal);
                throw new Exception("Failed to generate service code. ", e);
            }
        }
コード例 #36
0
    public override void Interpret(Script script)
    {
        MaxProgress = script.Entries.Count;
        for (int i = 0; i < script.Entries.Count; i++)
        {
            if (!Engine.Working)
            {
                Thread.CurrentThread.Abort();
            }
            CurProgress = i;
            var entry = script.Entries [i];
            CodeTypeDeclaration codeType = new CodeTypeDeclaration();
            //codeType.CustomAttributes.
            codeType.BaseTypes.Add(new CodeTypeReference(typeof(LocalisationTag)));
            codeType.Name = entry.Identifier as string + i;
            codeTypes.Add(codeType);

            if (ScriptEngine.AnalyzeDebug)
            {
                Debug.LogWarning((entry.Identifier as string).ToUpper());
            }

            var  ctx         = entry.Context as Context;
            bool hasValue    = false;
            var  utMethod    = typeof(LocalisationTag).GetMethod("Utility");
            var  scopeMethod = typeof(LocalisationTag).GetMethod("Filter");
            var  valMethod   = typeof(LocalisationTag).GetMethod("Value");
            CodeAttributeDeclaration attr = new CodeAttributeDeclaration("LocalisationTagAttribute");
            codeType.CustomAttributes.Add(attr);
            CodeAttributeArgument typeArg = new CodeAttributeArgument("Type", new CodeSnippetExpression("\"{0}\"".Fmt(entry.Identifier as string)));
            attr.Arguments.Add(typeArg);
            FunctionBlock dependenciesBlock = new FunctionBlock(null, null, codeType);
            if (ctx != null)
            {
                for (int j = 0; j < ctx.Entries.Count; j++)
                {
                    var op = ctx.Entries[j] as Operator;
                    if (op != null)
                    {
                        if (op.Identifier as string == "scope")
                        {
                            //It's a filter function
                            //					Debug.Log (op.Context.GetType ());
                            if (ScriptEngine.AnalyzeDebug)
                            {
                                Debug.Log((op.Context as Expression).Operands[0].GetType());
                            }

                            (((op.Context as Expression).Operands[0] as ExprAtom).Content as Scope).Parts.Add("true");
                            DeclareVariableStatement retVal = new DeclareVariableStatement();
                            retVal.IsReturn       = true;
                            retVal.Name           = "applicable";
                            retVal.Type           = typeof(bool);
                            retVal.InitExpression = "false";

                            CreateEventFunction("Filter", op.Context, codeType, scopeMethod, retVal);
                            //CreateFilterFunction (op.Context as Expression, codeType);
                        }
                        else if (op.Identifier as string == "value")
                        {
                            hasValue = true;
                            DeclareVariableStatement utVal = new DeclareVariableStatement();
                            utVal.IsReturn       = true;
                            utVal.Name           = "val";
                            utVal.Type           = typeof(string);
                            utVal.InitExpression = "\"\"";
                            CreateEventFunction(op.Identifier as string, op.Context, codeType, valMethod, utVal);
                        }
                        else if (op.Identifier as string == "utility")
                        {
                            DeclareVariableStatement utVal = new DeclareVariableStatement();
                            utVal.IsReturn       = true;
                            utVal.Name           = "ut";
                            utVal.Type           = typeof(float);
                            utVal.InitExpression = "0";
                            CreateEventFunction(op.Identifier as string, op.Context, codeType, utMethod, utVal);
                        }
                        else
                        {
                            //No idea
                        }
                    }
                }
            }
            else
            {
                (((entry.Context as Expression).Operands[0] as ExprAtom).Content as Scope).Parts.Add("true");
                DeclareVariableStatement retVal = new DeclareVariableStatement();
                retVal.IsReturn       = true;
                retVal.Name           = "applicable";
                retVal.Type           = typeof(bool);
                retVal.InitExpression = "false";

                CreateEventFunction("Filter", entry.Context, codeType, scopeMethod, retVal);
            }
            if (!hasValue)
            {
                CodeMemberMethod method = new CodeMemberMethod();
                method.Name       = "Value";
                method.Attributes = MemberAttributes.Override | MemberAttributes.Public;
                method.ReturnType = new CodeTypeReference(typeof(string));
                method.Statements.Add(new CodeSnippetStatement("return \"" + entry.Args[0].ToString().ClearFromBraces().Trim(' ') + "\";"));
                codeType.Members.Add(method);
            }
        }

        CurProgress = MaxProgress;
        foreach (var type in codeTypes)
        {
            cNamespace.Types.Add(type);
        }

        CSharpCodeProvider   provider = new CSharpCodeProvider();
        CodeGeneratorOptions options  = new CodeGeneratorOptions();
        var writer = new StringWriter();

        provider.GenerateCodeFromNamespace(cNamespace, writer, options);
        Debug.Log(writer.ToString());
        var asm = loader.Load(new string[] { writer.ToString() }, "LocalisationTags");

        if (ScriptEngine.AnalyzeDebug)
        {
            Debug.LogWarning(asm.FullName);
        }
        Engine.AddAssembly(asm);
    }
コード例 #37
0
ファイル: Utilities.cs プロジェクト: vsliouniaev/pinvoke
        static internal CodeAttributeDeclaration CreateArrayParamTypeAttribute(UnmanagedType arraySubType, CodeAttributeArgument sizeArg)
        {
            CodeAttributeDeclaration decl = CreateUnmanagedTypeAttribute(UnmanagedType.LPArray);

            decl.Arguments.Add(new CodeAttributeArgument("ArraySubType", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(UnmanagedType)), arraySubType.ToString())));
            decl.Arguments.Add(sizeArg);
            return(decl);
        }
コード例 #38
0
        private CodeAttributeArgument[] GetDefaultValueArguments(PrimitiveMapping mapping, object value, out CodeExpression initExpression)
        {
            initExpression = null;
            if (value == null)
            {
                return(null);
            }
            CodeExpression left        = null;
            CodeExpression expression2 = null;
            Type           type        = value.GetType();

            CodeAttributeArgument[] argumentArray = null;
            if (mapping is EnumMapping)
            {
                if (((EnumMapping)mapping).IsFlags)
                {
                    string[] strArray = ((string)value).Split(null);
                    for (int i = 0; i < strArray.Length; i++)
                    {
                        if (strArray[i].Length != 0)
                        {
                            CodeExpression right = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(mapping.TypeDesc.FullName), strArray[i]);
                            if (left != null)
                            {
                                left = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.BitwiseOr, right);
                            }
                            else
                            {
                                left = right;
                            }
                        }
                    }
                }
                else
                {
                    left = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(mapping.TypeDesc.FullName), (string)value);
                }
                initExpression = left;
                argumentArray  = new CodeAttributeArgument[] { new CodeAttributeArgument(left) };
            }
            else if (((type == typeof(bool)) || (type == typeof(int))) || ((type == typeof(string)) || (type == typeof(double))))
            {
                initExpression = left = new CodePrimitiveExpression(value);
                argumentArray  = new CodeAttributeArgument[] { new CodeAttributeArgument(left) };
            }
            else if (((type == typeof(short)) || (type == typeof(long))) || (((type == typeof(float)) || (type == typeof(byte))) || (type == typeof(decimal))))
            {
                left           = new CodePrimitiveExpression(Convert.ToString(value, NumberFormatInfo.InvariantInfo));
                expression2    = new CodeTypeOfExpression(type.FullName);
                argumentArray  = new CodeAttributeArgument[] { new CodeAttributeArgument(expression2), new CodeAttributeArgument(left) };
                initExpression = new CodeCastExpression(type.FullName, new CodePrimitiveExpression(value));
            }
            else if (((type == typeof(sbyte)) || (type == typeof(ushort))) || ((type == typeof(uint)) || (type == typeof(ulong))))
            {
                value          = CodeExporter.PromoteType(type, value);
                left           = new CodePrimitiveExpression(Convert.ToString(value, NumberFormatInfo.InvariantInfo));
                expression2    = new CodeTypeOfExpression(type.FullName);
                argumentArray  = new CodeAttributeArgument[] { new CodeAttributeArgument(expression2), new CodeAttributeArgument(left) };
                initExpression = new CodeCastExpression(type.FullName, new CodePrimitiveExpression(value));
            }
            else if (type == typeof(DateTime))
            {
                string   str;
                long     ticks;
                DateTime time = (DateTime)value;
                if (mapping.TypeDesc.FormatterName == "Date")
                {
                    str = XmlCustomFormatter.FromDate(time);
                    DateTime time2 = new DateTime(time.Year, time.Month, time.Day);
                    ticks = time2.Ticks;
                }
                else if (mapping.TypeDesc.FormatterName == "Time")
                {
                    str   = XmlCustomFormatter.FromDateTime(time);
                    ticks = time.Ticks;
                }
                else
                {
                    str   = XmlCustomFormatter.FromDateTime(time);
                    ticks = time.Ticks;
                }
                left           = new CodePrimitiveExpression(str);
                expression2    = new CodeTypeOfExpression(type.FullName);
                argumentArray  = new CodeAttributeArgument[] { new CodeAttributeArgument(expression2), new CodeAttributeArgument(left) };
                initExpression = new CodeObjectCreateExpression(new CodeTypeReference(typeof(DateTime)), new CodeExpression[] { new CodePrimitiveExpression(ticks) });
            }
            else if (type == typeof(Guid))
            {
                left           = new CodePrimitiveExpression(Convert.ToString(value, NumberFormatInfo.InvariantInfo));
                expression2    = new CodeTypeOfExpression(type.FullName);
                argumentArray  = new CodeAttributeArgument[] { new CodeAttributeArgument(expression2), new CodeAttributeArgument(left) };
                initExpression = new CodeObjectCreateExpression(new CodeTypeReference(typeof(Guid)), new CodeExpression[] { left });
            }
            if ((mapping.TypeDesc.FullName != type.ToString()) && !(mapping is EnumMapping))
            {
                initExpression = new CodeCastExpression(mapping.TypeDesc.FullName, initExpression);
            }
            return(argumentArray);
        }
コード例 #39
0
        static void AddValidationAttributes(OpenApiSchema fieldSchema, CodeMemberField memberField)
        {
            if (fieldSchema.MaxLength.HasValue || fieldSchema.MinLength.HasValue)
            {
                if (fieldSchema.Type == "string")
                {
                    List <CodeAttributeArgument> attributeParams = new List <CodeAttributeArgument>();

                    if (fieldSchema.MaxLength.HasValue)
                    {
                        CodeSnippetExpression max = new CodeSnippetExpression(fieldSchema.MaxLength.Value.ToString());
                        attributeParams.Add(new CodeAttributeArgument(max));
                    }
                    else
                    {
                        CodeSnippetExpression max = new CodeSnippetExpression("int.MaxValue");
                        attributeParams.Add(new CodeAttributeArgument(max));
                    }

                    if (fieldSchema.MinLength.HasValue)
                    {
                        CodeSnippetExpression min = new CodeSnippetExpression(fieldSchema.MinLength.Value.ToString());
                        attributeParams.Add(new CodeAttributeArgument("MinimumLength", min));
                    }

                    CodeAttributeDeclaration cad = new CodeAttributeDeclaration("System.ComponentModel.DataAnnotations.StringLength", attributeParams.ToArray());
                    memberField.CustomAttributes.Add(cad);
                }
                else
                {
                    if (fieldSchema.MinLength.HasValue)
                    {
                        CodeSnippetExpression    len             = new CodeSnippetExpression(fieldSchema.MinLength.Value.ToString());
                        CodeAttributeArgument[]  attributeParams = new CodeAttributeArgument[] { new CodeAttributeArgument(len) };
                        CodeAttributeDeclaration cad             = new CodeAttributeDeclaration("System.ComponentModel.DataAnnotations.MinLength", attributeParams);
                        memberField.CustomAttributes.Add(cad);
                    }

                    if (fieldSchema.MaxLength.HasValue)
                    {
                        CodeSnippetExpression    len             = new CodeSnippetExpression(fieldSchema.MaxLength.Value.ToString());
                        CodeAttributeArgument[]  attributeParams = new CodeAttributeArgument[] { new CodeAttributeArgument(len) };
                        CodeAttributeDeclaration cad             = new CodeAttributeDeclaration("System.ComponentModel.DataAnnotations.MaxLength", attributeParams);
                        memberField.CustomAttributes.Add(cad);
                    }
                }
            }

            if (fieldSchema.Maximum.HasValue || fieldSchema.Minimum.HasValue)
            {
                Type type = TypeRefHelper.PrimitiveSwaggerTypeToClrType(fieldSchema.Type, fieldSchema.Format);
                List <CodeAttributeArgument> attributeParams = new List <CodeAttributeArgument>();
                if (fieldSchema.Type == "string")
                {
                    Trace.TraceWarning("A string type property shouldn't be decorated by Maximum or Minimum but MaxLength or MinLength.");                    //Xero_bankfeeds.yaml has such problem.
                    return;
                }

                if (fieldSchema.Minimum.HasValue)
                {
                    CodeSnippetExpression min = new CodeSnippetExpression($"{fieldSchema.Minimum.Value}");
                    attributeParams.Add(new CodeAttributeArgument(min));
                }
                else
                {
                    CodeSnippetExpression min = new CodeSnippetExpression($"{type.FullName}.MinValue");
                    attributeParams.Add(new CodeAttributeArgument(min));
                }

                if (fieldSchema.Maximum.HasValue)
                {
                    CodeSnippetExpression max = new CodeSnippetExpression($"{fieldSchema.Maximum.Value}");
                    attributeParams.Add(new CodeAttributeArgument(max));
                }
                else
                {
                    CodeSnippetExpression max = new CodeSnippetExpression($"{type.FullName}.MaxValue");
                    attributeParams.Add(new CodeAttributeArgument(max));
                }

                CodeAttributeDeclaration cad = new CodeAttributeDeclaration("System.ComponentModel.DataAnnotations.Range", attributeParams.ToArray());
                memberField.CustomAttributes.Add(cad);
            }

            if (fieldSchema.MinItems.HasValue)
            {
                CodeSnippetExpression    len             = new CodeSnippetExpression(fieldSchema.MinItems.Value.ToString());
                CodeAttributeArgument[]  attributeParams = new CodeAttributeArgument[] { new CodeAttributeArgument(len) };
                CodeAttributeDeclaration cad             = new CodeAttributeDeclaration("System.ComponentModel.DataAnnotations.MinLength", attributeParams);
                memberField.CustomAttributes.Add(cad);
            }

            if (fieldSchema.MaxItems.HasValue)
            {
                CodeSnippetExpression    len             = new CodeSnippetExpression(fieldSchema.MaxItems.Value.ToString());
                CodeAttributeArgument[]  attributeParams = new CodeAttributeArgument[] { new CodeAttributeArgument(len) };
                CodeAttributeDeclaration cad             = new CodeAttributeDeclaration("System.ComponentModel.DataAnnotations.MaxLength", attributeParams);
                memberField.CustomAttributes.Add(cad);
            }
        }
コード例 #40
0
        private static CodeAttributeDeclaration CreatePrimitiveAttribute <T>(string attributeName, T value)
        {
            var arguments = new CodeAttributeArgument(new CodePrimitiveExpression(value));

            return(CreateAttribute(attributeName, arguments));
        }
コード例 #41
0
 public static string GetArgumentValue(this CodeAttributeArgument codeExpression)
 {
     return(((CodePrimitiveExpression)codeExpression.Value).Value.ToString());
 }
コード例 #42
0
 public static string GetStringValue(this CodeAttributeArgument argument)
 {
     return((argument.Value as CodePrimitiveExpression).Value.ToString());
 }
コード例 #43
0
 static CodeAttributeDeclaration createAttribute(CodeTypeReference ctr, CodeAttributeArgument cad)
 {
     return(new CodeAttributeDeclaration(ctr, cad));
 }
コード例 #44
0
    static SupportedType()
    {
#if xxx
        -3;
        3;
        -333;
        333;
        -45678;
        45678;
        -1234567890;
        1234567890;
        'A';
        (float)(1.0 / 17.0);
        1.0 / 17.0;
        true;
        "Hello";
        Convert.ToDateTime("5/19/1971 9:23pm");
        new TimeSpan(23, 11, 7, 2, 42);
#endif

        jscriptHackType = new CodeTypeDeclaration("JScriptHackConvert");
        CodeMemberMethod hackMethod = new CodeMemberMethod();
        hackMethod.Name       = "Hack";
        hackMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
        hackMethod.ReturnType = new CodeTypeReference(typeof(IConvertible));
        hackMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "obj"));
        CodeCastExpression hackCast = new CodeCastExpression(typeof(IConvertible), new CodeVariableReferenceExpression("obj"));
        hackMethod.Statements.Add(new CodeMethodReturnStatement(hackCast));
        jscriptHackType.Members.Add(hackMethod);

        CodeTypeReference           jscriptHackTypeReference  = new CodeTypeReference(jscriptHackType.Name);
        CodeTypeReferenceExpression jscriptHackTypeExpression = new CodeTypeReferenceExpression(jscriptHackTypeReference);

        CodePrimitiveExpression Null     = new CodePrimitiveExpression(null);
        CodeExpression[]        arg1null = new CodeExpression[] { Null };
        CodePrimitiveExpression i8       = new CodePrimitiveExpression((int)-3);
        CodePrimitiveExpression u16      = new CodePrimitiveExpression((int)333);
        CodePrimitiveExpression u32      = new CodePrimitiveExpression((int)4567);
        CodePrimitiveExpression u64      = new CodePrimitiveExpression((long)1234567890);

        CodeExpression initSByte  = new CodeMethodInvokeExpression(new CodeCastExpression(typeof(IConvertible), i8), "ToSByte", arg1null);
        CodeExpression initUInt16 = new CodeMethodInvokeExpression(new CodeCastExpression(typeof(IConvertible), u16), "ToUInt16", arg1null);
        CodeExpression initUInt32 = new CodeMethodInvokeExpression(new CodeCastExpression(typeof(IConvertible), u32), "ToUInt32", arg1null);
        CodeExpression initUInt64 = new CodeMethodInvokeExpression(new CodeCastExpression(typeof(IConvertible), u64), "ToUInt64", arg1null);

        // JSCript Hack
        initSByte  = new CodeMethodInvokeExpression(new CodeMethodInvokeExpression(jscriptHackTypeExpression, hackMethod.Name, new CodeExpression[] { i8 }), "ToSByte", arg1null);
        initUInt16 = new CodeMethodInvokeExpression(new CodeMethodInvokeExpression(jscriptHackTypeExpression, hackMethod.Name, new CodeExpression[] { u16 }), "ToUInt16", arg1null);
        initUInt32 = new CodeMethodInvokeExpression(new CodeMethodInvokeExpression(jscriptHackTypeExpression, hackMethod.Name, new CodeExpression[] { u32 }), "ToUInt32", arg1null);
        initUInt64 = new CodeMethodInvokeExpression(new CodeMethodInvokeExpression(jscriptHackTypeExpression, hackMethod.Name, new CodeExpression[] { u64 }), "ToUInt64", arg1null);

        ArrayList     all = new ArrayList();
        SupportedType type;

        type             = new SupportedType();
        type.type        = typeof(sbyte);
        type.initializer = initSByte;
        all.Add(type);

        type             = new SupportedType();
        type.type        = typeof(byte);
        type.initializer = new CodePrimitiveExpression((byte)3);
        all.Add(type);

        type             = new SupportedType();
        type.type        = typeof(short);
        type.initializer = new CodePrimitiveExpression((short)-333);
        all.Add(type);

        type             = new SupportedType();
        type.type        = typeof(ushort);
        type.initializer = initUInt16;
        all.Add(type);

        type             = new SupportedType();
        type.type        = typeof(int);
        type.initializer = new CodePrimitiveExpression((int)-4567);
        all.Add(type);

        type             = new SupportedType();
        type.type        = typeof(uint);
        type.initializer = initUInt32;
        all.Add(type);

        type             = new SupportedType();
        type.type        = typeof(long);
        type.initializer = new CodePrimitiveExpression((long)-1234567890);
        all.Add(type);

        type             = new SupportedType();
        type.type        = typeof(ulong);
        type.initializer = initUInt64;
        all.Add(type);

        type             = new SupportedType();
        type.type        = typeof(char);
        type.initializer = new CodePrimitiveExpression((char)'A');
        all.Add(type);

        type             = new SupportedType();
        type.type        = typeof(float);
        type.initializer = new CodePrimitiveExpression((float)(1.0 / 17.0));
        all.Add(type);

        type             = new SupportedType();
        type.type        = typeof(double);
        type.initializer = new CodePrimitiveExpression((double)(1.0 / 17.0));
        all.Add(type);

        type             = new SupportedType();
        type.type        = typeof(bool);
        type.initializer = new CodePrimitiveExpression((bool)true);
        all.Add(type);

        type             = new SupportedType();
        type.type        = typeof(string);
        type.initializer = new CodePrimitiveExpression((string)"Hello");
        all.Add(type);

        type      = new SupportedType();
        type.type = typeof(DateTime);

        // JScriptHack
//        CodeExpression[] argDateTimeString = new CodeExpression[] {new CodePrimitiveExpression("5/19/1971 9:23pm")};
//        type.initializer = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(Convert)), "ToDateTime", argDateTimeString);
        type.initializer = new CodeMethodInvokeExpression(
            new CodeMethodInvokeExpression(
                jscriptHackTypeExpression,
                hackMethod.Name,
                new CodeExpression[] { new CodePrimitiveExpression("5/19/1971 9:23pm") }),
            "ToDateTime",
            arg1null);


        all.Add(type);

        type      = new SupportedType();
        type.type = typeof(TimeSpan);
        CodeExpression[] argTimeSpanCTOR = new CodeExpression[] { new CodePrimitiveExpression(23),
                                                                  new CodePrimitiveExpression(11),
                                                                  new CodePrimitiveExpression(7),
                                                                  new CodePrimitiveExpression(2),
                                                                  new CodePrimitiveExpression(42) };
        type.initializer = new CodeObjectCreateExpression(typeof(TimeSpan), argTimeSpanCTOR);
        all.Add(type);

        All = (SupportedType[])all.ToArray(typeof(SupportedType));

        // Fill in hashtable
        foreach (SupportedType supportedType in All)
        {
            typeToTypeMap.Add(supportedType.type, supportedType);
        }

        CodeTypeReferenceExpression provType = new CodeTypeReferenceExpression(typeof(InstrumentationType));

        CodeFieldReferenceExpression provTypeEvent = new CodeFieldReferenceExpression(provType, "Event");
        CodeAttributeArgument        attrArgEvent  = new CodeAttributeArgument(provTypeEvent);
        attrProvEvent = new CodeAttributeDeclaration(typeof(InstrumentationClassAttribute).Name, new CodeAttributeArgument[] { attrArgEvent });

        CodeFieldReferenceExpression provTypeAbstract = new CodeFieldReferenceExpression(provType, "Abstract");
        CodeAttributeArgument        attrArgAbstract  = new CodeAttributeArgument(provTypeAbstract);
        attrProvAbstract = new CodeAttributeDeclaration(typeof(InstrumentationClassAttribute).Name, new CodeAttributeArgument[] { attrArgAbstract });

        CodeFieldReferenceExpression provTypeInstance = new CodeFieldReferenceExpression(provType, "Instance");
        CodeAttributeArgument        attrArgInstance  = new CodeAttributeArgument(provTypeInstance);
        attrProvInstance = new CodeAttributeDeclaration(typeof(InstrumentationClassAttribute).Name, new CodeAttributeArgument[] { attrArgInstance });
    }
コード例 #45
0
 private IBindingSourceAttributeValueProvider CreateAttributeValue(CodeAttributeArgument customAttributeArgument)
 {
     return(new VsBindingSourceAttributeValueProvider(customAttributeArgument));
 }
コード例 #46
0
    public override void Interpret(Script script)
    {
        MaxProgress = script.Entries.Count;
        for (int i = 0; i < script.Entries.Count; i++)
        {
            if (!Engine.Working)
            {
                Thread.CurrentThread.Abort();
            }
            CurProgress = i;
            var entry = script.Entries[i];

            var eTypeName = NameTranslator.CSharpNameFromScript(entry.Args[0].ToString().ClearFromBraces()).TrimEnd(' ');
            //Debug.Log(eTypeName);
            //Engine.ListTypes();
            var eType = Engine.GetType(eTypeName);
            if (eType == null)
            {
                Debug.LogErrorFormat("Can't find event {0} in {1}", eTypeName, entry);
            }
            CodeTypeDeclaration codeType = new CodeTypeDeclaration();
            //codeType.CustomAttributes.
            codeType.BaseTypes.Add(new CodeTypeReference(typeof(Reaction)));
            codeType.Name = entry.Identifier as string;
            codeTypes.Add(codeType);

            if (ScriptEngine.AnalyzeDebug)
            {
                Debug.LogWarning((entry.Identifier as string).ToUpper());
            }

            var ctx = entry.Context as Context;
            if (ctx == null)
            {
                continue;
            }
            var actionMethod        = typeof(Reaction).GetMethod("Action");
            var scopeMethod         = typeof(Reaction).GetMethod("Filter");
            var personalScopeMethod = typeof(PersonalReaction).GetMethod("RootFilter");
            var eventScopeMethod    = typeof(PersonalReaction).GetMethod("EventFilter");

            CodeAttributeDeclaration attr = new CodeAttributeDeclaration("ReactionAttribute");
            codeType.CustomAttributes.Add(attr);
            CodeAttributeArgument repeatableArg = new CodeAttributeArgument("IsRepeatable", new CodeSnippetExpression("false"));
            CodeAttributeArgument eventFeedArg;
            CodeAttributeArgument eventTypeArg = new CodeAttributeArgument("EventType", new CodeSnippetExpression("\"\""));
            attr.Arguments.Add(repeatableArg);
            attr.Arguments.Add(eventTypeArg);
            FunctionBlock dependenciesBlock = new FunctionBlock(null, null, codeType);
            List <string> deps       = new List <string>();
            bool          isPersonal = false;
            for (int j = 0; j < ctx.Entries.Count; j++)
            {
                var op = ctx.Entries[j] as Operator;
                if (op == null)
                {
                    continue;
                }
                if (op.Identifier as string == "feed")
                {
                    var feedTypeName = (op.Context as InternalDSL.Expression).Operands[0].ToString().ClearFromBraces().TrimEnd(' ');
                    var type         = Engine.FindType(NameTranslator.CSharpNameFromScript(feedTypeName));
                    eventFeedArg = new CodeAttributeArgument("EventFeed",
                                                             new CodeSnippetExpression("typeof({0})".Fmt(type.Name)));

                    attr.Arguments.Add(eventFeedArg);
                    //here I should change the reaction to personal one
                    codeType.BaseTypes.Clear();
                    codeType.BaseTypes.Add(typeof(PersonalReaction));
                    isPersonal = true;
                }
                else if (op.Identifier as string == "is_repeatable")
                {
                    repeatableArg.Value = new CodeSnippetExpression("true");
                }
                else if (op.Identifier as string == "scope")
                {
                    //It's a filter function
                    //					Debug.Log (op.Context.GetType ());
                    if (ScriptEngine.AnalyzeDebug)
                    {
                        Debug.Log((op.Context as Expression).Operands[0].GetType());
                    }

                    (((op.Context as Expression).Operands[0] as ExprAtom).Content as Scope).Parts.Add("true");
                    DeclareVariableStatement retVal = new DeclareVariableStatement();
                    retVal.IsReturn       = true;
                    retVal.Name           = "applicable";
                    retVal.Type           = typeof(bool);
                    retVal.InitExpression = "false";

                    if (isPersonal)
                    {
                        DeclareVariableStatement rootField = new DeclareVariableStatement();
                        rootField.Name           = "root";
                        rootField.Type           = typeof(GameObject);
                        rootField.InitExpression = "false";
                        rootField.IsArg          = true;
                        rootField.IsContext      = true;
                        string eventVar = "var root = this.root;";
                        CreateEventFunction("RootFilter", op.Context, eType, codeType, personalScopeMethod, false, retVal, rootField, eventVar);
                    }
                    else
                    {
                        DeclareVariableStatement rootField = new DeclareVariableStatement();
                        rootField.Name           = "trigger_root";
                        rootField.Type           = typeof(GameObject);
                        rootField.InitExpression = "false";
                        rootField.IsArg          = true;
                        rootField.IsContext      = true;
                        string eventVar = "var trigger_root = this.trigger.Root;";
                        CreateEventFunction("Filter", op.Context, eType, codeType, scopeMethod, true, rootField, eventVar, retVal);
                    }
                    //CreateFilterFunction (op.Context as Expression, codeType);
                }
                else if (op.Identifier as string == "event_scope")
                {
                    //It's a filter function
                    //					Debug.Log (op.Context.GetType ());
                    if (ScriptEngine.AnalyzeDebug)
                    {
                        Debug.Log((op.Context as Expression).Operands[0].GetType());
                    }

                    (((op.Context as Expression).Operands[0] as ExprAtom).Content as Scope).Parts.Add("true");
                    DeclareVariableStatement retVal = new DeclareVariableStatement();
                    retVal.IsReturn       = true;
                    retVal.Name           = "applicable";
                    retVal.Type           = typeof(bool);
                    retVal.InitExpression = "false";
                    DeclareVariableStatement rootField = new DeclareVariableStatement();
                    rootField.Name           = "root";
                    rootField.Type           = typeof(GameObject);
                    rootField.InitExpression = "false";
                    rootField.IsArg          = true;
                    rootField.IsContext      = false;
                    string eventVar = "var root = this.root;";
                    DeclareVariableStatement triggerRoot = new DeclareVariableStatement();
                    triggerRoot.Name           = "trigger_root";
                    triggerRoot.Type           = typeof(GameObject);
                    triggerRoot.InitExpression = "false";
                    triggerRoot.IsArg          = true;
                    triggerRoot.IsContext      = true;
                    string triggerRootVar = "var trigger_root = this.trigger.Root;";
                    CreateEventFunction("EventFilter", op.Context, eType, codeType, eventScopeMethod, true, retVal, rootField, triggerRoot, triggerRootVar, eventVar);

                    //CreateFilterFunction (op.Context as Expression, codeType);
                }
                else if (op.Identifier as string == "action")
                {
                    //It's an action function
                    if (isPersonal)
                    {
                        DeclareVariableStatement rootField = new DeclareVariableStatement();
                        rootField.Name           = "root";
                        rootField.Type           = typeof(GameObject);
                        rootField.InitExpression = "false";
                        rootField.IsArg          = true;
                        rootField.IsContext      = true;
                        string eventVar = "var root = this.root;";
                        DeclareVariableStatement triggerRoot = new DeclareVariableStatement();
                        triggerRoot.Name           = "trigger_root";
                        triggerRoot.Type           = typeof(GameObject);
                        triggerRoot.InitExpression = "false";
                        triggerRoot.IsArg          = true;
                        triggerRoot.IsContext      = false;
                        string triggerRootVar = "var trigger_root = this.trigger.Root;";
                        CreateEventFunction(op.Identifier as string, op.Context, eType, codeType, actionMethod, false, rootField, triggerRoot, triggerRootVar, eventVar);
                    }
                    else
                    {
                        DeclareVariableStatement triggerRoot = new DeclareVariableStatement();
                        triggerRoot.Name           = "trigger_root";
                        triggerRoot.Type           = typeof(GameObject);
                        triggerRoot.InitExpression = "false";
                        triggerRoot.IsArg          = true;
                        triggerRoot.IsContext      = true;
                        string triggerRootVar = "var trigger_root = this.trigger.Root;";
                        CreateEventFunction(op.Identifier as string, op.Context, eType, codeType, actionMethod, true, triggerRoot, triggerRootVar);
                    }
                }
            }
            CodeMemberProperty eventRootProp = new CodeMemberProperty();
            eventRootProp.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            CodeMemberField eventRootField = new CodeMemberField();
            eventRootProp.Type  = new CodeTypeReference(typeof(Event));
            eventTypeArg.Value  = new CodeSnippetExpression("typeof({0})".Fmt(eTypeName));
            eventRootField.Type = new CodeTypeReference(eType);
            codeType.Members.Add(eventRootField);
            codeType.Members.Add(eventRootProp);
            if (isPersonal)
            {
                eventRootProp.Name  = "Event";
                eventRootField.Name = "trigger";
                eventRootProp.GetStatements.Add(new CodeSnippetStatement("return trigger;"));
                eventRootProp.SetStatements.Add(new CodeSnippetStatement("trigger = value as {0};".Fmt(eTypeName)));
            }
            else
            {
                eventRootProp.Name  = "Event";
                eventRootField.Name = "trigger";
                eventRootProp.GetStatements.Add(new CodeSnippetStatement("return trigger;"));
                eventRootProp.SetStatements.Add(new CodeSnippetStatement("trigger = value as {0};".Fmt(eTypeName)));
            }
        }

        CurProgress = MaxProgress;
        foreach (var type in codeTypes)
        {
            cNamespace.Types.Add(type);
        }

        CSharpCodeProvider   provider = new CSharpCodeProvider();
        CodeGeneratorOptions options  = new CodeGeneratorOptions();
        var writer = new StringWriter();

        provider.GenerateCodeFromNamespace(cNamespace, writer, options);
        Engine.GetPlugin <ScriptCompiler>().AddSource(writer.ToString());
    }
コード例 #47
0
        private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, String nameSpace, String baseName, String resourcesNamespace, bool internalClass, bool useStatic, bool supportsTryCatch)
        {
            const String tmpVarName = "temp";
            String       resMgrCtorParam;

            if (resourcesNamespace != null)
            {
                if (resourcesNamespace.Length > 0)
                {
                    resMgrCtorParam = resourcesNamespace + '.' + baseName;
                }
                else
                {
                    resMgrCtorParam = baseName;
                }
            }
            else if ((nameSpace != null) && (nameSpace.Length > 0))
            {
                resMgrCtorParam = nameSpace + '.' + baseName;
            }
            else
            {
                resMgrCtorParam = baseName;
            }

            CodeAttributeDeclaration suppressMessageAttrib = new CodeAttributeDeclaration(new CodeTypeReference(typeof(System.Diagnostics.CodeAnalysis.SuppressMessageAttribute)));

            suppressMessageAttrib.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference;
            suppressMessageAttrib.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("Microsoft.Performance")));
            suppressMessageAttrib.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("CA1811:AvoidUncalledPrivateCode")));

            // Emit a constructor - make it protected even if it is a "static" class to allow subclassing
            CodeConstructor ctor = new CodeConstructor();

            ctor.CustomAttributes.Add(suppressMessageAttrib);
            if (useStatic || internalClass)
            {
                ctor.Attributes = MemberAttributes.FamilyAndAssembly;
            }
            else
            {
                ctor.Attributes = MemberAttributes.Public;
            }
            srClass.Members.Add(ctor);

            // Emit _resMgr field.
            CodeTypeReference ResMgrCodeTypeReference = new CodeTypeReference(typeof(ResourceManager), CodeTypeReferenceOptions.GlobalReference);
            CodeMemberField   field = new CodeMemberField(ResMgrCodeTypeReference, ResMgrFieldName);

            field.Attributes = MemberAttributes.Private;
            if (useStatic)
            {
                field.Attributes |= MemberAttributes.Static;
            }
            srClass.Members.Add(field);

            // Emit _resCulture field, and leave it set to null.
            CodeTypeReference CultureTypeReference = new CodeTypeReference(typeof(CultureInfo), CodeTypeReferenceOptions.GlobalReference);

            field            = new CodeMemberField(CultureTypeReference, CultureInfoFieldName);
            field.Attributes = MemberAttributes.Private;
            if (useStatic)
            {
                field.Attributes |= MemberAttributes.Static;
            }
            srClass.Members.Add(field);

            // Emit ResMgr property
            CodeMemberProperty resMgr = new CodeMemberProperty();

            srClass.Members.Add(resMgr);
            resMgr.Name   = ResMgrPropertyName;
            resMgr.HasGet = true;
            resMgr.HasSet = false;
            resMgr.Type   = ResMgrCodeTypeReference;
            if (internalClass)
            {
                resMgr.Attributes = MemberAttributes.Assembly;
            }
            else
            {
                resMgr.Attributes = MemberAttributes.Public;
            }
            if (useStatic)
            {
                resMgr.Attributes |= MemberAttributes.Static;
            }

            // Mark the ResMgr property as advanced
            CodeTypeReference editorBrowsableStateTypeRef = new CodeTypeReference(typeof(System.ComponentModel.EditorBrowsableState));

            editorBrowsableStateTypeRef.Options = CodeTypeReferenceOptions.GlobalReference;

            CodeAttributeArgument    editorBrowsableStateAdvanced     = new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(editorBrowsableStateTypeRef), "Advanced"));
            CodeAttributeDeclaration editorBrowsableAdvancedAttribute = new CodeAttributeDeclaration("System.ComponentModel.EditorBrowsableAttribute",
                                                                                                     new CodeAttributeArgument[] { editorBrowsableStateAdvanced });

            editorBrowsableAdvancedAttribute.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference;
            resMgr.CustomAttributes.Add(editorBrowsableAdvancedAttribute);

            // Emit the Culture property (read/write)
            CodeMemberProperty culture = new CodeMemberProperty();

            srClass.Members.Add(culture);
            culture.Name   = CultureInfoPropertyName;
            culture.HasGet = true;
            culture.HasSet = true;
            culture.Type   = CultureTypeReference;
            if (internalClass)
            {
                culture.Attributes = MemberAttributes.Assembly;
            }
            else
            {
                culture.Attributes = MemberAttributes.Public;
            }

            if (useStatic)
            {
                culture.Attributes |= MemberAttributes.Static;
            }

            // Mark the Culture property as advanced
            culture.CustomAttributes.Add(editorBrowsableAdvancedAttribute);


            /*
             * // Here's what I'm trying to emit.  Since not all languages support
             * // try/finally, we'll avoid our double lock pattern here.
             * // This will only hurt perf when we get two threads racing through
             * // this method the first time.  Unfortunate, but not a big deal.
             * // Also, the .NET Compact Framework doesn't support
             * // Thread.MemoryBarrier (they only run on processors w/ a strong
             * // memory model, and who knows about IA64...)
             * // Once we have Interlocked.CompareExchange<T>, we should use it here.
             * if (_resMgr == null) {
             *    ResourceManager tmp = new ResourceManager("<resources-name-with-namespace>", typeof("<class-name>").Assembly);
             *    _resMgr = tmp;
             * }
             * return _resMgr;
             */
            CodeFieldReferenceExpression  field_resMgr        = new CodeFieldReferenceExpression(null, ResMgrFieldName);
            CodeMethodReferenceExpression object_equalsMethod = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Object)), "ReferenceEquals");

            CodeMethodInvokeExpression isResMgrNull = new CodeMethodInvokeExpression(object_equalsMethod, new CodeExpression[] { field_resMgr, new CodePrimitiveExpression(null) });

            // typeof(<class-name>).Assembly
            CodePropertyReferenceExpression getAssembly = new CodePropertyReferenceExpression(new CodeTypeOfExpression(new CodeTypeReference(srClass.Name)), "Assembly");

            // new ResourceManager(resMgrCtorParam, typeof(<class-name>).Assembly);
            CodeObjectCreateExpression newResMgr = new CodeObjectCreateExpression(ResMgrCodeTypeReference, new CodePrimitiveExpression(resMgrCtorParam), getAssembly);

            CodeStatement[] init = new CodeStatement[2];
            init[0] = new CodeVariableDeclarationStatement(ResMgrCodeTypeReference, tmpVarName, newResMgr);
            init[1] = new CodeAssignStatement(field_resMgr, new CodeVariableReferenceExpression(tmpVarName));

            resMgr.GetStatements.Add(new CodeConditionStatement(isResMgrNull, init));
            resMgr.GetStatements.Add(new CodeMethodReturnStatement(field_resMgr));

            // Add a doc comment to the ResourceManager property
            resMgr.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true));
            resMgr.Comments.Add(new CodeCommentStatement(SR.GetString(SR.ResMgrPropertyComment), true));
            resMgr.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true));


            // Emit code for Culture property
            CodeFieldReferenceExpression field_resCulture = new CodeFieldReferenceExpression(null, CultureInfoFieldName);

            culture.GetStatements.Add(new CodeMethodReturnStatement(field_resCulture));

            CodePropertySetValueReferenceExpression newCulture = new CodePropertySetValueReferenceExpression();

            culture.SetStatements.Add(new CodeAssignStatement(field_resCulture, newCulture));

            // Add a doc comment to Culture property
            culture.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true));
            culture.Comments.Add(new CodeCommentStatement(SR.GetString(SR.CulturePropertyComment1), true));
            culture.Comments.Add(new CodeCommentStatement(SR.GetString(SR.CulturePropertyComment2), true));
            culture.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true));
        }
コード例 #48
0
        private string GenerateCode(out string extension)
        {
            CodeDomProvider provider;

            extension = null;
            bool flag = false;

            try
            {
                provider = CodeDomProvider.CreateProvider(this.Language);
            }
            catch (ConfigurationException exception)
            {
                base.Log.LogErrorWithCodeFromResources("WriteCodeFragment.CouldNotCreateProvider", new object[] { this.Language, exception.Message });
                return(null);
            }
            catch (SecurityException exception2)
            {
                base.Log.LogErrorWithCodeFromResources("WriteCodeFragment.CouldNotCreateProvider", new object[] { this.Language, exception2.Message });
                return(null);
            }
            extension = provider.FileExtension;
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            CodeNamespace   namespace2  = new CodeNamespace();

            compileUnit.Namespaces.Add(namespace2);
            string text = Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("WriteCodeFragment.Comment", new object[] { DateTime.Now.ToString() });

            namespace2.Comments.Add(new CodeCommentStatement(text));
            if (this.AssemblyAttributes == null)
            {
                return(string.Empty);
            }
            namespace2.Imports.Add(new CodeNamespaceImport("System"));
            namespace2.Imports.Add(new CodeNamespaceImport("System.Reflection"));
            foreach (ITaskItem item in this.AssemblyAttributes)
            {
                CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(new CodeTypeReference(item.ItemSpec));
                IDictionary dictionary             = item.CloneCustomMetadata();
                List <CodeAttributeArgument> list  = new List <CodeAttributeArgument>(new CodeAttributeArgument[dictionary.Count + 1]);
                List <CodeAttributeArgument> list2 = new List <CodeAttributeArgument>();
                foreach (DictionaryEntry entry in dictionary)
                {
                    string key  = (string)entry.Key;
                    string str3 = (string)entry.Value;
                    if (key.StartsWith("_Parameter", StringComparison.OrdinalIgnoreCase))
                    {
                        int num;
                        if (!int.TryParse(key.Substring("_Parameter".Length), out num))
                        {
                            base.Log.LogErrorWithCodeFromResources("General.InvalidValue", new object[] { key, "WriteCodeFragment" });
                            return(null);
                        }
                        if ((num > list.Count) || (num < 1))
                        {
                            base.Log.LogErrorWithCodeFromResources("WriteCodeFragment.SkippedNumberedParameter", new object[] { num });
                            return(null);
                        }
                        list[num - 1] = new CodeAttributeArgument(string.Empty, new CodePrimitiveExpression(str3));
                    }
                    else
                    {
                        list2.Add(new CodeAttributeArgument(key, new CodePrimitiveExpression(str3)));
                    }
                }
                bool flag2 = false;
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i] == null)
                    {
                        flag2 = true;
                    }
                    else
                    {
                        if (flag2)
                        {
                            base.Log.LogErrorWithCodeFromResources("WriteCodeFragment.SkippedNumberedParameter", new object[] { i + 1 });
                            return(null);
                        }
                        declaration.Arguments.Add(list[i]);
                    }
                }
                foreach (CodeAttributeArgument argument in list2)
                {
                    declaration.Arguments.Add(argument);
                }
                compileUnit.AssemblyCustomAttributes.Add(declaration);
                flag = true;
            }
            StringBuilder sb = new StringBuilder();

            using (StringWriter writer = new StringWriter(sb, CultureInfo.CurrentCulture))
            {
                provider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions());
            }
            string str4 = sb.ToString();

            if (!flag)
            {
                return(string.Empty);
            }
            return(str4);
        }
コード例 #49
0
        /// <summary>
        ///     Method called by the tool importing the wsdl whenever a operation/web method is found in the wsdl file.
        /// </summary>
        /// <remarks>
        ///     <para>
        ///         This is called once per binding in the wsdl. Each binding is associated with a different
        ///         web method. ImportMethod add attributes to each web method and the web service class
        ///         to add client (proxy) validation capabilities.
        ///     </para>
        ///     <para>
        ///         This class depends on the wsdl file containing the definition of
        ///         just a single service. At present the wsdl files generated by
        ///         the WebService class create wsdl files that meet this restriction.
        ///     </para>
        /// </remarks>
        /// <param name="metadata">Code DOM being created by tool</param>
        public override void ImportMethod(CodeAttributeDeclarationCollection metadata)
        {
            Argument.Assert.IsNotNull(metadata, "metadata");

            // get the ImportContext, it provides access
            // to Wsdl File
            SoapProtocolImporter importer = ImportContext;

            // if there are no validation attributes in any bindings then no
            // DevInterop.Web.Service attributes should be added to
            // generated code. This prevents unneeded attributes from
            // being added to code that does not make use of them
            if (false == CheckedForValidation)
            {
                // this is what does the checking for validation
                CheckedForValidation = true;
                // check every binding in wsdl file for this service
                foreach (Binding binding in importer.Service.ServiceDescription.Bindings)
                {
                    // check every operation in the binding
                    foreach (OperationBinding operationBinding in binding.Operations)
                    {
                        // check to see if the binding has a validation extensibility element
                        HasValidation = null != operationBinding.Input.Extensions.Find("validation", ValidationNamespaces.DevInterop);
                        if (HasValidation)
                        {
                            break;
                        }
                    }
                    if (HasValidation)
                    {
                        break;
                    }
                }
            }
            if (false == HasValidation)
            {
                return;
            }
            // do web service (rather than web method) specific code
            // generation when first method is processed
            if (MethodPos == 0)
            {
                // add a comment to the class to indicate the source of the extension creating the code
                importer.CodeTypeDeclaration.Comments.Add(new CodeCommentStatement("Proxy validation code generated by http://www.DevInterop.net"));
                // Add an attribute to the web service for each schema
                // found in the wsdl file. This will be used for client side validation
                // of messages
                foreach (XmlSchema s in importer.ConcreteSchemas)
                {
                    // string builder is needed to hold serialzation fo schems
                    StringBuilder sb = new StringBuilder();
                    // text writer wraped around string builder captures schema
                    XmlTextWriter xwr = new XmlTextWriter(new StringWriter(sb));
                    // write schema to string builder
                    s.Write(xwr);
                    // convert string builder rto string
                    string schema = sb.ToString();
                    // strip off xml declaration, it is not needed
                    // and its encoding may cause problems
                    schema = schema.Substring(schema.IndexOf("?>") + 2);
                    // build an attribute (a ValdiationSchemaValueAttribute) to be
                    // inserted into the code dom
                    CodeAttributeDeclaration attr =
                        new CodeAttributeDeclaration(typeof(ValidationSchemaValueAttribute).FullName);
                    // build an unnamed attribute argument.
                    CodeAttributeArgument arg =
                        new CodeAttributeArgument(string.Empty,
                                                  // the value of this argument is the string which represents the schema
                                                  new CodePrimitiveExpression(schema));
                    // add this argument to the attribute
                    attr.Arguments.Add(arg);
                    // add this attribute to the code dom. This will add it
                    // to the web service class being processed
                    importer.CodeTypeDeclaration.CustomAttributes.Add(attr);
                }
                // The first binding is being looked at to find the namespace
                // declaration extensibility elements in the binding that contains it.
                // In the current implementation only the binding for the
                // first operation found is checked.
                // This would have to be enhanced
                // to support multiple services defined in a single wsdl file
                Binding    firstBinding = importer.Binding;
                XmlElement ov           = firstBinding.Extensions.Find("validationNS", ValidationNamespaces.DevInterop);
                // no need to process if no validation extensibiltity element exists
                if (null != ov)
                {
                    // make an XPathDocument out of the XmlElement that was found.
                    XPathDocument xpdoc = new XPathDocument(new XmlNodeReader(ov));
                    // now make a navigator to use to find things
                    XPathNavigator xpnav = xpdoc.CreateNavigator();
                    // A namespace manager will be required to use XPathExpressions
                    XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xpnav.NameTable);
                    // add the DevInterop.Web.Services to the collection of namespaces
                    namespaceManager.AddNamespace("dm", ValidationNamespaces.DevInterop);
                    // compile an XPath expression that will find all of the
                    // namespace bindings in the extensibility element
                    XPathExpression exp = xpnav.Compile("/dm:validationNS/dm:namespaces/dm:namespace");
                    // add the namespace to the expression
                    exp.SetContext(namespaceManager);
                    // find all of the namespace bindings
                    XPathNodeIterator itr = xpnav.Select(exp);
                    // iterate through all of the namespace bindings
                    // that were found
                    while (itr.MoveNext())
                    {
                        // clone the iterator so it is not moved while you look
                        // for parts of the namespace binding
                        XPathNodeIterator assert = itr.Clone();
                        // first child of the binding is the prefix
                        assert.Current.MoveToFirstChild();
                        // create an AssertNamspaceBindingAttribute to be inserted into the code dom
                        CodeAttributeDeclaration attr = new CodeAttributeDeclaration(typeof(AssertNamespaceBindingAttribute).FullName);
                        // make the argurments for the AssertNamespaceBindingAttribute
                        CodeAttributeArgument arg =
                            new CodeAttributeArgument(string.Empty,
                                                      new CodePrimitiveExpression(assert.Current.Value));
                        // add the first argument, that is the prefix

                        attr.Arguments.Add(arg);
                        // move to the next sibling of the prefix, that is the namespace uri itself
                        assert.Current.MoveToNext();
                        // build an argument out of the namespace uri
                        arg =
                            new CodeAttributeArgument(string.Empty,
                                                      new CodePrimitiveExpression(assert.Current.Value));
                        // add the namespace uri as the second argument of the constructor
                        attr.Arguments.Add(arg);
                        // add this AssertNamespaceBindingAttribute to the class
                        importer.CodeTypeDeclaration.CustomAttributes.Add(attr);
                    }
                }
                // keep method count up to date
                MethodPos++;
            }
            // get binding for method being processed
            OperationBinding methodBinding = importer.OperationBinding;
            // now see if it has a validation extensibility element from the DevInterop.Web.Services namespace
            XmlElement validationExtensibity =
                methodBinding.Input.Extensions.Find("validation", ValidationNamespaces.DevInterop);

            if (null != validationExtensibity)
            {
                // if there was an extensibilty element, process it
                // turn extensibility element into XPathDocument so
                // you can use XPath to find the parts of it you want.
                XPathDocument xpdoc = new XPathDocument(new XmlNodeReader(validationExtensibity));
                // make a navigator to look things up
                XPathNavigator xpnav = xpdoc.CreateNavigator();
                // make a namespace manager for the XPath expressions
                XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xpnav.NameTable);
                // add the DevInterop.Web.Services namespac to it
                namespaceManager.AddNamespace("dm", ValidationNamespaces.DevInterop);
                // make an XPath expression that can be used to look for
                // asserts in the extensibilty element
                XPathExpression expression = xpnav.Compile("/dm:validation/dm:assertions/dm:assert");
                // add namespace to XPath expression
                expression.SetContext(namespaceManager);
                // make an XPath expression that can be evaluated to see
                // if schema validation is enabled
                XPathExpression validate = xpnav.Compile("/dm:validation/@SchemaValidation='true'");
                // add the namepaces to the validate XPath expression
                validate.SetContext(namespaceManager);
                // build a attribute that can be used to add a Validation attribute
                CodeAttributeDeclaration validateAttr = new CodeAttributeDeclaration(typeof(ValidationAttribute).FullName);
                // build argument for the validation attribute
                CodeAttributeArgument schemaArg =
                    new CodeAttributeArgument("SchemaValidation",
                                              // evaluate the validation
                                              new CodePrimitiveExpression((bool)xpnav.Evaluate(validate)));
                // added the arguement to the validation attribute, this
                // determines whether or not shchema validation is done
                validateAttr.Arguments.Add(schemaArg);
                // add the attribute to the method
                metadata.Add(validateAttr);
                // now find all of the asserts in the extensibilty element
                XPathNodeIterator pathNodeIterator = xpnav.Select(expression);
                // iterate through all of them
                while (pathNodeIterator.MoveNext())
                {
                    // clone the iterator so it is not changed while looking for its parts
                    XPathNodeIterator assert = pathNodeIterator.Clone();
                    // move to the first child, this is the XPath expression itself
                    assert.Current.MoveToFirstChild();
                    // create an AssertAttribute
                    CodeAttributeDeclaration attr = new CodeAttributeDeclaration(typeof(AssertAttribute).FullName);
                    // create an argument for the AssertAttribute constructor
                    CodeAttributeArgument arg =
                        new CodeAttributeArgument(string.Empty,
                                                  // use the XPath expression string as the first argument
                                                  new CodePrimitiveExpression(assert.Current.Value));
                    // add the first argument to the constructor
                    attr.Arguments.Add(arg);
                    // move to the next sibling of the xpath expression,
                    // that is the message to be passed back if the
                    // assert is not true
                    assert.Current.MoveToNext();
                    // now create an argument for the second parameter of
                    // the AssertAttribute constructor
                    arg =
                        new CodeAttributeArgument(string.Empty,
                                                  // use the error message itself as the second argument value
                                                  new CodePrimitiveExpression(assert.Current.Value));
                    // add the second argument to the constructor
                    attr.Arguments.Add(arg);
                    // add the AssertAttribute to the method
                    metadata.Add(attr);
                }
            }
        }
コード例 #50
0
	// Output an attribute argument.
	protected virtual void OutputAttributeArgument
				(CodeAttributeArgument arg)
			{
				if(arg.Name != null)
				{
					OutputIdentifier(arg.Name);
					Output.Write("=");
				}
				((ICodeGenerator)this).GenerateCodeFromExpression
						(arg.Value, writer.InnerWriter, Options);
			}
コード例 #51
0
		public void Ctor_NullObjectInArguments_ThrowsArgumentNullException()
		{
			CodeAttributeArgument[] arguments = new CodeAttributeArgument[] { null };
			Assert.Throws<ArgumentNullException>("value", () => new CodeAttributeDeclaration("name", arguments));
			Assert.Throws<ArgumentNullException>("value", () => new CodeAttributeDeclaration(new CodeTypeReference(), arguments));
		}
	public void AddRange(CodeAttributeArgument[] value) {}
コード例 #53
0
ファイル: CodeGenerator.cs プロジェクト: dotnet/corefx
 protected virtual void OutputAttributeArgument(CodeAttributeArgument arg)
 {
     if (!string.IsNullOrEmpty(arg.Name))
     {
         OutputIdentifier(arg.Name);
         Output.Write('=');
     }
     ((ICodeGenerator)this).GenerateCodeFromExpression(arg.Value, _output.InnerWriter, _options);
 }
コード例 #54
0
		public void Ctor_Default()
		{
			var argument = new CodeAttributeArgument();
			Assert.Empty(argument.Name);
			Assert.Null(argument.Value);
		}