Example #1
0
        /// <summary>
        /// This method writes the generated code into a single file.
        /// </summary>
        private void WriteSingleCodeFile()
        {
            // Some assertions to make debugging easier.
            Debug.Assert(!string.IsNullOrEmpty(options.OutputLocation), "This action cannot be performed when output location is null or an empty string.");
            Debug.Assert(!string.IsNullOrEmpty(options.OutputFileName), "This action cannot be performed when output file name is null or an empty string");

            CodeExtension.RefineCodeWithShortName(codeCompileUnit);
            CodeNamespace codeNamespace = CodeExtension.GenerateCode(codeCompileUnit);

            codeNamespace.Name = options.TargetNamespace;
            CodeCompileUnit tempUnit = new CodeCompileUnit();

            tempUnit.Namespaces.Add(codeNamespace);

            // Get the destination file name.
            string fileName = CodeWriter.GetUniqueFileName(options.OutputLocation, options.OutputFileName, options.Language, options.OverwriteExistingFiles);
            // Create a StreamWriter for writing to the destination file.
            StreamWriter writer = new StreamWriter(fileName, false, Encoding.UTF8);

            try
            {
                // Write out the code to the destination file.
                provider.GenerateCodeFromCompileUnit(tempUnit, writer, codeGenerationOptions);
                // Flush all buffers in the writer.
                writer.Flush();
                // Initialize generatedFileNames array to hold the one and only one
                // file we just generated.
                generatedCodeFileNames = new string[1];
                // Finally add the file name to the generatedFileNames array.
                generatedCodeFileNames[0] = fileName;
            }
            catch (IOException e)
            {
                // Wrap the IOException in a CodeWriterException with little bit
                // more information.
                throw new CodeWriterException(
                          string.Format("An error occurred while trying write to file {0}: {1}", fileName, e.Message), e);
            }
            finally
            {
                // No matter what happens, dispose the stream writer and release the unmanaged
                // resources.
                writer.Dispose();
            }
        }