public void Constructor1_Deny_Unrestricted()
        {
            CodeCommentStatementCollection coll = new CodeCommentStatementCollection(array);

            coll.CopyTo(array, 0);
            Assert.AreEqual(1, coll.Add(ccs), "Add");
            Assert.AreSame(ccs, coll[0], "this[int]");
            coll.AddRange(array);
            coll.AddRange(coll);
            Assert.IsTrue(coll.Contains(ccs), "Contains");
            Assert.AreEqual(0, coll.IndexOf(ccs), "IndexOf");
            coll.Insert(0, ccs);
            coll.Remove(ccs);
        }
Beispiel #2
0
        public void AddRange()
        {
            CodeCommentStatement ccs1 = new CodeCommentStatement();
            CodeCommentStatement ccs2 = new CodeCommentStatement();
            CodeCommentStatement ccs3 = new CodeCommentStatement();

            CodeCommentStatementCollection coll1 = new CodeCommentStatementCollection();

            coll1.Add(ccs1);
            coll1.Add(ccs2);

            CodeCommentStatementCollection coll2 = new CodeCommentStatementCollection();

            coll2.Add(ccs3);
            coll2.AddRange(coll1);
            Assert.AreEqual(3, coll2.Count, "#1");
            Assert.AreEqual(1, coll2.IndexOf(ccs1), "#2");
            Assert.AreEqual(2, coll2.IndexOf(ccs2), "#3");
            Assert.AreEqual(0, coll2.IndexOf(ccs3), "#4");

            CodeCommentStatementCollection coll3 = new CodeCommentStatementCollection();

            coll3.Add(ccs3);
            coll3.AddRange(new CodeCommentStatement[] { ccs1, ccs2 });
            Assert.AreEqual(3, coll2.Count, "#5");
            Assert.AreEqual(1, coll2.IndexOf(ccs1), "#6");
            Assert.AreEqual(2, coll2.IndexOf(ccs2), "#7");
            Assert.AreEqual(0, coll2.IndexOf(ccs3), "#8");
        }
Beispiel #3
0
        public void AddRange_Self()
        {
            CodeCommentStatementCollection coll = new CodeCommentStatementCollection();

            coll.Add(new CodeCommentStatement());
            Assert.AreEqual(1, coll.Count, "#1");
            coll.AddRange(coll);
            Assert.AreEqual(2, coll.Count, "#2");
        }
Beispiel #4
0
    private void GenerateProperty(CodeMemberMethod getter, CodeMemberMethod setter = null)
    {
        CodeCommentStatementCollection comments = new CodeCommentStatementCollection();

        comments.AddRange(getter.Comments);
        getter.Comments.Clear();
        if (setter != null)
        {
            comments.AddRange(setter.Comments);
            setter.Comments.Clear();
        }
        if (type.Members.OfType <CodeSnippetTypeMember>().All(
                p => string.Compare(getter.Name, p.Name, StringComparison.OrdinalIgnoreCase) != 0) &&
            type.Members.OfType <CodeMemberProperty>().All(
                p => string.Compare(getter.Name, p.Name, StringComparison.OrdinalIgnoreCase) != 0))
        {
            CodeMemberProperty property = new CodeMemberProperty();
            property.Name       = getter.Name;
            property.Type       = getter.ReturnType;
            property.Attributes = setter == null ? getter.Attributes : setter.Attributes;
            property.GetStatements.AddRange(getter.Statements);
            if (setter != null)
            {
                CodeVariableDeclarationStatement variableStatement =
                    setter.Statements.OfType <CodeVariableDeclarationStatement>().First();
                CodeArrayCreateExpression       arrayExpression = (CodeArrayCreateExpression)variableStatement.InitExpression;
                CodeArgumentReferenceExpression argExpression   =
                    arrayExpression.Initializers.OfType <CodeArgumentReferenceExpression>().First();
                argExpression.ParameterName = "value";
                property.SetStatements.AddRange(setter.Statements);
            }
            CodeSnippetTypeMember completeProperty = AddAttributes(getter, setter, property);
            AddComments(completeProperty, comments, setter == null);
            type.Members.Add(completeProperty);
            if (type.Members.Contains(getter))
            {
                type.Members.Remove(getter);
            }
            if (setter != null && this.type.Members.Contains(setter))
            {
                type.Members.Remove(setter);
            }
        }
    }
        private void GenerateConstructors(CodeTypeDeclaration proxyClass, CodeTypeDeclaration contractInterface, EnableClientAccessAttribute enableClientAccessAttribute, CodeMethodInvokeExpression onCreatedExpression)
        {
            CodeTypeReference uriTypeRef     = CodeGenUtilities.GetTypeReference(typeof(Uri), this.ClientProxyGenerator, proxyClass);
            CodeTypeReference uriKindTypeRef = CodeGenUtilities.GetTypeReference(typeof(UriKind), this.ClientProxyGenerator, proxyClass);

            string            containingNamespace   = proxyClass.UserData["Namespace"] as string;
            CodeTypeReference contractTypeParameter =
                CodeGenUtilities.GetTypeReference(
                    containingNamespace + "." + proxyClass.Name + "." + contractInterface.Name,
                    containingNamespace,
                    true);

            // construct relative URI
            string         relativeServiceUri    = string.Format(CultureInfo.InvariantCulture, "{0}.svc", this._domainServiceDescription.DomainServiceType.FullName.Replace('.', '-'));
            CodeExpression relativeUriExpression = new CodeObjectCreateExpression(
                uriTypeRef,
                new CodePrimitiveExpression(relativeServiceUri),
                new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(uriKindTypeRef), "Relative"));

            // ----------------------------------------------------------------
            // Default ctor decl (using relative URI)
            // ----------------------------------------------------------------

            // ctor parameters
            List <CodeParameterDeclarationExpression> ctorParams = null;

            // base params
            List <CodeExpression> baseParams = new List <CodeExpression>(1);

            baseParams.Add(relativeUriExpression);

            // add <summary> doc comments
            string comment = string.Format(CultureInfo.CurrentCulture, Resource.CodeGen_Default_Constructor_Summary_Comments, proxyClass.Name);
            CodeCommentStatementCollection comments = CodeGenUtilities.GenerateSummaryCodeComment(comment, this.ClientProxyGenerator.IsCSharp);

            // <comments>...</comments>
            // public .ctor() : this(new Uri("Foo-Bar.svc", UriKind.Relative))
            GenerateConstructor(proxyClass, ctorParams, baseParams, comments, false);

            // ----------------------------------------------------------------
            // DomainContext(System.Uri serviceUri) ctor decl
            // ----------------------------------------------------------------

            // ctor params
            ctorParams = new List <CodeParameterDeclarationExpression>(1);
            ctorParams.Add(new CodeParameterDeclarationExpression(uriTypeRef, "serviceUri"));

            // add <summary> and <param> comments
            comments = CodeGenUtilities.GenerateSummaryCodeComment(string.Format(CultureInfo.CurrentCulture, Resource.EntityCodeGen_ConstructorComments_Summary_ServiceUri, proxyClass.Name), this.ClientProxyGenerator.IsCSharp);
            comments.AddRange(CodeGenUtilities.GenerateParamCodeComment("serviceUri", string.Format(CultureInfo.CurrentCulture, Resource.EntityCodeGen_ConstructorComments_Param_ServiceUri, this._domainServiceDescription.DomainServiceType.Name), this.ClientProxyGenerator.IsCSharp));

            // <comments>...</comments>
            // public .ctor(Uri serviceUri) : this(DomainContext.CreateDomainClient(typeof(TContract), serviceUri, true/false))

            // ctor base parameters
            baseParams = new List <CodeExpression>(1);
            CodeTypeReference domainContextRef = CodeGenUtilities.GetTypeReference(TypeConstants.DomainContextTypeFullName, proxyClass.UserData["Namespace"] as string, false);

            baseParams.Add(new CodeMethodInvokeExpression(
                               new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(domainContextRef), "CreateDomainClient"),
                               new CodeTypeOfExpression(contractTypeParameter),
                               new CodeArgumentReferenceExpression("serviceUri"),
                               new CodePrimitiveExpression(enableClientAccessAttribute.RequiresSecureEndpoint)));

            GenerateConstructor(proxyClass, ctorParams, baseParams, comments, false);

            // -----------------------------------------------------------------------
            // DomainContext(DomainClient domainClient) ctor decl
            // -----------------------------------------------------------------------

            // ctor parameters --[(DomainClient domainClient)]
            ctorParams = new List <CodeParameterDeclarationExpression>(1);
            ctorParams.Add(new CodeParameterDeclarationExpression(CodeGenUtilities.GetTypeReference(TypeConstants.DomainClientTypeFullName, proxyClass.UserData["Namespace"] as string, false), "domainClient"));

            // parameters to invoke on base -- [: base(domainClient)]
            baseParams = new List <CodeExpression>(1);
            baseParams.Add(new CodeArgumentReferenceExpression("domainClient"));

            // add <summary> and <param> comments
            comments = CodeGenUtilities.GenerateSummaryCodeComment(string.Format(CultureInfo.CurrentCulture, Resource.EntityCodeGen_ConstructorComments_Summary_DomainClientAccumulating, proxyClass.Name), this.ClientProxyGenerator.IsCSharp);
            comments.AddRange(CodeGenUtilities.GenerateParamCodeComment("domainClient", string.Format(CultureInfo.CurrentCulture, Resource.EntityCodeGen_ConstructorComments_Param_DomainClient), this.ClientProxyGenerator.IsCSharp));

            // <comments>...</comments>
            // public .ctor(DomainClient domainClient) : base(domainClient)]
            CodeConstructor proxyCtor = GenerateConstructor(proxyClass, ctorParams, baseParams, comments, true);

            proxyCtor.Statements.Add(onCreatedExpression);
        }
Beispiel #6
0
        public void AddRange_Null_Collection()
        {
            CodeCommentStatementCollection coll = new CodeCommentStatementCollection();

            coll.AddRange((CodeCommentStatementCollection)null);
        }
        /// <summary>
        /// Generates code for the given set of custom attributes
        /// </summary>
        /// <param name="proxyGenerator">Root client proxy generator</param>
        /// <param name="referencingType">The referencing type</param>
        /// <param name="getLogWarningMessage">The function to call to get the warning message to be logged</param>
        /// <param name="attributes">Collection of attributes for which to generate code</param>
        /// <param name="comments">Collection of comments that should be updated if errors are discovered.</param>
        /// <param name="customCommentHeader">A custom comment header that will be displayed for any generated comment errors.</param>
        /// <param name="forcePropagation">Indicates whether or not to force attribute propagation.</param>
        /// <returns>The collection of generated attribute declarations corresponding to <paramref name="attributes"/></returns>
        private static IEnumerable <CodeAttributeDeclaration> GenerateCustomAttributes(CodeDomClientCodeGenerator proxyGenerator, CodeTypeDeclaration referencingType, Func <AttributeBuilderException, string> getLogWarningMessage, IEnumerable <Attribute> attributes, CodeCommentStatementCollection comments, string customCommentHeader, bool forcePropagation)
        {
            bool emittedErrorCommentHeader         = false;
            List <CodeAttributeDeclaration> result = new List <CodeAttributeDeclaration>(attributes.Count());

            // Enumerate over attributes sorted by name.  Here, we sort by name to ensure that our
            // generated baselines (including possible error comments!) are ordered consistently.
            foreach (Attribute attribute in attributes.OrderBy(a => a.GetType().Name))
            {
                Type attributeType = attribute.GetType();

                // Check if this attribute should be blocked
                if (IsAttributeBlocked(attributeType))
                {
                    continue;
                }

                bool attributePropagated        = false;
                bool isDataAnnotationsAttribute = string.Equals(attributeType.Namespace, typeof(ValidationAttribute).Namespace, StringComparison.Ordinal);

                ICustomAttributeBuilder cab = GetCustomAttributeBuilder(attributeType);

                if (cab != null)
                {
                    AttributeDeclaration attributeDeclaration = null;
                    // If the attempt to build the attribute fails, log a clean error.
                    // One common exception path is InvalidOperationException arising from
                    // attributes that have been improperly constructed (see DisplayAttribute)
                    try
                    {
                        attributeDeclaration = cab.GetAttributeDeclaration(attribute);
                    }
                    catch (AttributeBuilderException attributeBuilderException)
                    {
                        // Ensure we've generated the attribute generation failure error header
                        GenerateCustomAttributesErrorCommentHeader(comments, customCommentHeader, ref emittedErrorCommentHeader);

                        // Generate comments stating the attribute couldn't be generated
                        comments.AddRange(ConstructCodeAttributeFailureComments(attributeBuilderException.Message));

                        // Log the build warning if a method was specified to get the warning message
                        if (getLogWarningMessage != null)
                        {
                            string warningMessage = getLogWarningMessage(attributeBuilderException);
                            proxyGenerator.LogWarning(warningMessage);
                        }

                        // Move on to the next attribute
                        continue;
                    }

                    // Null is acceptable indicator that code-gen was not possible.
                    if (attributeDeclaration != null)
                    {
                        if (!forcePropagation)
                        {
                            // Verify attribute's shared type|property|method requirements are met
                            ValidateAttributeDeclarationRequirements(proxyGenerator, attributeDeclaration);
                        }

                        if (attributeDeclaration.HasErrors)
                        {
                            // Only generate comments if the attribute is a DataAnnotations attribute
                            if (isDataAnnotationsAttribute)
                            {
                                // Ensure we've generated the attribute generation failure error header
                                GenerateCustomAttributesErrorCommentHeader(comments, customCommentHeader, ref emittedErrorCommentHeader);

                                // Generate attribute and an error message as comments
                                comments.AddRange(ConstructCodeAttributeFailureComments(proxyGenerator, attributeDeclaration));
                            }
                        }
                        else
                        {
                            // Generate the attribute declaration
                            CodeAttributeDeclaration codeAttributeDeclaration = CreateCodeAttributeDeclaration(proxyGenerator, referencingType, attributeDeclaration);
                            result.Add(codeAttributeDeclaration);
                            attributePropagated = true;
                        }
                    }
                }

                // We generate VS warnings in certain scenarios:
                //  - A DataAnnotation attribute type was not available on the client, user needs to add a reference.
                //  - An attribute subclassed ValidationAttribute (custom or framework) and we couldn't build it.
                if (!attributePropagated)
                {
                    // Was it a DA attribute that wasn't available?  If so, log a warning.
                    if (isDataAnnotationsAttribute)
                    {
                        CodeMemberShareKind shareKind = proxyGenerator.GetTypeShareKind(attributeType);
                        if (shareKind == CodeMemberShareKind.NotShared)
                        {
                            // Indicate that a reference to 'System.ComponentModel.DataAnnotations' is required.
                            proxyGenerator.LogWarning(
                                string.Format(
                                    CultureInfo.CurrentCulture,
                                    Resource.ClientCodeGen_Attribute_RequiresDataAnnotations,
                                    attributeType,
                                    proxyGenerator.ClientProjectName));
                        }
                    }
                    // Was it a validation attribute that we couldn't build?  If so, log a warning.
                    else if (cab == null && typeof(ValidationAttribute).IsAssignableFrom(attributeType))
                    {
                        // Indicate that a builder was not found, attribute does not meet heuristics.
                        proxyGenerator.LogWarning(
                            string.Format(
                                CultureInfo.CurrentCulture,
                                Resource.ClientCodeGen_Attribute_RequiresBuilder,
                                attributeType));
                    }
                }
            }

            // Issue -- CodeDom outputs the attributes in the order they are generated.
            // To allow consistent output for easy baseline comparisons, sort the list.
            result.Sort(new Comparison <CodeAttributeDeclaration>((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal)));
            return(result);
        }
Beispiel #8
0
    public void PostMembersHook(Smoke* smoke, Smoke.Class* klass, CodeTypeDeclaration type)
    {
        if (Util.IsQObject(klass))
        {
            CodeMemberProperty emit = new CodeMemberProperty();
            emit.Name = "Emit";
            emit.Attributes = MemberAttributes.Family | MemberAttributes.New | MemberAttributes.Final;
            emit.HasGet = true;
            emit.HasSet = false;

            string signalsIfaceName = "I" + type.Name + "Signals";
            CodeTypeReference returnType = new CodeTypeReference(signalsIfaceName);
            emit.Type = returnType;

            emit.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(
                returnType,
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Q_EMIT")
            )));

            type.Members.Add(emit);

            string className = ByteArrayManager.GetString(klass->className);
            int colon = className.LastIndexOf("::", StringComparison.Ordinal);
            string prefix = (colon != -1) ? className.Substring(0, colon) : string.Empty;

            IList typeCollection = Data.GetTypeCollection(prefix);
            CodeTypeDeclaration ifaceDecl = new CodeTypeDeclaration(signalsIfaceName);
            ifaceDecl.IsInterface = true;

            if (className != "QObject")
            {
                string parentClassName = ByteArrayManager.GetString(smoke->classes[smoke->inheritanceList[klass->parents]].className);
                colon = parentClassName.LastIndexOf("::", StringComparison.Ordinal);
                prefix = (colon != -1) ? parentClassName.Substring(0, colon) : string.Empty;
                if (colon != -1)
                {
                    parentClassName = parentClassName.Substring(colon + 2);
                }

                string parentInterface = (prefix != string.Empty) ? prefix.Replace("::", ".") + "." : string.Empty;
                parentInterface += "I" + parentClassName + "Signals";

                ifaceDecl.BaseTypes.Add(new CodeTypeReference(parentInterface));
            }
            Dictionary<CodeSnippetTypeMember, CodeMemberMethod> signalEvents = new Dictionary<CodeSnippetTypeMember, CodeMemberMethod>();
            GetSignals(smoke, klass, delegate(string signature, string name, string typeName, IntPtr metaMethod)
            {
                CodeMemberMethod signal = new CodeMemberMethod();
                signal.Attributes = MemberAttributes.Abstract;

                // capitalize the first letter
                StringBuilder builder = new StringBuilder(name);
                builder[0] = char.ToUpper(builder[0]);
                string tmp = builder.ToString();

                signal.Name = tmp;
                bool isRef;
                try
                {
                    if (typeName == string.Empty)
                        signal.ReturnType = new CodeTypeReference(typeof(void));
                    else
                        signal.ReturnType = Translator.CppToCSharp(typeName, out isRef);
                }
                catch (NotSupportedException)
                {
                    Debug.Print("  |--Won't wrap signal {0}::{1}", className, signature);
                    return;
                }

                CodeAttributeDeclaration attr = new CodeAttributeDeclaration("Q_SIGNAL",
                    new CodeAttributeArgument(new CodePrimitiveExpression(signature)));
                signal.CustomAttributes.Add(attr);

                int argNum = 1;
                StringBuilder fullNameBuilder = new StringBuilder("Slot");
                GetMetaMethodParameters(metaMethod, delegate(string paramType, string paramName)
                {
                    if (paramName == string.Empty)
                    {
                        paramName = "arg" + argNum.ToString();
                    }
                    argNum++;

                    CodeParameterDeclarationExpression param;
                    try
                    {
                        short id = smoke->IDType(paramType);
                        CodeTypeReference paramTypeRef;
                        if (id > 0)
                        {
                            paramTypeRef = Translator.CppToCSharp(smoke->types + id, out isRef);
                        }
                        else
                        {
                            if (!paramType.Contains("::"))
                            {
                                id = smoke->IDType(className + "::" + paramType);
                                if (id > 0)
                                {
                                    paramTypeRef = Translator.CppToCSharp(smoke->types + id, out isRef);
                                }
                                else
                                {
                                    paramTypeRef = Translator.CppToCSharp(paramType, out isRef);
                                }
                            }
                            else
                            {
                                paramTypeRef = Translator.CppToCSharp(paramType, out isRef);
                            }
                        }
                        param = new CodeParameterDeclarationExpression(paramTypeRef, paramName);
                    }
                    catch (NotSupportedException)
                    {
                        Debug.Print("  |--Won't wrap signal {0}::{1}", className, signature);
                        return;
                    }
                    if (isRef)
                    {
                        param.Direction = FieldDirection.Ref;
                    }
                    signal.Parameters.Add(param);
                    if (argNum == 2)
                    {
                        fullNameBuilder.Append('<');
                    }
                    fullNameBuilder.Append(param.Type.BaseType);
                    fullNameBuilder.Append(',');
                });
                if (fullNameBuilder[fullNameBuilder.Length - 1] == ',')
                {
                    fullNameBuilder[fullNameBuilder.Length - 1] = '>';
                }
                ifaceDecl.Members.Add(signal);
                CodeSnippetTypeMember signalEvent = new CodeSnippetTypeMember();
                signalEvent.Name = signal.Name;
                CodeSnippetTypeMember existing = signalEvents.Keys.FirstOrDefault(m => m.Name == signal.Name);
                if (existing != null)
                {
                    CodeSnippetTypeMember signalEventToUse;
                    CodeMemberMethod signalToUse;
                    if (signal.Parameters.Count == 0)
                    {
                        signalEventToUse = existing;
                        signalToUse = signalEvents[existing];
                    }
                    else
                    {
                        signalEventToUse = signalEvent;
                        signalToUse = signal;
                    }
                    string suffix = signalToUse.Parameters.Cast<CodeParameterDeclarationExpression>().Last().Name;
                    if (suffix.StartsWith("arg") && suffix.Length > 3 && char.IsDigit(suffix[3]))
                    {
                        string lastType = signalToUse.Parameters.Cast<CodeParameterDeclarationExpression>().Last().Type.BaseType;
                        suffix = lastType.Substring(lastType.LastIndexOf('.') + 1);
                    }
                    else
                    {
                        StringBuilder lastParamBuilder = new StringBuilder(suffix);
                        lastParamBuilder[0] = char.ToUpper(lastParamBuilder[0]);
                        suffix = lastParamBuilder.ToString();
                    }
                    signalEventToUse.Text = signalEventToUse.Text.Replace(signalEventToUse.Name, signalEventToUse.Name += suffix);
                }
                signalEvent.Text = string.Format(@"
        public event {0} {1}
        {{
            add
            {{
                QObject.Connect(this, Qt.SIGNAL(""{2}""), (QObject) value.Target, Qt.SLOT(value.Method.Name + ""{3}""));
            }}
            remove
            {{
                QObject.Disconnect(this, Qt.SIGNAL(""{2}""), (QObject) value.Target, Qt.SLOT(value.Method.Name + ""{3}""));
            }}
        }}", fullNameBuilder, signalEvent.Name, signature, signature.Substring(signature.IndexOf('(')));
                signalEvents.Add(signalEvent, signal);
            });

            typeCollection.Add(ifaceDecl);
            foreach (KeyValuePair<CodeSnippetTypeMember, CodeMemberMethod> signalEvent in signalEvents)
            {
                CodeSnippetTypeMember implementation = signalEvent.Key;
                CodeCommentStatementCollection comments = new CodeCommentStatementCollection();
                foreach (CodeTypeMember current in from CodeTypeMember member in type.Members
                                                   where member.Name == implementation.Name
                                                   select member)
                {
                    if (comments.Count == 0)
                    {
                        comments.AddRange(current.Comments);
                    }
                    current.Name = "On" + current.Name;
                }
                signalEvent.Value.Comments.AddRange(comments);
                signalEvent.Key.Comments.AddRange(comments);
                type.Members.Add(signalEvent.Key);
            }
        }
    }
Beispiel #9
0
        // CodeCommentStatementCollection
        public void CodeCommentStatementCollectionExample()
        {
            //<Snippet1>
            //<Snippet2>
            // Creates an empty CodeCommentStatementCollection.
            CodeCommentStatementCollection collection = new CodeCommentStatementCollection();

            //</Snippet2>

            //<Snippet3>
            // Adds a CodeCommentStatement to the collection.
            collection.Add(new CodeCommentStatement("Test comment"));
            //</Snippet3>

            //<Snippet4>
            // Adds an array of CodeCommentStatement objects to the collection.
            CodeCommentStatement[] comments = { new CodeCommentStatement("Test comment"), new CodeCommentStatement("Another test comment") };
            collection.AddRange(comments);

            // Adds a collection of CodeCommentStatement objects to the collection.
            CodeCommentStatementCollection commentsCollection = new CodeCommentStatementCollection();

            commentsCollection.Add(new CodeCommentStatement("Test comment"));
            commentsCollection.Add(new CodeCommentStatement("Another test comment"));
            collection.AddRange(commentsCollection);
            //</Snippet4>

            //<Snippet5>
            // Tests for the presence of a CodeCommentStatement in the
            // collection, and retrieves its index if it is found.
            CodeCommentStatement testComment = new CodeCommentStatement("Test comment");
            int itemIndex = -1;

            if (collection.Contains(testComment))
            {
                itemIndex = collection.IndexOf(testComment);
            }
            //</Snippet5>

            //<Snippet6>
            // Copies the contents of the collection, beginning at index 0,
            // to the specified CodeCommentStatement array.
            // 'comments' is a CodeCommentStatement array.
            collection.CopyTo(comments, 0);
            //</Snippet6>

            //<Snippet7>
            // Retrieves the count of the items in the collection.
            int collectionCount = collection.Count;

            //</Snippet7>

            //<Snippet8>
            // Inserts a CodeCommentStatement at index 0 of the collection.
            collection.Insert(0, new CodeCommentStatement("Test comment"));
            //</Snippet8>

            //<Snippet9>
            // Removes the specified CodeCommentStatement from the collection.
            CodeCommentStatement comment = new CodeCommentStatement("Test comment");

            collection.Remove(comment);
            //</Snippet9>

            //<Snippet10>
            // Removes the CodeCommentStatement at index 0.
            collection.RemoveAt(0);
            //</Snippet10>
            //</Snippet1>
        }
Beispiel #10
0
 private void GenerateProperties(ICollection<CodeMemberMethod> methods, IEnumerable<CodeMemberMethod> settersToUse, bool readOnly)
 {
     foreach (CodeMemberMethod setter in settersToUse)
     {
         if (!this.type.Members.Contains(setter))
         {
             continue;
         }
         string afterSet = setter.Name.Substring(3);
         for (int i = this.nonSetters.Count - 1; i >= 0; i--)
         {
             CodeMemberMethod getter = this.nonSetters[i];
             if (!this.type.Members.Contains(getter))
             {
                 continue;
             }
             if (string.Compare(getter.Name, afterSet, StringComparison.OrdinalIgnoreCase) == 0 &&
                 getter.ReturnType.BaseType == setter.Parameters[0].Type.BaseType &&
                 !methods.Any(m => m != getter && string.Compare(getter.Name, m.Name, StringComparison.OrdinalIgnoreCase) == 0))
             {
                 methods.Remove(getter);
                 if (this.type.IsInterface)
                 {
                     CodeSnippetTypeMember property = new CodeSnippetTypeMember();
                     property.Name = getter.Name;
                     string template = readOnly ? "        {0} {1} {{ get; }}" : "        {0} {1} {{ get; set; }}";
                     property.Text = string.Format(template, getter.ReturnType.BaseType, getter.Name);
                     CodeCommentStatementCollection comments = new CodeCommentStatementCollection(getter.Comments);
                     if (!readOnly)
                     {
                         comments.AddRange(setter.Comments);
                     }
                     AddComments(property, comments, readOnly);
                     this.type.Members.Add(property);
                     this.type.Members.Remove(getter);
                     if (!readOnly)
                     {
                         this.type.Members.Remove(setter);
                     }
                 }
                 else
                 {
                     this.GenerateProperty(getter, readOnly ? null : setter);
                 }
                 goto next;
             }
         }
         CodeTypeMember baseVirtualProperty = this.GetBaseVirtualProperty(this.type, afterSet);
         if (!this.type.IsInterface && baseVirtualProperty != null)
         {
             CodeMemberMethod getter = new CodeMemberMethod { Name = baseVirtualProperty.Name };
             getter.ReturnType = setter.Parameters[0].Type;
             getter.Statements.Add(new CodeSnippetStatement(string.Format("            return base.{0};", afterSet)));
             this.GenerateProperty(getter, readOnly ? null : setter);
         }
         next:
         ;
     }
     foreach (CodeMemberMethod nonSetter in this.nonSetters)
     {
         CodeTypeMember baseVirtualProperty = this.GetBaseVirtualProperty(this.type, nonSetter.Name);
         if (!this.type.IsInterface && baseVirtualProperty != null)
         {
             bool isReadOnly = (baseVirtualProperty is CodeMemberProperty && !((CodeMemberProperty) baseVirtualProperty).HasSet) ||
                               !regexPropertySetter.IsMatch(((CodeSnippetTypeMember) baseVirtualProperty).Text);
             if (readOnly == isReadOnly)
             {
                 CodeMemberMethod setter = new CodeMemberMethod { Name = baseVirtualProperty.Name };
                 setter.Statements.Add(new CodeSnippetStatement(string.Format("            base.{0} = value;", nonSetter.Name)));
                 this.GenerateProperty(nonSetter, readOnly ? null : setter);
             }
         }
     }
 }
Beispiel #11
0
 private void GenerateProperty(CodeMemberMethod getter, CodeMemberMethod setter = null)
 {
     CodeCommentStatementCollection comments = new CodeCommentStatementCollection();
     comments.AddRange(getter.Comments);
     getter.Comments.Clear();
     if (setter != null)
     {
         comments.AddRange(setter.Comments);
         setter.Comments.Clear();
     }
     if (this.type.Members.OfType<CodeSnippetTypeMember>().All(
         p => string.Compare(getter.Name, p.Name, StringComparison.OrdinalIgnoreCase) != 0 ||
              p.UserData["interface"] != getter.PrivateImplementationType) &&
         this.type.Members.OfType<CodeMemberProperty>().All(
             p => string.Compare(getter.Name, p.Name, StringComparison.OrdinalIgnoreCase) != 0 ||
                  p.PrivateImplementationType != getter.PrivateImplementationType))
     {
         CodeMemberProperty property = new CodeMemberProperty();
         property.Name = getter.Name;
         property.Type = getter.ReturnType;
         property.Attributes = MemberAttributes.Public;
         if ((getter.Attributes & MemberAttributes.Static) == MemberAttributes.Static)
         {
             property.Attributes |= MemberAttributes.Static;
         }
         if ((getter.Attributes & MemberAttributes.Final) == MemberAttributes.Final &&
             (setter == null || (setter.Attributes & MemberAttributes.Final) == MemberAttributes.Final))
         {
             property.Attributes |= MemberAttributes.Final;
         }
         if ((getter.Attributes & MemberAttributes.Override) == MemberAttributes.Override ||
             (setter != null && (setter.Attributes & MemberAttributes.Override) == MemberAttributes.Override))
         {
             property.Attributes |= MemberAttributes.Override;
         }
         property.GetStatements.AddRange(getter.Statements);
         if (setter != null)
         {
             CodeVariableDeclarationStatement variableStatement =
                 setter.Statements.OfType<CodeVariableDeclarationStatement>().First();
             CodeArrayCreateExpression arrayExpression = (CodeArrayCreateExpression) variableStatement.InitExpression;
             CodeArgumentReferenceExpression argExpression =
                 arrayExpression.Initializers.OfType<CodeArgumentReferenceExpression>().First();
             argExpression.ParameterName = "value";
             property.SetStatements.AddRange(setter.Statements);
         }
         property.PrivateImplementationType = getter.PrivateImplementationType;
         if (property.PrivateImplementationType == null && setter != null)
         {
             property.PrivateImplementationType = setter.PrivateImplementationType;
         }
         CodeSnippetTypeMember completeProperty = AddAttributes(getter, setter, property);
         AddComments(completeProperty, comments, setter == null);
         type.Members.Add(completeProperty);
         if (type.Members.Contains(getter))
         {
             type.Members.Remove(getter);
         }
         if (setter != null && this.type.Members.Contains(setter))
         {
             type.Members.Remove(setter);
         }
     }
 }
Beispiel #12
0
    public void PostMembersHook(Smoke *smoke, Smoke.Class *klass, CodeTypeDeclaration type)
    {
        if (Util.IsQObject(klass))
        {
            CodeMemberProperty emit = new CodeMemberProperty();
            emit.Name       = "Emit";
            emit.Attributes = MemberAttributes.Family | MemberAttributes.New | MemberAttributes.Final;
            emit.HasGet     = true;
            emit.HasSet     = false;

            string            signalsIfaceName = "I" + type.Name + "Signals";
            CodeTypeReference returnType       = new CodeTypeReference(signalsIfaceName);
            emit.Type = returnType;

            emit.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(
                                                                     returnType,
                                                                     new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Q_EMIT")
                                                                     )));

            type.Members.Add(emit);

            string className = ByteArrayManager.GetString(klass->className);
            int    colon     = className.LastIndexOf("::", StringComparison.Ordinal);
            string prefix    = (colon != -1) ? className.Substring(0, colon) : string.Empty;

            IList typeCollection          = Data.GetTypeCollection(prefix);
            CodeTypeDeclaration ifaceDecl = new CodeTypeDeclaration(signalsIfaceName);
            ifaceDecl.IsInterface = true;

            if (className != "QObject")
            {
                string parentClassName = ByteArrayManager.GetString(smoke->classes[smoke->inheritanceList[klass->parents]].className);
                colon  = parentClassName.LastIndexOf("::", StringComparison.Ordinal);
                prefix = (colon != -1) ? parentClassName.Substring(0, colon) : string.Empty;
                if (colon != -1)
                {
                    parentClassName = parentClassName.Substring(colon + 2);
                }

                string parentInterface = (prefix != string.Empty) ? prefix.Replace("::", ".") + "." : string.Empty;
                parentInterface += "I" + parentClassName + "Signals";

                ifaceDecl.BaseTypes.Add(new CodeTypeReference(parentInterface));
            }
            Dictionary <CodeSnippetTypeMember, CodeMemberMethod> signalEvents = new Dictionary <CodeSnippetTypeMember, CodeMemberMethod>();
            GetSignals(smoke, klass, delegate(string signature, string name, string typeName, IntPtr metaMethod)
            {
                CodeMemberMethod signal = new CodeMemberMethod();
                signal.Attributes       = MemberAttributes.Abstract;

                // capitalize the first letter
                StringBuilder builder = new StringBuilder(name);
                builder[0]            = char.ToUpper(builder[0]);
                string tmp            = builder.ToString();

                signal.Name = tmp;
                bool isRef;
                try
                {
                    if (typeName == string.Empty)
                    {
                        signal.ReturnType = new CodeTypeReference(typeof(void));
                    }
                    else
                    {
                        signal.ReturnType = Translator.CppToCSharp(typeName, out isRef);
                    }
                }
                catch (NotSupportedException)
                {
                    Debug.Print("  |--Won't wrap signal {0}::{1}", className, signature);
                    return;
                }

                CodeAttributeDeclaration attr = new CodeAttributeDeclaration("Q_SIGNAL",
                                                                             new CodeAttributeArgument(new CodePrimitiveExpression(signature)));
                signal.CustomAttributes.Add(attr);

                int argNum = 1;
                StringBuilder fullNameBuilder = new StringBuilder("Slot");
                GetMetaMethodParameters(metaMethod, delegate(string paramType, string paramName)
                {
                    if (paramName == string.Empty)
                    {
                        paramName = "arg" + argNum.ToString();
                    }
                    argNum++;

                    CodeParameterDeclarationExpression param;
                    try
                    {
                        short id = smoke->IDType(paramType);
                        CodeTypeReference paramTypeRef;
                        if (id > 0)
                        {
                            paramTypeRef = Translator.CppToCSharp(smoke->types + id, out isRef);
                        }
                        else
                        {
                            if (!paramType.Contains("::"))
                            {
                                id = smoke->IDType(className + "::" + paramType);
                                if (id > 0)
                                {
                                    paramTypeRef = Translator.CppToCSharp(smoke->types + id, out isRef);
                                }
                                else
                                {
                                    paramTypeRef = Translator.CppToCSharp(paramType, out isRef);
                                }
                            }
                            else
                            {
                                paramTypeRef = Translator.CppToCSharp(paramType, out isRef);
                            }
                        }
                        param = new CodeParameterDeclarationExpression(paramTypeRef, paramName);
                    }
                    catch (NotSupportedException)
                    {
                        Debug.Print("  |--Won't wrap signal {0}::{1}", className, signature);
                        return;
                    }
                    if (isRef)
                    {
                        param.Direction = FieldDirection.Ref;
                    }
                    signal.Parameters.Add(param);
                    if (argNum == 2)
                    {
                        fullNameBuilder.Append('<');
                    }
                    fullNameBuilder.Append(param.Type.BaseType);
                    fullNameBuilder.Append(',');
                });
                if (fullNameBuilder[fullNameBuilder.Length - 1] == ',')
                {
                    fullNameBuilder[fullNameBuilder.Length - 1] = '>';
                }
                ifaceDecl.Members.Add(signal);
                CodeSnippetTypeMember signalEvent = new CodeSnippetTypeMember();
                signalEvent.Name = signal.Name;
                CodeSnippetTypeMember existing = signalEvents.Keys.FirstOrDefault(m => m.Name == signal.Name);
                if (existing != null)
                {
                    CodeSnippetTypeMember signalEventToUse;
                    CodeMemberMethod signalToUse;
                    if (signal.Parameters.Count == 0)
                    {
                        signalEventToUse = existing;
                        signalToUse      = signalEvents[existing];
                    }
                    else
                    {
                        signalEventToUse = signalEvent;
                        signalToUse      = signal;
                    }
                    string suffix = signalToUse.Parameters.Cast <CodeParameterDeclarationExpression>().Last().Name;
                    if (suffix.StartsWith("arg") && suffix.Length > 3 && char.IsDigit(suffix[3]))
                    {
                        string lastType = signalToUse.Parameters.Cast <CodeParameterDeclarationExpression>().Last().Type.BaseType;
                        suffix          = lastType.Substring(lastType.LastIndexOf('.') + 1);
                    }
                    else
                    {
                        StringBuilder lastParamBuilder = new StringBuilder(suffix);
                        lastParamBuilder[0]            = char.ToUpper(lastParamBuilder[0]);
                        suffix = lastParamBuilder.ToString();
                    }
                    signalEventToUse.Text = signalEventToUse.Text.Replace(signalEventToUse.Name, signalEventToUse.Name += suffix);
                }
                signalEvent.Text = string.Format(@"
        public event {0} {1}
		{{
			add
			{{
                QObject.Connect(this, Qt.SIGNAL(""{2}""), (QObject) value.Target, Qt.SLOT(value.Method.Name + ""{3}""));
			}}
			remove
			{{
                QObject.Disconnect(this, Qt.SIGNAL(""{2}""), (QObject) value.Target, Qt.SLOT(value.Method.Name + ""{3}""));
			}}
		}}"        , fullNameBuilder, signalEvent.Name, signature, signature.Substring(signature.IndexOf('(')));
                signalEvents.Add(signalEvent, signal);
            });

            typeCollection.Add(ifaceDecl);
            foreach (KeyValuePair <CodeSnippetTypeMember, CodeMemberMethod> signalEvent in signalEvents)
            {
                CodeSnippetTypeMember          implementation = signalEvent.Key;
                CodeCommentStatementCollection comments       = new CodeCommentStatementCollection();
                foreach (CodeTypeMember current in from CodeTypeMember member in type.Members
                         where member.Name == implementation.Name
                         select member)
                {
                    if (comments.Count == 0)
                    {
                        comments.AddRange(current.Comments);
                    }
                    current.Name = "On" + current.Name;
                }
                signalEvent.Value.Comments.AddRange(comments);
                signalEvent.Key.Comments.AddRange(comments);
                type.Members.Add(signalEvent.Key);
            }
        }
    }