Exemple #1
0
 /// <summary>
 /// Gets the dispose.
 /// </summary>
 /// <param name="objectName">Name of the object.</param>
 /// <returns>return dispose CodeDom</returns>
 internal static CodeConditionStatement GetDispose(string objectName)
 {
     var statments = new CodeStatementCollection();
     statments.Add(GetInvokeMethod(objectName, "Dispose"));
     return
         new CodeConditionStatement(
             new CodeBinaryOperatorExpression(
                 new CodeVariableReferenceExpression(objectName),
                 CodeBinaryOperatorType.IdentityInequality,
                 new CodePrimitiveExpression(null)),
                 statments.ToArray());
 }
Exemple #2
0
        /// <summary>
        /// Gets the throw clause.
        /// </summary>
        /// <returns>return catch...throw statment</returns>
        internal static CodeCatchClause[] GetThrowClause()
        {
            var catchStatmanents = new CodeStatementCollection();
            catchStatmanents.Add(new CodeThrowExceptionStatement(new CodeVariableReferenceExpression("ex")));
            var catchClause = new CodeCatchClause(
                                                    "ex",
                                                    new CodeTypeReference(typeof(Exception)),
                                                    catchStatmanents.ToArray());

            var catchClauses = new[] { catchClause };
            return catchClauses;
        }
Exemple #3
0
        /// <summary>
        /// Get Deserialize method
        /// </summary>
        /// <param name="type">represent a type declaration of class</param>
        /// <returns>Deserialize CodeMemberMethod</returns>
        protected virtual CodeMemberMethod[] GetOverrideDeserializeMethods(CodeTypeDeclaration type)
        {
            var deserializeMethodList = new List<CodeMemberMethod>();
            string deserializeTypeName = GeneratorContext.GeneratorParams.UseGenericBaseClass ? "T" : type.Name;

            // -------------------------------------------------------------------------------------
            // public static bool Deserialize(string xml, out T obj, out System.Exception exception)
            // -------------------------------------------------------------------------------------
            var deserializeMethod = new CodeMemberMethod
                                        {
                                            Attributes = MemberAttributes.Public | MemberAttributes.Static,
                                            Name = GeneratorContext.GeneratorParams.DeserializeMethodName
                                        };

            deserializeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "xml"));

            var param = new CodeParameterDeclarationExpression(deserializeTypeName, "obj") { Direction = FieldDirection.Out };
            deserializeMethod.Parameters.Add(param);

            param = new CodeParameterDeclarationExpression(typeof(Exception), "exception") { Direction = FieldDirection.Out };

            deserializeMethod.Parameters.Add(param);

            deserializeMethod.ReturnType = new CodeTypeReference(typeof(bool));

            // -----------------
            // exception = null;
            // -----------------
            deserializeMethod.Statements.Add(
                new CodeAssignStatement(
                    new CodeArgumentReferenceExpression("exception"),
                    new CodePrimitiveExpression(null)));

            // -----------------
            // obj = default(T);
            // -----------------
            deserializeMethod.Statements.Add(
                        new CodeAssignStatement(
                          new CodeArgumentReferenceExpression("obj"),
                            new CodeDefaultValueExpression(new CodeTypeReference(deserializeTypeName))
                            ));

            /* DCM REMOVE Switch Statement Dependent Code
            switch (GeneratorContext.GeneratorParams.Language)
            {
                case GenerationLanguage.CSharp:
                    {
                        deserializeMethod.Statements.Add(
                            new CodeAssignStatement(
                              new CodeArgumentReferenceExpression("obj"),
                                new CodeSnippetExpression(string.Format("default({0})", deserializeTypeName))));
                    }

                    break;
                case GenerationLanguage.VisualBasic:
                    {
                        deserializeMethod.Statements.Add(
                             new CodeAssignStatement(
                                new CodeArgumentReferenceExpression("obj"),
                                    new CodePrimitiveExpression(null)));
                    }

                    break;
            }
             */

            // ---------------------
            // try {...} catch {...}
            // ---------------------
            var tryStatmanentsCol = new CodeStatementCollection();

            // Call Desrialize method
            var deserializeInvoke =
                new CodeMethodInvokeExpression(
                      new CodeMethodReferenceExpression(null, GeneratorContext.GeneratorParams.DeserializeMethodName),
                        new CodeExpression[] { new CodeArgumentReferenceExpression("xml") });

            tryStatmanentsCol.Add(
                new CodeAssignStatement(
                    new CodeArgumentReferenceExpression("obj"),
                        deserializeInvoke));

            tryStatmanentsCol.Add(CodeDomHelper.GetReturnTrue());

            // catch
            var catchClauses = CodeDomHelper.GetCatchClause();

            var trycatch = new CodeTryCatchFinallyStatement(tryStatmanentsCol.ToArray(), catchClauses);
            deserializeMethod.Statements.Add(trycatch);

            // --------
            // Comments
            // --------
            deserializeMethod.Comments.AddRange(
                CodeDomHelper.GetSummaryComment(string.Format("Deserializes workflow markup into an {0} object", type.Name)));

            deserializeMethod.Comments.Add(CodeDomHelper.GetParamComment("xml", "string workflow markup to deserialize"));
            deserializeMethod.Comments.Add(CodeDomHelper.GetParamComment("obj", string.Format("Output {0} object", type.Name)));
            deserializeMethod.Comments.Add(CodeDomHelper.GetParamComment("exception", "output Exception value if deserialize failed"));

            deserializeMethod.Comments.Add(
                CodeDomHelper.GetReturnComment("true if this XmlSerializer can deserialize the object; otherwise, false"));
            deserializeMethodList.Add(deserializeMethod);

            // -----------------------------------------------------
            // public static bool Deserialize(string xml, out T obj)
            // -----------------------------------------------------
            deserializeMethod = new CodeMemberMethod
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Static,
                Name = GeneratorContext.GeneratorParams.DeserializeMethodName
            };
            deserializeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "xml"));
            deserializeMethod.ReturnType = new CodeTypeReference(typeof(bool));

            param = new CodeParameterDeclarationExpression(deserializeTypeName, "obj") { Direction = FieldDirection.Out };
            deserializeMethod.Parameters.Add(param);

            // ---------------------------
            // Exception exception = null;
            // ---------------------------
            deserializeMethod.Statements.Add(
            new CodeVariableDeclarationStatement(typeof(Exception), "exception", new CodePrimitiveExpression(null)));

            // ------------------------------------------------
            // return Deserialize(xml, out obj, out exception);
            // ------------------------------------------------
            var xmlStringParam = new CodeArgumentReferenceExpression("xml");
            var objParam = new CodeDirectionExpression(
                FieldDirection.Out, new CodeFieldReferenceExpression(null, "obj"));

            var expParam = new CodeDirectionExpression(
                FieldDirection.Out, new CodeFieldReferenceExpression(null, "exception"));

            deserializeInvoke =
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(null, GeneratorContext.GeneratorParams.DeserializeMethodName),
                    new CodeExpression[] { xmlStringParam, objParam, expParam });

            var returnStmt = new CodeMethodReturnStatement(deserializeInvoke);
            deserializeMethod.Statements.Add(returnStmt);
            deserializeMethodList.Add(deserializeMethod);
            return deserializeMethodList.ToArray();
        }
        /// <summary>
        /// Gets the Silverlight save to isolate storage file.
        /// </summary>
        /// <param name="type">CodeTypeDeclaration type.</param>
        /// <returns>return the save to file code DOM method statment </returns>
        protected override CodeMemberMethod GetSaveToFileMethod()
        {
            // -----------------------------------------------
            // public virtual void SaveToFile(string fileName)
            // -----------------------------------------------
            var saveToFileMethod = new CodeMemberMethod
            {
                Attributes = MemberAttributes.Public,
                Name = GeneratorContext.GeneratorParams.Serialization.SaveToFileMethodName
            };

            saveToFileMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "fileName"));

            if (GeneratorContext.GeneratorParams.Serialization.EnableEncoding)
            {
                saveToFileMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Encoding), "encoding"));
            }

            saveToFileMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(typeof(StreamWriter)),
                    "streamWriter",
                    new CodePrimitiveExpression(null)));

            saveToFileMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(typeof(IsolatedStorageFile)),
                    "isoFile",
                    new CodePrimitiveExpression(null)));

            saveToFileMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(typeof(IsolatedStorageFileStream)),
                    "isoStream",
                    new CodePrimitiveExpression(null)));

            // ------------------------
            // try {...} finally {...}
            // -----------------------
            var tryExpression = new CodeStatementCollection();

            tryExpression.Add(
                new CodeAssignStatement(
                new CodeVariableReferenceExpression("isoFile"),
                CodeDomHelper.GetInvokeMethod("IsolatedStorageFile", "GetUserStoreForApplication")));

            tryExpression.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("isoStream"),
                    new CodeObjectCreateExpression(
                        typeof(IsolatedStorageFileStream),
                        new CodeExpression[]
                        {
                             new CodeArgumentReferenceExpression("fileName"),
                             CodeDomHelper.GetEnum("FileMode","Create"),
                             new CodeVariableReferenceExpression("isoFile")
                    })));

            tryExpression.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("streamWriter"),
                    new CodeObjectCreateExpression(
                        typeof(StreamWriter),
                        new CodeExpression[]
                        {
                            new CodeVariableReferenceExpression("isoStream"),
                    })));
            // ---------------------------------------
            // string xmlString = Serialize(encoding);
            // ---------------------------------------

            CodeMethodInvokeExpression serializeMethodInvoke;
            if (GeneratorContext.GeneratorParams.Serialization.EnableEncoding)
            {
                serializeMethodInvoke = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(null,
                                                      GeneratorContext.GeneratorParams.Serialization.SerializeMethodName),
                    new CodeExpression[] { new CodeArgumentReferenceExpression("encoding") });
            }
            else
            {
                serializeMethodInvoke = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(null,
                                                      GeneratorContext.GeneratorParams.Serialization.SerializeMethodName));
            }

            var xmlString = new CodeVariableDeclarationStatement(
                new CodeTypeReference(typeof(string)), "xmlString", serializeMethodInvoke);

            tryExpression.Add(xmlString);

            if (GeneratorContext.GeneratorParams.Serialization.EnableEncoding)
            {
                // ----------------------------------------------------------------
                // streamWriter = new StreamWriter(fileName, false, Encoding.UTF8);
                // ----------------------------------------------------------------
                tryExpression.Add(new CodeAssignStatement(
                                      new CodeVariableReferenceExpression("streamWriter"),
                                      new CodeObjectCreateExpression(
                                          typeof(StreamWriter),
                                          new CodeExpression[]
                                              {
                                                  new CodeSnippetExpression("fileName"),
                                                  new CodeSnippetExpression("false"),
                                                  new CodeSnippetExpression(GeneratorContext.GeneratorParams.Serialization.GetEncoderString())
                        })));
            }
            else
            {
                // --------------------------------------------------------------
                // System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
                // --------------------------------------------------------------
                tryExpression.Add(CodeDomHelper.CreateObject(typeof(FileInfo), "xmlFile", new[] { "fileName" }));

                // ----------------------------------------
                // StreamWriter Tex = xmlFile.CreateText();
                // ----------------------------------------
                var createTextMethodInvoke = CodeDomHelper.GetInvokeMethod("xmlFile", "CreateText");

                tryExpression.Add(
                    new CodeAssignStatement(
                        new CodeVariableReferenceExpression("streamWriter"),
                        createTextMethodInvoke));
            }
            // ----------------------------------
            // streamWriter.WriteLine(xmlString);
            // ----------------------------------
            var writeLineMethodInvoke =
                CodeDomHelper.GetInvokeMethod(
                                                "streamWriter",
                                                "WriteLine",
                                                new CodeExpression[]
                                                  {
                                                      new CodeVariableReferenceExpression("xmlString")
                                                  });

            tryExpression.Add(writeLineMethodInvoke);
            tryExpression.Add(CodeDomHelper.GetInvokeMethod("streamWriter", "Close"));
            tryExpression.Add(CodeDomHelper.GetInvokeMethod("isoStream", "Close"));

            var finallyStatmanentsCol = new CodeStatementCollection();
            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("streamWriter"));
            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("isoFile"));
            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("isoStream"));

            var trycatch = new CodeTryCatchFinallyStatement(tryExpression.ToArray(), new CodeCatchClause[0], finallyStatmanentsCol.ToArray());
            saveToFileMethod.Statements.Add(trycatch);

            return saveToFileMethod;
        }
Exemple #5
0
        /// <summary>
        /// Get Deserialize method
        /// </summary>
        /// <param name="type">represent a type declaration of class</param>
        /// <returns>Deserialize CodeMemberMethod</returns>
        protected virtual CodeMemberMethod GetDeserializeMethod(CodeTypeDeclaration type)
        {
            string deserializeTypeName = GeneratorContext.GeneratorParams.UseGenericBaseClass ? "T" : type.Name;

            // ---------------------------------------
            // public static T Deserialize(string xml)
            // ---------------------------------------
            var deserializeMethod = new CodeMemberMethod
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Static,
                Name = GeneratorContext.GeneratorParams.DeserializeMethodName
            };

            deserializeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "xml"));
            deserializeMethod.ReturnType = new CodeTypeReference(deserializeTypeName);

            deserializeMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(typeof(StringReader)),
                    "stringReader",
                    new CodePrimitiveExpression(null)));

            var tryStatmanentsCol = new CodeStatementCollection();
            var finallyStatmanentsCol = new CodeStatementCollection();

            // ------------------------------------------------------
            // stringReader = new StringReader(xml);
            // ------------------------------------------------------
            var deserializeStatmanents = new CodeStatementCollection();

            tryStatmanentsCol.Add(new CodeAssignStatement(
                          new CodeVariableReferenceExpression("stringReader"),
                          new CodeObjectCreateExpression(
                              new CodeTypeReference(typeof(StringReader)),
                              new CodeExpression[] { new CodeArgumentReferenceExpression("xml") })));

            // ----------------------------------------------------------
            // obj = (ClassName)serializer.Deserialize(xmlReader);
            // return true;
            // ----------------------------------------------------------
            var deserialize = CodeDomHelper.GetInvokeMethod(
                                                            "Serializer",
                                                            "Deserialize",
                                                            new CodeExpression[]
                                                            {
                                                                CodeDomHelper.GetInvokeMethod(
                                                                "System.Xml.XmlReader",
                                                                "Create",
                                                                new CodeExpression[] { new CodeVariableReferenceExpression("stringReader") })
                                                            });

            var castExpr = new CodeCastExpression(deserializeTypeName, deserialize);
            var returnStmt = new CodeMethodReturnStatement(castExpr);

            tryStatmanentsCol.Add(returnStmt);
            tryStatmanentsCol.AddRange(deserializeStatmanents);

            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("stringReader"));

            var tryfinallyStmt = new CodeTryCatchFinallyStatement(tryStatmanentsCol.ToArray(), new CodeCatchClause[0], finallyStatmanentsCol.ToArray());
            deserializeMethod.Statements.Add(tryfinallyStmt);

            return deserializeMethod;
        }
Exemple #6
0
        /// <summary>
        /// Gets the serialize CodeDOM method.
        /// </summary>
        /// <param name="type">The type object to serilize.</param>
        /// <returns>return the CodeDOM serialize method</returns>
        protected virtual CodeMemberMethod CreateSerializeMethod(CodeTypeDeclaration type)
        {
            var serializeMethod = new CodeMemberMethod
                                      {
                                          Attributes = MemberAttributes.Public,
                                          Name = GeneratorContext.GeneratorParams.SerializeMethodName
                                      };

            var tryStatmanentsCol = new CodeStatementCollection();
            var finallyStatmanentsCol = new CodeStatementCollection();

            // ------------------------------------------------------------
            // System.IO.StreamReader streamReader = null;
            // System.IO.MemoryStream memoryStream = null;
            // ------------------------------------------------------------
            serializeMethod.Statements.Add(
                    new CodeVariableDeclarationStatement(
                        new CodeTypeReference(typeof(StreamReader)),
                        "streamReader",
                        new CodePrimitiveExpression(null)));

            serializeMethod.Statements.Add(
                    new CodeVariableDeclarationStatement(
                        new CodeTypeReference(typeof(MemoryStream)),
                        "memoryStream",
                        new CodePrimitiveExpression(null)));

            tryStatmanentsCol.Add(new CodeAssignStatement(
                new CodeVariableReferenceExpression("memoryStream"),
                CodeDomHelper.CreateInstance(typeof(MemoryStream))));

            // --------------------------------------------------------------------------
            // Serializer.Serialize(memoryStream, this);
            // --------------------------------------------------------------------------
            tryStatmanentsCol.Add(
                CodeDomHelper.GetInvokeMethod(
                    "Serializer",
                    "Serialize",
                    new CodeExpression[]
                        {
                            new CodeTypeReferenceExpression("memoryStream"),
                            new CodeThisReferenceExpression()
                        }));

            // ---------------------------------------------------------------------------
            // memoryStream.Seek(0, SeekOrigin.Begin);
            // System.IO.StreamReader streamReader = new System.IO.StreamReader(memoryStream);
            // ---------------------------------------------------------------------------
            tryStatmanentsCol.Add(
                CodeDomHelper.GetInvokeMethod(
                                              "memoryStream",
                                              "Seek",
                                              new CodeExpression[]
                                                  {
                                                      new CodePrimitiveExpression(0),
                                                      new CodeTypeReferenceExpression("System.IO.SeekOrigin.Begin")
                                                  }));

            tryStatmanentsCol.Add(new CodeAssignStatement(
                new CodeVariableReferenceExpression("streamReader"),
                CodeDomHelper.CreateInstance(typeof(StreamReader), new[] { "memoryStream" })));

            var readToEnd = CodeDomHelper.GetInvokeMethod("streamReader", "ReadToEnd");
            tryStatmanentsCol.Add(new CodeMethodReturnStatement(readToEnd));

            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("streamReader"));
            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("memoryStream"));

            var tryfinallyStmt = new CodeTryCatchFinallyStatement(tryStatmanentsCol.ToArray(), new CodeCatchClause[0], finallyStatmanentsCol.ToArray());
            serializeMethod.Statements.Add(tryfinallyStmt);

            serializeMethod.ReturnType = new CodeTypeReference(typeof(string));

            // --------
            // Comments
            // --------
            serializeMethod.Comments.AddRange(
                CodeDomHelper.GetSummaryComment(string.Format("Serializes current {0} object into an XML document", type.Name)));

            serializeMethod.Comments.Add(CodeDomHelper.GetReturnComment("string XML value"));
            return serializeMethod;
        }
Exemple #7
0
        /// <summary>
        /// Creates the static serializer.
        /// </summary>
        /// <param name="classType">Type of the class.</param>
        private static void CreateStaticSerializer(CodeTypeDeclaration classType)
        {
            string typeName = GeneratorContext.GeneratorParams.UseGenericBaseClass ? "T" : classType.Name;

            //VB is not Case Sensitive
            string fieldName = GeneratorContext.GeneratorParams.Language == GenerationLanguage.VisualBasic ?  "sSerializer" : "serializer" ;

            // -----------------------------------------------------------------
            // private static System.Xml.Serialization.XmlSerializer serializer;
            // -----------------------------------------------------------------
            var serializerfield = new CodeMemberField(typeof(XmlSerializer), fieldName);
            serializerfield.Attributes = MemberAttributes.Static | MemberAttributes.Private;
            classType.Members.Add(serializerfield);

            var typeRef = new CodeTypeReference(typeName);
            var typeofValue = new CodeTypeOfExpression(typeRef);

            // private static System.Xml.Serialization.XmlSerializer Serializer { get {...} }
            var serializerProperty = new CodeMemberProperty();
            serializerProperty.Type = new CodeTypeReference(typeof(XmlSerializer));
            serializerProperty.Name = "Serializer";

            serializerProperty.HasSet = false;
            serializerProperty.HasGet = true;
            serializerProperty.Attributes = MemberAttributes.Static | MemberAttributes.Private;

            var statments = new CodeStatementCollection();

            statments.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression(fieldName),
                    new CodeObjectCreateExpression(
                        new CodeTypeReference(typeof(XmlSerializer)), new CodeExpression[] { typeofValue })));

            serializerProperty.GetStatements.Add(
                new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(
                        new CodeVariableReferenceExpression(fieldName),
                        CodeBinaryOperatorType.IdentityEquality,
                        new CodePrimitiveExpression(null)),
                        statments.ToArray()));

            serializerProperty.GetStatements.Add(
                new CodeMethodReturnStatement(new CodeVariableReferenceExpression(fieldName)));

            classType.Members.Add(serializerProperty);
        }
Exemple #8
0
        /// <summary>
        /// Gets the save to file code DOM method.
        /// </summary>
        /// <returns>
        /// return the save to file code DOM method statment
        /// </returns>
        protected virtual CodeMemberMethod GetSaveToFileMethod()
        {
            // -----------------------------------------------
            // public virtual void SaveToFile(string fileName)
            // -----------------------------------------------
            var saveToFileMethod = new CodeMemberMethod
            {
                Attributes = MemberAttributes.Public,
                Name = GeneratorContext.GeneratorParams.SaveToFileMethodName
            };

            saveToFileMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "fileName"));

            saveToFileMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(typeof(StreamWriter)),
                    "streamWriter",
                    new CodePrimitiveExpression(null)));

            // ------------------------
            // try {...} finally {...}
            // -----------------------
            var tryExpression = new CodeStatementCollection();

            // ------------------------------
            // string xmlString = Serialize();
            // -------------------------------
            var serializeMethodInvoke = new CodeMethodInvokeExpression(
                new CodeMethodReferenceExpression(null, GeneratorContext.GeneratorParams.SerializeMethodName));

            var xmlString = new CodeVariableDeclarationStatement(
                new CodeTypeReference(typeof(string)), "xmlString", serializeMethodInvoke);

            tryExpression.Add(xmlString);

            // --------------------------------------------------------------
            // System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
            // --------------------------------------------------------------
            tryExpression.Add(CodeDomHelper.CreateObject(typeof(FileInfo), "xmlFile", new[] { "fileName" }));

            // ----------------------------------------
            // StreamWriter Tex = xmlFile.CreateText();
            // ----------------------------------------
            var createTextMethodInvoke = CodeDomHelper.GetInvokeMethod("xmlFile", "CreateText");

            tryExpression.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("streamWriter"),
                    createTextMethodInvoke));

            // ----------------------------------
            // streamWriter.WriteLine(xmlString);
            // ----------------------------------
            var writeLineMethodInvoke =
                CodeDomHelper.GetInvokeMethod(
                                                "streamWriter",
                                                "WriteLine",
                                                new CodeExpression[]
                                                  {
                                                      new CodeVariableReferenceExpression("xmlString")
                                                  });

            tryExpression.Add(writeLineMethodInvoke);
            var closeMethodInvoke = CodeDomHelper.GetInvokeMethod("streamWriter", "Close");

            tryExpression.Add(closeMethodInvoke);

            var finallyStatmanentsCol = new CodeStatementCollection();
            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("streamWriter"));

            var trycatch = new CodeTryCatchFinallyStatement(tryExpression.ToArray(), new CodeCatchClause[0], finallyStatmanentsCol.ToArray());
            saveToFileMethod.Statements.Add(trycatch);

            return saveToFileMethod;
        }
Exemple #9
0
        /// <summary>
        /// Gets the save to file code DOM method.
        /// </summary>
        /// <param name="type">CodeTypeDeclaration type.</param>
        /// <returns>
        /// return the save to file code DOM method statment
        /// </returns>
        protected virtual CodeMemberMethod[] GetOverrideSaveToFileMethods(CodeTypeDeclaration type)
        {
            var saveToFileMethodList = new List<CodeMemberMethod>();
            var saveToFileMethod = new CodeMemberMethod
                                       {
                                           Attributes = MemberAttributes.Public,
                                           Name = GeneratorContext.GeneratorParams.SaveToFileMethodName
                                       };

            saveToFileMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "fileName"));

            var paramException = new CodeParameterDeclarationExpression(
                typeof(Exception), "exception")
                                     {
                                         Direction = FieldDirection.Out
                                     };

            saveToFileMethod.Parameters.Add(paramException);

            saveToFileMethod.ReturnType = new CodeTypeReference(typeof(bool));

            saveToFileMethod.Statements.Add(
                new CodeAssignStatement(new CodeArgumentReferenceExpression("exception"), new CodePrimitiveExpression(null)));

            // ---------------------
            // try {...} catch {...}
            // ---------------------
            var tryExpression = new CodeStatementCollection();

            // ---------------------
            // SaveToFile(fileName);
            // ---------------------
            var xmlStringParam = new CodeArgumentReferenceExpression("fileName");

            var saveToFileInvoke =
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(null, GeneratorContext.GeneratorParams.SaveToFileMethodName),
                    new CodeExpression[] { xmlStringParam });

            tryExpression.Add(saveToFileInvoke);
            tryExpression.Add(CodeDomHelper.GetReturnTrue());

            // -----------
            // Catch {...}
            // -----------
            var catchstmts = new CodeStatementCollection();
            catchstmts.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("exception"), new CodeVariableReferenceExpression("e")));

            catchstmts.Add(CodeDomHelper.GetReturnFalse());
            var codeCatchClause = new CodeCatchClause("e", new CodeTypeReference(typeof(Exception)), catchstmts.ToArray());

            var codeCatchClauses = new[] { codeCatchClause };

            var trycatch = new CodeTryCatchFinallyStatement(tryExpression.ToArray(), codeCatchClauses);
            saveToFileMethod.Statements.Add(trycatch);

            saveToFileMethod.Comments.AddRange(
                CodeDomHelper.GetSummaryComment(string.Format("Serializes current {0} object into file", type.Name)));

            saveToFileMethod.Comments.Add(CodeDomHelper.GetParamComment("fileName", "full path of outupt xml file"));
            saveToFileMethod.Comments.Add(CodeDomHelper.GetParamComment("exception", "output Exception value if failed"));
            saveToFileMethod.Comments.Add(CodeDomHelper.GetReturnComment("true if can serialize and save into file; otherwise, false"));

            saveToFileMethodList.Add(saveToFileMethod);
            return saveToFileMethodList.ToArray();
        }