Наследование: MonoBehaviour
Пример #1
3
        private static S3File UploadImage(string key, Stream inputStream)
        {
            var s3Config = new AmazonS3Config() { ServiceURL = "http://" + _s3_bucket_region };
            using (var cli = new AmazonS3Client(
                _s3_access_key,
                _s3_secret_access_key,
                s3Config))
            {
                PutObjectRequest req = new PutObjectRequest()
                {
                    BucketName = _s3_bucket_name,
                    ContentType = "image/jpg",
                    InputStream = inputStream,
                    Key = key,
                    CannedACL = S3CannedACL.PublicRead
                };

                var response = cli.PutObject(req);
                if (response.HttpStatusCode != System.Net.HttpStatusCode.OK)
                {
                    throw new Exception("s3: upload failed.");
                }
                else
                {
                    return new S3File()
                    {
                        Key = key,
                        Url = HttpUtility.HtmlEncode(
                            String.Format("http://{0}.{1}/{2}", _s3_bucket_name, _s3_bucket_region, key))
                    };
                }
            }
        }
Пример #2
1
		public static int IntPtrCopy(IntPtr source, Stream dest, int length)
		{
			var buffer = new Byte[length];
			Marshal.Copy(source, buffer, 0, length);
			dest.Write(buffer, 0, length);
			return length;
		}
Пример #3
1
 private static string ReadStream(Stream stream)
 {
     using (var reader = new StreamReader(stream, Encoding.UTF8))
     {
         return reader.ReadToEnd();
     }
 }
        /// <inheritdoc/>
        public Object Read(Stream mask0)
        {
            var result = new TrainingContinuation();
            var ins0 = new EncogReadHelper(mask0);
            EncogFileSection section;

            while ((section = ins0.ReadNextSection()) != null)
            {
                if (section.SectionName.Equals("CONT")
                    && section.SubSectionName.Equals("PARAMS"))
                {
                    IDictionary<String, String> paras = section.ParseParams();

                    foreach (String key  in  paras.Keys)
                    {
                        if (key.Equals("type", StringComparison.InvariantCultureIgnoreCase))
                        {
                            result.TrainingType = paras[key];
                        }
                        else
                        {
                            double[] list = EncogFileSection
                                .ParseDoubleArray(paras, key);
                            result.Put(key, list);
                        }
                    }
                }
            }

            return result;
        }
Пример #5
1
        private string CheckMetaCharSetAndReEncode(Stream memStream, string html)
        {
            Match m = new Regex(@"<meta\s+.*?charset\s*=\s*(?<charset>[A-Za-z0-9_-]+)", RegexOptions.Singleline | RegexOptions.IgnoreCase).Match(html);
            if (m.Success)
            {
                string charset = m.Groups["charset"].Value.ToLower() ?? "iso-8859-1";
                if ((charset == "unicode") || (charset == "utf-16"))
                {
                    charset = "utf-8";
                }

                try
                {
                    Encoding metaEncoding = Encoding.GetEncoding(charset);
                    if (Encoding != metaEncoding)
                    {
                        memStream.Position = 0L;
                        StreamReader recodeReader = new StreamReader(memStream, metaEncoding);
                        html = recodeReader.ReadToEnd().Trim();
                        recodeReader.Close();
                    }
                }
                catch (ArgumentException)
                {
                }
            }

            return html;
        }
Пример #6
1
 public override int Read(byte[] buffer, int offset, int count)
 {
     if (current == null && streams.Count == 0)
     {
         return -1;
     }
     if (current == null)
     {
         current = streams.Dequeue();
     }
     int totalRead = 0;
     while (totalRead < count)
     {
         int read = current.Read(buffer, offset + totalRead, count - totalRead);
         if (read <= 0)
         {
             if (streams.Count == 0)
             {
                 return totalRead;
             }
             else
             {
                 current = streams.Dequeue();
             }
         }
         totalRead += read;
     }
     return totalRead;
 }
Пример #7
1
 private void UpdateMainListFromStream(Stream s)
 {
     using (s)
     {
         _mainList = ParserFactory.ParseMainListData(s);
     }
 }
Пример #8
1
		/// <summary>
		/// Creates texture atlas from stream.
		/// </summary>
		/// <param name="device"></param>
		public TextureAtlas ( RenderSystem rs, Stream stream, bool useSRgb = false )
		{
			var device = rs.Game.GraphicsDevice;

			using ( var br = new BinaryReader(stream) ) {
			
				br.ExpectFourCC("ATLS", "texture atlas");
				
				int count = br.ReadInt32();
				
				for ( int i=0; i<count; i++ ) {
					var element = new Element();
					element.Index	=	i;
					element.Name	=	br.ReadString();
					element.X		=	br.ReadInt32();
					element.Y		=	br.ReadInt32();
					element.Width	=	br.ReadInt32();
					element.Height	=	br.ReadInt32();

					elements.Add( element );
				}				

				int ddsFileLength	=	br.ReadInt32();
				
				var ddsImageBytes	=	br.ReadBytes( ddsFileLength );

				texture	=	new UserTexture( rs, ddsImageBytes, useSRgb );
			}


			dictionary	=	elements.ToDictionary( e => e.Name );
		}
Пример #9
1
 private static object Load(Stream stream)
 {
     var pc = new ParserContext();
     MethodInfo loadBamlMethod = typeof (XamlReader).GetMethod("LoadBaml",
         BindingFlags.NonPublic | BindingFlags.Static);
     return loadBamlMethod.Invoke(null, new object[] {stream, pc, null, false});
 }
Пример #10
1
        /// <inheritdoc/>
        public async Task<Uri> UploadMessageAsync(Stream content, DateTime expirationUtc, string contentType, string contentEncoding, IProgress<int> bytesCopiedProgress, CancellationToken cancellationToken = default(CancellationToken))
        {
            Requires.NotNull(content, "content");
            Requires.Range(expirationUtc > DateTime.UtcNow, "expirationUtc");

            string blobName = Utilities.CreateRandomWebSafeName(DesktopUtilities.BlobNameLength);
            if (expirationUtc < DateTime.MaxValue)
            {
                DateTime roundedUp = expirationUtc - expirationUtc.TimeOfDay + TimeSpan.FromDays(1);
                blobName = roundedUp.ToString("yyyy.MM.dd") + "/" + blobName;
            }

            var blob = this.container.GetBlockBlobReference(blobName);

            // Set metadata with the precise expiration time, although for efficiency we also put the blob into a directory
            // for efficient deletion based on approximate expiration date.
            if (expirationUtc < DateTime.MaxValue)
            {
                blob.Metadata["DeleteAfter"] = expirationUtc.ToString(CultureInfo.InvariantCulture);
            }

            blob.Properties.ContentType = contentType;
            blob.Properties.ContentEncoding = contentEncoding;

            await blob.UploadFromStreamAsync(content.ReadStreamWithProgress(bytesCopiedProgress), cancellationToken);
            return blob.Uri;
        }
Пример #11
1
 public BoundedStream(Stream stream, long offset, long length)
 {
     mStream = stream;
     mOffset = offset;
     mLength = length;
     mPosition = 0;
 }
Пример #12
1
        public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
        {
            Mixin.CheckModule (module);
            Mixin.CheckStream (symbolStream);

            return new PdbReader (Disposable.NotOwned (symbolStream));
        }
        public static IncomingTransportMessage Deserialize(string messageId, Stream inputStream)
        {
            var headers = new Dictionary<string, string>();
            var serializedMessageData = "";
            using (var reader = new XmlTextReader(inputStream))
            {
                reader.WhitespaceHandling = WhitespaceHandling.None;
                reader.Read(); // read <root>
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        var elementName = reader.Name;
                        reader.Read(); // read the child;
                        while (reader.NodeType == XmlNodeType.Element)
                        {
                            // likely an empty header element node
                            headers.Add(elementName, reader.Value);

                            elementName = reader.Name;
                            reader.Read(); // read the child;
                        }
                        if (string.Equals(elementName, "body", StringComparison.InvariantCultureIgnoreCase) && reader.NodeType == XmlNodeType.CDATA)
                        {
                            serializedMessageData = reader.Value;
                        }
                        else if (reader.NodeType == XmlNodeType.Text)
                        {
                            headers.Add(elementName, reader.Value);
                        }
                    }
                }
            }
            return new IncomingTransportMessage(messageId, headers, serializedMessageData);
        }
Пример #14
1
        static Map LoadHeaderInternal( Stream stream ) {
            BinaryReader bs = new BinaryReader( stream );

            byte version = bs.ReadByte();
            if( version != 1 && version != 2 ) throw new MapFormatException();

            Position spawn = new Position();

            // Read in the spawn location
            spawn.X = (short)(IPAddress.NetworkToHostOrder( bs.ReadInt16() ) * 32);
            spawn.H = (short)(IPAddress.NetworkToHostOrder( bs.ReadInt16() ) * 32);
            spawn.Y = (short)(IPAddress.NetworkToHostOrder( bs.ReadInt16() ) * 32);

            // Read in the spawn orientation
            spawn.R = bs.ReadByte();
            spawn.L = bs.ReadByte();

            // Read in the map dimesions
            int widthX = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
            int widthY = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
            int height = IPAddress.NetworkToHostOrder( bs.ReadInt16() );

            Map map = new Map( null, widthX, widthY, height, false );
            map.SetSpawn( spawn );

            return map;
        }
 /// <summary>
 /// Creates a new instance of <see cref="MockClientHttpResponse"/>.
 /// </summary>
 /// <param name="body">The body of the response as a stream.</param>
 /// <param name="headers">The response headers.</param>
 /// <param name="statusCode">The response status code.</param>
 /// <param name="statusDescription">The response status description.</param>
 public MockClientHttpResponse(Stream body, HttpHeaders headers, HttpStatusCode statusCode, string statusDescription)
 {
     this.body = body;
     this.headers = headers;
     this.statusCode = statusCode;
     this.statusDescription = statusDescription;
 }
        public override byte[] Handle(string path, Stream requestData,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            // path = /wifi/...
            //m_log.DebugFormat("[Wifi]: path = {0}", path);
            //m_log.DebugFormat("[Wifi]: ip address = {0}", httpRequest.RemoteIPEndPoint);
            //foreach (object o in httpRequest.Query.Keys)
            //    m_log.DebugFormat("  >> {0}={1}", o, httpRequest.Query[o]);

            string result = string.Empty;
            try
            {
                Request request = RequestFactory.CreateRequest(string.Empty, httpRequest, Localization.GetLanguageInfo(httpRequest.Headers.Get("accept-language")));
                Environment env = new Environment(request);

                result = m_WebApp.Services.LogoutRequest(env);

                httpResponse.ContentType = "text/html";
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[LOGOUT HANDLER]: Exception {0}: {1}", e.Message, e.StackTrace);
            }

            return WebAppUtils.StringToBytes(result);
        }
Пример #17
1
        /// <summary>
        /// Initializes a new instance of the BZip2DecoderStream class.
        /// </summary>
        /// <param name="stream">The compressed input stream.</param>
        /// <param name="ownsStream">Whether ownership of stream passes to the new instance.</param>
        public BZip2DecoderStream(Stream stream, Ownership ownsStream)
        {
            _compressedStream = stream;
            _ownsCompressed = ownsStream;

            _bitstream = new BigEndianBitStream(new BufferedStream(stream));

            // The Magic BZh
            byte[] magic = new byte[3];
            magic[0] = (byte)_bitstream.Read(8);
            magic[1] = (byte)_bitstream.Read(8);
            magic[2] = (byte)_bitstream.Read(8);
            if (magic[0] != 0x42 || magic[1] != 0x5A || magic[2] != 0x68)
            {
                throw new InvalidDataException("Bad magic at start of stream");
            }

            // The size of the decompression blocks in multiples of 100,000
            int blockSize = (int)_bitstream.Read(8) - 0x30;
            if (blockSize < 1 || blockSize > 9)
            {
                throw new InvalidDataException("Unexpected block size in header: " + blockSize);
            }

            blockSize *= 100000;

            _rleStream = new BZip2RleStream();
            _blockDecoder = new BZip2BlockDecoder(blockSize);
            _blockBuffer = new byte[blockSize];

            if (ReadBlock() == 0)
            {
                _eof = true;
            }
        }
 public void SerializeRequest(Stream stm, XmlRpcRequest request)
 {
     var xtw = XmlRpcXmlWriter.Create(stm, XmlRpcFormatSettings);
     xtw.WriteStartDocument();
     xtw.WriteStartElement(string.Empty, "methodCall", string.Empty);
     {
         var mappingActions = new MappingActions();
         mappingActions = GetTypeMappings(request.Mi, mappingActions);
         mappingActions = GetMappingActions(request.Mi, mappingActions);
         WriteFullElementString(xtw, "methodName", request.Method);
         if (request.Args.Length > 0 || UseEmptyParamsTag)
         {
             xtw.WriteStartElement("params");
             try
             {
                 if (!IsStructParamsMethod(request.Mi))
                     SerializeParams(xtw, request, mappingActions);
                 else
                     SerializeStructParams(xtw, request, mappingActions);
             }
             catch (XmlRpcUnsupportedTypeException ex)
             {
                 throw new XmlRpcUnsupportedTypeException(
                     ex.UnsupportedType,
                     string.Format(
                         "A parameter is of, or contains an instance of, type {0} which cannot be mapped to an XML-RPC type",
                         ex.UnsupportedType));
             }
             WriteFullEndElement(xtw);
         }
     }
     WriteFullEndElement(xtw);
     xtw.Flush();
 }
Пример #19
1
        private UnzipCode UnzipFileHandler(string fileName, Stream fileStream)
        {
            fileName = fileName.ToLower();
            if (fileName.EndsWith(".cfg") ||
                fileName.EndsWith("local.ip") ||
                fileName.EndsWith("password") ||
                fileName.EndsWith(".bat") ||
                fileName.EndsWith(".settings"))
            {
                if (this.NeedUpdateConfigFiles)
                {
                    if (fileStream != null)
                    {
                        WriteFile(fileStream, this.destPath + "\\" + fileName);
                    }
                    return UnzipCode.Compare;
                }
                return UnzipCode.Ignore;
            }

            if (fileName.EndsWith("scada.update.exe") || 
                (fileName.EndsWith("scada.watch.exe") && this.UpdateByWatch) ||
                fileName.EndsWith("icsharpcode.sharpziplib.dll"))
            {
                Console.WriteLine("File <" + fileName + "> In use:!");
                UpdateLog.Instance().AddName(fileName + " <iu>");
                return UnzipCode.Ignore;
            }

            return UnzipCode.None;
        }
        // called before MediaOpened is raised, and when the Media pipeline is building a topology
        protected override void OnAcquireLicense(Stream licenseChallenge, Uri licenseServerUri)
        {
            StreamReader objStreamReader = new StreamReader(licenseChallenge);
            challengeString = objStreamReader.ReadToEnd();

            // set License Server URL, based on whether there is an override
            Uri resolvedLicenseServerUri;
            if (LicenseServerUriOverride == null)
                resolvedLicenseServerUri = licenseServerUri;
            else
                resolvedLicenseServerUri = LicenseServerUriOverride;

            //SMFPlayer bug: converting & to &amp; in query string parameters. This line fixes it.
            resolvedLicenseServerUri = new Uri(System.Windows.Browser.HttpUtility.HtmlDecode(resolvedLicenseServerUri.AbsoluteUri));

            //construct HttpWebRequest to license server
            HttpWebRequest objHttpWebRequest = WebRequest.Create(resolvedLicenseServerUri) as HttpWebRequest;
            objHttpWebRequest.Method = "POST";
            objHttpWebRequest.ContentType = "application/xml";
            //The headers below are necessary so that error handling and redirects are handled properly via the Silverlight client.
            objHttpWebRequest.Headers["msprdrm_server_redirect_compat"] = "false";
            objHttpWebRequest.Headers["msprdrm_server_exception_compat"] = "false";

            if (AddAuthorizationToken)
            {                
                string token = Token;
                objHttpWebRequest.Headers["Authorization"] = token;   //e.g.: Bearer=urn:microsoft:azure:mediaservices:contentkeyidentifier=42b3ddc1-2b93-4813-b50b-af1ec3c9c771&urn%3aServiceAccessible=service&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fnimbusvoddev.accesscontrol.windows.net%2f&Audience=urn%3atest&ExpiresOn=1406385025&Issuer=http://testacs.com&HMACSHA256=kr1fHp0chSNaMcRimmENpk1E8LaS1ufknb8mR3xQhx4%3d
            }

            //  Initiate getting request stream  
            IAsyncResult objIAsyncResult = objHttpWebRequest.BeginGetRequestStream(new AsyncCallback(RequestStreamCallback), objHttpWebRequest);
        }
Пример #21
1
 protected int ReadByteAfterWhitespace(Stream s)
 {
     int buff = s.ReadByte();
     while (buff >= 0 && IsWhitespace(buff))
         buff = s.ReadByte();
     return buff;
 }
        void IExtension.EndAppend(Stream stream, bool commit)
        {
            using (stream)
            {
                int len;
                if (commit && (len = (int)stream.Length) > 0)
                {
                    MemoryStream ms = (MemoryStream)stream;

                    if (buffer == null)
                    {   // allocate new buffer
                        buffer = ms.ToArray();
                    }
                    else
                    {   // resize and copy the data
                        // note: Array.Resize not available on CF
                        int offset = buffer.Length;
                        byte[] tmp = new byte[offset + len];
                        Buffer.BlockCopy(buffer, 0, tmp, 0, offset);
                        Buffer.BlockCopy(ms.GetBuffer(), 0, tmp, offset, len);
                        buffer = tmp;
                    }
                }
            }
        }
Пример #23
1
 private static void WriteInt(Stream stream, int value)
 {
     stream.WriteByte((byte)(value));
     stream.WriteByte((byte)(value >> 8));
     stream.WriteByte((byte)(value >> 16));
     stream.WriteByte((byte)(value >> 24));
 }
Пример #24
1
 public LogWriter(Stream stream, bool ownsStream)
 {
     _stream = stream;
     _ownsStream = ownsStream;
     BlockHelper.WriteBlock(_stream, BlockType.MagicBytes, new ArraySegment<byte>(Encoding.ASCII.GetBytes("TeraConnectionLog")));
     BlockHelper.WriteBlock(_stream, BlockType.Start, new ArraySegment<byte>(new byte[0]));
 }
Пример #25
1
 public KinectReader(Stream fileStream, int width, int height)
 {
     this.Width = width;
     this.Height = height;
     this.reader = new BinaryReader(fileStream);
     this.createIndexes();
 }
Пример #26
1
 public static void SaveDrawing(Drawing drawing, Stream stream)
 {
     using (var writer = XmlWriter.Create(stream, XmlSettings))
     {
         SaveDrawing(drawing, writer);
     }
 }
        public void Send(string remoteUrl, IDictionary<string, string> headers, Stream data)
        {
            var request = WebRequest.Create(remoteUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers = Encode(headers);
            request.UseDefaultCredentials = true;
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                data.CopyTo(stream);
            }

            HttpStatusCode statusCode;

            //todo make the receiver send the md5 back so that we can double check that the transmission went ok
            using (var response = (HttpWebResponse) request.GetResponse())
            {
                statusCode = response.StatusCode;
            }

            Logger.Debug("Got HTTP response with status code " + statusCode);

            if (statusCode != HttpStatusCode.OK)
            {
                Logger.Warn("Message not transferred successfully. Trying again...");
                throw new Exception("Retrying");
            }
        }
Пример #28
0
        public static void TransformFile(byte[] key, byte[] iv, Stream dstfs, Stream srcfs, long offset, long length)
        {
            var aes = new Aes128Ctr(key, iv);
            var counter = BitConverter.ToUInt64(aes._iv.Reverse().ToArray(), 0); //get the nonce

            byte[] buffer;
            long buffersize = 1024 * 1024 * 4;
            while (offset > 0)
            {
                buffersize = offset > buffersize ? buffersize : offset;
                buffer = new byte[buffersize];
                srcfs.Read(buffer, 0, (int)buffersize);
                counter = aes.TransformBlock(buffer, counter);
                offset -= buffersize;
            }
            buffersize = 1024 * 1024 * 4;
            while (length > 0)
            {
                buffersize = length > buffersize ? buffersize : length;
                buffer = new byte[buffersize];
                srcfs.Read(buffer, 0, (int)buffersize);
                counter = aes.TransformBlock(buffer, counter);
                dstfs.Write(buffer, 0, (int)buffersize);
                length -= buffersize;
            }
        }
Пример #29
0
 public virtual void Write(
     Stream zOut)
 {
     Stream inStr = Read();
     Streams.PipeAll(inStr, zOut);
     inStr.Close();
 }
Пример #30
0
        public override void Handle(string requested, Stream stream)
        {
            uint photo_id = uint.Parse (requested);
            Photo photo = App.Instance.Database.Photos.Get (photo_id);

            SendImage (photo, stream);
        }
        /// <summary>
        /// Writes Queue service properties to a stream, formatted in XML.
        /// </summary>
        /// <param name="properties">A <see cref="ServiceProperties"/> object.</param>
        /// <param name="outputStream">The <see cref="System.IO.Stream"/> object to which the formatted properties are to be written.</param>
        public static void WriteServiceProperties(ServiceProperties properties, Stream outputStream)
        {
            CommonUtility.AssertNotNull("properties", properties);

            properties.WriteServiceProperties(outputStream);
        }
Пример #32
0
 private static void Serialize(object toSerialize, Stream stream)
 {
     XamlServices.Save(stream, toSerialize);
     stream.Seek(0, SeekOrigin.Begin);
 }
Пример #33
0
 public static void Write(this Stream stream, string content)
 {
     using (var writer = new StreamWriter(stream))
         writer.Write(content);
 }
Пример #34
0
 public virtual void SetAuth(HttpWebRequest request, Stream body)
 {
 }
Пример #35
0
        /// <summary>
        /// Http方式下载文件
        /// </summary>
        /// <param name="url">http地址</param>
        /// <param name="localfile">本地文件</param>
        /// <returns></returns>
        public bool Download(string url, string localfile)
        {
            bool flag = false;
            long startPosition = 0; // 上次下载的文件起始位置
            FileStream writeStream; // 写入本地文件流对象

            long remoteFileLength = GetHttpLength(url);// 取得远程文件长度
            //System.Console.WriteLine("remoteFileLength=" + remoteFileLength);
            if (remoteFileLength == 745)
            {
                System.Console.WriteLine("远程文件不存在.");
                return false;
            }

            // 判断要下载的文件夹是否存在
            if (File.Exists(localfile))
            {

                writeStream = File.OpenWrite(localfile);             // 存在则打开要下载的文件
                startPosition = writeStream.Length;                  // 获取已经下载的长度

                if (startPosition >= remoteFileLength)
                {
                    System.Console.WriteLine("本地文件长度" + startPosition + "已经大于等于远程文件长度" + remoteFileLength);
                    writeStream.Close();

                    return false;
                }
                else
                {
                    writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
                }
            }
            else
            {
                writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
                startPosition = 0;
            }


            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接

                if (startPosition > 0)
                {
                    myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
                }


                Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流


                byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
                int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次

                long currPostion = startPosition;

                while (contentSize > 0)// 如果读取长度大于零则继续读
                {
                    currPostion += contentSize;
                    int percent = (int)(currPostion * 100 / remoteFileLength);
                    System.Console.WriteLine("percent=" + percent + "%");

                    writeStream.Write(btArray, 0, contentSize);// 写入本地文件
                    contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
                }

                //关闭流
                writeStream.Close();
                readStream.Close();

                flag = true;        //返回true下载成功
            }
            catch (Exception)
            {
                writeStream.Close();
                flag = false;       //返回false下载失败
            }

            return flag;
        }
Пример #36
0
		public override void PreLoad(Stream stream, Format format, Handler handler)
		{
			base.PreLoad(stream, format, handler);
			SetBGI(handler as RipHandler);
		}
Пример #37
0
		protected override void LoadingAnimated(Stream stream, Format format, Handler handler)
		{
			base.LoadingAnimated(stream, format, handler);
			
			SetBGI(handler as RipHandler);
		}
Пример #38
0
  public int Run(string[] args){
    this.exitCode = 0;

    try{
      this.fPrintBanner = true;
      this.fBannerPrinted = false;
      this.fPrintTargets = false;
      this.fHelp = false;
      this.fUtf8Output = false;
      this.targets = new ArrayList();
      this.currentTarget = null;

      if (args.Length == 0){
        PrintUsage();
        return 0;
      }
      // preprocess the entire command line before compilation begins
      this.ParseArguments(args, false);

      // set the encoding option here in case the user wants help in UTF-8
      if (this.fUtf8Output){
        Stream s = Console.OpenStandardOutput();
        StreamWriter sw = new StreamWriter(s, new System.Text.UTF8Encoding(false));
        sw.AutoFlush = true;
        Console.SetOut(TextWriter.Synchronized(sw));
      }
      // do not compile if help is asked for
      if (this.fHelp){
        PrintUsage();
        return 0;
      }
      // final error checking before beginning compilation
      foreach(CompilerOptions target in this.targets){
        if (target.SourceFileNames.Count == 0)
          throw new CmdLineException(CmdLineError.NoInputSourcesSpecified, JScriptCompiler.GetCultureInfo());
      }
      // We will print out the names of the files we are generating if
      // there there are multiple compilations
      if (this.targets.Count > 1)
        this.fPrintTargets = true;

      PrintBanner();

      foreach(CompilerOptions target in this.targets){
        if (!target.fForceCodepage){
          // set the codepage if and only if the codepage hasn't been set explicitly
          target.codepage = JScriptCompiler.GetCultureInfo().TextInfo.ANSICodePage;
        }
        if (target.strOutputFileName == null){
          string outputName = Path.GetFileNameWithoutExtension((string)target.SourceFileNames[0]);
          target.strOutputFileName = outputName + (target.PEFileKind == PEFileKinds.Dll? ".dll" : ".exe");
        }
        if (!Compile(target))
          this.exitCode = 10;
      }
    }catch(CmdLineException e){
      PrintBanner();
      Console.WriteLine(e.Message);
      this.exitCode = 10;
    }catch(Exception e){
      PrintBanner();
      Console.WriteLine("fatal error JS2999: " + e.Message);
      this.exitCode = 10;
    }
    return this.exitCode;
  }
Пример #39
0
 /// <summary>Loads the Google client secret from the input stream.</summary>
 public static GoogleClientSecrets Load(Stream stream)
 {
     return(NewtonsoftJsonSerializer.Instance.Deserialize <GoogleClientSecrets>(stream));
 }
Пример #40
0
    private void OnGetResponse(IAsyncResult asyncResult)
    {
        responseReceived = true;
        Debug.Log("OnGetResponse");
        byte[] imageBuffer = new byte[1024 * 1024];

        Debug.Log("Starting request");
        // get the response
        HttpWebRequest req = (HttpWebRequest)asyncResult.AsyncState;

        try
        {
            Debug.Log("OnGetResponse try entered.");
            HttpWebResponse resp = (HttpWebResponse)req.EndGetResponse(asyncResult);
            Debug.Log("response received");
            // find our magic boundary value
            string contentType = resp.Headers["Content-Type"];
            if (!string.IsNullOrEmpty(contentType) && !contentType.Contains("="))
            {
                Debug.Log("MJPEG Exception thrown");
                throw new Exception("Invalid content-type header.  The camera is likely not returning a proper MJPEG stream.");
            }

            string boundary      = resp.Headers["Content-Type"].Split('=')[1].Replace("\"", "");
            byte[] boundaryBytes = Encoding.UTF8.GetBytes(boundary.StartsWith("--") ? boundary : "--" + boundary);

            Stream       s  = resp.GetResponseStream();
            BinaryReader br = new BinaryReader(s);

            _streamActive = true;
            while (_streamActive)
            {
                byte[] prova = br.ReadBytes(100);

                int    lengthOffset = 54;
                String result       = "";
                while (true)
                {
                    byte c = prova[lengthOffset];
                    if (c < 48 || c > 57)
                    {
                        break;
                    }
                    result += (c - 48);
                    lengthOffset++;
                }
                int imageLength = Convert.ToInt32(result);

                int startImage    = FindBytes(prova, JpegHeader);
                int copiedToImage = prova.Length - startImage;
                Array.Copy(prova, startImage, imageBuffer, 0, copiedToImage);

                int    restOfImageLength = imageLength - copiedToImage + 2;
                byte[] restOfImage       = br.ReadBytes(restOfImageLength);

                Array.Copy(restOfImage, 0, imageBuffer, prova.Length - startImage, restOfImage.Length);
                CurrentFrame = imageBuffer;
                if (FrameReady != null)
                {
                    FrameReady(this, new FrameReadyEventArgs());
                }

                if (!_streamActive)
                {
                    Debug.Log("CLOSING");
                    resp.Close();
                    break;
                }
            }

            resp.Close();
        }
        catch (Exception ex)
        {
            Debug.Log($"Errore {ex.StackTrace}");
            if (Error != null)
            {
                _context.Post(delegate { Error(this, new ErrorEventArgs()
                    {
                        Message = ex.Message
                    }); }, null);
            }

            return;
        }
    }
Пример #41
0
        private async void StartClient()
        {
            int i = 0;

            while (true)
            {
                if (!UWconnectedflag)
                {
                    UI_Stream_ready_flag = false;
                    DRBE_softwarePage.UI_Stream_ready_flag = false;
                    DRBE_ap.UI_Stream_ready_flag           = false;
                    try
                    {
                        // Create the StreamSocket and establish a connection to the echo server.
                        DRBE_frontPage.Statues_tb.Text += "\r\n Client Try to Connect";
                        await Task.Delay(300);

                        await UWstreamsocket.ConnectAsync(UWhostname, UWPportnumber);

                        DRBE_frontPage.Statues_tb.Text += "\r\n Client Connected: " + UWstreamsocket.Information.LocalAddress.ToString();

                        DRBE_frontPage.DRBE_controlpanel.Message_tb.Text        += "\r\n" + DateTime.Now.ToString("HH: mm: ss~~") + "Server Connected";
                        DRBE_frontPage.DRBE_controlpanel.Server_ui_tb.Text       = "Connected";
                        DRBE_frontPage.DRBE_controlpanel.Server_ui_tb.Foreground = green_bright_button_brush;


                        UWconnectedflag = true;

                        UWoutputstream = UWstreamsocket.OutputStream.AsStreamForWrite();
                        UWinputstream  = UWstreamsocket.InputStream.AsStreamForRead();

                        UWbinarywriter = new BinaryWriter(UWoutputstream);
                        UWbinaryreader = new BinaryReader(UWinputstream);

                        DRBE_softwarePage.UWbinarywriter       = UWbinarywriter;
                        DRBE_softwarePage.UI_Stream_ready_flag = true;

                        DRBE_ap.UWbinarywriter       = UWbinarywriter;
                        DRBE_ap.UI_Stream_ready_flag = true;

                        UI_Stream_ready_flag = true;
                        testpacket           = new List <byte>(mpacket.Pass(new List <byte>()));

                        await Task.Delay(500);

                        //UWbinarywriter.Write(testpacket.ToArray(), 0, 255);
                        //UWbinarywriter.Flush();
                        StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                        string        path          = storageFolder.Path;
                        List <byte>   tosend        = new List <byte>();
                        byte[]        tbytes        = Encoding.ASCII.GetBytes(path);
                        tosend = new List <byte>(tbytes);
                        UInt16 totallen = Convert.ToUInt16(tosend.Count() + 3);
                        tosend.Insert(0, BitConverter.GetBytes(totallen)[0]);
                        tosend.Insert(0, BitConverter.GetBytes(totallen)[1]);
                        tosend.Insert(0, 0x90);
                        UWbinarywriter.Write(tosend.ToArray(), 0, tosend.Count);
                        UWbinarywriter.Flush();

                        ClientReading();
                        break;
                    }
                    catch (Exception ex)
                    {
                        await Task.Delay(1000);

                        i++;
                    }
                }
            }
            //}
        }
Пример #42
0
        public ZInputStream(Stream input, int level)
            : this(input, level, false)
		{
        }
Пример #43
0
		public ZInputStream(Stream input)
			: this(input, false)
		{
		}
Пример #44
0
		public ZInputStream(Stream input, bool nowrap)
            : this(input, GetDefaultZStream(nowrap))
		{
		}
Пример #45
0
 /// <param name="downloadFileStream"></param>
 /// <param name="mediaType">Media type for the data in the stream</param>
 public DownloadFile(Stream downloadFileStream)
 {
     DownloadFileStream = downloadFileStream;
 }
Пример #46
0
 public static void WriteMessageContent(string messageContent, Stream outputStream)
 {
     throw new System.NotImplementedException();
 }
Пример #47
0
        public byte[] GetData(string search, string count)
        {
            int.TryParse(count, out int countSave); 
            var result = new StringBuilder();

            if (search != null)
                search = search.Replace(" ", "%20");

            var res = string.Format("{0}{1}{2}", URL_FOR_DATA , search, SAVE_FORMAT);

            var request = (HttpWebRequest)WebRequest.Create(res);
            request.UserAgent = "anyone";
            var response = (HttpWebResponse)request.GetResponse();

            using (Stream responseStream = response.GetResponseStream())
            using (StreamReader htmlStream = new StreamReader(responseStream, Encoding.UTF8)) 
            {
                var isStart = false;
                var isEnd = false;
                var isWrite = true;
                var coordinates = string.Empty;
                var countCoordinates = 0;
                var previousSymbol = ' ';
                var currentSymbol = ' ';
                while (!htmlStream.EndOfStream)
                {
                    previousSymbol = currentSymbol;
                    currentSymbol = (char)htmlStream.Read();

                    if ((previousSymbol == '[') && (currentSymbol == '[') ||
                        (previousSymbol == ':') && (currentSymbol == '['))
                    {
                        countCoordinates = 0;
                    }

                    if ((previousSymbol == '[') && char.IsDigit(currentSymbol))
                    {
                        var resultLength = result.Length;

                        isStart = true;
                        isWrite = false;
                        coordinates += previousSymbol;

                        // remove excess ',' or ',['
                        if (result[resultLength - 2] == ',')
                        {
                            result.Remove(resultLength - 2, 2);
                        }
                        else
                        {
                            result.Remove(resultLength - 1, 1);
                        }
                    }
                    if (isStart)
                    {
                        coordinates += currentSymbol;
                    }
                    if (char.IsDigit(previousSymbol) && (currentSymbol == ']') && isStart)
                    {
                        isEnd = true;
                        countCoordinates++;
                    }

                    if (isWrite)
                        result.Append(currentSymbol);

                    if (isStart && isEnd)
                    {
                        if (countCoordinates == 1)
                        {
                            result.Append(coordinates);
                        }
                        else if(countCoordinates % countSave == 1)
                        {
                            result.Append(',');
                            result.Append(coordinates);
                        }
                        isEnd = false;
                        isStart = false;
                        isWrite = true;
                        coordinates = string.Empty;
                    }

                }
                return Encoding.UTF8.GetBytes(result.ToString()); ;
            }
        }        
Пример #48
0
 public static void WriteSharedAccessIdentifiers(SharedAccessQueuePolicies sharedAccessPolicies, Stream outputStream)
 {
     throw new System.NotImplementedException();
 }
Пример #49
0
		protected override void SaveStream(Stream stream, Format format, Handler handler)
		{
			var formatRip = (FormatRip)format;
			formatRip.Save(stream, this);
		}
Пример #50
0
        /// <summary>
        /// Dies Methode hält die Kommuniktion mit dem Client aufrecht, um den Synchronisierungsfortschritt
        /// pro Foto in den Ausgabefluss zu schreiben
        /// </summary>
        /// <param name="stream">Der Stream mit dem Client</param>
        /// <param name="content">Der Inhalt des Streams. Wird nicht verwendet, ist aber für den Aufruf erfordern</param>
        /// <param name="context">Der Context der Verbindung. Wird nicht verwendet, ist aber für den Aufruf erfordern</param>
        /// <remarks>Es ist nicht sichergestellt, dass die Verbindung offen bleibt. Außerdem ist unklar wie die Browser auf den
        /// Flush reaagieren, so dass das Parsen der einzelnen Fortschirttinformatioen <see cref="SynchProgress"/> nicht klar ist</remarks>
        public void OnStreamAvailable(Stream stream, HttpContent content, TransportContext context)
        {
            try
            {
                var serializer = new JsonSerializer();
                var memberId = GetMemberId();
                bool streamIsOpen = true;
                foreach (var currentStep in _connector.RefreshFolderContent())
                {
                    try
                    {
                        NotificationHub.PushNotification(new Notification()
                        {
                            Data = currentStep,
                            Type = NotificationType.PhotoSynch,
                            Date = DateTime.Now,
                            MemberId = memberId,
                            PhotoName = currentStep.Photo == null ? string.Empty : currentStep.Photo.Name,
                            PhotoTitle  = currentStep.Photo == null ? string.Empty : currentStep.Photo.Title 
                        });

                        if (currentStep.Photo != null)
                        {
                            SavePhotosToDatabase(currentStep.Photo);
                        }

                        if (!streamIsOpen) continue;

                        using (var writer = new StreamWriter(stream))
                        {
                            if (currentStep.Photo != null)
                            {
                                dynamic currentPhoto = new
                                {
                                    currentStep.Photo.Id,
                                    currentStep.Photo.Title,
                                    currentStep.Photo.Name,
                                    currentStep.Photo.OriginalName,
                                    currentStep.Photo.MemberId,
                                    currentStep.Photo.IsPrivate,
                                    DirectLinks = currentStep.Photo.DirectLinks.Where(l => l.Size <= 400).ToList(),
                                    currentStep.Photo.Color
                                };
                                dynamic progress = new
                                {
                                    currentStep.TotalFileCount,
                                    currentStep.Index,
                                    Photo = currentPhoto
                                };
                                var returnValue = new Result<object>() { Data = progress };
                                serializer.Serialize(writer, returnValue);
                            }
                            else
                            {
                                var returnValue = new Result<SynchProgress> { Data = currentStep };
                                serializer.Serialize(writer, returnValue);
                            }
                            stream.Flush();
                        }
                    }

                    catch (HttpException ex)
                    {
                        // Die Verbindung zum Client wurde unterbrochen, die Synchronisierung läuft jedoch weiter
                        if (ex.ErrorCode == -2147023667)
                        {
                            streamIsOpen = false;
                        }
                    }
                }
                var notification = new Notification()
                {
                    Type = NotificationType.PhotoSynch,
                    MemberId = memberId,
                    UserAlias = "fotosteam"
                };
                DataRepository.Add(notification);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                var error = new Result<SynchProgress> { Data = new SynchProgress() };
                error.Status.Code = Controller.StatusCode.Failure;
                error.Status.Message = ResultMessages.UnhandledException;
                try
                {
                    using (var writer = new StreamWriter(stream))
                    {
                        var serializer = new JsonSerializer();
                        serializer.Serialize(writer, error);

                    }
                }
                catch (Exception ex1)
                {
                    //Da können wir jetzt auch nicht mehr machen.
                    Log.Error(ex1);
                }

            }
            finally
            {
                // Close output stream as we are done
                stream.Close();
            }
        }
Пример #51
0
        public static void AppendFile(this IVirtualPathProvider pathProvider, string filePath, Stream stream)
        {
            var writableFs = pathProvider as IVirtualFiles;
            if (writableFs == null)
                throw new InvalidOperationException(ErrorNotWritable.Fmt(pathProvider.GetType().Name));

            writableFs.AppendFile(filePath, stream);
        }
 private static VideoDataResult GetResult(Stream stream) => new NicoApiClient().ParseResponse(GetResponse(stream));
Пример #53
0
 public Processor(Stream stream, int?numberOfBytesToConsume)
 {
     this.stream = stream;
     this.numberOfBytesToConsume = numberOfBytesToConsume;
 }
 private static NicoResponse GetResponse(Stream stream)
 {
     using (stream) {
         return(XmlRequest.GetXmlResponse <NicoResponse>(stream));
     }
 }
Пример #55
0
        public override void Decode(Stream input, Stream output)
        {
            using (var br = new BitReader(input, BitOrder.MostSignificantBitFirst, 4, ByteOrder.LittleEndian))
            {
                var uncompressedSize = br.ReadInt32() >> 8;
                br.ReadByte();
                HuffmanReader.BuildTree(br);
                SetupDisplacementTable(br, 3);

                while (output.Length < uncompressedSize)
                {
                    if (br.ReadBit() == 1)
                    {
                        var matchLength = 0;
                        int displacement;

                        var dispIndex = br.ReadBits <byte>(2);
                        if (dispIndex == 3)
                        {
                            // 8098E4C
                            byte readValue;
                            // Add lengthBitCount bit values as long as read values' LSB is set
                            // Seems to be a variable length value
                            do
                            {
                                readValue   = br.ReadBits <byte>(3);
                                matchLength = (matchLength << 2) | (readValue >> 1);
                            } while ((readValue & 0x1) == 1);

                            if (br.ReadBit() == 1)
                            {
                                // 8098E64
                                dispIndex    = br.ReadBits <byte>(2);
                                displacement = GetDisplacement(br, dispIndex) << 1;

                                matchLength = ((matchLength << 3) | br.ReadBits <byte>(3)) + 2;
                                // Goto 8098EA2
                            }
                            else
                            {
                                // 8098E88
                                matchLength++;
                                ReadHuffmanValues(br, output, matchLength, 2);

                                continue;
                            }
                        }
                        else
                        {
                            // 8098E32
                            displacement = GetDisplacement(br, dispIndex) << 1;

                            matchLength = br.ReadBits <byte>(3) + 2;
                            // Goto 8098EA2
                        }

                        // Label 8098EA2
                        ReadDisplacement(output, displacement, matchLength, 2);
                    }
                    else
                    {
                        // 8098E14
                        ReadHuffmanValues(br, output, 1, 2);
                    }
                }
            }
        }
Пример #56
0
 internal void ParseFieldData(uint length, Stream s)
 {
     s.Position     = this.fieldPosition;
     this.fieldData = new DataBlobHandler(requestedApiVersion, handler, length, s);
 }
Пример #57
0
 /// <summary>
 /// Creates a new <see cref="PdfImage"/> object from specified stream, format and optional image effect collection.
 /// </summary>
 /// <param name="stream">Image as stream.</param>
 /// <param name="configuration">An image configuration to apply.</param>
 /// <returns>
 /// A new <see cref="PdfImage"/> reference represents image.
 /// </returns>
 public static PdfImage FromStream(Stream stream, PdfImageConfig configuration = null) => FromImage(NativeImage.FromStream(stream), configuration);
Пример #58
0
        /// <summary>
        /// Checks the stream header if it matches with
        /// any of the supported image file types.
        /// </summary>
        /// <param name="stream">An open stream pointing to an image file.</param>
        /// <returns>true if the stream is an image file (BMP, TIFF, PNG, GIF, JPEG, WMF, EMF, ICO, CUR);
        /// false otherwise.</returns>
        internal static bool IsImage(Stream stream)
        {
            // Sniff some bytes from the start of the stream
            // and check against magic numbers of supported 
            // image file formats
            byte[] header = new byte[8];
            stream.Seek(0, SeekOrigin.Begin);
            if (stream.Read(header, 0, header.Length) != header.Length)
                return false;

            // BMP
            string bmpHeader = Encoding.ASCII.GetString(header, 0, 2);
            if (bmpHeader == "BM") // BM - Windows bitmap
                return true;
            else if (bmpHeader == "BA") // BA - Bitmap array
                return true;
            else if (bmpHeader == "CI") // CI - Color Icon
                return true;
            else if (bmpHeader == "CP") // CP - Color Pointer
                return true;
            else if (bmpHeader == "IC") // IC - Icon
                return true;
            else if (bmpHeader == "PT") // PI - Pointer
                return true;

            // TIFF
            string tiffHeader = Encoding.ASCII.GetString(header, 0, 4);
            if (tiffHeader == "MM\x00\x2a") // Big-endian
                return true;
            else if (tiffHeader == "II\x2a\x00") // Little-endian
                return true;

            // PNG
            if (header[0] == 0x89 && header[1] == 0x50 && header[2] == 0x4E && header[3] == 0x47 &&
                header[4] == 0x0D && header[5] == 0x0A && header[6] == 0x1A && header[7] == 0x0A)
                return true;

            // GIF
            string gifHeader = Encoding.ASCII.GetString(header, 0, 4);
            if (gifHeader == "GIF8")
                return true;

            // JPEG
            if (header[0] == 0xFF && header[1] == 0xD8)
                return true;

            // WMF
            if (header[0] == 0xD7 && header[1] == 0xCD && header[2] == 0xC6 && header[3] == 0x9A)
                return true;

            // EMF
            if (header[0] == 0x01 && header[1] == 0x00 && header[2] == 0x00 && header[3] == 0x00)
                return true;

            // Windows Icons
            if (header[0] == 0x00 && header[1] == 0x00 && header[2] == 0x01 && header[3] == 0x00) // ICO
                return true;
            else if (header[0] == 0x00 && header[1] == 0x00 && header[2] == 0x02 && header[3] == 0x00) // CUR
                return true;

            return false;
        }
Пример #59
0
 protected override void WriteElement(Stream s, Field element)
 {
     throw new NotImplementedException();
 }
Пример #60
0
 private static object Deserialize(Stream stream)
 {
     stream.Seek(0, SeekOrigin.Begin);
     return(XamlServices.Load(stream));
 }