Пример #1
0
 /// <summary>
 /// Generated a code file from a RESX file.
 /// </summary>
 /// <param name="resxContent">The content of the RESX file to generate from.</param>
 /// <param name="reporter">An object used to communicate diagnostics back to the caller.</param>
 /// <returns>The content of the generated code file.</returns>
 public string RunOnContent(string resxContent, IDiagnosticReporter reporter)
 {
     using (var reader = ResXResourceReader.FromFileContents(resxContent))
     {
         return(GenerateCodeForResx(reader, reporter));
     }
 }
        private void KGySerializeObjects(object[] referenceObjects, bool compatibilityMode = true, bool checkCompatibleEquality = true, Func <Type, string> typeNameConverter = null, ITypeResolutionService typeResolver = null)
        {
            Console.WriteLine($"------------------KGySoft ResXResourceWriter (Items Count: {referenceObjects.Length}; Compatibility mode: {compatibilityMode})--------------------");
            StringBuilder sb = new StringBuilder();

            using (ResXResourceWriter writer = new ResXResourceWriter(new StringWriter(sb), typeNameConverter)
            {
                CompatibleFormat = compatibilityMode
            })
            {
                int i = 0;
                foreach (object item in referenceObjects)
                {
                    writer.AddResource(i++ + "_" + (item == null ? "null" : item.GetType().Name), item);
                }
            }

            Console.WriteLine(sb.ToString());
            List <object> deserializedObjects = new List <object>();

            using (ResXResourceReader reader = ResXResourceReader.FromFileContents(sb.ToString(), typeResolver))
            {
                foreach (DictionaryEntry item in reader)
                {
                    deserializedObjects.Add(item.Value);
                }
            }

            AssertItemsEqual(referenceObjects, deserializedObjects.ToArray());

#if NETFRAMEWORK
            if (compatibilityMode)
            {
                deserializedObjects.Clear();
                using (SystemResXResourceReader reader = SystemResXResourceReader.FromFileContents(sb.ToString(), typeResolver))
                {
                    try
                    {
                        foreach (DictionaryEntry item in reader)
                        {
                            deserializedObjects.Add(item.Value);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"System serialization failed: {e}");
                        Console.WriteLine("Skipping equality check");
                        return;
                    }
                }

                if (checkCompatibleEquality)
                {
                    AssertItemsEqual(referenceObjects, deserializedObjects.ToArray());
                }
            }
#endif
        }
        /// <summary>
        /// Returns content of opened ResX file's buffer
        /// </summary>
        /// <param name="data">Content of the buffer</param>
        /// <param name="file">File path</param>
        public static void LoadDataFromBuffer(ref Dictionary <string, ResXDataNode> data, string file)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            object docData = GetDocData(file); // get document's buffer

            if (docData is ResXEditor)
            {
                ResXEditor editor = docData as ResXEditor;
                data = editor.UIControl.GetData(false);
            }
            else
            {
                IVsTextLines textLines  = GetTextLinesFrom(docData); // get text buffer
                string       textBuffer = GetTextFrom(textLines);    // get plain text

                ResXResourceReader reader = null;
                try {
                    data = new Dictionary <string, ResXDataNode>();

                    // use reader to parse given ResX text
                    reader                  = ResXResourceReader.FromFileContents(textBuffer);
                    reader.BasePath         = Path.GetDirectoryName(file);
                    reader.UseResXDataNodes = true;
                    foreach (DictionaryEntry entry in reader)
                    {
                        data.Add(entry.Key.ToString().ToLower(), entry.Value as ResXDataNode);
                    }
                } finally {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }
        private void ReadWriteReadResX(string path, bool generateAliases, bool compatibilityMode)
        {
            // read from file
            List <DictionaryEntry> reference, check;
            string basePath = Path.GetDirectoryName(path);

            using (ResXResourceReader reader = new ResXResourceReader(path)
            {
                BasePath = basePath, SafeMode = true
            })
            {
                // reference contains now string-ResXDataNode elements
                reference = reader.Cast <DictionaryEntry>().ToList();
            }

            // write to string: from ResXDataNodes without generated values
            StringBuilder sb = new StringBuilder();

            using (ResXResourceWriter writer = new ResXResourceWriter(new StringWriter(sb))
            {
                AutoGenerateAlias = generateAliases, CompatibleFormat = compatibilityMode
            })
            {
                reference.ForEach(e => writer.AddResource(e.Key.ToString(), e.Value));
            }

            // re-read from string
            using (ResXResourceReader reader = ResXResourceReader.FromFileContents(sb.ToString()))
            {
                reader.BasePath = basePath;
                // check contains now string-object elements
                check = reader.Cast <DictionaryEntry>().ToList();
            }

            // compare 1: check is from ResXDataNodes objects with original DataNodeInfos and without generated values
            AssertItemsEqual(reference.Select(de => new DictionaryEntry(de.Key, ((ResXDataNode)de.Value).GetValue())), check);

            // -----------------

            // write to string: from objects (fileref resources will be embedded now)
            sb = new StringBuilder();
            using (ResXResourceWriter writer = new ResXResourceWriter(new StringWriter(sb))
            {
                AutoGenerateAlias = generateAliases, CompatibleFormat = compatibilityMode
            })
            {
                // cleaning up nodes during the compare so DataNodeInfos will be nullified in reference
                reference.ForEach(de => writer.AddResource(de.Key.ToString(), ((ResXDataNode)de.Value).GetValue(cleanupRawData: true)));
            }

            // re-read from string
            using (ResXResourceReader reader = ResXResourceReader.FromFileContents(sb.ToString()))
            {
                // no base path is needed because there are no filerefs
                // check contains now string-object elements
                check = reader.Cast <DictionaryEntry>().ToList();
            }

            // compare 2: check is from objects so DataNodeInfos are generated, every object is embedded
            AssertItemsEqual(reference.Select(de => new DictionaryEntry(de.Key, ((ResXDataNode)de.Value).GetValue())), check);

            // -----------------

            // write to string: from ResXDataNodes with nullified DataNodeInfos
            sb = new StringBuilder();
            using (ResXResourceWriter writer = new ResXResourceWriter(new StringWriter(sb))
            {
                AutoGenerateAlias = generateAliases, CompatibleFormat = compatibilityMode
            })
            {
                // DataNodeInfos will be now re-generated in ResXDataNodes
                reference.ForEach(de => writer.AddResource(de.Key.ToString(), de.Value));
            }

            // re-read from string
            using (ResXResourceReader reader = ResXResourceReader.FromFileContents(sb.ToString()))
            {
                reader.BasePath = basePath;
                // check contains now string-object elements
                check = reader.Cast <DictionaryEntry>().ToList();
            }

            // compare 3: check is from ResXDataNodes objects with re-generated DataNodeInfos from values
            AssertItemsEqual(reference.Select(de => new DictionaryEntry(de.Key, ((ResXDataNode)de.Value).GetValue())), check);
        }
        void IVsSingleFileGenerator.Generate(string wszInputFilePath,
                                             string bstrInputFileContents,
                                             string wszDefaultNamespace,
                                             out IntPtr outputFileContents,
                                             out int outputFileContentSize,
                                             IVsGeneratorProgress generationProgress)
        {
            if (bstrInputFileContents == null || bstrInputFileContents.Length <= 0)
            {
                outputFileContents    = IntPtr.Zero;
                outputFileContentSize = 0;

                if (generationProgress != null)
                {
                    generationProgress.Progress(100, 100);
                }

                return;
            }

            try {
                MemoryStream          outputStream = new MemoryStream();
                IResourceReader       reader       = ResXResourceReader.FromFileContents(bstrInputFileContents, this.typeResolver);
                IResourceWriter       writer       = new ResourceWriter(outputStream);
                IDictionaryEnumerator resEnum      = reader.GetEnumerator();

                // main conversion loop
                while (resEnum.MoveNext())
                {
                    string name  = (string)resEnum.Key;
                    object value = resEnum.Value;
                    writer.AddResource(name, value);
                }

                // cleanup
                reader.Close();
                writer.Generate();
                // don't close writer just yet -- that closes the stream, which we still need

                // Marshal into a bstr
                byte[] buffer        = outputStream.ToArray();
                int    bufferLength  = buffer.Length;
                IntPtr bufferPointer = Marshal.AllocCoTaskMem(bufferLength);
                Marshal.Copy(buffer, 0, bufferPointer, bufferLength);

                outputFileContents    = bufferPointer;
                outputFileContentSize = bufferLength;

                if (generationProgress != null)
                {
                    generationProgress.Progress(100, 100);
                }

                // Now close the stream
                writer.Close();
                outputStream.Close();

                writer       = null;
                outputStream = null;
                reader       = null;
            }
            catch (Exception e) {
                if (e.InnerException != null)
                {
                    throw e.InnerException;
                }
                else
                {
                    throw;
                }
            }
        }
        protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
        {
            CodeCompileUnit codeCompileUnit;

            if (string.IsNullOrEmpty(inputFileContent) || IsLocalizedFile(inputFileName))
            {
                if (base.CodeGeneratorProgress != null)
                {
                    NativeMethods.ThrowOnFailure(base.CodeGeneratorProgress.Progress(100, 100));
                }

                return(null);
            }

            using (MemoryStream codeStream = new MemoryStream())
            {
                using (StreamWriter streamWriter = new StreamWriter(codeStream, Encoding.UTF8))
                {
                    IDictionary nodeDictionary         = new Hashtable(StringComparer.OrdinalIgnoreCase);
                    IDictionary nodePositionDictionary = new Hashtable(StringComparer.OrdinalIgnoreCase);
                    using (IResourceReader resourceReader = ResXResourceReader.FromFileContents(inputFileContent))
                    {
                        ResXResourceReader resXResourceReader = resourceReader as ResXResourceReader;
                        if (resXResourceReader != null)
                        {
                            resXResourceReader.UseResXDataNodes = true;
                            string inputDirectoryName = Path.GetDirectoryName(inputFileName);
                            resXResourceReader.BasePath = Path.GetFullPath(inputDirectoryName);
                        }
                        foreach (DictionaryEntry resourceEntry in resourceReader)
                        {
                            ResXDataNode resXNode = (ResXDataNode)resourceEntry.Value;
                            nodeDictionary.Add(resourceEntry.Key, resXNode);
                            nodePositionDictionary.Add(resourceEntry.Key, resXNode.GetNodePosition());
                        }
                    }

                    string resourceNamespace             = this.GetResourcesNamespace();
                    string inputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(inputFileName);

                    List <Tools.ResourceErrorData> unmatchableResources = new List <Tools.ResourceErrorData>();
                    if (resourceNamespace != null)
                    {
                        codeCompileUnit = Tools.StronglyTypedResourceBuilderEx.Create(this.GetType(),
                                                                                      nodeDictionary, inputFileNameWithoutExtension, base.FileNameSpace, resourceNamespace,
                                                                                      this.CodeProvider, GenerateInternalClass, unmatchableResources);
                    }
                    else
                    {
                        codeCompileUnit = Tools.StronglyTypedResourceBuilderEx.Create(this.GetType(),
                                                                                      nodeDictionary, inputFileNameWithoutExtension, base.FileNameSpace, this.CodeProvider,
                                                                                      GenerateInternalClass, unmatchableResources);
                    }

                    if (base.CodeGeneratorProgress != null)
                    {
                        foreach (Tools.ResourceErrorData resourceErrorData in unmatchableResources)
                        {
                            Point nodePosition = (Point)nodePositionDictionary[resourceErrorData.ResourceKey];
                            base.CodeGeneratorProgress.GeneratorError(1, 1, resourceErrorData.ErrorString,
                                                                      (uint)nodePosition.Y, (uint)nodePosition.X);
                        }

                        base.CodeGeneratorProgress.Progress(70, 100);
                    }

                    this.HandleCodeCompileUnit(codeCompileUnit);

                    if (base.CodeGeneratorProgress != null)
                    {
                        base.CodeGeneratorProgress.Progress(0x4b, 100);
                    }

                    ICodeGenerator codeGenerator = this.CodeProvider.CreateGenerator();
                    codeGenerator.GenerateCodeFromCompileUnit(codeCompileUnit, streamWriter, null);
                    if (base.CodeGeneratorProgress != null)
                    {
                        NativeMethods.ThrowOnFailure(base.CodeGeneratorProgress.Progress(100, 100));
                    }

                    streamWriter.Flush();
                    codeStream.Flush();

                    return(EnsureSilverlighCompatibility(codeStream.ToArray(), codeCompileUnit));
                }
            }
        }
Пример #7
0
        /// <summary>Performs code generation</summary>
        /// <param name="inputFileName">Name of file to convert. Note: May be invalid or inactual. <paramref name="inputFileContent"/> is more important.</param>
        /// <param name="inputFileContent">Content of file to convert</param>
        /// <returns>Converted content</returns>
        protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
        {
            CodeCompileUnit codeCompileUnit;

            if (string.IsNullOrEmpty(inputFileContent) || IsLocalizedFile(inputFileName))
            {
                if (CodeGeneratorProgress != null)
                {
                    NativeMethods.ThrowOnFailure(CodeGeneratorProgress.Progress(100, 100));
                }

                return(null);
            }

            StreamWriter streamWriter           = new StreamWriter(new MemoryStream(), Encoding.UTF8);
            IDictionary  nodeDictionary         = new Hashtable(StringComparer.OrdinalIgnoreCase);
            IDictionary  nodePositionDictionary = new Hashtable(StringComparer.OrdinalIgnoreCase);

            using (IResourceReader resourceReader = ResXResourceReader.FromFileContents(inputFileContent)) {
                ResXResourceReader resXResourceReader = resourceReader as ResXResourceReader;
                if (resXResourceReader != null)
                {
                    resXResourceReader.UseResXDataNodes = true;
                    string inputDirectoryName = Path.GetDirectoryName(inputFileName);
                    resXResourceReader.BasePath = Path.GetFullPath(inputDirectoryName);
                }
                foreach (DictionaryEntry resourceEntry in resourceReader)
                {
                    ResXDataNode resXNode = (ResXDataNode)resourceEntry.Value;
                    nodeDictionary.Add(resourceEntry.Key, resXNode);
                    nodePositionDictionary.Add(resourceEntry.Key, resXNode.GetNodePosition());
                }
            }

            string resourceNamespace             = this.GetResourcesNamespace(false);
            string logicalName                   = this.GetResourcesNamespace(true);//Logical name added by Ðonny
            string inputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(inputFileName);
            string className = inputFileNameWithoutExtension;

            //className from logical name added by Ðonny:
            GetClassNameFromLogicalName(ref className);


            List <ResourceErrorData> unmatchableResources = new List <ResourceErrorData>();

            if (resourceNamespace != null)
            {
                codeCompileUnit = StronglyTypedResourceBuilderEx.Create(this.GetType(),
                                                                        nodeDictionary, className, FileNamespace, resourceNamespace,                  //className added by Ðonny
                                                                        this.CodeProvider, GenerateInternalClass, unmatchableResources, logicalName); //Logical name added by Ðonny
            }
            else
            {
                codeCompileUnit = StronglyTypedResourceBuilderEx.Create(this.GetType(),
                                                                        nodeDictionary, className, base.FileNamespace, this.CodeProvider, //className added by Ðonny
                                                                        GenerateInternalClass, unmatchableResources, logicalName);        //Logical name added by Ðonny
            }
            if (base.CodeGeneratorProgress != null)
            {
                foreach (var resourceErrorData in unmatchableResources)
                {
                    Point nodePosition = (Point)nodePositionDictionary[resourceErrorData.ResourceKey];
                    base.CodeGeneratorProgress.GeneratorError(1, 1, resourceErrorData.ErrorString,
                                                              (uint)nodePosition.Y, (uint)nodePosition.X);
                }

                base.CodeGeneratorProgress.Progress(70, 100);
            }

            this.HandleCodeCompileUnit(codeCompileUnit);

            if (base.CodeGeneratorProgress != null)
            {
                base.CodeGeneratorProgress.Progress(0x4b, 100);
            }

            ICodeGenerator codeGenerator = this.CodeProvider.CreateGenerator();

            if (BeforeGenerateText != null)
            {
                BeforeGenerateText(codeGenerator);
            }
            codeGenerator.GenerateCodeFromCompileUnit(codeCompileUnit, streamWriter, null);
            if (base.CodeGeneratorProgress != null)
            {
                NativeMethods.ThrowOnFailure(base.CodeGeneratorProgress.Progress(100, 100));
            }

            streamWriter.Flush();

            return(StreamToBytes(streamWriter.BaseStream));
        }
        /// <summary>
        /// Add string data from given ResX file to the list of data for translation
        /// </summary>
        private void AddDataForTranslation(GlobalTranslateProjectItem item, List <AbstractTranslateInfoItem> data)
        {
            string path = item.ProjectItem.GetFullPath();

            if (RDTManager.IsFileOpen(path))                              // file is open
            {
                object docData = VLDocumentViewsManager.GetDocData(path); // get document buffer
                if (docData is ResXEditor)                                // document is opened in ResX editor -> use custom method to get string data
                {
                    ResXEditor editor = (ResXEditor)docData;
                    editor.UIControl.AddForTranslation(data);
                }
                else     // document is opened in original VS editor
                {
                    IVsTextLines lines = VLDocumentViewsManager.GetTextLinesForFile(path, false);
                    string       text  = VLDocumentViewsManager.GetTextFrom(lines); // get plain text of ResX file

                    ResXResourceReader reader = null;

                    BufferTranslateInfoItem prev  = null;
                    BufferTranslateInfoItem first = null;

                    try {
                        reader = ResXResourceReader.FromFileContents(text);
                        reader.UseResXDataNodes = true;

                        // add all string resources to the list
                        // items are linked like a linked-list, allowing ApplyTranslation to work
                        foreach (DictionaryEntry entry in reader)
                        {
                            ResXDataNode node = (entry.Value as ResXDataNode);
                            if (node.HasValue <string>())
                            {
                                BufferTranslateInfoItem translateItem = new BufferTranslateInfoItem();
                                translateItem.ResourceKey         = entry.Key.ToString();
                                translateItem.Value               = node.GetValue <string>();
                                translateItem.Filename            = path;
                                translateItem.Applied             = false;
                                translateItem.GlobalTranslateItem = item;
                                translateItem.Prev         = prev;
                                translateItem.IVsTextLines = lines;

                                data.Add(translateItem);
                                prev = translateItem;
                                if (first == null)
                                {
                                    first = translateItem;
                                }
                            }
                            else
                            {
                                item.NonStringData.Add(node);
                            }
                        }
                        if (first != null)
                        {
                            first.Prev = prev;
                        }
                    } finally {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                }
            }
            else     // file is closed
            {
                ResXProjectItem resxItem = ResXProjectItem.ConvertToResXItem(item.ProjectItem, item.ProjectItem.ContainingProject);
                resxItem.Load();
                loadedResxItems.Add(resxItem);

                // add string data from ResX file
                resxItem.AddAllStringReferencesUnique(data);
            }
        }