public override void apply(CodeTypeDeclaration mock, Type target)
        {
            CodeTypeMemberCollection mockMethods = mock.Members;

            foreach (CodeTypeMember member in mockMethods)
            {
                if (member is CodeMemberMethod)
                {
                    CodeMemberMethod        method     = (CodeMemberMethod)member;
                    CodeStatementCollection statements = method.Statements;
                    if (statements.Count > 0)
                    {
                        CodeStatement lastStatement = statements[statements.Count - 1];
                        if (lastStatement is CodeMethodReturnStatement)
                        {
                            statements.Remove(lastStatement);
                        }
                    }
                    CodeTypeReference           typeToThrow      = new CodeTypeReference(typeof(System.NotSupportedException));
                    CodeObjectCreateExpression  createExpression = new CodeObjectCreateExpression(typeToThrow, new CodeExpression[] {});
                    CodeThrowExceptionStatement throwStatement   = new CodeThrowExceptionStatement(createExpression);
                    statements.Add(throwStatement);
                }
            }
        }
Example #2
0
        protected static void RemoveFromStatements <TCodeObject>(CodeStatementCollection statements, Predicate <TCodeObject> shouldRemove)
            where TCodeObject : CodeObject
        {
            List <CodeStatement> toRemove = new List <CodeStatement>();

            foreach (CodeStatement statement in statements)
            {
                TCodeObject             typedStatement = statement as TCodeObject;
                CodeExpressionStatement expression     = statement as CodeExpressionStatement;
                if (typedStatement == null && expression != null)
                {
                    typedStatement = expression.Expression as TCodeObject;
                }

                if (typedStatement != null && shouldRemove(typedStatement))
                {
                    toRemove.Add(statement);
                }
            }

            foreach (CodeStatement statement in toRemove)
            {
                statements.Remove(statement);
            }
        }
Example #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeDomSerializer baseClassSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer));
            object            codeObject          = baseClassSerializer.Serialize(manager, value);

            if (value.GetType().GetInterface("IWSerializer") == null)
            {
                System.Windows.Forms.MessageBox.Show("Must not never reach here:" + value.GetType().ToString());
                return(codeObject);
            }

            MethodInfo mInf = value.GetType().GetInterface("IWSerializer").GetMethod("ShouldSerialize");

            if (codeObject is CodeStatementCollection)
            {
                CodeStatementCollection statements = (CodeStatementCollection)codeObject;

                //--- loop through all statements
                int count = statements.Count;
                for (int i = 0; i < count; i++)
                {
                    CodeStatement st = statements[i];

                    if (st is CodeAssignStatement)
                    {
                        CodeAssignStatement cAssign = (CodeAssignStatement)st;

                        // If left is eg. 'this.BorderColor'
                        if (cAssign.Left is CodePropertyReferenceExpression)
                        {
                            /*  if(cAssign.Right is CodeCastExpression){
                             *              CodeCastExpression c = (CodeCastExpression)cAssign.Right;
                             *              if(c.Expression is CodeMethodInvokeExpression){
                             *                      CodeMethodInvokeExpression mI = (CodeMethodInvokeExpression)c.Expression;
                             *                      if(mI.Method.TargetObject is CodeVariableReferenceExpression){
                             *                              CodeVariableReferenceExpression vR = (CodeVariableReferenceExpression)mI.Method.TargetObject;
                             *                              System.Windows.Forms.MessageBox.Show(vR.);
                             *                      }
                             *              }
                             *      }*/

                            string propertyName = ((CodePropertyReferenceExpression)cAssign.Left).PropertyName;
                            //--- Check if we need to serialize property.
                            if (!(bool)mInf.Invoke(value, new object[] { propertyName }))
                            {
                                statements.Remove(st);
                                count--;
                                i--;
                            }
                        }
                    }
                }
            }

            return(codeObject);
        }
Example #4
0
        private static void ReplaceControlCreateStatement(Type ctrlType, CodeAssignStatement objAssignStatement, CodeStatementCollection statements)
        {
            /* Generate code like below
             *
             * IServiceProvider __activator = HttpRuntime.WebObjectActivator;
             *
             * if (activator != null) {
             *  _ctrl = (ctrlType)activator.GetService(ctrlType);
             * }
             *
             * // if default c-tor exists
             * else {
             *  _ctrl = new ....
             * }
             * // if no default c-tor
             * else {
             *  throw new InvalidOperationException(SR.GetString(SR.Could_not_create_type_instance, ctrlType))
             * }
             *
             */
            var webObjectActivatorExpr = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("System.Web.HttpRuntime"), "WebObjectActivator");
            var activatorRefExpr       = new CodeVariableReferenceExpression("__activator");

            var getServiceExpr        = new CodeMethodInvokeExpression(webObjectActivatorExpr, "GetService", new CodeTypeOfExpression(ctrlType));
            var castExpr              = new CodeCastExpression(new CodeTypeReference(ctrlType), getServiceExpr);
            var createObjectStatement = new CodeConditionStatement()
            {
                Condition = new CodeBinaryOperatorExpression(activatorRefExpr,
                                                             CodeBinaryOperatorType.IdentityInequality,
                                                             new CodePrimitiveExpression(null))
            };

            createObjectStatement.TrueStatements.Add(new CodeAssignStatement(objAssignStatement.Left, castExpr));

            // If default c-tor exists
            if (DoesTypeHaveDefaultCtor(ctrlType))
            {
                createObjectStatement.FalseStatements.Add(objAssignStatement);
            }
            else
            {
                var throwExceptionStatement = new CodeThrowExceptionStatement(new CodeObjectCreateExpression(
                                                                                  new CodeTypeReference(typeof(System.InvalidOperationException)),
                                                                                  new CodeExpression[] { new CodePrimitiveExpression(SR.GetString(SR.Could_not_create_type_instance, ctrlType)) }));
                createObjectStatement.FalseStatements.Add(throwExceptionStatement);
            }

            // replace the old assign statement
            var indexOfStatement = statements.IndexOf(objAssignStatement);

            statements.Insert(indexOfStatement, createObjectStatement);
            statements.Insert(indexOfStatement, new CodeAssignStatement(activatorRefExpr, webObjectActivatorExpr));
            statements.Insert(indexOfStatement, new CodeVariableDeclarationStatement(typeof(IServiceProvider), "__activator"));
            statements.Remove(objAssignStatement);
        }
Example #5
0
        public void Constructor1_Deny_Unrestricted()
        {
            CodeStatementCollection coll = new CodeStatementCollection(array);

            coll.CopyTo(array, 0);
            Assert.AreEqual(1, coll.Add(cs), "Add");
            Assert.AreSame(cs, coll[0], "this[int]");
            coll.AddRange(array);
            coll.AddRange(coll);
            Assert.IsTrue(coll.Contains(cs), "Contains");
            Assert.AreEqual(0, coll.IndexOf(cs), "IndexOf");
            coll.Insert(0, cs);
            coll.Remove(cs);
        }
Example #6
0
        public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
        {
            CodeDomSerializer LbaseSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(System.ComponentModel.Component), typeof(CodeDomSerializer));

            if (codeObject is CodeStatementCollection)
            {
                CodeStatementCollection statements = (CodeStatementCollection)codeObject;
                CodeStatement           assignPropertyStatement = GetPropertyAssignStatement(statements, PropertyName);
                if (assignPropertyStatement != null)
                {
                    statements.Remove(assignPropertyStatement);
                    statements.Insert(statements.Count, assignPropertyStatement);
                }
            }
            return(LbaseSerializer.Deserialize(manager, codeObject));
        }
        public override object Deserialize(IDesignerSerializationManager AManager, object ACodeObject)
        {
            CodeDomSerializer LbaseSerializer = (CodeDomSerializer)AManager.GetSerializer(typeof(Alphora.Dataphor.DAE.Client.DataSession).BaseType, typeof(CodeDomSerializer));

            if (ACodeObject is CodeStatementCollection)
            {
                CodeStatementCollection LStatements = (CodeStatementCollection)ACodeObject;
                CodeStatement           LSetActivePropertyStatement = GetPropertyAssignStatement(LStatements, CPropertyName);
                if (LSetActivePropertyStatement != null)
                {
                    LStatements.Remove(LSetActivePropertyStatement);
                    LStatements.Insert(LStatements.Count, LSetActivePropertyStatement);
                }
            }
            return(LbaseSerializer.Deserialize(AManager, ACodeObject));
        }
        public void Remove()
        {
            CodeStatement cs1 = new CodeStatement();
            CodeStatement cs2 = new CodeStatement();

            CodeStatementCollection coll = new CodeStatementCollection();

            coll.Add(cs1);
            coll.Add(cs2);
            Assert.AreEqual(2, coll.Count, "#1");
            Assert.AreEqual(0, coll.IndexOf(cs1), "#2");
            Assert.AreEqual(1, coll.IndexOf(cs2), "#3");
            coll.Remove(cs1);
            Assert.AreEqual(1, coll.Count, "#4");
            Assert.AreEqual(-1, coll.IndexOf(cs1), "#5");
            Assert.AreEqual(0, coll.IndexOf(cs2), "#6");
        }
        public static void AddBeforeReturn(this CodeStatementCollection statements, params CodeObject[] codes)
        {
            var last = statements[statements.Count - 1];

            statements.Remove(last);
            foreach (var code in codes)
            {
                if (code is CodeStatement stmt)
                {
                    statements.Add(stmt);
                }
                else if (code is CodeExpression expr)
                {
                    statements.Add(expr);
                }
            }

            statements.Add(last);
        }
Example #10
0
        // CodeStatementCollection
        public void CodeStatementCollectionSample()
        {
            //<Snippet1>
            //<Snippet2>
            // Creates an empty CodeStatementCollection.
            CodeStatementCollection collection = new CodeStatementCollection();

            //</Snippet2>

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

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

            // Adds a collection of CodeStatement objects to the collection.
            CodeStatement           testStatement        = new CodeCommentStatement("Test comment statement");
            CodeStatementCollection statementsCollection = new CodeStatementCollection();

            statementsCollection.Add(new CodeCommentStatement("Test comment statement"));
            statementsCollection.Add(new CodeCommentStatement("Test comment statement"));
            statementsCollection.Add(testStatement);

            collection.AddRange(statementsCollection);
            //</Snippet4>

            //<Snippet5>
            // Tests for the presence of a CodeStatement in the
            // collection, and retrieves its index if it is found.
            int itemIndex = -1;

            if (collection.Contains(testStatement))
            {
                itemIndex = collection.IndexOf(testStatement);
            }

            //</Snippet5>

            //<Snippet6>
            // Copies the contents of the collection beginning at index 0 to the specified CodeStatement array.
            // 'statements' is a CodeStatement array.
            CodeStatement[] statementArray = new CodeStatement[collection.Count];
            collection.CopyTo(statementArray, 0);
            //</Snippet6>

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

            //</Snippet7>

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

            //<Snippet9>
            // Removes the specified CodeStatement from the collection.
            collection.Remove(testStatement);
            //</Snippet9>

            //<Snippet10>
            // Removes the CodeStatement at index 0.
            collection.RemoveAt(0);
            //</Snippet10>
            //</Snippet1>
        }
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            ViewStyle viewStyle = (ViewStyle)value;

            CodeDomSerializer baseClassSerializer = (CodeDomSerializer)manager.GetSerializer(value.GetType().BaseType, typeof(CodeDomSerializer));
            object            codeObject          = baseClassSerializer.Serialize(manager, value);

            if (codeObject is CodeStatementCollection)
            {
                CodeStatementCollection statements = (CodeStatementCollection)codeObject;

                ArrayList dontSerializeList = new ArrayList();

                //--- loop through all statements
                foreach (CodeStatement st in statements)
                {
                    if (st is CodeAssignStatement)
                    {
                        CodeAssignStatement cAssign = (CodeAssignStatement)st;

                        // If left is eg. 'this.ViewStyle.BorderColor'
                        if (cAssign.Left is CodePropertyReferenceExpression)
                        {
                            string propertyName  = ((CodePropertyReferenceExpression)cAssign.Left).PropertyName;
                            object propertyValue = null;

                            // If right is eg. 'System.Drawing.Color.FromArgb(183,193,214)'
                            if (cAssign.Right is CodeMethodInvokeExpression)
                            {
                                CodeMethodInvokeExpression mInvokeExp = (CodeMethodInvokeExpression)cAssign.Right;

                                if (mInvokeExp.Method.MethodName == "FromArgb")
                                {
                                    CodeCastExpression cCastExpR = (CodeCastExpression)mInvokeExp.Parameters[0];
                                    CodeCastExpression cCastExpG = (CodeCastExpression)mInvokeExp.Parameters[1];
                                    CodeCastExpression cCastExpB = (CodeCastExpression)mInvokeExp.Parameters[2];

                                    int r = Convert.ToInt32(((CodePrimitiveExpression)cCastExpR.Expression).Value);
                                    int g = Convert.ToInt32(((CodePrimitiveExpression)cCastExpG.Expression).Value);
                                    int b = Convert.ToInt32(((CodePrimitiveExpression)cCastExpB.Expression).Value);

                                    propertyValue = Color.FromArgb(r, g, b);
                                }
                            }

                            // If right is eg. 'System.Drawing.Color.Lime'
                            if (cAssign.Right is CodePropertyReferenceExpression)
                            {
                                CodePropertyReferenceExpression propRefExp = (CodePropertyReferenceExpression)cAssign.Right;
                                CodeTypeReferenceExpression     tRefExp    = (CodeTypeReferenceExpression)propRefExp.TargetObject;

                                if (tRefExp.Type.BaseType == "System.Drawing.Color" || tRefExp.Type.BaseType == "System.Drawing.SystemColors")
                                {
                                    propertyValue = Color.FromName(propRefExp.PropertyName);
                                }
                            }

                            if (cAssign.Right is CodeFieldReferenceExpression)
                            {
                                CodeFieldReferenceExpression fRefExp = (CodeFieldReferenceExpression)cAssign.Right;

                                if (fRefExp.FieldName == "FullSelect")
                                {
                                    propertyValue = VRS.UI.Controls.WOutlookBar.ItemsStyle.FullSelect;
                                }
                                if (fRefExp.FieldName == "IconSelect")
                                {
                                    propertyValue = VRS.UI.Controls.WOutlookBar.ItemsStyle.IconSelect;
                                }
                                if (fRefExp.FieldName == "UseDefault")
                                {
                                    propertyValue = VRS.UI.Controls.WOutlookBar.ItemsStyle.UseDefault;
                                }
                            }

                            //--- Check if we need to serialize property.
                            if (!viewStyle.MustSerialize(propertyName, propertyValue))
                            {
                                // Add to remove list
                                dontSerializeList.Add(st);
                            }
                        }
                    }
                }

                // Remove not neede properties
                foreach (CodeStatement obj in dontSerializeList)
                {
                    statements.Remove(obj);
                }
            }

            return(codeObject);
        }
        public override object Serialize(IDesignerSerializationManager manager, object obj)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (manager.Context == null)
            {
                throw new ArgumentException("manager", SR.GetString("Error_MissingContextProperty"));
            }
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            DependencyObject component = obj as DependencyObject;

            if (component == null)
            {
                throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(DependencyObject).FullName }), "obj");
            }
            Activity context = obj as Activity;

            if (context != null)
            {
                manager.Context.Push(context);
            }
            CodeStatementCollection statements = null;

            try
            {
                if (context != null)
                {
                    CodeDomSerializer serializer = manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer)) as CodeDomSerializer;
                    if (serializer == null)
                    {
                        throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(CodeDomSerializer).FullName }));
                    }
                    statements = serializer.Serialize(manager, context) as CodeStatementCollection;
                }
                else
                {
                    statements = base.Serialize(manager, obj) as CodeStatementCollection;
                }
                if (statements == null)
                {
                    return(statements);
                }
                CodeStatementCollection statements2  = new CodeStatementCollection(statements);
                CodeExpression          targetObject = base.SerializeToExpression(manager, obj);
                if (targetObject == null)
                {
                    return(statements);
                }
                ArrayList list = new ArrayList();
                List <DependencyProperty> list2 = new List <DependencyProperty>(component.MetaDependencyProperties);
                foreach (DependencyProperty property in component.DependencyPropertyValues.Keys)
                {
                    if (property.IsAttached && ((property.IsEvent && (property.OwnerType.GetField(property.Name + "Event", BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) != null)) || (!property.IsEvent && (property.OwnerType.GetField(property.Name + "Property", BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) != null))))
                    {
                        list2.Add(property);
                    }
                }
                foreach (DependencyProperty property2 in list2)
                {
                    object binding = null;
                    if (component.IsBindingSet(property2))
                    {
                        binding = component.GetBinding(property2);
                    }
                    else if (!property2.IsEvent)
                    {
                        binding = component.GetValue(property2);
                    }
                    else
                    {
                        binding = component.GetHandler(property2);
                    }
                    if ((binding != null) && (property2.IsAttached || (!property2.DefaultMetadata.IsMetaProperty && (binding is ActivityBind))))
                    {
                        object[] attributes = property2.DefaultMetadata.GetAttributes(typeof(DesignerSerializationVisibilityAttribute));
                        if (attributes.Length > 0)
                        {
                            DesignerSerializationVisibilityAttribute attribute = attributes[0] as DesignerSerializationVisibilityAttribute;
                            if (attribute.Visibility == DesignerSerializationVisibility.Hidden)
                            {
                                continue;
                            }
                        }
                        CodeExpression expression2 = null;
                        string         name        = property2.Name + (property2.IsEvent ? "Event" : "Property");
                        FieldInfo      field       = property2.OwnerType.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
                        if ((field != null) && !field.IsPublic)
                        {
                            expression2 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(DependencyProperty)), "FromName", new CodeExpression[] { new CodePrimitiveExpression(property2.Name), new CodeTypeOfExpression(property2.OwnerType) });
                        }
                        else
                        {
                            expression2 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(property2.OwnerType), name);
                        }
                        CodeExpression expression = base.SerializeToExpression(manager, binding);
                        if ((expression2 != null) && (expression != null))
                        {
                            CodeMethodInvokeExpression expression4 = null;
                            if (binding is ActivityBind)
                            {
                                expression4 = new CodeMethodInvokeExpression(targetObject, "SetBinding", new CodeExpression[] { expression2, new CodeCastExpression(new CodeTypeReference(typeof(ActivityBind)), expression) });
                            }
                            else
                            {
                                expression4 = new CodeMethodInvokeExpression(targetObject, property2.IsEvent ? "AddHandler" : "SetValue", new CodeExpression[] { expression2, expression });
                            }
                            statements.Add(expression4);
                            foreach (CodeStatement statement in statements2)
                            {
                                if ((statement is CodeAssignStatement) && (((CodeAssignStatement)statement).Left is CodePropertyReferenceExpression))
                                {
                                    CodePropertyReferenceExpression left = ((CodeAssignStatement)statement).Left as CodePropertyReferenceExpression;
                                    if ((left.PropertyName == property2.Name) && left.TargetObject.Equals(targetObject))
                                    {
                                        statements.Remove(statement);
                                    }
                                }
                            }
                        }
                        list.Add(property2);
                    }
                }
                if (!(manager.GetService(typeof(IEventBindingService)) is IEventBindingService))
                {
                    foreach (EventDescriptor descriptor in TypeDescriptor.GetEvents(component))
                    {
                        string eventHandlerName = WorkflowMarkupSerializationHelpers.GetEventHandlerName(component, descriptor.Name);
                        if (!string.IsNullOrEmpty(eventHandlerName))
                        {
                            CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression(targetObject, descriptor.Name);
                            CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression(new CodeTypeReference(descriptor.EventType), new CodeThisReferenceExpression(), eventHandlerName);
                            statements.Add(new CodeAttachEventStatement(eventRef, listener));
                        }
                    }
                }
                if (!component.UserData.Contains(UserDataKeys.DesignTimeTypeNames))
                {
                    return(statements);
                }
                Hashtable hashtable = component.UserData[UserDataKeys.DesignTimeTypeNames] as Hashtable;
                foreach (object obj4 in hashtable.Keys)
                {
                    string             str3     = null;
                    string             fullName = null;
                    string             str5     = hashtable[obj4] as string;
                    DependencyProperty item     = obj4 as DependencyProperty;
                    if (item != null)
                    {
                        if (list.Contains(item))
                        {
                            continue;
                        }
                        object[] objArray2 = item.DefaultMetadata.GetAttributes(typeof(DesignerSerializationVisibilityAttribute));
                        if (objArray2.Length > 0)
                        {
                            DesignerSerializationVisibilityAttribute attribute2 = objArray2[0] as DesignerSerializationVisibilityAttribute;
                            if (attribute2.Visibility == DesignerSerializationVisibility.Hidden)
                            {
                                continue;
                            }
                        }
                        str3     = item.Name;
                        fullName = item.OwnerType.FullName;
                    }
                    else if (obj4 is string)
                    {
                        int length = ((string)obj4).LastIndexOf('.');
                        if (length != -1)
                        {
                            fullName = ((string)obj4).Substring(0, length);
                            str3     = ((string)obj4).Substring(length + 1);
                        }
                    }
                    if ((!string.IsNullOrEmpty(str5) && !string.IsNullOrEmpty(str3)) && !string.IsNullOrEmpty(fullName))
                    {
                        if (fullName == obj.GetType().FullName)
                        {
                            CodePropertyReferenceExpression expression8 = new CodePropertyReferenceExpression(targetObject, str3);
                            statements.Add(new CodeAssignStatement(expression8, new CodeTypeOfExpression(str5)));
                        }
                        else
                        {
                            CodeExpression expression9  = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(fullName), str3 + "Property");
                            CodeExpression expression10 = new CodeTypeOfExpression(str5);
                            statements.Add(new CodeMethodInvokeExpression(targetObject, "SetValue", new CodeExpression[] { expression9, expression10 }));
                        }
                    }
                }
            }
            finally
            {
                if (context != null)
                {
                    manager.Context.Pop();
                }
            }
            return(statements);
        }
Example #13
0
        public override object Serialize(IDesignerSerializationManager manager, object obj)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            if (manager.Context == null)
            {
                throw new ArgumentException("manager", SR.GetString(SR.Error_MissingContextProperty));
            }

            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }

            DependencyObject dependencyObject = obj as DependencyObject;

            if (dependencyObject == null)
            {
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(DependencyObject).FullName), "obj");
            }

            Activity activity = obj as Activity;

            if (activity != null)
            {
                manager.Context.Push(activity);
            }

            CodeStatementCollection retVal = null;

            try
            {
                if (activity != null)
                {
                    CodeDomSerializer componentSerializer = manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer)) as CodeDomSerializer;
                    if (componentSerializer == null)
                    {
                        throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(CodeDomSerializer).FullName));
                    }
                    retVal = componentSerializer.Serialize(manager, activity) as CodeStatementCollection;
                }
                else
                {
                    retVal = base.Serialize(manager, obj) as CodeStatementCollection;
                }

                if (retVal != null)
                {
                    CodeStatementCollection codeStatements   = new CodeStatementCollection(retVal);
                    CodeExpression          objectExpression = SerializeToExpression(manager, obj);
                    if (objectExpression != null)
                    {
                        ArrayList propertiesSerialized = new ArrayList();
                        List <DependencyProperty> dependencyProperties = new List <DependencyProperty>(dependencyObject.MetaDependencyProperties);
                        foreach (DependencyProperty dp in dependencyObject.DependencyPropertyValues.Keys)
                        {
                            if (dp.IsAttached)
                            {
                                if ((dp.IsEvent && dp.OwnerType.GetField(dp.Name + "Event", BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) ||
                                    (!dp.IsEvent && dp.OwnerType.GetField(dp.Name + "Property", BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly) != null))
                                {
                                    dependencyProperties.Add(dp);
                                }
                            }
                        }
                        foreach (DependencyProperty dependencyProperty in dependencyProperties)
                        {
                            object value = null;
                            if (dependencyObject.IsBindingSet(dependencyProperty))
                            {
                                value = dependencyObject.GetBinding(dependencyProperty);
                            }
                            else if (!dependencyProperty.IsEvent)
                            {
                                value = dependencyObject.GetValue(dependencyProperty);
                            }
                            else
                            {
                                value = dependencyObject.GetHandler(dependencyProperty);
                            }
                            // Attached property should always be set through SetValue, no matter if it's a meta property or if there is a data context.
                            // Other meta properties will be directly assigned.
                            // Other instance property will go through SetValue if there is a data context or if it's of type Bind.
                            if (value != null &&
                                (dependencyProperty.IsAttached || (!dependencyProperty.DefaultMetadata.IsMetaProperty && value is ActivityBind)))
                            {
                                object[] attributes = dependencyProperty.DefaultMetadata.GetAttributes(typeof(DesignerSerializationVisibilityAttribute));
                                if (attributes.Length > 0)
                                {
                                    DesignerSerializationVisibilityAttribute serializationVisibilityAttribute = attributes[0] as DesignerSerializationVisibilityAttribute;
                                    if (serializationVisibilityAttribute.Visibility == DesignerSerializationVisibility.Hidden)
                                    {
                                        continue;
                                    }
                                }

                                // Events of type Bind will go through here.  Regular events will go through IEventBindingService.
                                CodeExpression param1 = null;
                                string         dependencyPropertyName = dependencyProperty.Name + ((dependencyProperty.IsEvent) ? "Event" : "Property");
                                FieldInfo      fieldInfo = dependencyProperty.OwnerType.GetField(dependencyPropertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
                                if (fieldInfo != null && !fieldInfo.IsPublic)
                                {
                                    param1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(DependencyProperty)), "FromName", new CodePrimitiveExpression(dependencyProperty.Name), new CodeTypeOfExpression(dependencyProperty.OwnerType));
                                }
                                else
                                {
                                    param1 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dependencyProperty.OwnerType), dependencyPropertyName);
                                }

                                CodeExpression param2 = SerializeToExpression(manager, value);

                                //Fields property fails to serialize to expression due to reference not being created,
                                //the actual code for fields are generated in datacontext code generator so we do nothing here
                                if (param1 != null && param2 != null)
                                {
                                    CodeMethodInvokeExpression codeMethodInvokeExpr = null;
                                    if (value is ActivityBind)
                                    {
                                        codeMethodInvokeExpr = new CodeMethodInvokeExpression(objectExpression, "SetBinding", new CodeExpression[] { param1, new CodeCastExpression(new CodeTypeReference(typeof(ActivityBind)), param2) });
                                    }
                                    else
                                    {
                                        codeMethodInvokeExpr = new CodeMethodInvokeExpression(objectExpression, (dependencyProperty.IsEvent) ? "AddHandler" : "SetValue", new CodeExpression[] { param1, param2 });
                                    }
                                    retVal.Add(codeMethodInvokeExpr);

                                    // Remove the property set statement for the event which is replaced by the SetValue() expression.
                                    foreach (CodeStatement statement in codeStatements)
                                    {
                                        if (statement is CodeAssignStatement && ((CodeAssignStatement)statement).Left is CodePropertyReferenceExpression)
                                        {
                                            CodePropertyReferenceExpression prop = ((CodeAssignStatement)statement).Left as CodePropertyReferenceExpression;
                                            if (prop.PropertyName == dependencyProperty.Name && prop.TargetObject.Equals(objectExpression))
                                            {
                                                retVal.Remove(statement);
                                            }
                                        }
                                    }
                                }

                                propertiesSerialized.Add(dependencyProperty);
                            }
                        }

                        IEventBindingService eventBindingService = manager.GetService(typeof(IEventBindingService)) as IEventBindingService;
                        if (eventBindingService == null)
                        {
                            // At compile time, we don't have an event binding service.  We need to mannually emit the code to add
                            // event handlers.
                            foreach (EventDescriptor eventDesc in TypeDescriptor.GetEvents(dependencyObject))
                            {
                                string handler = WorkflowMarkupSerializationHelpers.GetEventHandlerName(dependencyObject, eventDesc.Name);
                                if (!string.IsNullOrEmpty(handler))
                                {
                                    CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression(objectExpression, eventDesc.Name);
                                    CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression(new CodeTypeReference(eventDesc.EventType), new CodeThisReferenceExpression(), handler);
                                    retVal.Add(new CodeAttachEventStatement(eventRef, listener));
                                }
                            }
                        }

                        // We also need to handle properties of type System.Type.  If the value is a design time type, xomlserializer
                        // is not going to be able to deserialize the type.  We then store the type name in the user data and
                        // output a "typeof(xxx)" expression using the type name w/o validating the type.
                        if (dependencyObject.UserData.Contains(UserDataKeys.DesignTimeTypeNames))
                        {
                            Hashtable typeNames = dependencyObject.UserData[UserDataKeys.DesignTimeTypeNames] as Hashtable;
                            foreach (object key in typeNames.Keys)
                            {
                                string             propName           = null;
                                string             ownerTypeName      = null;
                                string             typeName           = typeNames[key] as string;
                                DependencyProperty dependencyProperty = key as DependencyProperty;
                                if (dependencyProperty != null)
                                {
                                    if (propertiesSerialized.Contains(dependencyProperty))
                                    {
                                        continue;
                                    }

                                    object[] attributes = dependencyProperty.DefaultMetadata.GetAttributes(typeof(DesignerSerializationVisibilityAttribute));
                                    if (attributes.Length > 0)
                                    {
                                        DesignerSerializationVisibilityAttribute serializationVisibilityAttribute = attributes[0] as DesignerSerializationVisibilityAttribute;
                                        if (serializationVisibilityAttribute.Visibility == DesignerSerializationVisibility.Hidden)
                                        {
                                            continue;
                                        }
                                    }

                                    propName      = dependencyProperty.Name;
                                    ownerTypeName = dependencyProperty.OwnerType.FullName;
                                }
                                else if (key is string)
                                {
                                    int indexOfDot = ((string)key).LastIndexOf('.');
                                    Debug.Assert(indexOfDot != -1, "Wrong property name in DesignTimeTypeNames hashtable.");
                                    if (indexOfDot != -1)
                                    {
                                        ownerTypeName = ((string)key).Substring(0, indexOfDot);
                                        propName      = ((string)key).Substring(indexOfDot + 1);
                                    }
                                }

                                if (!string.IsNullOrEmpty(typeName) && !string.IsNullOrEmpty(propName) && !string.IsNullOrEmpty(ownerTypeName))
                                {
                                    if (ownerTypeName == obj.GetType().FullName)
                                    {
                                        // Property is not an attached property.  Serialize using regular property set expression.
                                        CodePropertyReferenceExpression propertyRef = new CodePropertyReferenceExpression(objectExpression, propName);
                                        retVal.Add(new CodeAssignStatement(propertyRef, new CodeTypeOfExpression(typeName)));
                                    }
                                    else
                                    {
                                        // This is an attached property.  Serialize using SetValue() expression.
                                        CodeExpression param1 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(ownerTypeName), propName + "Property");
                                        CodeExpression param2 = new CodeTypeOfExpression(typeName);
                                        retVal.Add(new CodeMethodInvokeExpression(objectExpression, "SetValue", new CodeExpression[] { param1, param2 }));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                if (activity != null)
                {
                    object pushedActivity = manager.Context.Pop();
                    System.Diagnostics.Debug.Assert(pushedActivity == activity);
                }
            }

            return(retVal);
        }
        public void Remove_Null()
        {
            CodeStatementCollection coll = new CodeStatementCollection();

            coll.Remove((CodeStatement)null);
        }
        public void Remove_NotInCollection()
        {
            CodeStatementCollection coll = new CodeStatementCollection();

            coll.Remove(new CodeStatement());
        }