コード例 #1
0
ファイル: MainForm.cs プロジェクト: mbrys/SubtitlesEditor
        //TODO: encoding problem with ♪ and d

        private void LoadLastFile()
        {
            if (!string.IsNullOrEmpty(fullPath) && File.Exists(fullPath))
            {
                try
                {
                    fileHelper = new FileHelper(GetReader(fullPath));
                    var enc = (encoding != null) ? encoding.GetEncoding() : Encoding.Default;
                    LoadFile(Settings.Default.LineNumber, enc);
                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }
            }
        }
コード例 #2
0
        public ParatextTextCorpus(ITokenizer <string, int> wordTokenizer, string projectDir)
        {
            string       settingsFileName = Path.Combine(projectDir, "Settings.xml");
            var          settingsDoc      = XDocument.Load(settingsFileName);
            var          codePage         = (int?)settingsDoc.Root.Element("Encoding") ?? 65001;
            EncodingInfo encodingInfo     = Encoding.GetEncodings().FirstOrDefault(ei => ei.CodePage == codePage);

            if (encodingInfo == null)
            {
                throw new InvalidOperationException("The Paratext project contains an unknown encoding.");
            }
            Encoding encoding = encodingInfo.GetEncoding();

            var scrVersType = (int?)settingsDoc.Root.Element("Versification") ?? (int)ScrVersType.English;

            Versification = new ScrVers((ScrVersType)scrVersType);

            var    stylesheetName     = (string)settingsDoc.Root.Element("StyleSheet") ?? "usfm.sty";
            string stylesheetFileName = Path.Combine(projectDir, stylesheetName);
            var    stylesheet         = new UsfmStylesheet(stylesheetFileName);

            foreach (string sfmFileName in Directory.EnumerateFiles(projectDir, "*.SFM"))
            {
                AddText(new UsfmFileText(wordTokenizer, stylesheet, encoding, sfmFileName, Versification));
            }
        }
コード例 #3
0
ファイル: MainForm.cs プロジェクト: mbrys/SubtitlesEditor
        private static FileHelper CreateTranslationHelper(string trPath, string origPath, EncodingInfo enc)
        {
            FileHelper helper;
            var        reader = GetReader(trPath);

            try
            {
                if (reader != null)
                {
                    helper = new FileHelper(reader);
                    if (helper != null)
                    {
                        helper.LoadLines(trPath, (enc != null) ? enc.GetEncoding() : Encoding.Default);
                    }
                }
                else
                {
                    var temp       = GetReader(origPath);
                    var tempHelper = new FileHelper(temp);
                    tempHelper.LoadLines(origPath, Encoding.Default);
                    tempHelper.SaveTranslationFile(trPath);
                    helper = new FileHelper(GetReader(trPath));
                    //helper.SaveTranslationFile(trPath);
                }
            }
            catch (Exception)
            {
                return(null);
            }
            return(helper);
        }
コード例 #4
0
        public void GetAllAvailableEncodings(EncodingInfo info)
        {
            // Requires <MandroidI18n>All</MandroidI18n> or can throw:
            //  System.NotSupportedException : Encoding 37 data could not be found. Make sure you have correct international codeset assembly installed and enabled.
            Encoding enc = info.GetEncoding();

            Assert.IsNotNull(enc.EncodingName, $"Failed to get Encoding from '{info.DisplayName}'.");
        }
コード例 #5
0
ファイル: FrmTestHttpPost.cs プロジェクト: cloud3g/HttpPost
        private void cboResEncoding_SelectedIndexChanged(object sender, EventArgs e)
        {
            EncodingInfo ei = cboResEncoding.SelectedItem as EncodingInfo;

            if (null == ei)
            {
                return;
            }
            _ResEncoding = ei.GetEncoding();
        }
コード例 #6
0
        public static Encoding parseText(String valueText)
        {
            EncodingInfo match = Encoding.GetEncodings().FirstOrDefault(enc => TextUtil.isEqualsIgnoreCase(enc.Name, valueText));

            if (match == null)
            {
                throw new InvalidArgumentException("Could not convert text '{0}' to an encoding", valueText);
            }

            return(match.GetEncoding());
        }
コード例 #7
0
ファイル: SerialPortTest.cs プロジェクト: liyahui520/LIS
        void serial_SerialDataReceivedCompleteEventHandler(object arg1, SerialDataReceivedCompleteEventArgs arg2)
        {
            StringBuilder str  = new StringBuilder();
            MySerialPort  prot = (MySerialPort)arg1;

            if (radioButton1.Checked)
            {
                arg2.Data.Any <byte>(by => { str.Append(by.ToString("X2") + " "); return(false); });
            }
            else if (radioButton2.Checked)
            {
                arg2.Data.Any <byte>(by => { str.Append(by.ToString() + " "); return(false); });
            }
            else
            {
                str = new StringBuilder(encodingInfo.GetEncoding().GetString(arg2.Data));
            }

            this.Invoke(new Action(() => this.textBox1.Text = prot.PortName + "接收到数据--------->\r\n" + str.ToString() + "\r\n"));
        }
コード例 #8
0
        public static Encoding GetResponseEncoding(this HttpRequestMessage request)
        {
            IEnumerable <StringWithQualityHeaderValue> charsets = request.Headers.AcceptCharset.OrderByDescending(p => p.Quality ?? 1);

            foreach (StringWithQualityHeaderValue charset in charsets)
            {
                EncodingInfo info = EncodingInfos.FirstOrDefault(p => p.Name == charset.Value);
                if (info != null)
                {
                    return(info.GetEncoding());
                }
            }
            return(Encoding.UTF8);
        }
コード例 #9
0
        public void AddFile(string strFileName, System.Text.Encoding Encoding, bool Warnings)
        {
            // Work out auto file encoding
            if (Encoding == null)
            {
                EncodingInfo e = TextFileUtils.DetectFileEncoding(strFileName);
                if (e != null)
                {
                    Encoding = e.GetEncoding();
                }
            }

            // Use same encoding for output
            if (OutputEncoding != null)
            {
                OutputEncoding = Encoding;
            }

            else
            {
                Encoding = Encoding.UTF8;
            }

            // Workout minify kind
            if (MinifyKind == MinifyKind.Auto)
            {
                if (strFileName.EndsWith(".js", StringComparison.InvariantCultureIgnoreCase))
                {
                    MinifyKind = MinifyKind.JS;
                }
                else if (strFileName.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase))
                {
                    MinifyKind = MinifyKind.CSS;
                }
            }

            // Add file info
            var i = new FileInfo();

            i.filename = strFileName;
            i.content  = File.ReadAllText(strFileName, Encoding);
            i.encoding = Encoding;
            i.warnings = Warnings;
            m_files.Add(i);
        }
コード例 #10
0
        internal void LoadFile(string fileName, bool createWatcher = false, EncodingInfo encoding = null)
        {
            var fi2 = new FileInfo(fileName);

            Text     = fi2.Name;
            FileName = fileName;

            Syncronized(() => fastColoredTextBox1.TextChanged -= fastColoredTextBox1_TextChanged);

            if (Config.UseLargeFiles)
            {
                Syncronized(() => fastColoredTextBox1.OpenBindingFile(fileName, encoding == null ? null : encoding.GetEncoding()));
            }
            else
            {
                if (encoding == null)
                {
                    Syncronized(() => fastColoredTextBox1.OpenFile(fileName));
                }
                else
                {
                    Syncronized(() => fastColoredTextBox1.OpenFile(fileName, encoding.GetEncoding()));
                }
            }

            Syncronized(() => fastColoredTextBox1.TextChanged += fastColoredTextBox1_TextChanged);


            Syncronized(() => tbRegExp.Text = @"(?i-msnx:\b(?<!-{2,}.*)go[^a-zA-Z])");
            Syncronized(() => tbRegExp.Text = RegexValues.DdlObjectsPreparedWithIndex);

            if (Config.RegexOnLoad)
            {
                BuildTree(RegexValues.DdlObjectsPreparedWithIndex, null);
            }

            var fi = new FileInfo(fileName);

            CreateFileWatcher(fi.DirectoryName);
        }
コード例 #11
0
        private static void SetFileProcessingOptions(VaultUserAccountsOptions Options)
        {
            string sep = ConfigurationManager.AppSettings["CSVSeparatorInAscii"];

            if (string.IsNullOrEmpty(sep) == false)
            {
                int code = Convert.ToInt32(sep);

                _separator = Convert.ToChar(code);
            }
            else
            {
                //default separator is comma
                _separator = Convert.ToChar(44);
            }

            EncodingInfo[] encodingInfos = Encoding.GetEncodings();
            EncodingInfo   encodingInfo  = null;

            if (encodingInfos != null)
            {
                encodingInfo = encodingInfos.FirstOrDefault(e => e.Name.Equals(Options.Encoding, StringComparison.CurrentCultureIgnoreCase));
                if (encodingInfo == null)
                {
                    int codePage;

                    if (Int32.TryParse(Options.Encoding, out codePage))
                    {
                        encodingInfo = encodingInfos.FirstOrDefault(e => e.CodePage == codePage);
                    }
                }
            }
            if (encodingInfo == null)
            {
                throw new ApplicationException("Invalid value for encoding. Either valid code page or encoding name must be provided.");
            }
            _encoding = encodingInfo.GetEncoding();
        }
コード例 #12
0
        private static Encoding GetEncoding(string name)
        {
            EncodingInfo[] encodingInfos = Encoding.GetEncodings();
            EncodingInfo   encodingInfo  = null;

            if (encodingInfos != null)
            {
                encodingInfo = encodingInfos.FirstOrDefault(e => e.Name != null && e.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));
                if (encodingInfo == null)
                {
                    int codePage;

                    if (Int32.TryParse(name, out codePage))
                    {
                        encodingInfo = encodingInfos.FirstOrDefault(e => e.CodePage == codePage);
                    }
                }
            }
            if (encodingInfo == null)
            {
                throw new ApplicationException("Invalid value for encoding. Either valid code page or encoding name must be provided.");
            }
            return(encodingInfo.GetEncoding());
        }
コード例 #13
0
        private static void SetFileEncodingOption(ApplicationOptions Options)
        {
            EncodingInfo[] encodingInfos = Encoding.GetEncodings();
            EncodingInfo   encodingInfo  = null;

            if (encodingInfos != null)
            {
                encodingInfo = encodingInfos.FirstOrDefault(e => e.Name.Equals(Options.Encoding, StringComparison.CurrentCultureIgnoreCase));
                if (encodingInfo == null)
                {
                    int codePage;

                    if (Int32.TryParse(Options.Encoding, out codePage))
                    {
                        encodingInfo = encodingInfos.FirstOrDefault(e => e.CodePage == codePage);
                    }
                }
            }
            if (encodingInfo == null)
            {
                throw new ApplicationException("Invalid value for encoding. Either valid code page or encoding name must be provided.");
            }
            _encoding = encodingInfo.GetEncoding();
        }
コード例 #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EncodingWrapper"/> class.
 /// </summary>
 /// <param name="encoding">The encoding.</param>
 /// <remarks>Documented by Dev02, 2008-02-13</remarks>
 public EncodingWrapper(EncodingInfo encoding)
 {
     this.encoding = encoding.GetEncoding();
 }
コード例 #15
0
ファイル: dcText.cs プロジェクト: drojaazu/dumpster
 internal void SetEncoding(EncodingInfo EncodingInfo)
 {
     this.SetEncoding(EncodingInfo.GetEncoding());
 }
コード例 #16
0
ファイル: ConvertHelper.cs プロジェクト: santatic/Xploit
        public static object ConvertTo(string input, Type type, object currentValue = null)
        {
            if (!string.IsNullOrEmpty(input))
            {
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    type = type.GenericTypeArguments[0];
                }
                if (type.IsEnum)
                {
                    string[] f = Enum.GetNames(type);

                    long   iret = 0;
                    object ret  = null;
                    foreach (string en in input.Split(GetSplitChar(type)))
                    {
                        foreach (string v in f)
                        {
                            if (string.Compare(v, en, true) == 0)
                            {
                                object v1 = Enum.Parse(type, v);
                                if (v1 != null)
                                {
                                    if (ret == null)
                                    {
                                        ret  = v1;
                                        iret = Convert.ToInt64(v1);
                                    }
                                    else
                                    {
                                        // TODO Convert multienum One|Two
                                        iret |= Convert.ToInt64(v1);
                                    }
                                }
                            }
                        }
                    }

                    return(ret);
                }

                // String conversion
                if (type == _StringType)
                {
                    return(input);
                }
                if (input.Trim().ToLowerInvariant() == "null")
                {
                    return(null);
                }

                // Bool
                if (type == _BoolType)
                {
                    bool r;
                    if (!bool.TryParse(input.Trim(), out r))
                    {
                        string si = input.ToLowerInvariant();
                        return(si == "y" || si == "s" || si == "yes" || si == "si" || si == "1" || si == "true");
                    }
                    return(r);
                }
                // Date/Time
                if (type == _TimeSpanType)
                {
                    TimeSpan r;
                    if (!TimeSpan.TryParse(input.Trim(), CultureInfo.InvariantCulture, out r))
                    {
                        long ms = Convert.ToInt64(MathHelper.Calc(input));
                        return(TimeSpan.FromMilliseconds(ms));
                    }
                    return(r);
                }
                if (type == _DateTimeType)
                {
                    DateTime r;
                    if (!DateTime.TryParse(input.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out r))
                    {
                        return(DateTime.MinValue);
                    }
                    return(r);
                }

                // Numeric Conversion
                if (type == _ByteType)
                {
                    byte r;
                    if (!byte.TryParse(input.Trim(), out r))
                    {
                        return(Convert.ToByte(MathHelper.Calc(input)));
                    }
                    return(r);
                }
                if (type == _SByteType)
                {
                    sbyte r;
                    if (!sbyte.TryParse(input.Trim(), out r))
                    {
                        return(Convert.ToSByte(MathHelper.Calc(input)));
                    }
                    return(r);
                }
                if (type == _Int64Type)
                {
                    long r;
                    if (!long.TryParse(input.Trim(), out r))
                    {
                        return(Convert.ToInt64(MathHelper.Calc(input)));
                    }
                    return(r);
                }
                if (type == _UInt64Type)
                {
                    ulong r;
                    if (!ulong.TryParse(input.Trim(), out r))
                    {
                        return(Convert.ToUInt64(MathHelper.Calc(input)));
                    }
                    return(r);
                }
                if (type == _Int32Type)
                {
                    int r;
                    if (!int.TryParse(input.Trim(), out r))
                    {
                        return(Convert.ToInt32(MathHelper.Calc(input)));
                    }
                    return(r);
                }
                if (type == _UInt32Type)
                {
                    uint r;
                    if (!uint.TryParse(input.Trim(), out r))
                    {
                        return(Convert.ToUInt32(MathHelper.Calc(input)));
                    }
                    return(r);
                }
                if (type == _Int16Type)
                {
                    short r;
                    if (!short.TryParse(input.Trim(), out r))
                    {
                        return(Convert.ToInt16(MathHelper.Calc(input)));
                    }
                    return(r);
                }
                if (type == _UInt16Type)
                {
                    ushort r;
                    if (!ushort.TryParse(input.Trim(), out r))
                    {
                        return(Convert.ToUInt16(MathHelper.Calc(input)));
                    }
                    return(r);
                }
                // Decimal (With '.' as decimal separator)
                if (type == _DoubleType)
                {
                    double r;
                    if (!double.TryParse(input.Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out r))
                    {
                        return(Convert.ToDouble(MathHelper.Calc(input)));
                    }
                    return(r);
                }
                if (type == _DecimalType)
                {
                    decimal r;
                    if (!decimal.TryParse(input.Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out r))
                    {
                        return(Convert.ToDecimal(MathHelper.Calc(input)));
                    }
                    return(r);
                }
                if (type == _FloatType)
                {
                    float r;
                    if (!float.TryParse(input.Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out r))
                    {
                        return(Convert.ToSingle(MathHelper.Calc(input)));
                    }
                    return(r);
                }
                if (type == _IPAddressType)
                {
                    ushort    prto = 0;
                    IPAddress ip;
                    if (IPHelper.ParseIpPort(input, out ip, ref prto))
                    {
                        return(ip);
                    }
                    return(IPAddress.Any);
                }
                if (type == _UriType)
                {
                    return(new Uri(input));
                }
                if (type == _RegexType)
                {
                    return(new Regex(input));
                }
                if (type == _FileInfoType)
                {
                    return(new FileInfo(input));
                }
                if (type == _DirectoryInfoType)
                {
                    return(new DirectoryInfo(input));
                }
                if (type == _EncodingType)
                {
                    EncodingInfo i = Encoding.GetEncodings().Where(u => string.Compare(input, u.Name, true) == 0 || string.Compare(input, u.DisplayName) == 0).FirstOrDefault();
                    return(i == null ? null : i.GetEncoding());
                }
                if (type == _IPEndPointType)
                {
                    IPAddress ip;
                    ushort    port = 0;
                    if (!IPHelper.ParseIpPort(input, out ip, ref port))
                    {
                        return(null);
                    }
                    if (port == 0)
                    {
                        if (currentValue != null && currentValue is IPEndPoint)
                        {
                            port = (ushort)((IPEndPoint)currentValue).Port;
                        }

                        if (port == 0)
                        {
                            return(null);
                        }
                    }
                    return(new IPEndPoint(ip, port));
                }
                if (type == _ByteArrayType)
                {
                    return(HexHelper.FromHexString(input));
                }

                // Array
                if (type.IsArray)
                {
                    List <object> l  = new List <object>();
                    Type          gt = type.GetElementType();
                    foreach (string ii in input.Split(GetSplitChar(gt)))
                    {
                        object ov = ConvertTo(ii, gt);
                        if (ov == null)
                        {
                            continue;
                        }

                        l.Add(ov);
                    }

                    Array a = (Array)Activator.CreateInstance(type, l.Count);
                    Array.Copy(l.ToArray(), a, l.Count);
                    return(a);
                }

                // List
                if (_IListType.IsAssignableFrom(type))
                {
                    IList l = (IList)Activator.CreateInstance(type);

                    // If dosent have T return null
                    if (type.GenericTypeArguments == null || type.GenericTypeArguments.Length == 0)
                    {
                        return(null);
                    }

                    Type gt = type.GenericTypeArguments[0];
                    foreach (string ii in input.Split(GetSplitChar(gt)))
                    {
                        object ov = ConvertTo(ii, gt);
                        if (ov == null)
                        {
                            continue;
                        }

                        l.Add(ov);
                    }
                    return(l);
                }

                // Objects
                if (type.IsClass)
                {
                    // Is Convertible (Like Password)
                    TypeConverter conv = TypeDescriptor.GetConverter(type);
                    if (conv.CanConvertFrom(_StringType))
                    {
                        return(conv.ConvertFrom(input));
                    }

                    // For generic Types is more easy
                    if (type.GetConstructor(new Type[] { _StringType }) != null)
                    {
                        return(Activator.CreateInstance(type, input));
                    }

                    if (input.StartsWith("{") && input.EndsWith("}"))
                    {
                        input = input.Substring(1, input.Length - 2);
                    }

                    return(ArgumentHelper.Parse(type, input));
                }
            }

            return(null);
        }
コード例 #17
0
        /// <summary>
        /// Generate a code file for the current xml file contents. Loads
        /// settings for the file off the Plix.xml settings file in the project to
        /// get the generation transform and other settings to apply to the specific file.
        /// </summary>
        /// <param name="fileContents">Contents of an xml file to transform</param>
        /// <param name="defaultNamespace">The namespace provided in the property grid</param>
        /// <returns>Contents of the corresponding code file</returns>
        private string GenerateCode(string fileContents, string defaultNamespace)
        {
                        #if VerifyUIThread
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                        #endif

            // Make sure we have a CodeDomProvider
            CodeDomProvider provider = CodeDomProvider;
            if (provider == null)
            {
                return(string.Empty);
            }

            // Get the current project item and project information
            EnvDTE.ProjectItem projectItem     = CurrentProjectItem;
            string             sourceFile      = (string)projectItem.Properties.Item("LocalPath").Value;
            EnvDTE.Project     project         = projectItem.ContainingProject;
            string             projectFile     = (string)project.Properties.Item("LocalPath").Value;
            string             projectLocation = projectFile.Substring(0, projectFile.LastIndexOf('\\') + 1);

            // If this is the Plix.xml settings file, then regenerate all other mentioned NUPlixLoader files
            if (0 == string.Compare(projectItem.Name, PlixProjectSettingsFile, true, CultureInfo.InvariantCulture))
            {
                RunCustomTool(
                    project.ProjectItems,
                    projectItem,
                    delegate(EnvDTE.ProjectItem matchItem)
                {
                                                #if VerifyUIThread
                    Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                                                #endif

                    VSProjectItem vsProjItem = matchItem.Object as VSProjectItem;
                    if (vsProjItem != null)
                    {
                        vsProjItem.RunCustomTool();
                    }
                });
                StringWriter writer = new StringWriter();
                provider.GenerateCodeFromStatement(new CodeCommentStatement(
                                                       @"Empty file generated by NUPlixLoader for Plix.xml.

Setting NUPlixLoader as the custom tool on the Plix.xml settings file enables automatic
regeneration of other NUPlixLoader files in the project when the settings file is changed.

There is no way to both successfully trigger regeneration and avoid writing this file."), writer, null);
                return(writer.ToString());
            }

            // Load a language formatter for this file extension
            string fileExtension = CodeDomProvider.FileExtension;
            if (fileExtension.StartsWith("."))
            {
                fileExtension = fileExtension.Substring(1);
            }
            XslCompiledTransform formatter = FormatterManager.GetFormatterTransform(fileExtension);
            if (formatter == null)
            {
                StringWriter writer = new StringWriter();
                provider.GenerateCodeFromStatement(new CodeCommentStatement(string.Format(CultureInfo.InvariantCulture, "A PLiX formatter transform for the '{0}' language was not found.", fileExtension)), writer, null);
                return(writer.ToString());
            }

            // Get options for this xml file
            XsltArgumentList arguments = new XsltArgumentList();
            string           automationObjectName;
            string           transformFile = LoadProjectSettings(sourceFile, projectLocation, arguments, project, out automationObjectName);

            // MSBUG: Beta2 There's a nasty bug with single-file generators right now where
            // the text for an open file that is not in a text document is
            // passed through as encoded bytes in the string.
            EnvDTE.Document itemDocument = projectItem.Document;
            if (itemDocument != null && "XML" != itemDocument.Language)
            {
                if (fileContents.Length > 1)
                {
                    char[]   leadChars = fileContents.ToCharArray(0, 2);
                    byte[]   leadBytes = new byte[2 * sizeof(char)];
                    GCHandle handle    = GCHandle.Alloc(leadBytes, GCHandleType.Pinned);
                    Marshal.Copy(leadChars, 0, Marshal.UnsafeAddrOfPinnedArrayElement(leadBytes, 0), 2);
                    handle.Free();
                    EncodingInfo[] encodingInfos  = Encoding.GetEncodings();
                    int            encodingsCount = encodingInfos.Length;
                    for (int i = 0; i < encodingsCount; ++i)
                    {
                        EncodingInfo encodingInfo      = encodingInfos[i];
                        Encoding     encoding          = encodingInfo.GetEncoding();
                        byte[]       preamble          = encoding.GetPreamble();
                        int          preambleByteCount = preamble.Length;
                        if (preambleByteCount != 0)
                        {
                            Debug.Assert(preambleByteCount <= 4);
                            int j;
                            for (j = 0; j < preambleByteCount; ++j)
                            {
                                if (preamble[j] != leadBytes[j])
                                {
                                    break;
                                }
                            }
                            if (j == preambleByteCount)
                            {
                                Decoder decoder = encoding.GetDecoder();
                                leadChars = fileContents.ToCharArray();
                                int startCharCount = leadChars.Length;
                                leadBytes = new byte[startCharCount * sizeof(char)];
                                int      byteCount = leadBytes.Length - preambleByteCount;
                                GCHandle handle2   = GCHandle.Alloc(leadBytes, GCHandleType.Pinned);
                                Marshal.Copy(leadChars, 0, Marshal.UnsafeAddrOfPinnedArrayElement(leadBytes, 0), startCharCount);
                                handle2.Free();
                                int    finalCharCount = decoder.GetCharCount(leadBytes, preambleByteCount, byteCount, true);
                                char[] finalChars     = new char[finalCharCount + 1];
                                decoder.GetChars(leadBytes, preambleByteCount, byteCount, finalChars, 0, true);

                                // Hack within a hack to make sure that the Xml element has a trailing >,
                                // byte data in a string has a tendency to lose the last byte
                                char testChar = finalChars[finalCharCount - 1];;
                                if (testChar != '>' && !char.IsWhiteSpace(testChar))
                                {
                                    finalChars[finalCharCount] = '>';
                                    ++finalCharCount;
                                }
                                fileContents = new string(finalChars, 0, finalCharCount);
                            }
                        }
                    }
                }
            }

            // Resolve any file redirections here. File redirection allows the same source file
            // to generate multiple outputs via multiple transforms.
            string alternateSourceFile = null;
            using (StringReader stringReader = new StringReader(fileContents))
            {
                try
                {
                    using (XmlTextReader reader = new XmlTextReader(stringReader))
                    {
                        if (XmlNodeType.Element == reader.MoveToContent())
                        {
                            if (reader.NamespaceURI == RedirectNamespace &&
                                reader.LocalName == RedirectElementName)
                            {
                                string   relativeTargetSourceFile = reader.GetAttribute(RedirectTargetAttribute);
                                FileInfo targetSourceFileInfo     = new FileInfo(sourceFile.Substring(0, sourceFile.LastIndexOf('\\') + 1) + relativeTargetSourceFile);
                                if (targetSourceFileInfo.Exists)
                                {
                                    alternateSourceFile = targetSourceFileInfo.FullName;
                                    sourceFile          = alternateSourceFile;
                                    try
                                    {
                                        itemDocument = null;
                                        itemDocument = project.DTE.Documents.Item(alternateSourceFile);
                                    }
                                    catch (ArgumentException)
                                    {
                                        // Swallow if the document is not open
                                    }
                                }
                                else
                                {
                                    StringWriter writer = new StringWriter();
                                    provider.GenerateCodeFromStatement(new CodeCommentStatement(string.Format(CultureInfo.InvariantCulture, "Redirection target file '{0}' not found", relativeTargetSourceFile)), writer, null);
                                    return(writer.ToString());
                                }
                            }
                        }
                    }
                }
                catch (XmlException ex)
                {
                    return(GenerateExceptionInformation(ex, provider));
                }
            }

            // Add standard defined attributes to the argument list
            string projectNamespace = (string)project.Properties.Item("DefaultNamespace").Value;
            if (null == arguments.GetParam("ProjectPath", ""))
            {
                arguments.AddParam("ProjectPath", "", projectLocation);
            }
            if (null == arguments.GetParam("SourceFile", ""))
            {
                arguments.AddParam("SourceFile", "", sourceFile.Substring(projectLocation.Length));
            }
            if (null == arguments.GetParam("CustomToolNamespace", ""))
            {
                if (defaultNamespace == null || defaultNamespace.Length == 0)
                {
                    defaultNamespace = projectNamespace;
                }
                arguments.AddParam("CustomToolNamespace", "", defaultNamespace);
            }
            if (null == arguments.GetParam("ProjectNamespace", ""))
            {
                arguments.AddParam("ProjectNamespace", "", projectNamespace);
            }

            try
            {
                XslCompiledTransform transform = null;
                if (transformFile != null)
                {
                    transform = new XslCompiledTransform();
                    using (FileStream transformStream = new FileStream(transformFile, FileMode.Open, FileAccess.Read))
                    {
                        using (StreamReader reader = new StreamReader(transformStream))
                        {
                            transform.Load(new XmlTextReader(reader), XsltSettings.TrustedXslt, XmlUtility.CreateFileResolver(transformFile));
                        }
                    }
                }
                MemoryStream plixStream = (transform != null) ? new MemoryStream() : null;
                using (XmlWriter xmlTextWriter = (transform != null) ? XmlWriter.Create(plixStream, transform.OutputSettings) : null)
                {
                    // Variables that need to be disposed
                    TextReader reader    = null;
                    Stream     docStream = null;

                    try
                    {
                        // First try to get data from the live object
                        string docText = null;
                        if (itemDocument != null)
                        {
                            if (automationObjectName != null)
                            {
                                docStream = itemDocument.Object(automationObjectName) as Stream;
                                if (docStream != null)
                                {
                                    reader = new StreamReader(docStream);
                                }
                            }

                            // Fall back on getting the contents of the text buffer from the live document
                            if (reader == null)
                            {
                                EnvDTE.TextDocument textDoc = itemDocument.Object("TextDocument") as EnvDTE.TextDocument;
                                if (textDoc != null)
                                {
                                    docText = textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint);
                                    reader  = new StringReader(docText);
                                }
                            }
                        }

                        // If this is a redirection, then pull direction from the file
                        if (reader == null && alternateSourceFile != null)
                        {
                            reader = new StreamReader(alternateSourceFile);
                        }

                        // Fallback on the default reading mechanism
                        if (reader == null)
                        {
                            docText = fileContents;
                            reader  = new StringReader(fileContents);
                        }

                        if (transform == null)
                        {
                            XmlReaderSettings testPlixDocumentReaderSettings = new XmlReaderSettings();
                            testPlixDocumentReaderSettings.CloseInput = false;
                            bool plixDocument = false;
                            try
                            {
                                using (XmlReader testPlixDocumentReader = XmlReader.Create(reader, testPlixDocumentReaderSettings))
                                {
                                    testPlixDocumentReader.MoveToContent();
                                    if (testPlixDocumentReader.NodeType == XmlNodeType.Element && testPlixDocumentReader.NamespaceURI == PlixSchemaNamespace)
                                    {
                                        plixDocument = true;
                                    }
                                }
                            }
                            catch (XmlException ex)
                            {
                                return(GenerateExceptionInformation(ex, provider));
                            }
                            if (!plixDocument)
                            {
                                StringWriter writer = new StringWriter();
                                provider.GenerateCodeFromStatement(new CodeCommentStatement("Transform file not found"), writer, null);
                                GenerateNUPlixLoaderExceptionLine(writer, provider);
                                return(writer.ToString());
                            }
                            if (docText != null)
                            {
                                reader.Dispose();
                                reader = new StringReader(docText);
                            }
                            else
                            {
                                StreamReader streamReader = (StreamReader)reader;
                                streamReader.BaseStream.Position = 0;
                            }
                        }
                        else
                        {
                            // Use an XmlTextReader here instead of an XPathDocument
                            // so that our transforms support the xsl:preserve-space element
                            transform.Transform(new XmlTextReader(reader), arguments, xmlTextWriter, XmlUtility.CreateFileResolver(sourceFile));
                            plixStream.Position = 0;
                        }
                        // From the plix stream, generate the code
                        using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
                        {
                            using (XmlReader plixReader = (plixStream != null) ? XmlReader.Create(plixStream, PlixReaderSettings) : XmlReader.Create(reader, PlixReaderSettings))
                            {
                                formatter.Transform(plixReader, new XsltArgumentList(), writer);
                            }
                            return(writer.ToString());
                        }
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            (reader as IDisposable).Dispose();
                        }
                        if (docStream != null)
                        {
                            (docStream as IDisposable).Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(GenerateExceptionInformation(ex, provider));
            }
            finally
            {
                // Regardless of how we finish process this file, we need to find files redirected to this
                // one and regenerate them.
                if (alternateSourceFile == null)                 // We only redirect one level
                {
                    FileInfo sourceFileInfo = new FileInfo(sourceFile);
                    RunCustomTool(
                        project.ProjectItems,
                        projectItem,
                        delegate(EnvDTE.ProjectItem matchItem)
                    {
                                                        #if VerifyUIThread
                        Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                                                        #endif

                        VSProjectItem vsProjItem = matchItem.Object as VSProjectItem;
                        if (vsProjItem != null)
                        {
                            string itemFile = (string)matchItem.Properties.Item("LocalPath").Value;
                            EnvDTE.Document liveDoc;
                            EnvDTE.TextDocument textDoc;
                            string liveText = null;
                            if (null != (liveDoc = matchItem.Document) &&
                                null != (textDoc = liveDoc.Object("TextDocument") as EnvDTE.TextDocument))
                            {
                                liveText = textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint);
                            }
                            try
                            {
                                using (FileStream fileStream = (liveText == null) ? new FileStream(itemFile, FileMode.Open, FileAccess.Read) : null)
                                {
                                    using (XmlTextReader reader = new XmlTextReader((liveText == null) ? new StreamReader(fileStream) as TextReader : new StringReader(liveText)))
                                    {
                                        if (XmlNodeType.Element == reader.MoveToContent())
                                        {
                                            if (reader.NamespaceURI == RedirectNamespace &&
                                                reader.LocalName == RedirectElementName)
                                            {
                                                FileInfo targetSourceFileInfo = new FileInfo(itemFile.Substring(0, itemFile.LastIndexOf('\\') + 1) + reader.GetAttribute(RedirectTargetAttribute));
                                                if (0 == string.Compare(sourceFileInfo.FullName, targetSourceFileInfo.FullName, true, CultureInfo.CurrentCulture))
                                                {
                                                    vsProjItem.RunCustomTool();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (XmlException)
                            {
                                // Swallow anything that Xml gripes about
                            }
                        }
                    });
                }
            }
        }
コード例 #18
0
ファイル: EncodingsForm.cs プロジェクト: atminatana/SerialRW
 public ListBoxItem(EncodingInfo AInfo)
 {
     this.Info = AInfo;
     Enc       = AInfo.GetEncoding();
 }