Flush() public method

public Flush ( ) : void
return void
 public GeneratorResults ParseToCode(string TemplateCode, string defaultnamespace, string defaultclassname, string baseClassFullName)
 {
     GeneratorResults razorResults;
     var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
     host.DefaultBaseClass = baseClassFullName;//typeof(BulaqTemplateForRazorBase).FullName;
     host.DefaultNamespace = defaultnamespace;
     host.DefaultClassName = defaultclassname;
     host.NamespaceImports.Add("System");
     host.NamespaceImports.Add("BulaqCMS.Models");
     host.GeneratedClassContext = new GeneratedClassContext("Execute", "Write", "WriteLiteral");
     var engine = new RazorTemplateEngine(host);
     using (var reader = new StringReader(TemplateCode))
     {
         razorResults = engine.GenerateCode(reader);
         CSharpCodeProvider codeProvider = new CSharpCodeProvider();
         CodeGeneratorOptions options = new CodeGeneratorOptions();
         options.BracingStyle = "C";
         using (StringWriter writer = new StringWriter())
         {
             IndentedTextWriter indentwriter = new IndentedTextWriter(writer, "    ");
             codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, indentwriter, options);
             indentwriter.Flush();
             indentwriter.Close();
             LastGeneratedCode = writer.GetStringBuilder().ToString();
             string codePath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\code.cs";
             File.WriteAllText(codePath, LastGeneratedCode, Encoding.UTF8);
         }
     }
     return razorResults;
 }
Beispiel #2
0
 public void Serializes()
 {
     using (var sw = new StringWriter())
     using (var writer = new IndentedTextWriter(sw, "    "))
     {
       //  new KoSerializer(writer).Serialize("viewModel", new TestSemanticView());
         writer.Flush();
         Console.WriteLine(sw.GetStringBuilder().ToString());
     }
 }
		/// <summary>
		/// Prints a UnityEngine.GameObject, along with its components and children. Prints properties of components, but not of GameObjects, and doesn't print GameObjects in properties.
		/// </summary>
		/// <param name="o">The game object to print</param>
		/// <param name="componentFilter">A filter that says which components to print fully (printing their properties). By default, all will be expanded.</param>
		/// <param name="gameObjectFilter">A filter that says which GameObject children to print recursively (e.g. print their components and their children). Only the names of filtered children will appear.</param>
		/// <returns></returns>
		public static string PrintUnityGameObject(GameObject o, Func<GameObject, bool> gameObjectFilter = null, Func<Component, bool> componentFilter = null) {
			componentFilter = componentFilter ?? (x => true);
			gameObjectFilter = gameObjectFilter ?? (x => true);
			var dumper = new UnityObjectDumper();
			var strWriter = new StringWriter();
			var identedWriter = new IndentedTextWriter(strWriter, "\t");
			dumper.PrintUnityGameObject(o, identedWriter,gameObjectFilter, componentFilter);
			identedWriter.Flush();
			strWriter.Flush();
			return strWriter.ToString();
		}
        public static string ToCSharp(this CodeCompileUnit unit)
        {
            using (var stream = new MemoryStream())
            {
                var csharp = new CSharpCodeProvider();

                var writer = new IndentedTextWriter(new StreamWriter(stream));
                csharp.GenerateCodeFromCompileUnit(unit, writer, new CodeGeneratorOptions());
                writer.Flush();

                return stream.ReadToEnd();
            }
        }
Beispiel #5
0
 public static void GenerateCode(string fileName,
                                 System.CodeDom.Compiler.CodeDomProvider provider,
                                 System.CodeDom.CodeCompileUnit compileUnit)
 {
     System.CodeDom.Compiler.ICodeGenerator     gen = provider.CreateGenerator();
     System.CodeDom.Compiler.IndentedTextWriter tw  = null;
     try
     {
         tw = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(fileName, false), "	");
         gen.GenerateCodeFromCompileUnit(compileUnit, tw, new System.CodeDom.Compiler.CodeGeneratorOptions());
     }
     finally
     {
         if (tw != null)
         {
             tw.Flush();
             tw.Close();
         }
     }
 }
Beispiel #6
0
 /// <summary>
 /// Writes the class file.  This method actually creates the physical
 /// class file and populates it accordingly.
 /// </summary>
 /// <param name="className">Name of the class file to be written.</param>
 /// <param name="codenamespace">The <see cref="CodeNamespace"/> which represents the
 /// file to be written.</param>
 private void WriteClassFile(string className, CodeNamespace codenamespace)
 {
     var csharpCodeProvider = new CSharpCodeProvider();
     string sourceFile = this.OutputDirectory + this.buildSystem.DirectorySeparatorChar +
                         className + "." + csharpCodeProvider.FileExtension;
     sourceFile = Utility.ScrubPathOfIllegalCharacters(sourceFile);
     var indentedTextWriter =
         new IndentedTextWriter(this.buildSystem.GetTextWriter(sourceFile, false), "  ");
     var codeGenerationOptions = new CodeGeneratorOptions { BracingStyle = "C" };
     csharpCodeProvider.GenerateCodeFromNamespace(
         codenamespace,
         indentedTextWriter,
         codeGenerationOptions);
     indentedTextWriter.Flush();
     indentedTextWriter.Close();
 }
        /// <summary>
        /// Converts a unit of CodeDOM code into the C# source equivalent
        /// </summary>
        public static string CompileToCSharpSourceCode(this CodeCompileUnit code)
        {
            var providerOptions = new Dictionary<string, string>();
            if (Environment.Version.Major < 4) providerOptions.Add("CompilerVersion", "v3.5");

            var compiler = new CSharpCodeProvider(providerOptions);
            string result;

            using (var sourceStream = new MemoryStream())
            {
                var tw = new IndentedTextWriter(new StreamWriter(sourceStream), "\t");

                compiler.GenerateCodeFromCompileUnit(code, tw, new CodeGeneratorOptions());

                tw.Flush();

                sourceStream.Seek(0, SeekOrigin.Begin);
                result = new StreamReader(sourceStream).ReadToEnd();
            }

            return result;
        }
Beispiel #8
0
        // TODO
        public void GeneratePackage(IProject project, PackageDescriptor pd)
        {
            string name = MakeIDName(pd.PackageName, pd);

            string fname = MakeSysCHeaderFileName(name);
            string path = project.AddFile(fname);
            project.AddFileAttribute(fname, pd);
            if (pd.Library != null)
                project.SetFileLibrary(fname, pd.Library);
            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            IndentedTextWriter tw = new IndentedTextWriter(sw, "  ");

            string cfname = MakeSysCSourceFileName(name);
            string path1 = project.AddFile(cfname);
            project.AddFileAttribute(cfname, pd);
            if (pd.Library != null)
                project.SetFileLibrary(cfname, pd.Library);
            MemoryStream ms1 = new MemoryStream();
            StreamWriter sw1 = new StreamWriter(ms1);
            IndentedTextWriter tw1 = new IndentedTextWriter(sw1, "  ");

            ClearDependencies();

            //tw.Indent++;
            tw1.WriteLine("#include \"" + fname + "\"");
            tw1.WriteLine();

            GenerateTypeDecls(pd, tw);

            foreach (MethodDescriptor md in pd.GetMethods())
            {
                GenerateMethodDecl(md, tw);
                tw.WriteLine();
                GenerateMethodImpl(md, tw1);
                tw1.WriteLine();
            }

            foreach (FieldDescriptor fd in pd.GetConstants())
            {
                DeclareField(fd, tw);
            }
            tw.Indent--;
            //tw.Indent++;
            tw.WriteLine("#endif");

            tw.Flush();
            sw = new StreamWriter(path);
            tw = new IndentedTextWriter(sw, "  ");

            tw1.Flush();
            sw1 = new StreamWriter(path1);
            tw1 = new IndentedTextWriter(sw1, "  ");

            CreateFileHeader(new GeneratorInfo(fname), tw);
            CreateFileHeader(new GeneratorInfo(cfname), tw1);
            GeneratePreProcDir(pd, tw);
            GenerateDependencies(pd, tw);
            //_extraLibraries.Add(new SysCLib(fname));

            tw.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            ms.CopyTo(sw.BaseStream);
            ms.Close();
            tw.Close();
            sw.Close();

            tw1.Flush();
            ms1.Seek(0, SeekOrigin.Begin);
            ms1.CopyTo(sw1.BaseStream);
            ms1.Close();
            tw1.Close();
            sw1.Close();

        }
Beispiel #9
0
		private void TouchEverything (IndentedTextWriter itw)
		{
			Assert.AreSame (writer.Encoding, itw.Encoding, "Encoding");
			Assert.AreEqual (0, itw.Indent, "Indent");
			itw.Indent = 1;
			Assert.AreSame (writer, itw.InnerWriter, "InnerWriter");
			Assert.AreEqual (writer.NewLine, itw.NewLine, "NewLine");

			itw.Write (true);
			itw.Write (Char.MinValue);
			itw.Write (Path.InvalidPathChars); // char[]
			itw.Write (Double.MinValue);
			itw.Write (Int32.MinValue);
			itw.Write (Int64.MaxValue);
			itw.Write (new object ());
			itw.Write (Single.MinValue);
			itw.Write (String.Empty);
			itw.Write ("{0}", String.Empty);
			itw.Write ("{0}{1}", Int32.MinValue, Int32.MaxValue);
			itw.Write ("{0}{1}{2}", Int32.MinValue, 0, Int32.MaxValue);
			itw.Write (Path.InvalidPathChars, 0, Path.InvalidPathChars.Length);
			itw.WriteLine ();
			itw.WriteLine (true);
			itw.WriteLine (Char.MinValue);
			itw.WriteLine (Path.InvalidPathChars); // char[]
			itw.WriteLine (Double.MinValue);
			itw.WriteLine (Int32.MinValue);
			itw.WriteLine (Int64.MaxValue);
			itw.WriteLine (new object ());
			itw.WriteLine (Single.MinValue);
			itw.WriteLine (String.Empty);
			itw.WriteLine (UInt32.MaxValue);
			itw.WriteLine ("{0}", String.Empty);
			itw.WriteLine ("{0}{1}", Int32.MinValue, Int32.MaxValue);
			itw.WriteLine ("{0}{1}{2}", Int32.MinValue, 0, Int32.MaxValue);
			itw.WriteLine (Path.InvalidPathChars, 0, Path.InvalidPathChars.Length);
			itw.WriteLineNoTabs (String.Empty);
			itw.Flush ();
			itw.Close ();
		}
Beispiel #10
0
        private static void WriteInventoryToFile(string fileName, ItemStacks slots)
        {
            Log.Info($"Writing inventory to filename: {fileName}");
            FileStream file = File.OpenWrite(fileName);

            IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(file));

            writer.WriteLine("// GENERATED CODE. DON'T EDIT BY HAND");
            writer.Indent++;
            writer.Indent++;
            writer.WriteLine("public static List<Item> CreativeInventoryItems = new List<Item>()");
            writer.WriteLine("{");
            writer.Indent++;

            foreach (var entry in slots)
            {
                var slot = entry;
                NbtCompound extraData = slot.ExtraData;
                if (extraData == null)
                {
                    writer.WriteLine($"new Item({slot.Id}, {slot.Metadata}, {slot.Count}),");
                }
                else
                {
                    NbtList ench = (NbtList) extraData["ench"];
                    NbtCompound enchComp = (NbtCompound) ench[0];
                    var id = enchComp["id"].ShortValue;
                    var lvl = enchComp["lvl"].ShortValue;
                    writer.WriteLine($"new Item({slot.Id}, {slot.Metadata}, {slot.Count}){{ExtraData = new NbtCompound {{new NbtList(\"ench\") {{new NbtCompound {{new NbtShort(\"id\", {id}), new NbtShort(\"lvl\", {lvl}) }} }} }} }},");
                }
            }

            // Template
            new ItemAir {ExtraData = new NbtCompound {new NbtList("ench") {new NbtCompound {new NbtShort("id", 0), new NbtShort("lvl", 0)}}}};
            //var compound = new NbtCompound(string.Empty) { new NbtList("ench", new NbtCompound()) {new NbtShort("id", 0),new NbtShort("lvl", 0),}, };

            writer.Indent--;
            writer.WriteLine("};");
            writer.Indent--;
            writer.Indent--;

            writer.Flush();
            file.Close();
        }
Beispiel #11
0
		private void WriteDatabaseProject(SolutionNode solution, DatabaseProjectNode project)
		{
			string projectFile = Helper.MakeFilePath(project.FullPath, project.Name, "dbp");
			IndentedTextWriter ps = new IndentedTextWriter(new StreamWriter(projectFile), "   ");

			kernel.CurrentWorkingDirectory.Push();

			Helper.SetCurrentDir(Path.GetDirectoryName(projectFile));

			using (ps)
			{
				ps.WriteLine("# Microsoft Developer Studio Project File - Database Project");
				ps.WriteLine("Begin DataProject = \"{0}\"", project.Name);
				ps.Indent++;
				ps.WriteLine("MSDTVersion = \"80\"");
				// TODO: Use the project.Files property
				if (ContainsSqlFiles(Path.GetDirectoryName(projectFile)))
					WriteDatabaseFoldersAndFiles(ps, Path.GetDirectoryName(projectFile));

				ps.WriteLine("Begin DBRefFolder = \"Database References\"");
				ps.Indent++;
				foreach (DatabaseReferenceNode reference in project.References)
				{
					ps.WriteLine("Begin DBRefNode = \"{0}\"", reference.Name);
					ps.Indent++;
					ps.WriteLine("ConnectStr = \"{0}\"", reference.ConnectionString);
					ps.WriteLine("Provider = \"{0}\"", reference.ProviderId.ToString("B").ToUpper());
					//ps.WriteLine("Colorizer = 5");
					ps.Indent--;
					ps.WriteLine("End");
				}
				ps.Indent--;
				ps.WriteLine("End");
				ps.Indent--;
				ps.WriteLine("End");

				ps.Flush();
			}

			kernel.CurrentWorkingDirectory.Pop();
		}
Beispiel #12
0
        //      ADDED
        private void GenerateMainFile(IProject project, IComponentDescriptor cd)
        {
            string fname = MakeSysCSourceFileName("main");
            string path = project.AddFile(fname);
            StreamWriter sw = new StreamWriter(path);
            IndentedTextWriter tw = new IndentedTextWriter(sw, "  ");
            string SimTimeUnit;

            CreateFileHeader(new GeneratorInfo(fname), tw);
            GenerateDependencies(null, tw, GetComponentName(cd));

            //  Get Simulation Time
            switch (SimTime.Unit)
            {
                case ETimeUnit.fs:
                    SimTimeUnit = "SC_FS";
                    break;
                case ETimeUnit.ps:
                    SimTimeUnit = "SC_PS";
                    break;
                case ETimeUnit.ns:
                    SimTimeUnit = "SC_NS";
                    break;
                case ETimeUnit.us:
                    SimTimeUnit = "SC_US";
                    break;
                case ETimeUnit.ms:
                    SimTimeUnit = "SC_MS";
                    break;
                case ETimeUnit.sec:
                    SimTimeUnit = "SC_SEC";
                    break;
                default:
                    throw new NotImplementedException();
            }

            tw.WriteLine();
            tw.WriteLine("int sc_main(int argc, char* argv[])");
            tw.WriteLine("{");
            tw.Indent++;
            tw.WriteLine("sc_report_handler::set_actions (SC_WARNING, SC_DO_NOTHING);");
            tw.WriteLine();
            tw.WriteLine(GetComponentName(cd) + " "
                + GetComponentName(((ComponentDescriptor)cd).Instance.Representant.Descriptor)
                + "(\"" + GetComponentName(cd) + "\");");

            tw.WriteLine();
            tw.WriteLine("sc_start(" + SimTime.Value + ", " + SimTimeUnit + ");");
            tw.WriteLine();
            tw.WriteLine("return 0;");
            tw.Indent--;
            tw.WriteLine("}");

            tw.Flush();
            tw.Close();
            sw.Close();
        }
Beispiel #13
0
		public static string PrintException(Exception ex) {
			var strWriter = new StringWriter();
			var indentedWriter = new IndentedTextWriter(strWriter);
			PrintException(indentedWriter, ex);
			indentedWriter.WriteLine(StackTraceUtility.ExtractStringFromException(ex));
			indentedWriter.Flush();
			strWriter.Flush();

			return strWriter.ToString();
		}
 /// <summary>
 /// Generates a value type implementation for forValueType.
 /// </summary>
 /// <returns>true if generated, false if skipped</returns>
 public bool GenerateValueTypeImpl(Type forValueType) {
     // create the fileName from targetDirectory and 
     // full type name
     string fileName = forValueType.FullName;
     fileName = fileName.Replace(".", "_") + "." + m_codeDomProvider.FileExtension;
     fileName = Path.Combine(m_targetDir.FullName, fileName);
     
     if (File.Exists(fileName) && !m_overwriteWhenExist) {
         Console.WriteLine("skip generation for " + 
                           forValueType.FullName + 
                           " because implementation file " +
                           fileName + " already exists ");
         return false;                                   
     }
     
     StreamWriter targetStream = new StreamWriter(fileName, false);
     IndentedTextWriter writer = new IndentedTextWriter(targetStream);
                  
     GenerateValueTypeImplToFile(forValueType, writer);
     
     writer.Flush();
     writer.Close();
     
     return true;
 }
 /// <summary>
 /// Writes the class file.  This method actually creates the physical
 /// class file and populates it accordingly.
 /// </summary>
 /// <param name="className">Name of the class file to be written.</param>
 /// <param name="codeNamespace">The CodeNamespace which represents the
 /// file to be written.</param>
 private void WriteClassFile(string className, CodeNamespace codeNamespace)
 {
     CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider();
     string sourceFile = _outputDirectory + Path.DirectorySeparatorChar +
         className + "." + cSharpCodeProvider.FileExtension;
     sourceFile = Utility.ScrubPathOfIllegalCharacters(sourceFile);
     IndentedTextWriter indentedTextWriter =
         new IndentedTextWriter(new StreamWriter(sourceFile, false), "  ");
     CodeGeneratorOptions codeGenerationOptions = new CodeGeneratorOptions();
     codeGenerationOptions.BracingStyle = "C";
     cSharpCodeProvider.GenerateCodeFromNamespace(codeNamespace, indentedTextWriter,
         codeGenerationOptions);
     indentedTextWriter.Flush();
     indentedTextWriter.Close();
 }
Beispiel #16
0
        /// <summary>
        /// Compiles the code within this object into the selected code format and saves it to the given file name.
        /// </summary>
        /// <returns>A FileInfo object set to point to the source file created.</returns>
        public FileInfo GenerateCode(string FileName)
        {
            // First, we're going to set the source FileInfo object to the next source file.
            fiSrc = new FileInfo(FileName);

            // Then, we check for an extension on that file and strip it if one was passed.
            #region DEBUG Output
#if DEBUG
            Console.Write(fiSrc.Extension);
#endif
            #endregion
            if (fiSrc.Extension.Length > 0 && fiSrc.Name.Length > fiSrc.Extension.Length)
                FileName = fiSrc.FullName.Substring(0, fiSrc.FullName.Length - fiSrc.Extension.Length);

            // We get the default extension from the provider object.  Some provider types do not supply the
            //   period on the extension, so we have to check for that.
            if (provider.FileExtension[0] == '.')
                FileName = FileName + provider.FileExtension;
            else
                FileName = FileName + "." + provider.FileExtension;

            IndentedTextWriter tw = null;
            try
            {
                // Now we create the text writer object.  We use an 'IndentedTextWriter' here to achieve
                //   more human-readable source code.
                tw = new IndentedTextWriter(new StreamWriter(FileName, false), "   ");

                // We need to reset our FileInfo object in case the filename was changed.
                fiSrc = new FileInfo(FileName);

                // Now we use the provider object to generate the source code.
                #region DEBUG Output
#if DEBUG
                for (int i = 0; i < compileUnit.Namespaces.Count; i++)
                {
                    Console.WriteLine("\nNamespace: {0}\n\nImports:\n", compileUnit.Namespaces[0].Name);
                    for (int t = 0; t < compileUnit.Namespaces[i].Imports.Count; t++)
                    {
                        Console.WriteLine("  using {0}", compileUnit.Namespaces[i].Imports[t].Namespace);
                    }
                    Console.WriteLine("\n\nClasses:\n");
                    for (int t = 0; t < compileUnit.Namespaces[i].Types.Count; t++)
                    {
                        Console.WriteLine("  -={0} {1}=-", compileUnit.Namespaces[i].Types[t].Attributes.ToString(), compileUnit.Namespaces[i].Types[t].Name);
                        for (int x = 0; x < compileUnit.Namespaces[i].Types[t].Members.Count; x++)
                        {
                            Console.WriteLine("      {0} {1}(-{2}-)", compileUnit.Namespaces[i].Types[t].Members[x].Attributes.ToString(), compileUnit.Namespaces[i].Types[t].Members[x].Name, compileUnit.Namespaces[i].Types[t].Members[x].LinePragma);
                            Console.WriteLine(compileUnit.Namespaces[i].Types[t].Members[x].ToString());
                            for (int j = 0; j < compileUnit.Namespaces[i].Types[t].Members[x].Comments.Count; j++)
                                Console.WriteLine(compileUnit.Namespaces[i].Types[t].Members[x].Comments[j].Comment.Text);
                        }
                    }
                }
#endif
                #endregion
                provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions());
            }
            catch
            { throw; }
            finally
            {
                // Can't forget to flush and close the output file.  Otherwise, any other functions that
                //   attempt to access it will cause an IO exception.
                if (tw != null)
                {
                    tw.Flush();
                    tw.Close();
                }
            }

            // Return the FileInfo object configured for the output file.
            return fiSrc;
        }
Beispiel #17
0
		public string PrintString(Object o) {
			var newTime = TimeSpan.FromTicks(Environment.TickCount).TotalMilliseconds;
			if (_timestamps.ContainsKey(o)) {
				var lastTime = _timestamps[o];
				if (newTime - lastTime < MillisecondInterval) {
					return "";
				}
			}
			_timestamps[o] = newTime;
			var strWriter = new StringWriter();
			var indentedWriter = new IndentedTextWriter(strWriter);
			var printer = new RecursiveObjectPrinter(indentedWriter, this);
			printer.PrintObject(o);
			indentedWriter.Flush();
			strWriter.Flush();
			_timestamps[o] = TimeSpan.FromTicks(Environment.TickCount).TotalMilliseconds;
			return strWriter.ToString();
		}
Beispiel #18
0
        string UniversalStreamRecordCollectionToString(Collection<UniversalStreamRecord> collection, string objectsFoundMessage, string noObjectsFoundMessage)
        {
            /* MTH: The old code was:
             * using (StringWriter baseBuffer = new System.IO.StringWriter()) {
             *    using (IndentedTextWriter indentWriter = new IndentedTextWriter(baseBuffer, "    "))
             * but this resulted in Code Review message
             *    CA2202: Do not dispose objects multiple time.
             * Therefore I changed it.
             */
            using (IndentedTextWriter indentWriter = new IndentedTextWriter(new System.IO.StringWriter(), "    ")) //Use four whitespaces as indent, this is the same amount the PowerShell help uses
            {
                indentWriter.Indent = 0;

                if (collection != null && collection.Count > 0)
                {
                    indentWriter.WriteLine(objectsFoundMessage);
                    indentWriter.Indent++;

                    foreach (UniversalStreamRecord unirecord in collection)
                    {
                        indentWriter.WriteLine(unirecord.Message);
                        indentWriter.Indent++;

                        InvocationInfo invocation = unirecord.InvocationInfo;
                        if (invocation == null)
                        {
                            //Do not display anything as InvocationInfo is NULL so we do not have any information to display
                        }
                        else
                        {
                            indentWriter.Write("from: ");

                            //It seems that InvocationInfo.Line normally contains better informationthan than InvocationInfo.MyCommand.Definition
                            if (string.IsNullOrWhiteSpace(invocation.Line))
                            {
                                if (invocation.MyCommand != null)
                                {
                                    indentWriter.WriteLine(ReturnLiteralNoneInAngleBracketsIfEmpty(invocation.MyCommand.Definition));
                                }
                                else
                                {
                                    indentWriter.WriteLine(LiteralNoneInAngleBrackets);
                                }

                            }
                            else
                            {
                                indentWriter.WriteLine(invocation.Line);
                            }

                            //If we have a PositionMessage, we will display it. Else we do not display it at all
                            if (string.IsNullOrWhiteSpace(invocation.PositionMessage) == false)
                            {
                                indentWriter.WriteLine(invocation.PositionMessage);
                            }

                            if (invocation.MyCommand != null)
                            {
                                indentWriter.Write("Source: ");
                                indentWriter.Write(ReturnLiteralNoneInAngleBracketsIfEmpty(invocation.MyCommand.Name));
                                indentWriter.Write("; ");

                                //Check if the we have a module name. If not, ignore it
                                if (string.IsNullOrWhiteSpace(invocation.MyCommand.ModuleName) == false)
                                {
                                    indentWriter.Write("Module: ");
                                    indentWriter.Write(invocation.MyCommand.ModuleName);
                                    indentWriter.Write("; ");
                                }

                                //For Power Shell each script starts at line 1, so this is ignored if the value is 0
                                if (invocation.ScriptLineNumber > 0)
                                {
                                    indentWriter.Write("Line: ");
                                    indentWriter.Write(invocation.ScriptLineNumber);
                                    indentWriter.Write("; ");
                                }
                            }

                            //If PowerShell has a script name, we will display it
                            if (string.IsNullOrWhiteSpace(invocation.ScriptName) == false)
                            {
                                indentWriter.Write("Script: ");
                                indentWriter.Write(ReturnLiteralNoneInAngleBracketsIfEmpty(invocation.ScriptName));
                                indentWriter.WriteLine("; ");
                            }
                        }

                        indentWriter.Indent--;
                    }

                }
                else
                {
                    indentWriter.Write(noObjectsFoundMessage);

                }

                indentWriter.Flush();
                return indentWriter.InnerWriter.ToString();
            }
        }
Beispiel #19
0
		/// <summary>
		/// Retorna a representação string da consulta SQL.
		/// </summary>
		/// <returns>A representação string da consulta SQL.</returns>
		public override string ToString()
		{
			var sb = new StringBuilder();

			using (var sw = new StringWriter(sb))
			using (var tw = new IndentedTextWriter(sw))
			{
				Render(tw);
				tw.Flush();
			}

			return sb.ToString();
		}
Beispiel #20
0
        public void GenerateComponent(IProject project, IComponentDescriptor cd)
        {
            string name = GetComponentName(cd);
            string fname = MakeVHDSourceFileName(name);
            string path = project.AddFile(fname);
            project.AddFileAttribute(fname, cd);
            if (cd.Library != null)
                project.SetFileLibrary(fname, cd.Library);
            _sim.PushScope();
            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            IndentedTextWriter tw = new IndentedTextWriter(sw, "  ");
            _curComponent = cd;
            ClearDependencies();
            DeclareEntity(cd, tw);
            tw.WriteLine();
            GenerateArchitecture(cd, tw);
            tw.Flush();
            sw = new StreamWriter(path);
            tw = new IndentedTextWriter(sw, "  ");

            CreateFileHeader(new GeneratorInfo(name), tw);
            GenerateDependencies((IPackageOrComponentDescriptor)cd, tw);
            tw.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            ms.CopyTo(sw.BaseStream);
            ms.Close();
            tw.Close();
            sw.Close();
            _curComponent = null;
            _sim.PopScope();

            InstanceDescriptor icd = cd as InstanceDescriptor;
            if (icd != null)
            {
                object[] attrs = icd.Instance.GetType().GetCustomAttributes(typeof(ComponentPurpose), true);
                if (attrs.Length > 0)
                {
                    ComponentPurpose purpose = (ComponentPurpose)attrs.First();
                    project.AddFileAttribute(fname, purpose.Purpose);
                }
            }

            var gi = new VHDLGenInfo(name, "inst_" + name, "behavioral", fname);
            var d = (DescriptorBase)cd;
            d.AddAttribute(gi);
        }
Beispiel #21
0
		public static string PrintException(Exception ex) {
			var strWriter = new StringWriter();
			var indentedWriter = new IndentedTextWriter(strWriter);
			PrintExceptionWithoutTrace(indentedWriter, ex);
			indentedWriter.WriteLine("Unity Stack Trace:");
			indentedWriter.Indent++;
			var traceLines = StackTraceUtility.ExtractStringFromException(ex).Split(new[] {
				"\r",
				"\n"
			}, StringSplitOptions.RemoveEmptyEntries);
			traceLines.ToList().ForEach(indentedWriter.WriteLine);
			indentedWriter.Flush();
			strWriter.Flush();
			return strWriter.ToString();
		}
Beispiel #22
0
        public void GeneratePackage(IProject project, PackageDescriptor pd)
        {
            string name = MakeIDName(pd.PackageName, pd);
            string fname = MakeVHDSourceFileName(name);
            string path = project.AddFile(fname);
            project.AddFileAttribute(fname, pd);
            if (pd.Library != null)
                project.SetFileLibrary(fname, pd.Library);
            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            IndentedTextWriter tw = new IndentedTextWriter(sw, "  ");
            ClearDependencies();
            tw.WriteLine("package " + name + " is");
            tw.Indent++;
            GenerateTypeDecls(pd, tw);
            foreach (MethodDescriptor md in pd.GetActiveMethods())
            {
                GenerateMethodDecl(md, tw);
            }
            foreach (FieldDescriptor fd in pd.GetConstants())
            {
                DeclareField(fd, tw);
            }
            tw.Indent--;
            tw.WriteLine("end;");
            tw.WriteLine();
            tw.WriteLine("package body " + name + " is");
            tw.Indent++;
            foreach (MethodDescriptor md in pd.GetActiveMethods())
            {
                GenerateMethodImpl(md, tw);
                tw.WriteLine();
            }
            tw.Indent--;
            tw.WriteLine("end package body;");
            tw.Flush();

            sw = new StreamWriter(path);
            tw = new IndentedTextWriter(sw, "  ");
            CreateFileHeader(new GeneratorInfo(name), tw);
            GenerateDependencies(pd, tw);
            tw.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            ms.CopyTo(sw.BaseStream);
            ms.Close();
            tw.Close();
            sw.Close();
        }
    public static void GenerateOutput(string outputFile,
                                      System.Xml.XmlDocument xmlMetaData,
                                      string tableName)
    {
        System.CodeDom.Compiler.IndentedTextWriter writer = null;
        //System.Xml.XmlNode node;
        System.Xml.XmlNodeList nodeList;
        try
        {
            writer   = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile));
            nodeList = xmlMetaData.SelectNodes("/DataSet/Table[@Name='" + tableName + "']/Column");

            writer.WriteLine("using System;");
            writer.WriteLine("");
            writer.WriteLine("/// <summary>");
            writer.WriteLine("/// ");
            writer.WriteLine("/// </summar>");
            writer.WriteLine("public class TargetOutput");
            writer.WriteLine("{");
            writer.Indent++;
            writer.WriteLine("#region Class level declarations");
            foreach (System.Xml.XmlNode node in nodeList)
            {
                writer.WriteLine("private " + node.Attributes["Type"].Value + " m_" + node.Attributes["Name"].Value + ";");
            }
            writer.WriteLine("#endregion");
            writer.WriteLine("");
            writer.WriteLine("#region Public Methods and Properties");
            foreach (System.Xml.XmlNode node in nodeList)
            {
                writer.WriteLine("public " + node.Attributes["Type"].Value + " " + node.Attributes["Name"].Value);
                writer.WriteLine("{");
                writer.Indent++;
                writer.WriteLine("get");
                writer.WriteLine("{");
                writer.Indent++;
                writer.WriteLine("return m_" + node.Attributes["Name"].Value + ";");
                writer.Indent--;
                writer.WriteLine("}");
                writer.WriteLine("set");
                writer.WriteLine("{");
                writer.Indent++;
                writer.WriteLine("m_" + node.Attributes["Name"].Value + " = value;");
                writer.Indent--;
                writer.WriteLine("}");
                writer.Indent--;
                writer.WriteLine("}");
                writer.WriteLine("");
            }
            writer.WriteLine("#endregion");
            writer.WriteLine("");
            writer.Indent--;
            writer.WriteLine("}");
        }
        finally
        {
            if (writer != null)
            {
                writer.Flush();
                writer.Close();
            }
        }
    }
Beispiel #24
0
        private static void OnMcpeCraftingData(Package message)
        {
            string fileName = Path.GetTempPath() + "Recipes_" + Guid.NewGuid() + ".txt";
            Log.Info("Writing recipes to filename: " + fileName);
            FileStream file = File.OpenWrite(fileName);

            McpeCraftingData msg = (McpeCraftingData)message;
            IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(file));

            writer.WriteLine("static RecipeManager()");
            writer.WriteLine("{");
            writer.Indent++;
            writer.WriteLine("Recipes = new Recipes");
            writer.WriteLine("{");
            writer.Indent++;

            foreach (Recipe recipe in msg.recipes)
            {
                ShapelessRecipe shapelessRecipe = recipe as ShapelessRecipe;
                if (shapelessRecipe != null)
                {
                    writer.WriteLine(string.Format("new ShapelessRecipe(new ItemStack(ItemFactory.GetItem({0}, {1}), {2}),", shapelessRecipe.Result.Id, shapelessRecipe.Result.Metadata, shapelessRecipe.Result.Count));
                    writer.Indent++;
                    writer.WriteLine("new List<ItemStack>");
                    writer.WriteLine("{");
                    writer.Indent++;
                    foreach (var itemStack in shapelessRecipe.Input)
                    {
                        writer.WriteLine(string.Format("new ItemStack(ItemFactory.GetItem({0}, {1}), {2}),", itemStack.Id, itemStack.Metadata, itemStack.Count));
                    }
                    writer.Indent--;
                    writer.WriteLine("}),");
                    writer.Indent--;

                    continue;
                }

                ShapedRecipe shapedRecipe = recipe as ShapedRecipe;
                if (shapedRecipe != null)
                {
                    writer.WriteLine(string.Format("new ShapedRecipe({0}, {1}, new ItemStack(ItemFactory.GetItem({2}, {3}), {4}),", shapedRecipe.Width, shapedRecipe.Height, shapedRecipe.Result.Id, shapedRecipe.Result.Metadata, shapedRecipe.Result.Count));
                    writer.Indent++;
                    writer.WriteLine("new Item[]");
                    writer.WriteLine("{");
                    writer.Indent++;
                    foreach (Item item in shapedRecipe.Input)
                    {
                        writer.WriteLine(string.Format("ItemFactory.GetItem({0}, {1}),", item.Id, item.Metadata));
                    }
                    writer.Indent--;
                    writer.WriteLine("}),");
                    writer.Indent--;

                    continue;
                }
            }

            writer.WriteLine("};");
            writer.Indent--;
            writer.WriteLine("}");
            writer.Indent--;

            writer.Flush();

            file.Close();
            //Environment.Exit(0);
        }
Beispiel #25
0
        private void OnMcpeCraftingData(Package message)
        {
            string fileName = Path.GetTempPath() + "Recipes_" + Guid.NewGuid() + ".txt";
            Log.Info("Writing recipes to filename: " + fileName);
            FileStream file = File.OpenWrite(fileName);

            McpeCraftingData msg = (McpeCraftingData) message;
            IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(file));

            writer.WriteLine("static RecipeManager()");
            writer.WriteLine("{");
            writer.Indent++;
            writer.WriteLine("Recipes = new Recipes");
            writer.WriteLine("{");
            writer.Indent++;

            foreach (Recipe recipe in msg.recipes)
            {
                ShapelessRecipe shapelessRecipe = recipe as ShapelessRecipe;
                if (shapelessRecipe != null)
                {
                    writer.WriteLine($"new ShapelessRecipe(new Item({shapelessRecipe.Result.Id}, {shapelessRecipe.Result.Metadata}, {shapelessRecipe.Result.Count}),");
                    writer.Indent++;
                    writer.WriteLine("new List<Item>");
                    writer.WriteLine("{");
                    writer.Indent++;
                    foreach (var itemStack in shapelessRecipe.Input)
                    {
                        writer.WriteLine($"new Item({itemStack.Id}, {itemStack.Metadata}, {itemStack.Count}),");
                    }
                    writer.Indent--;
                    writer.WriteLine("}),");
                    writer.Indent--;

                    continue;
                }

                ShapedRecipe shapedRecipe = recipe as ShapedRecipe;

                if (shapedRecipe != null && _recipeToSend == null)
                {
                    if (shapedRecipe.Result.Id == 5 && shapedRecipe.Result.Count == 4 && shapedRecipe.Result.Metadata == 0)
                    {
                        Log.Error("Setting recipe! " + shapedRecipe.Id);
                        _recipeToSend = shapedRecipe;
                    }
                }

                if (shapedRecipe != null)
                {
                    writer.WriteLine($"new ShapedRecipe({shapedRecipe.Width}, {shapedRecipe.Height}, new Item({shapedRecipe.Result.Id}, {shapedRecipe.Result.Metadata}, {shapedRecipe.Result.Count}),");
                    writer.Indent++;
                    writer.WriteLine("new Item[]");
                    writer.WriteLine("{");
                    writer.Indent++;
                    foreach (Item item in shapedRecipe.Input)
                    {
                        writer.WriteLine($"new Item({item.Id}, {item.Metadata}),");
                    }
                    writer.Indent--;
                    writer.WriteLine("}),");
                    writer.Indent--;

                    continue;
                }
            }

            writer.WriteLine("};");
            writer.Indent--;
            writer.WriteLine("}");
            writer.Indent--;

            writer.Flush();
            file.Close();
            //Environment.Exit(0);
        }
Beispiel #26
0
        /// <summary>
        ///     Handles the specified package.
        /// </summary>
        /// <param name="message">The package.</param>
        /// <param name="senderEndpoint">The sender's endpoint.</param>
        private void HandlePackage(Package message, IPEndPoint senderEndpoint)
        {
            if (typeof (McpeBatch) == message.GetType())
            {
                Log.Debug("Processing Batch package");
                McpeBatch batch = (McpeBatch) message;

                var messages = new List<Package>();

                // Get bytes
                byte[] payload = batch.payload;
                // Decompress bytes

                MemoryStream stream = new MemoryStream(payload);
                if (stream.ReadByte() != 0x78)
                {
                    throw new InvalidDataException("Incorrect ZLib header. Expected 0x78");
                }
                stream.ReadByte();
                using (var defStream2 = new DeflateStream(stream, CompressionMode.Decompress, false))
                {
                    // Get actual package out of bytes
                    MemoryStream destination = new MemoryStream();
                    defStream2.CopyTo(destination);
                    destination.Position = 0;
                    NbtBinaryReader reader = new NbtBinaryReader(destination, true);
                    do
                    {
                        int len = reader.ReadInt32();
                        byte[] internalBuffer = reader.ReadBytes(len);
                        messages.Add(PackageFactory.CreatePackage(internalBuffer[0], internalBuffer) ?? new UnknownPackage(internalBuffer[0], internalBuffer));
                    } while (destination.Position < destination.Length); // throw new Exception("Have more data");
                }
                foreach (var msg in messages)
                {
                    HandlePackage(msg, senderEndpoint);
                    msg.PutPool();
                }
                return;
            }

            TraceReceive(message);

            if (typeof (UnknownPackage) == message.GetType())
            {
                return;
            }

            if (typeof (McpeDisconnect) == message.GetType())
            {
                McpeDisconnect msg = (McpeDisconnect) message;
                Log.InfoFormat("Disconnect {1}: {0}", msg.message, Username);
                SendDisconnectionNotification();
                StopClient();
                return;
            }

            if (typeof (ConnectedPing) == message.GetType())
            {
                ConnectedPing msg = (ConnectedPing) message;
                SendConnectedPong(msg.sendpingtime);
                return;
            }

            if (typeof (McpeFullChunkData) == message.GetType())
            {
                //McpeFullChunkData msg = (McpeFullChunkData) message;
                //ChunkColumn chunk = ClientUtils.DecocedChunkColumn(msg.chunkData);
                //if (chunk != null)
                //{
                //	Log.DebugFormat("Chunk X={0}", chunk.x);
                //	Log.DebugFormat("Chunk Z={0}", chunk.z);

                //	//ClientUtils.SaveChunkToAnvil(chunk);
                //}
                return;
            }

            if (typeof (ConnectionRequestAccepted) == message.GetType())
            {
                Thread.Sleep(50);
                SendNewIncomingConnection();
                //_connectedPingTimer = new Timer(state => SendConnectedPing(), null, 1000, 1000);
                Thread.Sleep(50);
                SendLogin(Username);
                return;
            }

            if (typeof (McpeSetSpawnPosition) == message.GetType())
            {
                McpeSetSpawnPosition msg = (McpeSetSpawnPosition) message;
                _spawn = new Vector3(msg.x, msg.y, msg.z);
                _level.SpawnX = (int) _spawn.X;
                _level.SpawnY = (int) _spawn.Y;
                _level.SpawnZ = (int) _spawn.Z;

                return;
            }

            if (typeof (McpeStartGame) == message.GetType())
            {
                McpeStartGame msg = (McpeStartGame) message;
                _entityId = msg.entityId;
                _spawn = new Vector3(msg.x, msg.y, msg.z);
                _level.LevelName = "Default";
                _level.Version = 19133;
                _level.GameType = msg.gamemode;

                //ClientUtils.SaveLevel(_level);

                return;
            }

            if (typeof (McpeTileEvent) == message.GetType())
            {
                McpeTileEvent msg = (McpeTileEvent) message;
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Case 1: {0}", msg.case1);
                Log.DebugFormat("Case 2: {0}", msg.case2);
                return;
            }
            if (typeof (McpeAddEntity) == message.GetType())
            {
                McpeAddEntity msg = (McpeAddEntity) message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);
                Log.DebugFormat("Entity Type: {0}", msg.entityType);
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Yaw: {0}", msg.yaw);
                Log.DebugFormat("Pitch: {0}", msg.pitch);
                Log.DebugFormat("Velocity X: {0}", msg.speedX);
                Log.DebugFormat("Velocity Y: {0}", msg.speedY);
                Log.DebugFormat("Velocity Z: {0}", msg.speedZ);
                //Log.DebugFormat("Metadata: {0}", msg.metadata.ToString());
                //Log.DebugFormat("Links count: {0}", msg.links);

                return;
            }
            if (typeof (McpeSetEntityData) == message.GetType())
            {
                McpeSetEntityData msg = (McpeSetEntityData) message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);
                MetadataDictionary metadata = msg.metadata;
                Log.DebugFormat("Metadata: {0}", metadata.ToString());
                return;
            }

            if (typeof (McpeMovePlayer) == message.GetType())
            {
                //McpeMovePlayer msg = (McpeMovePlayer) message;
                //Log.DebugFormat("Entity ID: {0}", msg.entityId);

                //CurrentLocation = new PlayerLocation(msg.x, msg.y + 10, msg.z);
                //SendMcpeMovePlayer();
                return;
            }

            if (typeof (McpeUpdateBlock) == message.GetType())
            {
                McpeUpdateBlock msg = (McpeUpdateBlock) message;
                Log.DebugFormat("No of Blocks: {0}", msg.blocks.Count);
                return;
            }

            if (typeof (McpeLevelEvent) == message.GetType())
            {
                McpeLevelEvent msg = (McpeLevelEvent) message;
                Log.DebugFormat("Event ID: {0}", msg.eventId);
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Data: {0}", msg.data);
                return;
            }

            if (typeof (McpeContainerSetContent) == message.GetType())
            {
                McpeContainerSetContent msg = (McpeContainerSetContent) message;
                Log.DebugFormat("Window ID: 0x{0:x2}, Count: {1}", msg.windowId, msg.slotData.Count);
                var slots = msg.slotData.GetValues();

                foreach (var entry in slots)
                {
                    MetadataSlot slot = (MetadataSlot) entry;
                    //Log.DebugFormat(" - Id: {0}, Metadata: {1}, Count: {2}", slot.Value.Item.Id, slot.Value.Item.Metadata, slot.Value.Count);
                }
                return;
            }

            if (typeof (McpeCraftingData) == message.GetType())
            {
                string fileName = Path.GetTempPath() + "Recipes_" + Guid.NewGuid() + ".txt";
                Log.Info("Writing recipes to filename: " + fileName);
                FileStream file = File.OpenWrite(fileName);

                McpeCraftingData msg = (McpeCraftingData) message;
                IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(file));

                writer.WriteLine("static RecipeManager()");
                writer.WriteLine("{");
                writer.Indent++;
                writer.WriteLine("Recipes = new Recipes");
                writer.WriteLine("{");
                writer.Indent++;

                foreach (Recipe recipe in msg.recipes)
                {
                    ShapelessRecipe shapelessRecipe = recipe as ShapelessRecipe;
                    if (shapelessRecipe != null)
                    {
                        writer.WriteLine(string.Format("new ShapelessRecipe(new ItemStack(ItemFactory.GetItem({0}, {1}), {2}),", shapelessRecipe.Result.Id, shapelessRecipe.Result.Metadata, shapelessRecipe.Result.Count));
                        writer.Indent++;
                        writer.WriteLine("new List<ItemStack>");
                        writer.WriteLine("{");
                        writer.Indent++;
                        foreach (var itemStack in shapelessRecipe.Input)
                        {
                            writer.WriteLine(string.Format("new ItemStack(ItemFactory.GetItem({0}, {1}), {2}),", itemStack.Id, itemStack.Metadata, itemStack.Count));
                        }
                        writer.Indent--;
                        writer.WriteLine("}),");
                        writer.Indent--;

                        continue;
                    }

                    ShapedRecipe shapedRecipe = recipe as ShapedRecipe;
                    if (shapedRecipe != null)
                    {
                        writer.WriteLine(string.Format("new ShapedRecipe({0}, {1}, new ItemStack(ItemFactory.GetItem({2}, {3}), {4}),", shapedRecipe.Width, shapedRecipe.Height, shapedRecipe.Result.Id, shapedRecipe.Result.Metadata, shapedRecipe.Result.Count));
                        writer.Indent++;
                        writer.WriteLine("new Item[]");
                        writer.WriteLine("{");
                        writer.Indent++;
                        foreach (Item item in shapedRecipe.Input)
                        {
                            writer.WriteLine(string.Format("ItemFactory.GetItem({0}, {1}),", item.Id, item.Metadata));
                        }
                        writer.Indent--;
                        writer.WriteLine("}),");
                        writer.Indent--;

                        continue;
                    }
                }

                writer.WriteLine("};");
                writer.Indent--;
                writer.WriteLine("}");
                writer.Indent--;

                writer.Flush();

                file.Close();
                Environment.Exit(0);
                return;
            }
        }
        protected override void GenerateTable(System.Data.DataTable table)
        {
            StringWriter sw = new StringWriter();
            IndentedTextWriter tw = new IndentedTextWriter(sw);
            tw.WriteLine("CREATE TABLE {0} (",
                formatTableName(table)
                );

            tw.Indent++;
            bool comma = false;
            foreach (DataColumn column in table.Columns)
            {
                if (comma)
                    tw.WriteLine(",");
                else
                    comma = true;
                GenerateColumn(column, tw);
            }
            tw.WriteLine(")");
            tw.Indent--;
            tw.Flush();

            this.Admin.ExecuteNonQuery(ConnectionString,sw.ToString());
        }
Beispiel #28
0
        //      ALTERADA
        public void GenerateComponent(IProject project, IComponentDescriptor cd)
        {
            string name = GetComponentName(cd);
            string fname = MakeSysCHeaderFileName(name);
            string path = project.AddFile(fname);
            bool IsTopComponent = (name == "top0") ? true : false;
            project.AddFileAttribute(fname, cd);
            if (cd.Library != null)
                project.SetFileLibrary(fname, cd.Library);
            _sim.PushScope();
            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            IndentedTextWriter tw = new IndentedTextWriter(sw, "  ");
            _curComponent = cd;
            ClearDependencies();
            DeclareAndGenerateModule(cd, tw);

            tw.Flush();
            sw = new StreamWriter(path);
            tw = new IndentedTextWriter(sw, "  ");

            CreateFileHeader(new GeneratorInfo(fname), tw);
            GeneratePreProcDir(cd, tw);
            GenerateDependencies(cd, tw, null);
            tw.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            ms.CopyTo(sw.BaseStream);
            ms.Close();
            tw.Close();
            sw.Close();
            _curComponent = null;
            _sim.PopScope();

            InstanceDescriptor icd = cd as InstanceDescriptor;
            if (icd != null)
            {
                object[] attrs = icd.Instance.GetType().GetCustomAttributes(typeof(ComponentPurpose), true);
                if (attrs.Length > 0)
                {
                    ComponentPurpose purpose = (ComponentPurpose)attrs.First();
                    project.AddFileAttribute(fname, purpose.Purpose);
                }
            }

            if (IsTopComponent)
            {
                GenerateMainFile(project, cd);
            }

        }