Example #1
0
        /// <summary>
        /// Override fill bytes by refernce.
        /// </summary>
        public override void FillBytesRef()
        {
            BytesRef bytes = BytesRef;
            var      utf16 = _charset.GetBytes(_charset.ToString());

            bytes.Bytes  = utf16;
            bytes.Offset = 0;
            bytes.Length = utf16.Length;
        }
        public ContentResultAssertions WithContentEncoding(Encoding expectedEncoding, string reason, params object[] reasonArgs)
        {
            Encoding actualContentEncoding = (Subject as ContentResult).ContentEncoding;

            Execute.Verification
                    .ForCondition(expectedEncoding == actualContentEncoding)
                    .BecauseOf(reason, reasonArgs)
                    .FailWith(Constants.CommonFailMessage, "ContentResult.ContentType", expectedEncoding.ToString(), actualContentEncoding.ToString());

            return this;
        }
Example #3
0
    static public string Convert(File file, Encoding targetEnc)
    {
      Trace.WriteLine("Converting " + file.Name + file.Extension + " to " + targetEnc.ToString("G"));

      // Read in file & formatting
      IAudioReader Reader = new DsReader(file.Path);
      IntPtr SourceFormat = Reader.ReadFormat();
      IntPtr TargetFormat = AudioCompressionManager.GetCompatibleFormat(SourceFormat, AudioCompressionManager.MpegLayer3FormatTag);
      
      // Create new file
      byte[] Data = Reader.ReadData();
      byte[] Output = AudioCompressionManager.Convert(SourceFormat, TargetFormat, Data, true);
      string Filename = Path.GetDirectoryName(file.Path) + "\\" + file.Name + "." + targetEnc.ToString("G").ToLower();
      BinaryWriter Writer = new BinaryWriter(System.IO.File.Create(Filename));
      Writer.Write(Output, 0, Output.Length);

      // Cleanup & remove source
      Reader.Close();
      Writer.Close();
      file.Delete();

      return Filename;
    }
Example #4
0
        /// <summary>
        /// バイト列から文字列に変換(文字コードの自動判別付き)
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string ToStringAutoEnc(byte[] data)
        {
            string src;

            // 文字コード判別
            System.Text.Encoding enc = GetCode(data);
            string enc_str           = enc.ToString();

            // UTF-8
            if (enc == Encoding.UTF8)
            {
                src = Encoding.UTF8.GetString(data);
            }
            // UNICODE
            else if (enc == Encoding.Unicode)
            {
                src = Encoding.Unicode.GetString(data);
            }
            // Shift_JIS
            else if (enc == System.Text.Encoding.GetEncoding(932))
            {
                src = System.Text.Encoding.GetEncoding(932).GetString(data);
            }
            // JIS
            else if (enc == Encoding.GetEncoding(50220))
            {
                src = System.Text.Encoding.GetEncoding(50220).GetString(data);
            }
            // EUC-JP
            else if (enc == Encoding.GetEncoding(51932))
            {
                src = System.Text.Encoding.GetEncoding(51932).GetString(data);
            }
            else if (enc == Encoding.ASCII)
            {
                src = Encoding.ASCII.GetString(data);
            }
            else
            {
                src = enc.GetString(data);
            }

            return(src);
        }
Example #5
0
        public MemoryGloballist Perform(
            Expression_Node_Filepath expr_Fpath_GloballistText,
            Encoding encoding,
            Log_Reports log_Reports,
            string sRunningHintName
            )
        {
            Log_Method pg_Method = new Log_MethodImpl(0);
            pg_Method.BeginMethod(Info_Operating.Name_Library, this, "Perform",log_Reports);

            MemoryGloballist moGl = new MemoryGloballistImpl();

            string sFpatha = expr_Fpath_GloballistText.Execute4_OnExpressionString(
                EnumHitcount.Unconstraint, log_Reports);//絶対ファイルパス
            if (!log_Reports.Successful)
            {
                // 既エラー。
                goto gt_EndMethod;
            }

            if ("" == sFpatha)
            {
                // グローバルリスト ファイルへのパスが空文字列だった場合
                if (log_Reports.CanCreateReport)
                {
                    Log_RecordReports r = log_Reports.BeginCreateReport(EnumReport.Error);
                    r.SetTitle("▲エラー080011!", pg_Method);
                    r.Message = "グローバルリスト ファイルへのパスを指定してください。";
                    log_Reports.EndCreateReport();
                }
            }

            string sText1;
            if (log_Reports.Successful)
            {
                // 正常時

                // テキスト読取り
                try
                {
                    sText1 = System.IO.File.ReadAllText(sFpatha, encoding);
                }
                catch(Exception ex)
                {
                    sText1 = null;
                    if (log_Reports.CanCreateReport)
                    {
                        Log_RecordReports r = log_Reports.BeginCreateReport(EnumReport.Error);
                        r.SetTitle("▲エラー0800023!", pg_Method);

                        StringBuilder t = new StringBuilder();
                        t.Append("ファイルの読み取りに失敗しました。");
                        t.Append(Environment.NewLine);
                        t.Append(Environment.NewLine);
                        t.Append("ファイルパス=[");
                        t.Append(sFpatha);
                        t.Append("]");
                        t.Append(Environment.NewLine);
                        t.Append(Environment.NewLine);
                        t.Append("エンコーディング=[");
                        t.Append(encoding.ToString());
                        t.Append("]");
                        t.Append(Environment.NewLine);
                        t.Append(Environment.NewLine);
                        t.Append("例外:[");
                        t.Append(ex.GetType().Name);
                        t.Append("]:");
                        t.Append(ex.Message);

                        r.Message = t.ToString();

                        log_Reports.EndCreateReport();
                    }
                }
            }
            else
            {
                // エラー時
                sText1 = null;
            }

            if (log_Reports.Successful)
            {
                // 正常時

                // テキストをストリーム化します。
                System.IO.StringReader reader = new System.IO.StringReader(sText1);

                while (-1 < reader.Peek())
                {
                    string sLine = reader.ReadLine();

                    string parent_SNode = sFpatha;
                    MemoryGloballistLine modelOfGlLine = this.Sub_ParseLine(sLine, log_Reports, parent_SNode);

                    if (log_Reports.Successful)
                    {
                        // 正常時

                        moGl.AddLine(modelOfGlLine);
                    }
                }
                // ストリームを閉じます。
                reader.Close();
            }

            //
            //
            //
            //
            gt_EndMethod:
            pg_Method.EndMethod(log_Reports);
            return moGl;
        }
Example #6
0
 public static RubyEncoding/*!*/ GetRubyEncoding(Encoding/*!*/ encoding) {
     ContractUtils.RequiresNotNull(encoding, "encoding");
     if (encoding == BinaryEncoding.Instance) {
         return Binary;
     } else if (encoding.ToString() == Encoding.UTF8.ToString()) {
         return UTF8;
     } else {
         throw new ArgumentException(String.Format("Unknown encoding: '{0}'", encoding));
     }
 }
Example #7
0
        /// <summary>
        /// Reads a textual line from a stream without reading ahead and consuming more
        /// bytes than necessary to read the line.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This method is intended to be use where a stream is used with both binary
        /// data and encoded text.
        /// </para>
        /// <para>
        /// Because decoding without buffering requires detecting end of line characters
        /// reliabily without buffering, this method only supports the UTF-8 and ASCII
        /// encodings.
        /// </para>
        /// <para>
        /// This method uses TLS buffers and is thread safe.
        /// </para>
        /// </remarks>
        /// <param name="stream">
        /// The stream to read the textual line from.
        /// </param>
        /// <param name="encoding">
        /// The encoding to use.
        /// Only <see cref="Encoding.UTF8"/> and <see cref="Encoding.ASCII"/> are supported.
        /// </param>
        /// <param name="maxBytes">
        /// The maximum number of bytes to read before throwing an <see cref="OverflowException"/>.
        /// If maxbytes is encountered, the stream is left in an unstable state for reading
        /// text.
        /// </param>
        /// <returns></returns>
        public static string ReadLineUnbuffered(this Stream stream, Encoding encoding, int maxBytes)
        {
            var lastByte = -1;
            var byteCount = 0;

            if (encoding != Encoding.UTF8 && encoding != Encoding.ASCII)
            {
                throw new ArgumentException(encoding.ToString(), "encoding");
            }

            var retval = stream.ReadDynamicBlock(delegate(byte x)
            {
                if (x == '\n' && lastByte == '\r')
                {
                    return false;
                }

                lastByte = x;
                byteCount++;

                if (byteCount > maxBytes)
                {
                    throw new OverflowException();
                }

                return true;
            });

            var maxCharCount = encoding.GetMaxCharCount(retval.Right);

            if (t_CharBuffer == null
                || (t_CharBuffer != null && maxCharCount > t_CharBuffer.Length))
            {
                int newLength = t_CharBuffer == null ? 64 : t_CharBuffer.Length;

                while (newLength < maxCharCount)
                {
                    newLength *= 2;
                }

                Array.Resize(ref t_CharBuffer, newLength);
            }

            var charCount = Encoding.UTF8.GetChars(retval.Left, 0, lastByte == '\r' ? retval.Right - 1 : retval.Right, t_CharBuffer, 0);

            return new string(t_CharBuffer, 0, charCount);
        }
Example #8
0
 public void SetContentType(string MimeType, Encoding Encoding)
 {
     Headers.Set("Content-Type", MimeType + "; charset=" + Encoding.ToString());
     this.Encoding = Encoding;
 }
Example #9
0
 internal void InitStreams(Encoding encoding)
 {
     Stream stream = this.controlSock.GetStream();
     if (encoding == null)
     {
         encoding = Encoding.ASCII;
     }
     this.encoding = encoding;
     this.log.Debug("Command encoding=" + encoding.ToString());
     this.writer = new StreamWriter(stream, encoding);
     this.reader = new StreamReader(stream, encoding);
 }
Example #10
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {                                                  //此处理并非是客户端直接传递过来的参数,而是经过代码处理后的结果
            RequestContext  request = filterContext.RequestContext;
            HttpContextBase hcb     = request.HttpContext; //HTTP请求相关参数

            //是否开启日志记录
            if (InitAppSetting.OpenDebugType)
            {
                StringBuilder   sb         = new StringBuilder();
                HttpRequestBase req        = hcb.Request;//包含请求头相关信息的实体
                string          webBrowser = req.UserAgent;
                sb.AppendLine("UserAgent=\t" + webBrowser);
                string[] userLanguage = req.UserLanguages;//用户使用的语言
                sb.AppendLine("UserLanguages =\t" + string.Join("|", userLanguage));
                string url = req.Url.ToString();
                sb.AppendLine("Url=\t" + url);
                string method = req.RequestType;//HTTP请求形式
                sb.AppendLine("RequestType=\t" + method);
                string httpMethod = req.HttpMethod;
                sb.AppendLine("HttpMethod=\t" + httpMethod);
                //req.Form //请求的表单
                //req.Headers //请求头
                HttpCookieCollection cookies = req.Cookies;//请求的cookie
                if (cookies.Count > 0)
                {
                    sb.AppendLine("Cookies=");

                    /*
                     * “System.InvalidCastException”类型的异常在 HRApp.Web.dll 中发生,但未在用户代码中进行处理
                     *
                     * 其他信息: 无法将类型为“System.String”的对象强制转换为类型“System.Web.HttpCookie”
                     * 不能直接使用foreach
                     * foreach (HttpCookie item in cookies)
                     * {
                     *  sb.AppendLine(item.ConvertJson()+"\r\n");
                     * }
                     * https://www.cnblogs.com/answercard/archive/2009/02/02/1382404.html
                     */
                    for (int i = 0; i < cookies.Count; i++)
                    {
                        HttpCookie hc = cookies[i];
                        sb.AppendLine(hc.ConvertJson() + "\r\n");
                    }
                }
                string mimeType = req.ContentType;//文件传输类型
                sb.AppendLine("ContentType=\t" + mimeType);
                System.Text.Encoding userEncoding = req.ContentEncoding;
                sb.AppendLine("ContentEncoding=\t" + userEncoding.ToString());
                HttpBrowserCapabilitiesBase browserInfo = req.Browser;
                sb.AppendLine("Browser=\t" + browserInfo.Browser + "\t");
                for (int i = 0; i < browserInfo.Browsers.Count; i++)
                {
                    sb.Append(browserInfo.Browsers[i].ToString() + "\t");
                }
                sb.AppendLine("\r\nMobileDeviceModel=\t" + browserInfo.MobileDeviceModel);
                sb.AppendLine("Platform=\t" + browserInfo.Platform);
                string[] browserSupperMimeType = req.AcceptTypes;//HTTP预返回前端支持的文件格式
                sb.AppendLine("\nAcceptTypes=\t" + string.Join(" ", browserSupperMimeType));
                sb.AppendLine("Ip:" + GetBrowserIp());
                ELogType el   = ELogType.DebugData;
                string   file = LogPrepare.GetLogName(el);
                LoggerWriter.CreateLogFile(sb.ToString(), LogPrepare.GetLogPath(), el, file, true);
            }
            IDictionary <string, object> apiParamList = filterContext.ActionParameters;//进入接口传递的参数
            RouteData rd = filterContext.RouteData;

            if (apiParamList.Count == 0)
            {
                return;
            }
            base.OnActionExecuting(filterContext);
        }
Example #11
0
        /// <summary>
        /// 将内容导出成特定格式的文件
        /// </summary>
        /// <param name="contents">需要导出的内容</param>
        /// <param name="fileName">导出的文件名</param>
        /// <param name="fileType">导出的文件类型,默认为导出Excel文件</param>
        /// <param name="encoding">输出流HTTP字符集</param>
        public static void ExportToExcel(string contents, string fileName, ExportFileType fileType, Encoding encoding)
        {
            if (HttpContext.Current.Response == null) return;

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = encoding.ToString();
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));

            //设置输出流HTTP字符集
            HttpContext.Current.Response.ContentEncoding = encoding;
            //设置输出文件类型 
            switch (fileType)
            {
                case ExportFileType.Excel:
                    HttpContext.Current.Response.ContentType = CONST_REPONSEHEADER_EXCEL;
                    break;
                case ExportFileType.Word:
                    HttpContext.Current.Response.ContentType = CONST_REPONSEHEADER_WORD;
                    break;
                case ExportFileType.PDF:
                    HttpContext.Current.Response.ContentType = CONST_REPONSEHEADER_PDF;
                    break;
                case ExportFileType.XML:
                    HttpContext.Current.Response.ContentType = CONST_REPONSEHEADER_XML;
                    break;
                case ExportFileType.ZIP:
                    HttpContext.Current.Response.ContentType = CONST_REPONSEHEADER_ZIP;
                    break;
                case ExportFileType.Txt:
                    HttpContext.Current.Response.ContentType = CONST_REPONSEHEADER_TEXT;
                    break;
                case ExportFileType.CSV:
                    HttpContext.Current.Response.ContentType = CONST_REPONSEHEADER_CSV;
                    break;
                default:
                    HttpContext.Current.Response.ContentType = CONST_REPONSEHEADER_EXCEL;
                    break;
            }

            HttpContext.Current.Response.Write(contents);

            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
 public static Value Encoding(X.Encoding x) => x.ToString();
Example #13
0
 /// <summary>  Obtain the reader/writer streams for this
 /// connection
 /// </summary>
 internal void InitStreams(Encoding encoding)
 {
     Stream stream = controlSock.GetStream();
     if (encoding == null)
     {
         try {
             encoding = Encoding.GetEncoding(WINDOWS_1252);
         }
         catch (Exception ex1) 
         {
             log.Debug("Could not set encoding to Windows-1252: {0}", ex1.Message);
             try
             {
                 encoding = Encoding.GetEncoding(ISO_8859_1_PAGE);
             }
             catch (Exception ex2)
             {
                 log.Debug("Could not set encoding to ISO-8859-1: {0}", ex2.Message);
                 encoding = Encoding.ASCII;
             }
         }
     }
     this.encoding = encoding;
     log.Info("Command encoding=" + encoding.ToString());
     writer = new StreamWriter(stream, encoding);
     reader = new StreamReader(stream, encoding);
 }