Write() public abstract méthode

public abstract Write ( byte buffer, int offset, int count ) : void
buffer byte
offset int
count int
Résultat void
Exemple #1
0
    /// <summary>
    /// Saves the JPEG image to the given stream. The caller is responsible for
    /// disposing the stream.
    /// </summary>
    /// <param name="stream">The data stream used to save the image.</param>
    public void Save(Stream stream)
    {
      // Write sections
      foreach (JPEGSection section in Sections)
      {
        // Section header (including length bytes and section marker) 
        // must not exceed 64 kB.
        if (section.Header.Length + 2 + 2 > 64 * 1024)
          throw new SectionExceeds64KBException();

        // Write section marker
        stream.Write(new byte[] { 0xFF, (byte)section.Marker }, 0, 2);

        // Write section header
        if (section.Header.Length != 0)
        {
          // Header length including the length field itself
          stream.Write(BitConverterEx.BigEndian.GetBytes((ushort)(section.Header.Length + 2)), 0, 2);

          // Section header
          stream.Write(section.Header, 0, section.Header.Length);
        }

        // Write entropy coded data
        if (section.EntropyData.Length != 0)
          stream.Write(section.EntropyData, 0, section.EntropyData.Length);
      }

      // Write trailing data, if any
      if (TrailingData.Length != 0)
        stream.Write(TrailingData, 0, TrailingData.Length);
    }
Exemple #2
0
        /// <summary>
        /// 将当前的文件数据写入到某个数据流中
        /// </summary>
        /// <param name="stream"></param>
        public void WriteTo(Stream stream)
        {
            byte[] buffer = new byte[512];
            int size = 0;            
            
            if (this.FileStream != null)
            {
                //写入文件流
                while ((size = this.FileStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    stream.Write(buffer, 0, size);
                }
            }

            if (!string.IsNullOrEmpty(this.FilePath)
                && File.Exists(this.FilePath))
            {
                //写入本地文件流
                using (var reader = new FileStream(this.FilePath, FileMode.Open, FileAccess.Read))
                {
                    while ((size = reader.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        stream.Write(buffer, 0, size);
                    }
                }
            }

        }
Exemple #3
0
 /// <summary>
 ///  Writes BSON cstring to stream
 /// </summary>
 public static void WriteCString(Stream stream, string value)
 {
   var buffer = ensureBuffer();
  
   var maxByteCount = value.Length * 2; // UTF8 string length in UNICODE16 pairs
   if (maxByteCount < BUFFER_LENGTH)
   {
     var actual = s_UTF8Encoding.GetBytes(value, 0, value.Length, buffer, 0);
     stream.Write(buffer, 0, actual);
   }
   else
   {
     int charCount;
     var totalCharsWritten = 0;
     while (totalCharsWritten < value.Length)
     {
       charCount = Math.Min(MAX_CHARS_IN_BUFFER, value.Length - totalCharsWritten);
       var count = s_UTF8Encoding.GetBytes(value, totalCharsWritten, charCount, buffer, 0);
       stream.Write(buffer, 0, count);
       totalCharsWritten += charCount;
     }
   }
 
   WriteTerminator(stream);
 }
Exemple #4
0
        public PlateFile2(string filename, int filecount)
        {
            fileStream = File.Open(filename, FileMode.Create);
            //Initialize the header
            header.Signature = 0x17914242;
            header.HashBuckets = NextPowerOfTwo(filecount);
            header.HashTableLocation = Marshal.SizeOf(header);
            header.FirstDirectoryEntry = header.HashTableLocation + header.HashBuckets * 8;
            header.NextFreeDirectoryEntry = header.FirstDirectoryEntry + Marshal.SizeOf(entry);
            header.FileCount = 0;
            header.FreeEntries = header.HashBuckets - 1;

            //Write the header and the empty Hash area. O/S will zero the data
            Byte[] headerData = GetHeaderBytes();
            fileStream.Write(headerData, 0, headerData.Length);
            fileStream.Seek(header.NextFreeDirectoryEntry + Marshal.SizeOf(entry) * header.HashBuckets, SeekOrigin.Begin);
            fileStream.WriteByte(42);

            fileStream.Seek(header.FirstDirectoryEntry, SeekOrigin.Begin);
            entry = new DirectoryEntry();
            entry.size = (uint)header.FreeEntries * (uint)Marshal.SizeOf(entry);
            entry.location = header.FirstDirectoryEntry;
            byte[] entryData = GetEntryBytes();
            fileStream.Write(entryData, 0, entryData.Length);

            fileStream.Seek(0, SeekOrigin.Begin);
        }
Exemple #5
0
        /// <summary>
        /// // TODO
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="data"></param>
        /// <param name="statusCode"></param>
        /// <param name="headers"></param>
        /// <param name="closeConnection">we don’t currently support persistent connection via Http1.1 so closeConnection:true</param>
        /// <returns></returns>
        public static int SendResponse(Stream stream, byte[] data, int statusCode, IDictionary<string,string[]> headers = null, bool closeConnection = true)
        {
            string initialLine = "HTTP/1.1 " + statusCode + " " + StatusCode.GetReasonPhrase(statusCode) + "\r\n";
            string headersPack = initialLine;

            if (headers == null)
                headers = new Dictionary<string,string[]>(StringComparer.OrdinalIgnoreCase);

            if (!headers.ContainsKey("Connection") && closeConnection)
            {
                headers.Add("Connection", new[] { "Close" });
            }

            if (!headers.ContainsKey("Content-Length"))
            {
                headers.Add("Content-Length", new [] { Convert.ToString(data.Length) });
            }

            headersPack = headers.Aggregate(headersPack, (current, header) => current + (header.Key + ": " + String.Join(",", header.Value) + "\r\n")) + "\r\n";

            int sent = stream.Write(Encoding.UTF8.GetBytes(headersPack));
            //Send headers and body separately
            //TODO It's needed for our client. Think out a way to avoid separate sending.
            stream.Flush();

            if (data.Length > 0)
                sent += stream.Write(data);

            Thread.Sleep(200);

            stream.Flush();
            return sent;
        }
Exemple #6
0
        /// <summary>
        /// Reconstructs remote data, given a delta stream and a random access / seekable input stream,
        /// all written to outputStream.
        /// </summary>
        /// <param name="deltaStream">sequential stream of deltas</param>
        /// <param name="inputStream">seekable and efficiently random access stream</param>
        /// <param name="outputStream">sequential stream for output</param>
        public void Receive(Stream deltaStream, Stream inputStream, Stream outputStream)
        {
            if (deltaStream == null) throw new ArgumentNullException("deltaStream");
            if (inputStream == null) throw new ArgumentNullException("inputStream");
            if (outputStream == null) throw new ArgumentNullException("outputStream");
            if (inputStream.CanSeek == false) throw new InvalidOperationException("inputStream must be seekable");

            int commandByte;
            while ((commandByte = deltaStream.ReadByte()) != -1)
            {
                if (commandByte == DeltaStreamConstants.NEW_BLOCK_START_MARKER)
                {
                    int length = deltaStream.ReadInt();
                    var buffer = new byte[length];
                    deltaStream.Read(buffer, 0, length);
                    outputStream.Write(buffer, 0, length);
                }
                else if (commandByte == DeltaStreamConstants.COPY_BLOCK_START_MARKER)
                {
                    long sourceOffset = deltaStream.ReadLong();
                    int length = deltaStream.ReadInt();
                    var buffer = new byte[length];
                    inputStream.Seek(sourceOffset, SeekOrigin.Begin);
                    inputStream.Read(buffer, 0, length);
                    outputStream.Write(buffer, 0, length);
                }
                else throw new IOException("Invalid data found in deltaStream");
            }
        }
        public void SerializeTraceData(TraceData data, Stream stream)
        {
            /* write the magic to the raw stream */
            stream.Write(BitConverter.GetBytes(MAGIC), 0, sizeof(uint));
            stream.Write(BitConverter.GetBytes(VERSION), 0, sizeof(uint));

            /* Write the magic */
            WriteUint(MAGIC);

            /* Write the version */
            WriteUint(VERSION);

            SerializeStatistics(data.Statistics);

            SerializeStackTraces(data.StackTraces);

            SerializeSQLStatements(data.SQLStatements);

            SerializeExecutionCalls(data.AllExecutionCalls);

            WriteLong(data.MaxCallDepth);

            ms.Seek(0, SeekOrigin.Begin);

            using (DeflateStream def = new DeflateStream(stream, CompressionLevel.Optimal))
            {
                ms.CopyTo(def);
            }
        }
            public override bool BuildFrame(MediaFile file, MediaFrame mediaFrame, Stream buffer)
            {
               
                if (mediaFrame.IsBinaryHeader)
                {
                    buffer.Write(_videoCodecHeaderInit,0, _videoCodecHeaderInit.Length);
                }
                else
                {
                    if (mediaFrame.IsKeyFrame)
                    {
                        // video key frame
                        buffer.Write(_videoCodecHeaderKeyFrame, 0,_videoCodecHeaderKeyFrame.Length);
                    }
                    else
                    {
                        //video normal frame
                        buffer.Write(_videoCodecHeader, 0, _videoCodecHeader.Length);
                    }
                    mediaFrame.CompositionOffset = IPAddress.HostToNetworkOrder(mediaFrame.CompositionOffset & 0x00ffffff) >> 8;
                    buffer.Write(BitConverter.GetBytes(mediaFrame.CompositionOffset), 0, 3);
                }

                return base.BuildFrame(file, mediaFrame, buffer);
            }
        public override void Save(Image i, Stream dest)
        {
            dest.WriteByte(0); // Write No Image ID
            dest.WriteByte(0); // Write No Color-Map
            dest.WriteByte(2); // Write Image Type (Uncompressed- True Color)
            byte[] dat = new byte[5];
            dest.Write(dat, 0, 5); // Write Color-Map Spec

            dest.WriteByte(0);
            dest.WriteByte(0); // Write X-Origin
            dest.WriteByte(0);
            dest.WriteByte(0); // Write Y-Origin
            dat = BitConverter.GetBytes((UInt16)i.Width);
            dest.Write(dat, 0, 2); // Write the Width
            dat = BitConverter.GetBytes((UInt16)i.Height);
            dest.Write(dat, 0, 2); // Write the Height
            dest.WriteByte(32); // Write the Color-Depth

            byte ImageDescriptor = 0;
            ImageDescriptor |= 8; // Set 8-Bit Alpha data.
            ImageDescriptor |= (byte)(1 << 5); // Set Top-Left Image origin
            dest.WriteByte(ImageDescriptor); // Write Image Descriptor Byte

            UInt32 len = (uint)(i.Width * i.Height);
            Pixel p;
            for (int loc = 0; loc < len; loc++) // Write the Image Data.
            {
                p = i.Data[loc];
                dest.WriteByte(p.B);
                dest.WriteByte(p.G);
                dest.WriteByte(p.R);
                dest.WriteByte(p.A);
            }
        }
 protected virtual void SendRequest(Stream outputStream)
 {
     byte[] headerBuffer = this._header.ToByte();
     outputStream.Write(headerBuffer, 0, headerBuffer.Length);
     if (_body != null)
         outputStream.Write(this._body, 0, this._body.Length);
 }
Exemple #11
0
		public void Write(Tag tag, Stream apeStream, Stream tempStream) {
			ByteBuffer tagBuffer = tc.Create(tag);

			if (!TagExists(apeStream)) {
				apeStream.Seek(0, SeekOrigin.End);
				apeStream.Write(tagBuffer.Data, 0, tagBuffer.Capacity);
			} else {
				apeStream.Seek( -32 + 8 , SeekOrigin.End);
			
				//Version
				byte[] b = new byte[4];
				apeStream.Read( b , 0,  b.Length);
				int version = Utils.GetNumber(b, 0, 3);
				if(version != 2000) {
					throw new CannotWriteException("APE Tag other than version 2.0 are not supported");
				}
				
				//Size
				b = new byte[4];
				apeStream.Read( b , 0,  b.Length);
				long oldSize = Utils.GetLongNumber(b, 0, 3) + 32;
				int tagSize = tagBuffer.Capacity;
				
				apeStream.Seek(-oldSize, SeekOrigin.End);
				apeStream.Write(tagBuffer.Data, 0, tagBuffer.Capacity);
					
				if(oldSize > tagSize) {
					//Truncate the file
					apeStream.SetLength(apeStream.Length - (oldSize-tagSize));
				}
			}
		}
 public override Stream Write(Stream stream)
 {
     base.Write(stream);
     stream.Write(Topic);
     stream.Write(IsAdd);
     return stream;
 }
Exemple #13
0
 public int GetCrc32AndCopy(Stream input, Stream output)
 {
     if (input == null)
     {
         throw new ZipException("bad input.", new ArgumentException("The input stream must not be null.", "input"));
     }
     byte[] buffer = new byte[0x2000];
     int readSize = 0x2000;
     this._TotalBytesRead = 0;
     int count = input.Read(buffer, 0, readSize);
     if (output != null)
     {
         output.Write(buffer, 0, count);
     }
     this._TotalBytesRead += count;
     while (count > 0)
     {
         this.SlurpBlock(buffer, 0, count);
         count = input.Read(buffer, 0, readSize);
         if (output != null)
         {
             output.Write(buffer, 0, count);
         }
         this._TotalBytesRead += count;
     }
     return (int) ~this._RunningCrc32Result;
 }
        public bool Duplicate(Stream dest, Stream src)
        {
            var decode = new Decode();
            if (!decode.CheckIntegrity(src))
            {
                Console.WriteLine("FIT file integrity failed.");
                return false;
            }

            fitDest = dest;

            // Copy header.
            var header = new Header(src);
            header.Write(fitDest);

            // Copy body.
            decode.MesgDefinitionEvent += this.OnMesgDefinition;
            decode.MesgEvent += this.OnMesg;
            var result = decode.Read(src);

            // Update header. (data size)
            fitDest.Position = 4;
            fitDest.Write(BitConverter.GetBytes((uint)(fitDest.Length - header.Size)), 0, 4);

            // Update CRC.
            var data = new byte[fitDest.Length];
            fitDest.Position = 0;
            fitDest.Read(data, 0, data.Length);
            fitDest.Write(BitConverter.GetBytes(CRC.Calc16(data, data.Length)), 0, 2);

            fitDest = null;
            Array.Clear(mesgDefinitions, 0, mesgDefinitions.Length);

            return result;
        }
Exemple #15
0
 public static void Uint32ToByteStreamLe(uint val, Stream stream)
 {
     stream.Write((byte)(val >> 0));
     stream.Write((byte)(val >> 8));
     stream.Write((byte)(val >> 16));
     stream.Write((byte)(val >> 24));
 }
Exemple #16
0
		/// <summary>
		/// Returns the CRC32 for the specified stream, and writes the input into the output stream.
		/// </summary>
		/// <param name="input">The stream over which to calculate the CRC32</param>
		/// <param name="output">The stream into which to deflate the input</param>
		/// <returns>the CRC32 calculation</returns>
		public UInt32 GetCrc32AndCopy(Stream input, Stream output)
		{
			unchecked
			{
				UInt32 crc32Result;
				crc32Result = 0xFFFFFFFF;
				byte[] buffer = new byte[BufferSize];
				int readSize = BufferSize;

				m_TotalBytesRead = 0;
				int count = input.Read(buffer, 0, readSize);
				if (output != null) output.Write(buffer, 0, count);
				m_TotalBytesRead += count;
				while (count > 0)
				{
					for (int i = 0; i < count; i++)
					{
						crc32Result = ((crc32Result) >> 8) ^ m_crc32Table[(buffer[i]) ^ ((crc32Result) & 0x000000FF)];
					}
					count = input.Read(buffer, 0, readSize);
					if (output != null) output.Write(buffer, 0, count);
					m_TotalBytesRead += count;

				}

				return ~crc32Result;
			}
		}
 public static void Signature(Stream input, Stream output, string privateKey)
 {
     using (var sha = new SHA256CryptoServiceProvider())
     using (var rsa = new RSACryptoServiceProvider())
     {
         // Compute hash
         var buffer = ReadAllBytes(input);
         var hash = sha.ComputeHash(buffer);
         // RSA Initialize
         rsa.FromXmlString(privateKey);
         // format
         var formatter = new RSAPKCS1SignatureFormatter(rsa);
         formatter.SetHashAlgorithm("SHA256");
         var signature = formatter.CreateSignature(hash);
         // Krile Signature Package
         var magic = MagicStr + ":" + signature.Length + ":";
         var magicbytes = Encoding.UTF8.GetBytes(magic);
         if (magicbytes.Length > 64)
             throw new Exception("Magic bits too long.");
         output.Write(magicbytes, 0, magicbytes.Length);
         var padding = new byte[64 - magicbytes.Length];
         output.Write(padding, 0, padding.Length);
         output.Write(signature, 0, signature.Length);
         output.Write(buffer, 0, buffer.Length);
     }
 }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
                                                TransportContext transportContext)
        {
            var callback = GetCallbackName();

            if (!String.IsNullOrEmpty(callback))
            {
                // select the correct encoding to use.
                Encoding encoding = SelectCharacterEncoding(content.Headers);

                // write the callback and opening paren.
                return Task.Factory.StartNew(() =>
                {
                    var bytes = encoding.GetBytes(callback + "(");
                    writeStream.Write(bytes, 0, bytes.Length);
                })
                    // then we do the actual JSON serialization...
                .ContinueWith(t => base.WriteToStreamAsync(type, value, writeStream, content, transportContext))

                // finally, we close the parens.
                .ContinueWith(t =>
                {
                    var bytes = encoding.GetBytes(")");
                    writeStream.Write(bytes, 0, bytes.Length);
                });
            }
            return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
        }
        public void Apply(Stream basisFileStream, IDeltaReader delta, Stream outputStream)
        {
            delta.Apply(
                writeData: (data) => outputStream.Write(data, 0, data.Length),
                copy: (startPosition, length) =>
                {
                    basisFileStream.Seek(startPosition, SeekOrigin.Begin);

                    var buffer = new byte[4*1024*1024];
                    int read;
                    do
                    {
                        read = basisFileStream.Read(buffer, 0, buffer.Length);

                        outputStream.Write(buffer, 0, read);
                    } while (read > 0);
                });

            if (!SkipHashCheck)
            {
                outputStream.Seek(0, SeekOrigin.Begin);

                var sourceFileHash = delta.ExpectedHash;
                var algorithm = delta.HashAlgorithm;

                var actualHash = algorithm.ComputeHash(outputStream);

                if (!StructuralComparisons.StructuralEqualityComparer.Equals(sourceFileHash, actualHash))
                    throw new UsageException("Verification of the patched file failed. The SHA1 hash of the patch result file, and the file that was used as input for the delta, do not match. This can happen if the basis file changed since the signatures were calculated.");
            }
        }
Exemple #20
0
        public async Task Encrypt(Stream input, Stream output)
        {
            _aes.GenerateIV();

            if (_cancelEvent.IsSet())
                return;

            byte[] vector = _aes.IV;
            byte[] vectorLength = BitConverter.GetBytes(vector.Length);
            output.Write(vectorLength, 0, 4);
            output.Write(vector, 0, vector.Length);

            if (_cancelEvent.IsSet())
                return;

            using (ICryptoTransform encryptor = _aes.CreateEncryptor())
            using (CryptoStream encryptionStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
            {
                if (_cancelEvent.IsSet())
                    return;

                await PatcherService.CopyAsync(input, encryptionStream, _cancelEvent, Progress);
                encryptionStream.FlushFinalBlock();
            }
        }
Exemple #21
0
	// uu encodes a stream in to another stream
	public void EncodeStream(  Stream ins , Stream outs ) {
	    
	    // write the start tag
	    outs.Write( beginTag , 0 , beginTag.Length );	   
	    
	    // create the uu transfom and the buffers
	    ToUUEncodingTransform tr = new ToUUEncodingTransform();
	    byte[] input = new byte[ tr.InputBlockSize ];
	    byte[] output = new byte[ tr.OutputBlockSize ];
	    
	    while( true ) {
			
		// read from the stream until no more data is available
		int check = ins.Read( input , 0 , input.Length );
		if( check < 1 ) break;
		
		// if the read length is not InputBlockSize
		// write a the final block
		if( check == tr.InputBlockSize ) {
		    tr.TransformBlock( input , 0 , check , output , 0 );
		    outs.Write( output , 0 , output.Length );
		    outs.Write( endl , 0 , endl.Length );
		} else {
		    byte[] finalBlock = tr.TransformFinalBlock( input , 0 , check );
		    outs.Write( finalBlock , 0 , finalBlock.Length );
		    outs.Write( endl , 0 , endl.Length );
		    break;
		}
				
	    }
	    
	    // write the end tag.
	    outs.Write( endTag , 0 , endTag.Length );
        }
Exemple #22
0
        public static int Compress(Stream input, Stream output)
        {
            var length = (int)(input.Length - input.Position);

            var varInt = new VarInt32(length).GetEncodedValue();
            output.Write(varInt, 0, varInt.Length);

            int bytesWritten = varInt.Length;

            int bytesToRead = Math.Min(length, CompressorConstants.BlockSize);

            var fragment = MemoryPool.Instance.Take(bytesToRead);

            int maxOutput = MaxCompressedOutput(bytesToRead);

            var block = MemoryPool.Instance.Take(maxOutput);

            while(length > 0)
            {
                var fragmentSize = input.Read(fragment, 0, bytesToRead);
                var hashTable = new HashTable(fragmentSize);

                int blockSize = CompressFragment(fragment, fragmentSize, hashTable, block);
                output.Write(block, 0, blockSize);
                bytesWritten += blockSize;

                length -= bytesToRead;
            }

            MemoryPool.Instance.Return(fragment);
            MemoryPool.Instance.Return(block);

            return bytesWritten;
        }
Exemple #23
0
        public int Compress(Stream input, Stream output)
        {
            var length = (int) input.Length;

            var varInt = new VarInt32(length).GetEncodedValue();
            output.Write(varInt, 0, varInt.Length);

            int bytesWritten = varInt.Length;

            int bytesToRead = Math.Min(length, CompressorConstants.BlockSize);
            var fragment = new byte[bytesToRead];
            int maxOutput = MaxCompressedOutput(bytesToRead);

            var block = new byte[maxOutput];

            while (length > 0)
            {
                var fragmentSize = input.Read(fragment, 0, bytesToRead);
                var hashTable = new HashTable(fragmentSize);

                int blockSize = CompressFragment(fragment, fragmentSize, hashTable, block);
                output.Write(block, 0, blockSize);
                bytesWritten += blockSize;

                length -= bytesToRead;
            }

            return bytesWritten;
        }
 /// <summary>
 /// Saves the token to a stream
 /// </summary>
 /// <param name="stream">the stream to save to</param>
 public void Save(Stream stream)
 {
     stream.WriteByte(1);
     stream.Write(CanWrite);
     stream.Write(CanRead);
     stream.Write(IsAdmin);
 }
Exemple #25
0
 public SignatureStream( string signature, Stream baseStream )
 {
     Signature = signature;
     this.baseStream = baseStream;
     if ( CanRead )
     {
         byte [] sig = new byte [ signature.Length ];
         try { baseStream.Read ( sig, 0, sig.Length ); }
         catch { throw new ArgumentException (); }
         if ( Encoding.UTF8.GetString ( sig, 0, sig.Length ) != Signature )
             throw new ArgumentException ();
     }
     else if ( CanWrite && CanSeek )
     {
         long pos = baseStream.Position;
         baseStream.Position = 0;
         byte [] sig = Encoding.UTF8.GetBytes ( signature );
         baseStream.Write ( sig, 0, sig.Length );
         baseStream.Position = pos + signature.Length;
     }
     else if ( CanWrite && !CanSeek && baseStream.Position == 0 )
     {
         byte [] sig = Encoding.UTF8.GetBytes ( signature );
         baseStream.Write ( sig, 0, sig.Length );
     }
 }
Exemple #26
0
 public uint GetCrc32AndCopy(Stream input, Stream output)
 {
     uint maxValue = uint.MaxValue;
     byte[] buffer = new byte[0x2000];
     int count = 0x2000;
     this._TotalBytesRead = 0;
     int num3 = input.Read(buffer, 0, count);
     if (output != null)
     {
         output.Write(buffer, 0, num3);
     }
     this._TotalBytesRead += num3;
     while (num3 > 0)
     {
         for (int i = 0; i < num3; i++)
         {
             maxValue = (maxValue >> 8) ^ this.crc32Table[(int) ((IntPtr) (buffer[i] ^ (maxValue & 0xff)))];
         }
         num3 = input.Read(buffer, 0, count);
         if (output != null)
         {
             output.Write(buffer, 0, num3);
         }
         this._TotalBytesRead += num3;
     }
     return ~maxValue;
 }
 /// <summary>
 /// Writes all key value pairs in current prefix to stream (prefix itself is not written)
 /// </summary>
 /// <param name="transaction">transaction from where export all data</param>
 /// <param name="stream">where to write it to</param>
 public static void Export(IKeyValueDBTransaction transaction, Stream stream)
 {
     if (transaction == null) throw new ArgumentNullException(nameof(transaction));
     if (stream == null) throw new ArgumentNullException(nameof(stream));
     if (!stream.CanWrite) throw new ArgumentException("stream must be writeable", nameof(stream));
     var keyValueCount = transaction.GetKeyValueCount();
     var tempbuf = new byte[16];
     tempbuf[0] = (byte)'B';
     tempbuf[1] = (byte)'T';
     tempbuf[2] = (byte)'D';
     tempbuf[3] = (byte)'B';
     tempbuf[4] = (byte)'E';
     tempbuf[5] = (byte)'X';
     tempbuf[6] = (byte)'P';
     tempbuf[7] = (byte)'2';
     PackUnpack.PackInt64LE(tempbuf, 8, keyValueCount);
     stream.Write(tempbuf, 0, 16);
     transaction.FindFirstKey();
     for (long kv = 0; kv < keyValueCount; kv++)
     {
         var key = transaction.GetKey();
         PackUnpack.PackInt32LE(tempbuf, 0, key.Length);
         stream.Write(tempbuf, 0, 4);
         stream.Write(key.Buffer, key.Offset, key.Length);
         var value = transaction.GetValue();
         PackUnpack.PackInt32LE(tempbuf, 0, value.Length);
         stream.Write(tempbuf, 0, 4);
         stream.Write(value.Buffer, value.Offset, value.Length);
         transaction.FindNextKey();
     }
 }
        public static int Copy(Stream source, Stream destination, byte[] buffer, int? mask, int count)
        {
            int totalRead = 0, read;
            if(mask == null)
            {
                while (count > 0 && (read = source.Read(buffer, 0, Math.Min(count, buffer.Length))) > 0)
                {
                    destination.Write(buffer, 0, read);
                    totalRead += read;
                    count -= read;
                }
            } else
            {
                int effectiveLength = (buffer.Length/8)*8; // need nice sized! e.g. 100-byte array, can only use 96 bytes
                if(effectiveLength == 0) throw new ArgumentException("buffer is too small to be useful", "buffer");

                // we read it big-endian, so we need to *write* it big-endian, and then we'll use unsafe code to read the value,
                // so that the endian-ness we use is CPU-endian, and so it matches whatever we do below
                int maskValue = mask.Value;
                buffer[0] = buffer[4] = (byte) (maskValue >> 24);
                buffer[1] = buffer[5] = (byte) (maskValue >> 16);
                buffer[2] = buffer[6] = (byte) (maskValue >> 8);
                buffer[3] = buffer[7] = (byte) maskValue;
                unsafe
                {
                    
                    fixed (byte* bufferPtr = buffer) // treat the byte-array as a pile-of-ulongs
                    {
                        var longPtr = (ulong*)bufferPtr;
                        ulong xorMask = *longPtr;
                        int bytesThisIteration;
                        do
                        {
                            // now, need to fill buffer as much as possible each time, as we want to work in exact
                            // units of 8 bytes; we don't need to worry about applying the mask to any garbage at the
                            // end of the buffer, as we simply won't copy that out
                            int offset = 0, available = effectiveLength;
                            while (available > 0 && (read = source.Read(buffer, offset, Math.Min(count, available))) > 0)
                            {
                                available -= read;
                                totalRead += read;
                                count -= read;
                                offset += read;
                            }
                            bytesThisIteration = effectiveLength - available;
                            int chunks = bytesThisIteration/8;
                            if ((available%8) != 0) chunks++;

                            // apply xor 8-bytes at a time, coz we haz 64-bit CPU, baby!
                            for (int i = 0; i < chunks; i++)
                                longPtr[i] ^= xorMask;

                            destination.Write(buffer, 0, bytesThisIteration);
                        } while (bytesThisIteration != 0);
                    }
                }
            }
            if(count != 0) throw new EndOfStreamException();
            return totalRead;
        }
Exemple #29
0
        protected override void InternalWrite(Stream Target)
        {
            Target.Seek(0, SeekOrigin.Begin);
            Target.Write(ByteHelper.StringToByte("ID3"));
            //                Version 3.0   Flags  dummy size
            Target.Write(new byte[] { 3,0,  0,     0, 0, 0, 0  }, 0, 7);

            long totalFrameSize = 0;
            Stream frameStream = null;
            foreach(Frame f in Frames)
            {
                frameStream = FrameObjectToByteArray(f);
                totalFrameSize += frameStream.Length;
                frameStream.CopyTo(Target);
                frameStream.Flush();
            }
            Target.Seek(6, SeekOrigin.Begin);
            Target.Write(ByteHelper.GetByteArrayWith7SignificantBitsPerByteForInt((int)totalFrameSize));

            // frame fertig geschrieben jetzt müssen die daten rein =>
            // sourcestream an die stelle spulen und lesen bis endpos
            Target.Seek(DataStart, SeekOrigin.Begin);

            // Target.Copy(SourceStream, DataStart, DataEnd);

            Target.Flush();
            Target.Close();
        }
 public void Save(Stream stream)
 {
     stream.Write((byte)1);
     stream.Write((byte)m_mode);
     stream.Write(m_first);
     stream.Write(m_second);
 }
Exemple #31
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Args"></param>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static void DownFile(string Url, string Args, string Path)
        {
            //string respHTML = "";
            string szError = "";
            bool   bAccess = false;

            try {
                System.Net.HttpWebRequest httpReq;
                //System.Net.HttpWebResponse httpResp;
                System.Uri httpURL = new System.Uri(Url);

                httpReq        = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(httpURL);
                httpReq.Method = "POST";

                byte[] bs = System.Text.Encoding.UTF8.GetBytes(Args);

                //httpReq.KeepAlive = false;
                httpReq.ContentType = "application/x-www-form-urlencoded";
                //httpReq.ContentLength = bs.Length;
                //httpReq.

                //异步提交
                httpReq.BeginGetRequestStream(new AsyncCallback((IAsyncResult ar) => {
                    try {
                        HttpWebRequest hwr = ar.AsyncState as HttpWebRequest;

                        //post数据
                        using (System.IO.Stream reqStream = hwr.EndGetRequestStream(ar)) {
                            reqStream.Write(bs, 0, bs.Length);
                            reqStream.Flush();
                            //reqStream.Close();
                        }

                        //异步获取
                        hwr.BeginGetResponse(new AsyncCallback((IAsyncResult wrar) => {
                            try {
                                HttpWebRequest wrwr = wrar.AsyncState as HttpWebRequest;
                                WebResponse wr      = wrwr.EndGetResponse(wrar);

                                using (System.IO.Stream MyStream = wr.GetResponseStream()) {
                                    //System.IO.StreamReader reader = new System.IO.StreamReader(MyStream, Encoding.UTF8);

                                    //byte[] TheBytes = new byte[MyStream.Length];
                                    //MyStream.Read(TheBytes, 0, (int)MyStream.Length);

                                    using (FileStream fs = File.Create(Path)) {
                                        byte[] bytes = new byte[102400];
                                        int n        = 0;
                                        do
                                        {
                                            n = MyStream.Read(bytes, 0, 10240);
                                            fs.Write(bytes, 0, n);
                                        } while (n > 0);
                                    }

                                    //下载成功
                                    bAccess = true;

                                    //respHTML = Encoding.UTF8.GetString(TheBytes);
                                    //respHTML = reader.ReadToEnd();
                                    //Console.WriteLine(respHTML);

                                    //reader.Dispose();
                                    MyStream.Dispose();
                                }
                            } catch (Exception ex) {
                                dpz2.Debug.WriteLine("BeginGetResponse:" + ex.Message);
                                szError = ex.Message;
                            }
                        }), hwr);
                    } catch (Exception ex) {
                        dpz2.Debug.WriteLine("BeginGetRequestStream:" + ex.Message);
                    }
                }), httpReq);

                int  tick   = Environment.TickCount;
                bool bCheck = true;

                while (bCheck)
                {
                    if (Environment.TickCount - tick > 10)
                    {
                        tick = Environment.TickCount;
                        //if (respHTML != "") {
                        //    bCheck = false;
                        //    return respHTML;
                        //}
                        if (szError != "")
                        {
                            bCheck = false;
                            throw new Exception(szError);
                        }
                        if (bAccess)
                        {
                            bCheck = false;
                        }
                    }
                    System.Threading.Thread.Sleep(1);
                }

                //httpResp = (System.Net.HttpWebResponse)httpReq.GetResponse();

                //httpResp.Close();
                //httpReq = null;
            } catch (Exception ex) {
                throw new Exception("获取HTML发生异常:" + ex.Message);
                //System.Windows.Forms.MessageBox.Show("获取信息发生异常:\r\n" + ex.Message + "\r\n" + Url);
                //Debug.WriteLine("Debug\\>GetHTML::Error(" + ex + ")");
            }

            //return respHTML;
        }
Exemple #32
0
        /// <summary>
        /// 提交文件并获取返回内容
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static string PostFile(string Url, string Path)
        {
            string respHTML = "";
            //string szError = "";
            Exception Err = null;

            try {
                System.Net.HttpWebRequest httpReq;
                //System.Net.HttpWebResponse httpResp;
                System.Uri httpURL = new System.Uri(Url);

                httpReq        = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(httpURL);
                httpReq.Method = "POST";
                //httpReq.KeepAlive = true;
                httpReq.Credentials = CredentialCache.DefaultCredentials;
                httpReq.KeepAlive   = false;
                httpReq.Timeout     = 600000;

                string boundary      = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endbytes      = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                httpReq.ContentType = "multipart/form-data; boundary=" + boundary;

                //异步提交
                httpReq.BeginGetRequestStream(new AsyncCallback((IAsyncResult ar) => {
                    try {
                        HttpWebRequest hwr = ar.AsyncState as HttpWebRequest;

                        //post数据
                        using (System.IO.Stream reqStream = hwr.EndGetRequestStream(ar)) {
                            //reqStream.Write(bs, 0, bs.Length);
                            //reqStream.Flush();

                            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
                            byte[] buffer         = new byte[4096];
                            int bytesRead         = 0;
                            //for (int i = 0; i < files.Length; i++) {
                            reqStream.Write(boundarybytes, 0, boundarybytes.Length);
                            string header      = string.Format(headerTemplate, "file0", System.IO.Path.GetFileName(Path));
                            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                            reqStream.Write(headerbytes, 0, headerbytes.Length);
                            using (System.IO.FileStream fileStream = new System.IO.FileStream(Path, FileMode.Open, FileAccess.Read)) {
                                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    reqStream.Write(buffer, 0, bytesRead);
                                }
                            }
                            //}

                            //1.3 form end
                            reqStream.Write(endbytes, 0, endbytes.Length);
                            //reqStream.Close();
                        }

                        //异步获取
                        hwr.BeginGetResponse(new AsyncCallback((IAsyncResult wrar) => {
                            try {
                                HttpWebRequest wrwr = wrar.AsyncState as HttpWebRequest;
                                WebResponse wr      = wrwr.EndGetResponse(wrar);

                                using (System.IO.Stream MyStream = wr.GetResponseStream()) {
                                    System.IO.StreamReader reader = new System.IO.StreamReader(MyStream, Encoding.UTF8);

                                    //byte[] TheBytes = new byte[MyStream.Length];
                                    //MyStream.Read(TheBytes, 0, (int)MyStream.Length);

                                    //respHTML = Encoding.UTF8.GetString(TheBytes);
                                    respHTML = reader.ReadToEnd();
                                    //Console.WriteLine(respHTML);

                                    reader.Dispose();
                                    MyStream.Dispose();
                                }
                            } catch (Exception ex) {
                                dpz2.Debug.WriteLine("BeginGetResponse:" + ex.Message);
                                //szError = ex.Message;
                                Err = ex;
                            }
                        }), hwr);
                    } catch (Exception ex) {
                        dpz2.Debug.WriteLine("BeginGetRequestStream:" + ex.Message);
                        Err = ex;
                    }
                }), httpReq);

                int  tick   = Environment.TickCount;
                bool bCheck = true;

                while (bCheck)
                {
                    if (Environment.TickCount - tick > 10)
                    {
                        tick = Environment.TickCount;
                        if (respHTML != "")
                        {
                            bCheck = false;
                            return(respHTML);
                        }
                        if (Err != null)
                        {
                            bCheck = false;
                            throw Err;
                        }
                    }
                    System.Threading.Thread.Sleep(1);
                }

                //httpResp = (System.Net.HttpWebResponse)httpReq.GetResponse();

                //httpResp.Close();
                //httpReq = null;
            } catch (Exception ex) {
                throw new Exception("获取HTML发生异常", ex);
                //System.Windows.Forms.MessageBox.Show("获取信息发生异常:\r\n" + ex.Message + "\r\n" + Url);
                //Debug.WriteLine("Debug\\>GetHTML::Error(" + ex + ")");
            }

            return(respHTML);
        }
Exemple #33
0
    private void checkAndResponse(HttpListenerRequest request, HttpListenerResponse response)
    {
        NCMBSettings._responseValidationFlag = true;
        MockServerObject mockObj = null;

        StreamReader stream   = new StreamReader(request.InputStream);
        string       bodyJson = stream.ReadToEnd();

        if (request.HttpMethod.Equals("GET") && request.Url.ToString().Equals(SERVER))
        {
            mockObj        = new MockServerObject();
            mockObj.status = 200;
        }
        else
        {
            foreach (MockServerObject mock in mockObjectDic[request.HttpMethod])
            {
                if (request.Url.ToString().Equals(mock.url))
                {
                    if (bodyJson.Length > 0)
                    {
                        if (bodyJson.Equals(mock.body) || request.ContentType.Equals("multipart/form-data; boundary=_NCMBBoundary"))
                        {
                            mockObj         = mock;
                            mockObj.request = request;
                            mockObj.validate();
                            if (mockObj.status == 200 || mockObj.status == 201)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        mockObj         = mock;
                        mockObj.request = request;
                        mockObj.validate();
                        if (mockObj.status == 200 || mockObj.status == 201)
                        {
                            break;
                        }
                    }
                }
            }
        }

        if (mockObj == null)
        {
            mockObj = new MockServerObject();
        }

        //Set response signature
        if (mockObj.responseSignature)
        {
            string signature = _makeResponseSignature(request, mockObj.responseJson);
            response.AddHeader("X-NCMB-Response-Signature", signature);
        }
        //Set status code
        response.StatusCode = mockObj.status;
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(mockObj.responseJson);
        // Get a response stream and write the response to it.
        response.ContentLength64 = buffer.Length;
        System.IO.Stream output = response.OutputStream;
        output.Write(buffer, 0, buffer.Length);
        // You must close the output stream.
        response.Close();
    }
Exemple #34
0
            public static Tuple <HttpStatusCode, string> Post(string url, Dictionary <string, string> param, Dictionary <string, string> header)
            {
                Stopwatch Watch = new Stopwatch();

                Watch.Start();
                try
                {
                    System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(url);
                    request.Method = "POST";
                    request.Headers.Add("UcAsp.Net_RPC", "true");
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.KeepAlive   = false;
                    request.Timeout     = 1000 * 30;
                    request.ServicePoint.Expect100Continue = false;
                    if (header != null)
                    {
                        foreach (KeyValuePair <string, string> kv in header)
                        {
                            request.Headers[kv.Key] = kv.Value;
                        }
                    }
                    StringBuilder sb = new StringBuilder();
                    if (param != null)
                    {
                        int i = 0;
                        if (param.ContainsKey(""))
                        {
                            sb.Append(param[""]);
                        }
                        else
                        {
                            foreach (KeyValuePair <string, string> kv in param)
                            {
                                if (i == 0)
                                {
                                    sb.AppendFormat("{0}={1}", kv.Key, kv.Value);
                                }
                                else
                                {
                                    sb.AppendFormat("&{0}={1}", kv.Key, kv.Value);
                                }
                            }
                        }
                    }

                    byte[] payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                    request.ContentLength = payload.Length;
                    System.IO.Stream writer = request.GetRequestStream();
                    writer.Write(payload, 0, payload.Length);
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                    string     responseText             = string.Empty;
                    GZipStream gzip = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress); //解压缩
                    using (StreamReader reader = new StreamReader(gzip, Encoding.UTF8))                         //中文编码处理
                    {
                        responseText = reader.ReadToEnd();
                    }

                    writer.Close();

                    return(new Tuple <HttpStatusCode, string>(response.StatusCode, responseText));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    return(new Tuple <HttpStatusCode, string>(HttpStatusCode.Moved, "{\"msg\":\"" + ex.Message + "\"}"));
                }
                finally
                {
                    Watch.Stop();
                }
            }
Exemple #35
0
        static void Listen()
        {
            // URI prefixes are required,
            var prefixes = new List <string>()
            {
                "http://127.0.0.1:8888/"
            };

            // Create a listener.
            HttpListener listener = new HttpListener();

            // Add the prefixes.
            foreach (string s in prefixes)
            {
                listener.Prefixes.Add(s);
            }
            listener.Start();
            Console.WriteLine("Listening...");

            bool listening = true;

            while (listening)
            {
                // Note: The GetContext method blocks while waiting for a request.
                HttpListenerContext context = listener.GetContext();

                HttpListenerRequest request = context.Request;

                string documentContents;
                using (Stream receiveStream = request.InputStream)
                {
                    using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                    {
                        documentContents = readStream.ReadToEnd();
                    }
                }
                Console.WriteLine($"Recived request for {request.Url}");
                Console.WriteLine(documentContents);


                HttpListenerResponse response = context.Response;
                // Construct a response.

                //string responseString = File.ReadAllText(@"..\..\Responses\basic.html");

                bool red = true;
                if (red)
                {
                    response.Redirect(@"http://127.0.0.1:5500/");
                    response.OutputStream.Close();
                }
                else
                {
                    string responseString = GenerateResponse(request.HttpMethod, documentContents);

                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                    // Get a response stream and write the response to it.
                    response.ContentLength64 = buffer.Length;
                    System.IO.Stream output = response.OutputStream;
                    output.Write(buffer, 0, buffer.Length);
                    // You must close the output stream.
                    output.Close();
                }
            }
            listener.Stop();
        }
Exemple #36
0
        private static void Main(string[] args)
        {
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("A more recent Windows version is required to use the HttpListener class.");
                return;
            }


            // Create a listener.
            HttpListener listener = new HttpListener();

            // Add the prefixes.
            if (args.Length != 0)
            {
                foreach (string s in args)
                {
                    listener.Prefixes.Add(s);
                    // don't forget to authorize access to the TCP/IP addresses localhost:xxxx and localhost:yyyy
                    // with netsh http add urlacl url=http://localhost:xxxx/ user="******"
                    // and netsh http add urlacl url=http://localhost:yyyy/ user="******"
                    // user="******" is language dependent, use user=Everyone in english
                }
            }
            else
            {
                Console.WriteLine("Syntax error: the call must contain at least one web server url as argument");
            }
            listener.Start();
            foreach (string s in args)
            {
                Console.WriteLine("Listening for connections on " + s);
            }

            while (true)
            {
                // Note: The GetContext method blocks while waiting for a request.
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request = context.Request;

                string documentContents;
                using (Stream receiveStream = request.InputStream)
                {
                    using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                    {
                        documentContents = readStream.ReadToEnd();
                    }
                }
                Console.WriteLine($"Received request for {request.Url}");
                Console.WriteLine(documentContents);

                // Obtain a response object.
                HttpListenerResponse response = context.Response;
                string responseString         = null;

                if (request.HttpMethod == "GET")
                {
                    // Construct a response.
                    try
                    {
                        responseString = File.ReadAllText("D:\\Documents\\Polytech\\Polytech SI4\\S8\\SOC\\eiin839\\TP1\\Echo\\www\\pub" + request.Url.AbsolutePath);
                    }
                    catch (Exception e)
                    { }
                }

                if (responseString != null)
                {
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                    // Get a response stream and write the response to it.
                    response.ContentLength64 = buffer.Length;
                    System.IO.Stream output = response.OutputStream;
                    output.Write(buffer, 0, buffer.Length);
                    // You must close the output stream.
                    output.Close();
                }
            }
            // Httplistener neither stop ...
            // listener.Stop();
        }
        /// <summary>
        /// HTTP_POST Aufruf
        /// </summary>
        /// <param name="ServerURL">URL für den Aufruf</param>
        /// <param name="Data">Eingabedaten für den Request</param>
        /// <param name="timeout">Timeout Wert für Request in Sekunden</param>
        /// <param name="useCertificate">HTTPS ServerZertifikatValidierung durchführen</param>
        /// <returns></returns>
        public virtual string HTTP_POST(string ServerURL, string Data, int timeout, bool useCertificate = false)

        /*#############################################################################################################################
        * Funktion für HTTP_POST's
        #############################################################################################################################*/
        {
            //_log.Info(string.Format("HTTP_POST, URL={0} timeout={1} ssl={2} Data={3}.", ServerURL, timeout, useCertificate, Data));

            string Out = String.Empty;

            req = (HttpWebRequest)WebRequest.Create(ServerURL);
            try
            {
                // Serverzertifikatsprüfung wird durchgeführt
                if (!useCertificate)
                {
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }
                }
                ;

                // Zertifikat muss bei Nutzung von Clientzertifikaten angegeben werden
                if (useCertificate && CertificateFile != null)
                {
                    X509Certificate cert = X509Certificate.CreateFromCertFile(CertificateFile);
                    req.ClientCertificates.Add(cert);
                }

                req.Method           = "POST";
                req.ReadWriteTimeout = timeout * 1000;
                req.Timeout          = timeout * 1000;
                req.ContentType      = "application/json";
                req.Credentials      = new NetworkCredential(ConnectionUsername, ConnectionUserPwd);
                byte[] sentData = Encoding.UTF8.GetBytes(Data);
                req.ContentLength = sentData.Length;
                using (System.IO.Stream sendStream = req.GetRequestStream())
                {
                    sendStream.Write(sentData, 0, sentData.Length);
                    sendStream.Close();
                }
                using (System.Net.WebResponse res = req.GetResponse())
                    using (System.IO.Stream ReceiveStream = res.GetResponseStream())
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
                        {
                            Char[] read  = new Char[256];
                            int    count = sr.Read(read, 0, 256);
                            while (count > 0)
                            {
                                String str = new String(read, 0, count);
                                Out  += str;
                                count = sr.Read(read, 0, 256);
                            }
                        }
                req.Abort();
                return(Out);
            }
            catch (ArgumentException ex)
            {
                //_log.Error("ArgumentException: ", ex);
                Out = string.Format("REST_HTTP_ERROR :: Ungültiger Parameter in HTTP POST Request :: {0}", ex.Message);
            }
            catch (WebException ex)
            {
                //_log.Error("WebException: ", ex);
                Out = string.Format("REST_HTTP_ERROR :: WebException beim HTTP POST Request :: {0}", ex.Message);
                if (ex.Response != null)
                {
                    Stream       dataStream         = ex.Response.GetResponseStream();
                    StreamReader reader             = new StreamReader(dataStream);
                    string       responseFromServer = reader.ReadToEnd();


                    return(responseFromServer);
                }
            }
            catch (Exception ex)
            {
                //_log.Error("Exception: ", ex);
                Out = string.Format("REST_HTTP_ERROR :: Exception beim HTTP POST Request :: {0}", ex.Message);
            }

            return(Out);
        }
        private void _PerpetualWriterMethod(object state)
        {
            TraceOutput(TraceBits.WriterThread, "_PerpetualWriterMethod START");

            try
            {
                do
                {
                    // wait for the next session
                    TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch    _sessionReset.WaitOne(begin) PWM");
                    _sessionReset.WaitOne();
                    TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch    _sessionReset.WaitOne(done)  PWM");

                    if (_isDisposed)
                    {
                        break;
                    }

                    TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch    _sessionReset.Reset()        PWM");
                    _sessionReset.Reset();

                    // repeatedly write buffers as they become ready
                    WorkItem         workitem = null;
                    Ionic.Zlib.CRC32 c        = new Ionic.Zlib.CRC32();
                    do
                    {
                        workitem = _pool[_nextToWrite % _pc];
                        lock (workitem)
                        {
                            if (_noMoreInputForThisSegment)
                            {
                                TraceOutput(TraceBits.Write,
                                            "Write    drain    wi({0}) stat({1}) canuse({2})  cba({3})",
                                            workitem.index,
                                            workitem.status,
                                            (workitem.status == (int)WorkItem.Status.Compressed),
                                            workitem.compressedBytesAvailable);
                            }

                            do
                            {
                                if (workitem.status == (int)WorkItem.Status.Compressed)
                                {
                                    TraceOutput(TraceBits.WriteBegin,
                                                "Write    begin    wi({0}) stat({1})              cba({2})",
                                                workitem.index,
                                                workitem.status,
                                                workitem.compressedBytesAvailable);

                                    workitem.status = (int)WorkItem.Status.Writing;
                                    _outStream.Write(workitem.compressed, 0, workitem.compressedBytesAvailable);
                                    c.Combine(workitem.crc, workitem.inputBytesAvailable);
                                    _totalBytesProcessed += workitem.inputBytesAvailable;
                                    _nextToWrite++;
                                    workitem.inputBytesAvailable = 0;
                                    workitem.status = (int)WorkItem.Status.Done;

                                    TraceOutput(TraceBits.WriteDone,
                                                "Write    done     wi({0}) stat({1})              cba({2})",
                                                workitem.index,
                                                workitem.status,
                                                workitem.compressedBytesAvailable);


                                    Monitor.Pulse(workitem);
                                    break;
                                }
                                else
                                {
                                    int wcycles = 0;
                                    // I've locked a workitem I cannot use.
                                    // Therefore, wake someone else up, and then release the lock.
                                    while (workitem.status != (int)WorkItem.Status.Compressed)
                                    {
                                        TraceOutput(TraceBits.WriteWait,
                                                    "Write    waiting  wi({0}) stat({1}) nw({2}) nf({3}) nomore({4})",
                                                    workitem.index,
                                                    workitem.status,
                                                    _nextToWrite, _nextToFill,
                                                    _noMoreInputForThisSegment);

                                        if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill)
                                        {
                                            break;
                                        }

                                        wcycles++;

                                        // wake up someone else
                                        Monitor.Pulse(workitem);
                                        // release and wait
                                        Monitor.Wait(workitem);

                                        if (workitem.status == (int)WorkItem.Status.Compressed)
                                        {
                                            TraceOutput(TraceBits.WriteWait,
                                                        "Write    A-OK     wi({0}) stat({1}) iba({2}) cba({3}) cyc({4})",
                                                        workitem.index,
                                                        workitem.status,
                                                        workitem.inputBytesAvailable,
                                                        workitem.compressedBytesAvailable,
                                                        wcycles);
                                        }
                                    }

                                    if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill)
                                    {
                                        break;
                                    }
                                }
                            }while (true);
                        }

                        if (_noMoreInputForThisSegment)
                        {
                            TraceOutput(TraceBits.Write,
                                        "Write    nomore  nw({0}) nf({1}) break({2})",
                                        _nextToWrite, _nextToFill, (_nextToWrite == _nextToFill));
                        }

                        if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill)
                        {
                            break;
                        }
                    } while (true);


                    // Finish:
                    // After writing a series of buffers, closing each one with
                    // Flush.Sync, we now write the final one as Flush.Finish, and
                    // then stop.
                    byte[]    buffer     = new byte[128];
                    ZlibCodec compressor = new ZlibCodec();
                    int       rc         = compressor.InitializeDeflate(_compressLevel, false);
                    compressor.InputBuffer       = null;
                    compressor.NextIn            = 0;
                    compressor.AvailableBytesIn  = 0;
                    compressor.OutputBuffer      = buffer;
                    compressor.NextOut           = 0;
                    compressor.AvailableBytesOut = buffer.Length;
                    rc = compressor.Deflate(FlushType.Finish);

                    if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
                    {
                        throw new Exception("deflating: " + compressor.Message);
                    }

                    if (buffer.Length - compressor.AvailableBytesOut > 0)
                    {
                        TraceOutput(TraceBits.WriteBegin,
                                    "Write    begin    flush bytes({0})",
                                    buffer.Length - compressor.AvailableBytesOut);

                        _outStream.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);

                        TraceOutput(TraceBits.WriteBegin,
                                    "Write    done     flush");
                    }

                    compressor.EndDeflate();

                    _Crc32 = c.Crc32Result;

                    // signal that writing is complete:
                    TraceOutput(TraceBits.Synch, "Synch    _writingDone.Set()           PWM");
                    _writingDone.Set();
                }while (true);
            }
            catch (System.Exception exc1)
            {
                lock (_eLock)
                {
                    // expose the exception to the main thread
                    if (_pendingException != null)
                    {
                        _pendingException = exc1;
                    }
                }
            }

            TraceOutput(TraceBits.WriterThread, "_PerpetualWriterMethod FINIS");
        }
Exemple #39
0
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered " + _activityName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace(_activityName + ".Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                string inputText = Content.Get(executionContext);
                if (inputText != string.Empty)
                {
                    inputText = HtmlTools.StripHTML(inputText);

                    IndexDocument myDoc = new IndexDocument
                    {
                        Content   = inputText,
                        Reference = (Email.Get(executionContext)).Id.ToString(),
                        Subject   = Subject.Get(executionContext),
                        Title     = Subject.Get(executionContext)
                    };

                    DocumentWrapper myWrapper = new DocumentWrapper();
                    myWrapper.Document = new List <IndexDocument>();
                    myWrapper.Document.Add(myDoc);

                    //serialize the myjsonrequest to json
                    System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myWrapper.GetType());
                    MemoryStream ms = new MemoryStream();
                    serializer.WriteObject(ms, myWrapper);
                    string jsonMsg = Encoding.Default.GetString(ms.ToArray());

                    //create the webrequest object and execute it (and post jsonmsg to it)
                    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(_webAddress);

                    //set request content type so it is treated as a regular form post
                    req.ContentType = "application/x-www-form-urlencoded";

                    //set method to post
                    req.Method = "POST";

                    StringBuilder postData = new StringBuilder();

                    //HttpUtility.UrlEncode
                    //set the apikey request value
                    postData.Append("apikey=" + System.Uri.EscapeDataString(_apiKey) + "&");
                    //postData.Append("apikey=" + _apiKey + "&");

                    //set the json request value
                    postData.Append("json=" + jsonMsg + "&");

                    //set the index name request value
                    postData.Append("index=" + _indexName);

                    //create a stream
                    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData.ToString());
                    req.ContentLength = bytes.Length;
                    System.IO.Stream os = req.GetRequestStream();
                    os.Write(bytes, 0, bytes.Length);
                    os.Close();

                    //get the response
                    System.Net.WebResponse resp = req.GetResponse();

                    //deserialize the response to a ResponseBody object
                    ResponseBody myResponse = new ResponseBody();
                    System.Runtime.Serialization.Json.DataContractJsonSerializer deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myResponse.GetType());
                    myResponse = deserializer.ReadObject(resp.GetResponseStream()) as ResponseBody;
                }
            }

            catch (WebException exception)
            {
                string str = string.Empty;
                if (exception.Response != null)
                {
                    using (StreamReader reader =
                               new StreamReader(exception.Response.GetResponseStream()))
                    {
                        str = reader.ReadToEnd();
                    }
                    exception.Response.Close();
                }
                if (exception.Status == WebExceptionStatus.Timeout)
                {
                    throw new InvalidPluginExecutionException(
                              "The timeout elapsed while attempting to issue the request.", exception);
                }
                throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                                                                        "A Web exception ocurred while attempting to issue the request. {0}: {1}",
                                                                        exception.Message, str), exception);
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }

            tracingService.Trace("Exiting " + _activityName + ".Execute(), Correlation Id: {0}", context.CorrelationId);
        }
Exemple #40
0
        private static void ProcessRequests(string[] prefixes)
        {
            if (!System.Net.HttpListener.IsSupported)
            {
                Console.WriteLine(
                    "Windows XP SP2, Server 2003, or higher is required to " +
                    "use the HttpListener class.");
                return;
            }
            // URI prefixes are required,
            if (prefixes == null || prefixes.Length == 0)
            {
                throw new ArgumentException("prefixes");
            }

            // Create a listener and add the prefixes.
            System.Net.HttpListener listener = new System.Net.HttpListener();
            foreach (string s in prefixes)
            {
                listener.Prefixes.Add(s);
            }

            try
            {
                // Start the listener to begin listening for requests.
                listener.Start();
                Console.WriteLine("Listening...");

                // Set the number of requests this application will handle.
                int numRequestsToBeHandled = 10;

                for (int i = 0; i < numRequestsToBeHandled; i++)
                {
                    HttpListenerResponse response = null;
                    try
                    {
                        // Note: GetContext blocks while waiting for a request.
                        HttpListenerContext context = listener.GetContext();

                        // Create the response.
                        response = context.Response;
                        string responseString =
                            "<HTML><BODY>The time is currently " +
                            DateTime.Now.ToString(
                                DateTimeFormatInfo.CurrentInfo) +
                            "</BODY></HTML>";
                        byte[] buffer =
                            System.Text.Encoding.UTF8.GetBytes(responseString);
                        response.ContentLength64 = buffer.Length;
                        System.IO.Stream output = response.OutputStream;
                        output.Write(buffer, 0, buffer.Length);
                    }
                    catch (HttpListenerException ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (response != null)
                        {
                            response.Close();
                        }
                    }
                }
            }
            catch (HttpListenerException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Stop listening for requests.
                listener.Close();
                Console.WriteLine("Done Listening.");
            }
        }
Exemple #41
0
        /// <summary>
        /// 获取网络数据
        /// </summary>
        public static string RequestUrl(string url, Dictionary <string, string> requestParams = null, bool isPost = false, bool hasFile = false)
        {
            string postData = string.Empty;

            if (requestParams != null)
            {
                postData = string.Join("&", requestParams.Select(c => c.Key + "=" + c.Value));
            }

            String responseFromServer = string.Empty;

            try
            {
                // Create a request using a URL that can receive a post.
                if (!isPost)
                {
                    url += string.IsNullOrEmpty(postData) ? string.Empty
                                                        : url.IndexOf("?") > -1 ? "&" : "?" + postData;
                }
                Console.WriteLine(url);
                WebRequest webRequest = HttpWebRequest.Create(url);
                {
                    try
                    {
                        ((HttpWebRequest)webRequest).KeepAlive = false;
                        webRequest.Timeout = 1000 * 30;                         //
                        if (isPost)
                        {
                            // Set the Method property of the request to POST.
                            webRequest.Method = "POST";
                            webRequest.Proxy  = null;
                            // Create POST data and convert it to a byte array.
                            byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData);
                            // Set the ContentType property of the WebRequest.
                            webRequest.ContentType = "application/x-www-form-urlencoded";
                            // Set the ContentLength property of the WebRequest.
                            webRequest.ContentLength = byteArray.Length;
                            // Get the request stream.
                            using (System.IO.Stream dataStream = webRequest.GetRequestStream())
                            {
                                dataStream.Write(byteArray, 0, byteArray.Length);
                            }
                        }
                    }
                    catch
                    {
                    }
                    // Get the response.
                    using (WebResponse response = webRequest.GetResponse())
                    {
                        //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                        // Get the stream containing content returned by the server.
                        using (System.IO.Stream responseStream = response.GetResponseStream())
                        {
                            using (StreamReader reader = new StreamReader(responseStream))
                            {
                                responseFromServer = reader.ReadToEnd();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                String error = ex.Message;
                System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();
                String method = stackTrace.GetFrame(0).GetMethod().Name;
            }
            return(responseFromServer);
        }
Exemple #42
0
        /// <summary>
        /// 带证书提交数据并获取返回内容
        /// </summary>
        /// <param name="Url">访问地址</param>
        /// <param name="Args">提交参数</param>
        /// <param name="enc">编码格式</param>
        /// <param name="StoreName">证书存储位置</param>
        /// <param name="CertName">证书名称</param>
        /// <returns></returns>
        public static string PostWithCert(string Url, string Args, Encoding enc, StoreName StoreName, string CertName)
        {
            string respHTML = "";

            try {
                X509Store store = new X509Store(StoreName, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

                System.Security.Cryptography.X509Certificates.X509Certificate2Collection certs =
                    store.Certificates.Find(X509FindType.FindBySubjectName, CertName, false);

                if (certs.Count <= 0)
                {
                    throw new Exception("未发现证书文件");
                }
                //System.Security.Cryptography.X509Certificates.X509Certificate2 cert =
                //store.Certificates.Find(X509FindType.FindBySubjectName, CertName, false)[0];

                System.Net.HttpWebRequest  httpReq;
                System.Net.HttpWebResponse httpResp;
                System.Uri httpURL = new System.Uri(Url);

                httpReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(httpURL);
                httpReq.ClientCertificates.Add(certs[0]);
                httpReq.Method = "POST";

                byte[] bs = enc.GetBytes(Args);

                httpReq.KeepAlive     = false;
                httpReq.ContentType   = "application/x-www-form-urlencoded";
                httpReq.ContentLength = bs.Length;
                httpReq.Timeout       = 30000;
                //httpReq.

                //post数据
                using (System.IO.Stream reqStream = httpReq.GetRequestStream()) {
                    reqStream.Write(bs, 0, bs.Length);
                    reqStream.Close();
                }

                httpResp = (System.Net.HttpWebResponse)httpReq.GetResponse();

                using (System.IO.Stream MyStream = httpResp.GetResponseStream()) {
                    System.IO.StreamReader reader = new System.IO.StreamReader(MyStream, Encoding.UTF8);

                    //byte[] TheBytes = new byte[MyStream.Length];
                    //MyStream.Read(TheBytes, 0, (int)MyStream.Length);

                    //respHTML = Encoding.UTF8.GetString(TheBytes);
                    respHTML = reader.ReadToEnd();

                    reader.Dispose();
                    MyStream.Dispose();
                }


                httpResp.Close();
                httpReq = null;
            } catch (Exception ex) {
                throw new Exception("获取HTML发生异常:" + ex.Message);
                //System.Windows.Forms.MessageBox.Show("获取信息发生异常:\r\n" + ex.Message + "\r\n" + Url);
                //Debug.WriteLine("Debug\\>GetHTML::Error(" + ex + ")");
            }

            return(respHTML);
        }
Exemple #43
0
 public override void Write(byte[] buffer, int offset, int count)
 {
     stream.Write(buffer, offset, count);
 }
Exemple #44
0
        // This example requires the System and System.Net namespaces.
        public static void SimpleListenerExample(string prefix)
        {
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
                return;
            }

            if (prefix == null)
            {
                throw new ArgumentException("prefix");
            }

            HttpListener listener = new HttpListener();

            listener.Prefixes.Add(prefix);
            Console.WriteLine("Listening...");

            listener.Start();
            byte[] buffer;


            while (true)
            {
                try
                {
                    // Note: The GetContext method blocks while waiting for a request.
                    context = listener.GetContext();

                    // Obtain a response object.

                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Current page: " + context.Request.RawUrl);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write("Status Code ");
                    Console.WriteLine(DateTime.UtcNow.AddYears(1).ToString("o"));
                    Console.WriteLine(context.Response.StatusCode);
                    if (context.Request.RawUrl == "/" || context.Request.RawUrl == "/index" || Directory.Exists(Directory.GetCurrentDirectory() + "/" + ContentFolderName + context.Request.RawUrl))
                    {
                        Redirect(context);
                    }
                    else
                    {
                        if (File.Exists(Directory.GetCurrentDirectory() + "/" + ContentFolderName + context.Request.RawUrl))
                        {
                            string filePath = Directory.GetCurrentDirectory() + "/" + ContentFolderName + context.Request.RawUrl;

                            context.Response.AddHeader("ETag", ComputeHash(filePath));
                            context.Response.AddHeader("Expires", DateTime.UtcNow.AddYears(1).ToString("o")); // detta funkar
                            context.Response.AddHeader("Content-Type", GetContentType(context.Request.RawUrl));



                            buffer = File.ReadAllBytes(filePath);
                            // Get a response stream and write the response to it.
                            context.Response.ContentLength64 = buffer.Length;
                            System.IO.Stream output = context.Response.OutputStream;
                            output.Write(buffer, 0, buffer.Length);

                            // You must close the output stream.
                            output.Close();
                        }
                        else
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                            Console.WriteLine("Not Found Object");
                            Console.WriteLine(context.Response.StatusCode);
                            context.Response.StatusDescription = "The link was broken";
                            string rstr = "<Html><Body><h1>The Website was not Found </h1></Body> </Html>";
                            buffer = Encoding.UTF8.GetBytes(rstr);
                            context.Response.ContentLength64 = buffer.Length;
                            System.IO.Stream output = context.Response.OutputStream;
                            output.Write(buffer, 0, buffer.Length);
                            // You must close the output stream.
                            output.Close();
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
        protected void ExecutePreCreateTitanic(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }
            IPluginExecutionContext context        = localContext.PluginExecutionContext;
            IOrganizationService    service        = localContext.OrganizationService;
            ITracingService         tracingService = localContext.TracingService;

            Entity titanicEntity = (Entity)context.InputParameters["Target"];

            try
            {
                JSONRequestResponse request = new JSONRequestResponse();
                request.InputObj = new TitanicPlugins.Input1();
                //request.inputObj2 = new Dictionary<string, string>() { };
                Input    input   = new Input();
                string[] columns = { "PassengerId", "Age", "Cabin", "Embarked", "Fare", "Name", "Parch", "Pclass", "SibSp", "Sex", "Ticket", "Survived" };
                object[] values  = { titanicEntity.Contains("new_passengerid") ? titanicEntity.GetAttributeValue <string>("new_passengerid") : "",
                                     titanicEntity.Contains("new_age") ? titanicEntity.GetAttributeValue <string>("new_age") : "",
                                     titanicEntity.Contains("new_cabin") ? titanicEntity.GetAttributeValue <string>("new_cabin") : "",
                                     titanicEntity.Contains("new_embarked") ? titanicEntity.GetAttributeValue <string>("new_embarked") : "",
                                     titanicEntity.Contains("new_fare") ? titanicEntity.GetAttributeValue <string>("new_fare") : "",
                                     titanicEntity.Contains("new_name") ? titanicEntity.GetAttributeValue <string>("new_name") : "",
                                     titanicEntity.Contains("new_parch") ? titanicEntity.GetAttributeValue <string>("new_parch") : "",
                                     titanicEntity.Contains("new_pclass") ? titanicEntity.GetAttributeValue <string>("new_pclass") : "",
                                     titanicEntity.Contains("new_sibsp") ? titanicEntity.GetAttributeValue <string>("new_sibsp") : "",
                                     titanicEntity.Contains("new_sex") ? titanicEntity.GetAttributeValue <string>("new_sex") : "",
                                     titanicEntity.Contains("new_ticket") ? titanicEntity.GetAttributeValue <string>("new_ticket") : "",
                                     titanicEntity.Contains("new_survived") ? titanicEntity.GetAttributeValue <string>("new_survived") : "" };
                input.Columns           = columns;
                input.Values            = new object[][] { values };
                request.InputObj.Inputs = new Input();
                request.InputObj.Inputs = input;

                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(request.GetType());
                MemoryStream ms = new MemoryStream();
                serializer.WriteObject(ms, request);
                string jsonMsg = Encoding.Default.GetString(ms.ToArray());

                const string endpoint = "https://ussouthcentral.services.azureml.net/workspaces/92e7c840c83f4673ac594e767da8b538/services/e8b5c75d168345189225fcb5eab964d5/execute?api-version=2.0";
                const string apiKey   = "PjAGXQN7aI8FhJ+bVPi7wFEt6QeUzLMTkx7FTkOcjxakVv2Fq4r8VNdnirlK2tBSIqp58sF4UiJ1tXT+l2eiTQ==";

                System.Net.WebRequest req = System.Net.WebRequest.Create(endpoint);
                req.ContentType = "application/json";
                req.Method      = "POST";
                req.Headers.Add(string.Format("Authorization:Bearer {0}", apiKey));


                //create a stream
                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(jsonMsg.ToString());
                req.ContentLength = bytes.Length;
                System.IO.Stream os = req.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);
                os.Close();

                //get the response
                System.Net.WebResponse resp = req.GetResponse();

                Stream responseStream = CopyAndClose(resp.GetResponseStream());
                // Do something with the stream
                StreamReader reader         = new StreamReader(responseStream, Encoding.UTF8);
                String       responseString = reader.ReadToEnd();
                tracingService.Trace("json response: {0}", responseString);

                responseStream.Position = 0;
                //deserialize the response to a myjsonresponse object
                JsonResponse myResponse = new JsonResponse();
                System.Runtime.Serialization.Json.DataContractJsonSerializer deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myResponse.GetType());
                myResponse = deserializer.ReadObject(responseStream) as JsonResponse;

                tracingService.Trace("Scored Label- " + myResponse.Results.Output1.Value.Values[0][9]);
                tracingService.Trace("Scored Probablility- " + myResponse.Results.Output1.Value.Values[0][10]);


                titanicEntity.Attributes.Add("new_scoredlabel", myResponse.Results.Output1.Value.Values[0][9]);
                titanicEntity.Attributes.Add("new_scoredprobability", myResponse.Results.Output1.Value.Values[0][10]);
            }

            catch (WebException exception)
            {
                string str = string.Empty;
                if (exception.Response != null)
                {
                    using (StreamReader reader =
                               new StreamReader(exception.Response.GetResponseStream()))
                    {
                        str = reader.ReadToEnd();
                    }
                    exception.Response.Close();
                }
                if (exception.Status == WebExceptionStatus.Timeout)
                {
                    throw new InvalidPluginExecutionException(
                              "The timeout elapsed while attempting to issue the request.", exception);
                }
                throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                                                                        "A Web exception ocurred while attempting to issue the request. {0}: {1}",
                                                                        exception.Message, str), exception);
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }

            tracingService.Trace(".Execute(), Correlation Id: {0}", context.CorrelationId);
        }
        /// <summary>
        /// 向服务器发送数据或请求数据
        /// </summary>
        /// <param name="data">向服务器发送的数据</param>
        public string Start(byte[] data)
        {
            Uri        endPoint = new Uri(this._Url, UriKind.Absolute);
            WebRequest request  = WebRequest.Create(endPoint);

            request.Method      = _method;
            request.Timeout     = _timeout; //超时时间
            request.ContentType = "application/x-www-form-urlencoded";
            if (data != null && data.Length > 0)
            {
                request.ContentLength = data.Length;
            }

            if (this._isAsync) //异步方式
            {
                #region 向服务器端POST信息
                request.BeginGetRequestStream(new AsyncCallback((asyncResult) =>
                {
                    WebRequest webRequest = (WebRequest)asyncResult.AsyncState;
                    try
                    {
                        if (data != null && data.Length > 0)
                        {
                            Stream postStream = webRequest.EndGetRequestStream(asyncResult);
                            postStream.Write(data, 0, data.Length);
                            postStream.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        if (this.DataErrorEvent != null)
                        {
                            this.DataErrorEvent(null, new DataMutualEventArgs(ex.Message, null));//调用数据异常事件
                        }
                    }
                    #region 向服务器端请求返回信息
                    //WebRequest类的一个特性就是可以异步请求页面。由于在给主机发送请求到接收响应之间有很长的延迟,因此,异步请求页面就显得比较重要。
                    //像WebClient.DownloadData()和WebRequest.GetResponse()等方法,在响应没有从服务器回来之前,是不会返回的。
                    //如果不希望在那段时间中应用程序处于等待状态,可以使用BeginGetResponse() 方法和 EndGetResponse()方法,
                    //BeginGetResponse()方法可以异步工作,并立即返回。在底层,运行库会异步管理一个后台线程,从服务器上接收响应。
                    //BeginGetResponse() 方法不返回WebResponse对象,而是返回一个执行IAsyncResult接口的对象。使用这个接口可以选择或等待可用的响应,然后调用EndGetResponse()搜集结果。
                    request.BeginGetResponse(new AsyncCallback((ar) =>
                    {
                        try
                        {
                            WebRequest wrq = (WebRequest)ar.AsyncState;
                            //对应 BeginGetResponse()方法,在此处调用EndGetResponse()搜集结果。
                            //WebResponse类代表从服务器获取的数据。调用EndGetResponse方法,实际上是把请求发送给Web服务器,创建一个Response对象。
                            WebResponse wrs = wrq.EndGetResponse(ar);
                            // 读取WebResponse对象中内含的从服务器端返回的结果数据流
                            using (Stream responseStream = wrs.GetResponseStream())
                            {
                                //StreamReader reader = new StreamReader(responseStream);
                                //string retGet = reader.ReadToEnd();//服务器返回的数据
                                if (this.DataReceivedEvent != null)
                                {
                                    this.DataReceivedEvent(null, new DataMutualEventArgs(null, responseStream));//调用数据接收事件
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            if (this.DataErrorEvent != null)
                            {
                                this.DataErrorEvent(null, new DataMutualEventArgs(ex.Message, null));//调用数据异常事件
                            }
                        }
                    }), webRequest);
                    #endregion
                }), request);
                return(string.Empty);

                #endregion
            }
            else  //同步方式
            {
                #region  步方式
                if (data != null && data.Length > 0)
                {
                    // 取得发向服务器的流
                    System.IO.Stream newStream = request.GetRequestStream();
                    // 使用 POST 方法请求的时候,实际的参数通过请求的 Body 部分以流的形式传送
                    newStream.Write(data, 0, data.Length);
                    // 完成后,关闭请求流.
                    newStream.Close();
                }
                // GetResponse 方法才真的发送请求,等待服务器返回
                try
                {
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                    Stream stream = response.GetResponseStream();
                    if (this.DataReceivedEvent != null)
                    {
                        this.DataReceivedEvent(null, new DataMutualEventArgs(null, stream));//调用数据接收事件
                    }
                    TextReader tr = new StreamReader(stream);
                    return(tr.ReadToEnd());
                }
                catch (Exception ex)
                {
                    return(ex.Message);
                }
                #endregion
            }
        }
Exemple #47
0
    public static void Main(string[] args)
    {
        if (!HttpListener.IsSupported)
        {
            Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
            return;
        }

        // Create a listener.
        HttpListener listener = new HttpListener();

        // Add the prefixes.
        listener.Prefixes.Add("http://+:42000/");

        int sessionCounter = 0;
        Dictionary <int, SCXML> sessions = new Dictionary <int, SCXML>();

        listener.Start();

        while (true)
        {
            // Note: The GetContext method blocks while waiting for a request.
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;

            // Obtain a response object.
            HttpListenerResponse response = context.Response;
            System.IO.Stream     output   = response.OutputStream;

            String jsonBody = new StreamReader(request.InputStream).ReadToEnd();

            //Dictionary<string, Dictionary<string,string>> values = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string,string>>>(jsonBody);
            JObject reqJson = JObject.Parse(jsonBody);

            JToken scxmlToken, eventToken, sessionJsonToken;
            int    sessionToken;

            try{
                if (reqJson.TryGetValue("load", out scxmlToken))
                {
                    Console.WriteLine("Loading new statechart");

                    string         scxmlStr             = scxmlToken.ToString();
                    SCXML          scxml                = new SCXML(new System.Uri(scxmlStr));
                    IList <string> initialConfiguration = scxml.Start();

                    sessionToken           = sessionCounter++;
                    sessions[sessionToken] = scxml;

                    // Construct a response.
                    string responseString = TestServer.getResponseJson(sessionToken, initialConfiguration);
                    System.Console.WriteLine(responseString);
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                    // Get a response stream and write the response to it.
                    response.ContentLength64 = buffer.Length;
                    output.Write(buffer, 0, buffer.Length);
                }
                else if (reqJson.TryGetValue("event", out eventToken) && reqJson.TryGetValue("sessionToken", out sessionJsonToken))
                {
                    string eventName = (string)reqJson["event"]["name"];
                    sessionToken = (int)reqJson["sessionToken"];

                    IList <string> nextConfiguration = sessions[sessionToken].Gen(eventName, null);

                    string responseString = TestServer.getResponseJson(sessionToken, nextConfiguration);
                    byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    output.Write(buffer, 0, buffer.Length);
                }
                else
                {
                    string responseString = "Unrecognized request.";
                    byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    output.Write(buffer, 0, buffer.Length);
                }
            }catch (Exception e) {
                string responseString = "An error occured: " + e.ToString();
                byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                output.Write(buffer, 0, buffer.Length);
            }

            output.Close();
        }
    }
        public static void HTTPHandler()
        {
            while (listener.IsListening)
            {
                try
                {
                    Console.WriteLine("Starting HTTP Client to Auto-get port and IP...");

                    string server_metadata = string.Empty;
                    using (WebClient client = new WebClient())
                    {
                        server_metadata = client.DownloadString("http://www.growtopia2.com/growtopia/server_data.php");
                        client.Dispose();
                    }

                    if (server_metadata != "")
                    {
                        Console.WriteLine("Got response, server metadata:\n" + server_metadata);
                        Console.WriteLine("Parsing server metadata...");

                        string[] tokens = server_metadata.Split('\n');
                        foreach (string s in tokens)
                        {
                            if (s[0] == '#')
                            {
                                continue;
                            }
                            if (s.StartsWith("RTENDMARKERBS1001"))
                            {
                                continue;
                            }
                            string key   = s.Substring(0, s.IndexOf('|')).Replace("\n", "");
                            string value = s.Substring(s.IndexOf('|') + 1);


                            switch (key)
                            {
                            case "server":
                            {
                                // server ip
                                MainForm.Growtopia_Master_IP = value.Substring(0, value.Length - 1);
                                break;
                            }

                            case "port":
                            {
                                MainForm.Growtopia_Master_Port = ushort.Parse(value);
                                break;
                            }

                            default:
                                break;
                            }
                        }
                        MainForm.Growtopia_IP   = MainForm.Growtopia_Master_IP;
                        MainForm.Growtopia_Port = MainForm.Growtopia_Master_Port;
                        Console.WriteLine("Parsing done, detected IP:Port -> " + MainForm.Growtopia_IP + ":" + MainForm.Growtopia_Port.ToString());
                    }

                    HttpListenerContext  context  = listener.GetContext();
                    HttpListenerRequest  request  = context.Request;
                    HttpListenerResponse response = context.Response;
                    Console.WriteLine("New request from client:\n" + request.RawUrl + " " + request.HttpMethod + " " + request.UserAgent);
                    if (request.HttpMethod == "POST")
                    {
                        byte[] buffer = Encoding.UTF8.GetBytes(
                            "server|127.0.0.1\n" +
                            "port|2\n" +
                            "type|1\n" +
                            "beta_server|127.0.0.1\n" +
                            "beta_port|2\n" +
                            "meta|growbrew.com\n");

                        response.ContentLength64 = buffer.Length;
                        System.IO.Stream output = response.OutputStream;
                        output.Write(buffer, 0, buffer.Length);
                        output.Close();
                        response.Close();
                    }
                }
                catch (HttpListenerException ex)
                {
                    Console.WriteLine(ex.Message);
                    // probably cuz we stopped it, no need to worry.
                }
            }
        }
Exemple #49
0
        public void Save(System.IO.Stream OutputStream, System.Web.HttpResponse response)
        {
            string filename        = "Export_" + Guid.NewGuid().ToString();
            string completePathOne = GenerateUniquePath(filename, "xlsx");
            string completePathTwo = GenerateUniquePath(filename, "xls");
            string completePath    = null;
            string tableName       = null;

            ISDWorksheet ws = (ISDWorksheet)this.Worksheets[0];
            ISDTable     ta = ws.Table;

            tableName = ws.Name;
            ArrayList       rows = ta.Rows;
            ISDWorksheetRow row0 = null;

            if (rows.Count > 0)
            {
                row0 = (ISDWorksheetRow)rows[0];
            }

            ISDWorksheetRow row1 = row0;

            if (rows.Count > 1)
            {
                row1 = (ISDWorksheetRow)rows[1];
            }

            ArrayList cols     = ta.Columns;
            string    colDefs  = GetColumnDefinitions(cols, row0.Cells, row1.Cells, true);
            string    colNames = GetColumnDefinitions(cols, row0.Cells, row1.Cells, false);

            completePath = completePathTwo;

            HSSFWorkbook hssfwb = new HSSFWorkbook();

            IDataFormat format = hssfwb.CreateDataFormat();

            ISheet sh = hssfwb.CreateSheet("Sheet1");

            int rIndex = 0;

            IRow r = sh.CreateRow(rIndex);

            int c = 0;


            HSSFCellStyle[] styles = new HSSFCellStyle[row0.Cells.Count + 1];

            foreach (ISDWorksheetCell hCell in row0.Cells)
            {
                HSSFCellStyle style = (HSSFCellStyle)hssfwb.CreateCellStyle();
                ICell         ce    = r.CreateCell(c);

                ce.SetCellValue(hCell.Text);

                style.WrapText = true;
                styles[c]      = (HSSFCellStyle)hssfwb.CreateCellStyle();
                ce.CellStyle   = style;
                c += 1;
            }

            for (rIndex = 1; rIndex <= rows.Count - 1; rIndex++)
            {
                ISDWorksheetRow currentRow = (ISDWorksheetRow)rows[rIndex];

                r = sh.CreateRow(rIndex);

                c = 0;

                for (int i = 0; i <= currentRow.Cells.Count - 1; i++)
                {
                    //myValue = myValue.Replace("$", "").Replace(",", "")
                    ICell ce = r.CreateCell(c);

                    HSSFCellStyle    style = styles[i];
                    ISDWorksheetCell dCell = (ISDWorksheetCell)currentRow.Cells[i];

                    string formatStr = dCell.Format;
                    if (dCell.Type == ISDDataType.ISDInteger || dCell.Type == ISDDataType.ISDNumber)
                    {
                        ce.SetCellType(CellType.NUMERIC);

                        if (dCell.Value != null)
                        {
                            ce.SetCellValue(Convert.ToDouble(dCell.Value));
                        }

                        if (GetBuildInFormat(dCell.Format) > 0)
                        {
                            style.DataFormat = HSSFDataFormat.GetBuiltinFormat(dCell.Format);
                        }
                        else
                        {
                            System.Globalization.NumberFormatInfo info = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
                            if (string.IsNullOrEmpty(dCell.Format) || dCell.Format == null)
                            {
                                formatStr = "##0.00";
                            }
                            else if (dCell.Format.Contains("C") || dCell.Format.Contains("c"))
                            {
                                formatStr = info.CurrencySymbol + "##0.00";
                            }
                            else if (dCell.Format.Contains("P") || dCell.Format.Contains("p"))
                            {
                                formatStr = "##0.00" + info.PercentSymbol;
                            }
                            else if (dCell.Format.Contains(info.CurrencySymbol) || dCell.Format.Contains(info.PercentSymbol))
                            {
                                // use the user given display format
                            }
                            else
                            {
                                formatStr = "##0.00";
                            }
                            style.DataFormat = format.GetFormat(formatStr);
                        }
                    }
                    else if (dCell.Type == ISDDataType.ISDDateTime)
                    {
                        if (dCell.Value != null)
                        {
                            ce.SetCellType(CellType.NUMERIC);
                            ce.SetCellValue(Convert.ToDateTime(dCell.Value));
                        }

                        if (GetBuildInFormat(dCell.Format) > 0)
                        {
                            style.DataFormat = HSSFDataFormat.GetBuiltinFormat(dCell.Format);
                        }
                        else
                        {
                            System.Globalization.DateTimeFormatInfo info = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;

                            // convert the date format understood by Excel
                            // see http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.71).aspx
                            switch (dCell.Format)
                            {
                            case "d":
                                formatStr = info.ShortDatePattern;
                                break;

                            case "D":
                                formatStr = info.LongDatePattern;
                                break;

                            case "t":
                                formatStr = info.ShortTimePattern;
                                break;

                            case "T":
                                formatStr = info.LongTimePattern;
                                break;

                            case "f":
                                formatStr = info.LongDatePattern + " " + info.ShortTimePattern;
                                break;

                            case "F":
                                formatStr = info.FullDateTimePattern;
                                break;

                            case "g":
                                formatStr = info.ShortDatePattern + " " + info.ShortTimePattern;
                                break;

                            case "G":
                                formatStr = info.ShortDatePattern + " " + info.LongTimePattern;
                                break;

                            case "M":
                            case "m":
                                formatStr = info.MonthDayPattern;
                                break;

                            case "R":
                            case "r":
                                formatStr = info.RFC1123Pattern;
                                break;

                            case "s":
                                formatStr = info.SortableDateTimePattern;
                                break;

                            case "u":
                                formatStr = info.UniversalSortableDateTimePattern;
                                break;

                            case "U":
                                formatStr = info.FullDateTimePattern;
                                break;

                            case "Y":
                            case "y":
                                formatStr = info.YearMonthPattern;
                                break;

                            default:
                                formatStr = info.ShortDatePattern;
                                break;
                            }

                            // some pattern above might return t but this is not recognized by Excel, so remove it
                            formatStr        = formatStr.Replace("t", "");
                            style.DataFormat = format.GetFormat(formatStr);
                        }
                    }
                    else
                    {
                        ce.SetCellType(CellType.STRING);
                        if (dCell.Value != null)
                        {
                            string myValue = dCell.Text;
                            if (myValue.Length > 255)
                            {
                                myValue = myValue.Substring(0, 255);
                            }
                            ce.SetCellValue(myValue);
                        }

                        if (GetBuildInFormat(dCell.Format) > 0)
                        {
                            style.DataFormat = HSSFDataFormat.GetBuiltinFormat(dCell.Format);
                        }
                        else
                        {
                            style.DataFormat = HSSFDataFormat.GetBuiltinFormat("TEXT");
                            style.WrapText   = true;
                        }
                    }

                    ce.CellStyle = style;
                    c           += 1;
                }
            }

            MemoryStream ms = new MemoryStream();

            hssfwb.Write(ms);

            string NPOIDownloadFileName = this.Properties.Title;

            if (completePath.EndsWith(".xlsx"))
            {
                NPOIDownloadFileName += ".xlsx";
            }
            else
            {
                NPOIDownloadFileName += ".xls";
            }

            response.ClearHeaders();
            response.Clear();
            response.Cache.SetCacheability(System.Web.HttpCacheability.Private);
            response.Cache.SetMaxAge(new TimeSpan(0));
            response.Cache.SetExpires(new DateTime(0));
            response.Cache.SetNoServerCaching();
            response.AppendHeader("Content-Disposition", ("attachment; filename=\"" + (NPOIDownloadFileName + "\"")));
            response.ContentType = "application/vnd.ms-excel";

            OutputStream.Write(ms.ToArray(), 0, ms.ToArray().Length);

            return;
        }
        private void OnFileDownloadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                {
                    ExMessageBox.Show("ダウンロードファイル保存処理で通信エラーが発生しました。" + Environment.NewLine + e.Error);
                }
                else
                {
                    try
                    {
                        byte[] data = ReadBinaryData(e.Result);

                        string _msg = "";
                        try
                        {
                            ExUTF8Encoding _encode = new ExUTF8Encoding();
                            _msg = _encode.OnGetString(data, 0, 200);
                            if (_msg.Length > 25)
                            {
                                if (_msg.IndexOf("error message start ==>") != -1)
                                {
                                    MessageBox.Show("ダウンロードファイル保存処理で予期せぬエラーが発生しました。" + Environment.NewLine + _msg.Replace("error message start ==>", ""));
                                    return;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }

                        using (System.IO.Stream fs = (System.IO.Stream) this.saveDialog.OpenFile())
                        {
                            fs.Write(data, 0, data.Length);
                            fs.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        ExMessageBox.Show("ダウンロードファイル保存処理で予期せぬエラーが発生しました。" + Environment.NewLine + ex.Message);
                        return;
                    }
                }
            }
            finally
            {
                if (this.utlParentFKey != null)
                {
                    this.utlParentFKey.IsEnabled = true;
                }

                this.saveDialog = null;
                if (dlgWin != null)
                {
                    dlgWin.Close();
                    dlgWin = null;
                }
                GC.Collect();
            }
        }
Exemple #51
0
        public AuthData GetAuthData(string openstackComponentName)
        {
            var            authData = new AuthData();
            var            uri      = new Uri(string.Format("{0}/tokens", _identity.AuthEndpoint));
            HttpWebRequest request  = (HttpWebRequest)HttpWebRequest.Create(uri);

            request.Method      = "POST";
            request.ContentType = "application/json";
            var bodyObject = new RequestBodyWrapper()
            {
                auth = new RequestBody()
                {
                    passwordCredentials = new PasswordCredentials()
                    {
                        password = _identity.Password,
                        username = _identity.Username,
                    },
                    tenantName = _identity.TenantName
                }
            };

            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string body = oSerializer.Serialize(bodyObject);

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(body);
            request.ContentLength = bytes.Length;
            System.IO.Stream os = request.GetRequestStream();
            os.Write(bytes, 0, bytes.Length); //Push it out there
            os.Close();

            HttpStatusCode  statusCode;
            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }
            statusCode = response.StatusCode;
            if (statusCode.Equals(HttpStatusCode.OK))
            {
                try
                {
                    byte[]         responseBody = { };
                    JsonTextReader reader       = new JsonTextReader(new StreamReader(response.GetResponseStream()));
                    reader.Read();
                    JsonSerializer se              = new JsonSerializer();
                    JObject        parsedData      = (JObject)se.Deserialize(reader);
                    var            responseContent = parsedData["access"];
                    authData.AuthToken = responseContent["token"]["id"].ToString();
                    _identity.TenantId = responseContent["token"]["tenant"]["id"].ToString();
                    foreach (var endpoint in responseContent["serviceCatalog"])
                    {
                        var subEndpoint  = endpoint["endpoints"];
                        var endpointName = endpoint["name"].ToString();
                        if (endpointName.Equals(openstackComponentName))
                        {
                            var endpointUrl = subEndpoint.FirstOrDefault()["publicURL"].ToString();
                            authData.Endpoint = endpointUrl;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception occured ", ex.Message);
                }
            }
            response.Close();
            return(authData);
        }
Exemple #52
0
        public static string HttpPost(string URI, List <KeyValuePair <string, string> > parameters, List <KeyValuePair <string, string> > headers)
        {
            try
            {
                System.Net.WebRequest req = System.Net.WebRequest.Create(URI);

                //req.Proxy = new System.Net.WebProxy(ProxyString, true);
                req.Timeout     = 600000;
                req.ContentType = "application/x-www-form-urlencoded";

                foreach (KeyValuePair <string, string> hdr in headers)
                {
                    if (!WebHeaderCollection.IsRestricted(hdr.Key))
                    {
                        req.Headers.Add(hdr.Key, hdr.Value);
                    }
                }

                string param = "";
                foreach (KeyValuePair <string, string> pr in parameters)
                {
                    param += pr.Key.ToString() + "=" + pr.Value.ToString() + "&";
                }

                param = param.TrimEnd('&');

                req.Method = "POST";
                //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(param);
                req.ContentLength = bytes.LongLength;
                System.IO.Stream os = req.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);                 //Push it out there
                os.Close();

                System.Net.WebResponse resp = req.GetResponse();
                if (resp == null)
                {
                    return(null);
                }
                System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                return(sr.ReadToEnd().Trim());
            }
            catch (WebException ex)
            {
                string errResponse = "";
                using (WebResponse response = ex.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    using (Stream data = response.GetResponseStream())
                        using (var reader = new StreamReader(data))
                        {
                            errResponse = reader.ReadToEnd();
                            Console.WriteLine(errResponse);
                        }
                }

                if (errResponse == "")
                {
                    throw new Exception(ex.Message);
                }
                else
                {
                    return(errResponse);
                }
            }
        }
Exemple #53
0
        static void Main(string[] args)
        {
            var h  = DBFactory.CreateDBHelper(@"Data Source=E:\git\memberManager\db\membermanager.db;Version=3;", DBType.SQLite);
            var tb = h.GetTableWithSQL("SELECT NAME FROM sqlite_master WHERE type='table'");

            #region id generator
            IIDGenerator  iDGenerator = IDGeneratorFactory.Create(GeneratorType.SnowFlak);
            List <string> idlist      = new List <string>();
            for (int i = 0; i < 10000; i++)
            {
                idlist.Add(iDGenerator.Generate());
            }

            #endregion

            TestClass tc = new TestClass
            {
                tc = new TestClass
                {
                    a  = "hello",
                    b  = "word",
                    tc = new TestClass
                    {
                        a = "deep",
                    }
                },
                test = new List <TestClass>
                {
                    new TestClass
                    {
                        a = "<",
                    }
                },
            };
            #region xml testing
            TestRequest req = new TestRequest
            {
                c = new TestClass
                {
                    a  = "a",
                    b  = "b",
                    d  = "d",
                    dt = DateTime.Now,
                }
            };
            ISerializable serial = new XmlSerializor();
            var           xml    = serial.Serialize(req);

            var obj = serial.Deserialize <TestRequest>(xml);

            Dictionary <string, object> arg = new Dictionary <string, object>();
            arg["a"] = "a";
            arg["b"] = 3;
            arg["c"] = req;
            xml      = serial.Serialize(arg);
            var dicobj = serial.Deserialize <Dictionary <string, object> >(xml);
            #endregion
            //string jsonstring = "{\"Buyers\":[{\"ID\":\"395f7ce8de8340eda2dfd22098c81290\",\"Name\":\"爱的色放\",\"CardType\":\"1\",\"IdentityCode\":\"4444444444\",\"Phone\":\"123123123123\",\"Gender\":\"1\",\"Marrage\":\"1\",\"Address\":\"啊都是法师打发而且额外人\",\"OrignalName\":\"\",\"OrignalIdentityCode\":\"\",\"BankCode\":\"\",\"BankType\":\"1\",\"WorkUnit\":\"\",\"Quotient\":\"222\"},{\"ID\":\"\",\"Name\":\"阿萨法 \",\"CardType\":\"1\",\"IdentityCode\":\"986799283948723984\",\"Phone\":\"123123\",\"Gender\":\"2\",\"Marrage\":\"1\",\"Address\":\"三个地方集团研究研究\",\"OrignalName\":\"\",\"OrignalIdentityCode\":\"\",\"BankCode\":\"\",\"BankType\":\"\",\"WorkUnit\":\"\",\"Quotient\":\"333\"},{\"ID\":\"712feaff6c034244ab3f066268b9fe5a\",\"Name\":\"阿斯顿飞\",\"CardType\":\"1\",\"IdentityCode\":\"12312312312323\",\"Phone\":\"123123123\",\"Gender\":\"1\",\"Marrage\":\"1\",\"Address\":\"嘎达嗦嘎多个地方十多个地方各个\",\"OrignalName\":\"\",\"OrignalIdentityCode\":\"\",\"BankCode\":\"\",\"BankType\":\"1\",\"WorkUnit\":\"\",\"Quotient\":\"222\"}],\"Sellers\":[{\"ID\":\"55b71c225dc841a7b99ead4cecc601c5\",\"Name\":\"aeeboo\",\"CardType\":\"1\",\"IdentityCode\":\"234234235235\",\"Phone\":\"324234234234\",\"Gender\":\"1\",\"Marrage\":\"2\",\"Address\":\"的方式购房合同和投入和\",\"OrignalName\":\"\",\"OrignalIdentityCode\":\"\",\"BankCode\":\"\",\"BankType\":\"2\",\"WorkUnit\":\"\",\"Quotient\":\"111\"},{\"ID\":\"\",\"Name\":\"阿萨德飞44\",\"CardType\":\"1\",\"IdentityCode\":\"237856234\",\"Phone\":\"34234234\",\"Gender\":\"1\",\"Marrage\":\"1\",\"Address\":\"然后统一集团研究与\",\"OrignalName\":\"\",\"OrignalIdentityCode\":\"\",\"BankCode\":\"\",\"BankType\":\"\",\"WorkUnit\":\"\",\"Quotient\":\"123\"}],\"Assets\":[{\"ID\":\"\",\"Code\":\"44444444\",\"Usage\":\"1\",\"Position\":\"2\",\"Address\":\"景田西路八个道路\",\"Area\":\"123\",\"RegPrice\":\"44232\"},{\"ID\":\"\",\"Code\":\"1412412132\",\"Usage\":\"1\",\"Position\":\"1\",\"Address\":\"水电费个人个人高\",\"Area\":\"234324\",\"RegPrice\":\"123123\"}],\"Project\":{\"Source\":\"1\",\"AgentName\":\"213213\",\"CertificateData\":\"2015-08-05\",\"AgentContact\":\"\",\"Rebater\":\"\",\"RebateAccount\":\"\",\"OtherRebateInfo\":\"\",\"OrignalMortgageBank\":\"1\",\"OrignalMortgageBranch\":\"阿斯顿发顺丰\",\"OrignalFundCenter\":\"1\",\"OrignalFundBranch\":\"\",\"SupplyCardCopy\":\"\",\"OrignalCreditPI\":\"123123\",\"OrignalCreditCommerceMoney\":\"123\",\"OrignalCreditFundMoney\":\"123\",\"AssetRansomCustomerManager\":\"124142\",\"AssetRansomContactPhone\":\"24124\",\"NewCreditBank\":\"1\",\"NewCreditBranch\":\"2r323\",\"ShortTermAssetRansomBank\":\"1\",\"ShortTermAssetRansomBranch\":\"\",\"GuaranteeMoney\":\"123\",\"GuaranteeMonth\":\"1231\",\"BuyerCreditCommerceMoney\":\"213\",\"BuyerCreditFundMoney\":\"2\",\"LoanMoney\":\"123123\",\"DealMoney\":\"123123\",\"EarnestMoney\":\"123123\",\"SupervisionMoney\":\"123123\",\"SupervisionBank\":\"12123\",\"AssetRansomMoney\":\"122323\",\"CustomerPredepositMoney\":\"323232\",\"CreditReceiverName\":\"23123\",\"CreditReceiverBank\":\"2323\",\"CreditReceiverAccount\":\"2323\",\"TrusteeshipAccount\":\"\",\"AssetRansomPredictMoney\":\"2323\",\"AssetRansomer\":\"232323\",\"AssetRansomType\":\"1\",\"PredictDays\":\"2323\",\"ChargeType\":\"1\",\"CheckNumbersAndLimit\":\"123123\",\"Stagnationer\":\"\"},\"token\":\"0cbbd08b6b694428a30afe52098e5f7a\"}";
            //var json = JsonHelper.Deserialize<AddProjectServiceForm>(jsonstring);
            #region domain
            //AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
            //AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve1;
            //AppDomainSetup info = new AppDomainSetup();
            //info.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory + "Modules";
            //AppDomain domain = AppDomain.CreateDomain("mydomain", null, info);
            //Console.WriteLine(domain.BaseDirectory);
            //var allass = domain.GetAssemblies();
            //var ass = domain.Load(new AssemblyName("Controller"));
            //allass = domain.GetAssemblies();
            //var type = ass.GetType("SOAFramework.Library.HttpServer");
            //var instance = Activator.CreateInstance(type, null);
            //var start = type.GetMethod("Start");
            //start.Invoke(instance, new object[] { new string[] { "http://10.1.50.195:8094/c" } });
            //domain.AssemblyLoad += Domain_AssemblyLoad;
            #endregion

            #region http server
            Console.WriteLine("begin");
            NodeServer nodeserver = new NodeServer("http://10.1.50.195:8094/");
            nodeserver.Start();
            Console.ReadLine();
            //nodeserver.Close();

            HttpServer server = new HttpServer(new string[] { "http://10.1.50.195:8094/a" });
            server.Executing += new HttpExecutingHandler((a, b) =>
            {
                StreamReader reder = new StreamReader(b.Request.InputStream, System.Text.Encoding.UTF8);
                string post        = reder.ReadToEnd();
                Console.WriteLine("key:" + post);
                return("");
            });
            server.Start();

            //HttpServer server2 = new HttpServer(new string[] { "http://10.1.50.195:8094/b" });
            //server2.Start();
            Console.ReadLine();

            string[] prefix = new string[] { "http://*****:*****@"http://localhost/Service/Execute/SOAFramework.Service.Server.DefaultService/DiscoverService", data);
            testresult = ZipHelper.UnZip(testresult);
            List <ServiceInfo>          serviceList   = JsonHelper.Deserialize <List <ServiceInfo> >(testresult);
            string                      path          = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + @"\Templates\SDKRequest.cst";
            Dictionary <string, object> argsCodeSmith = new Dictionary <string, object>();
            argsCodeSmith["RequestNameSpace"] = "a.b.c";
            argsCodeSmith["ServiceInfo"]      = serviceList[0];
            string render = CodeSmithHelper.GenerateString(path, argsCodeSmith);

            string  fileName = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\SOAFramework.Library.CodeSmithConsole.exe ";
            Process p        = new Process();
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.FileName               = fileName;
            p.StartInfo.Arguments              = " " + path.Replace(@"\\", @"\" + " ") + " " + JsonHelper.Serialize(argsCodeSmith).Replace("\"", "\\\"") + " ";
            p.StartInfo.RedirectStandardInput  = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.Start();
            p.WaitForExit();
            return;

            #endregion

            #region razor
            //string strr = File.ReadAllText("Temp.txt");
            //Dictionary<string, object> dicargs = new Dictionary<string, object>();
            //dicargs["a"] = "22222";
            //string r = Razor.Parse(strr, dicargs);
            #endregion

            #region json tester
            //List<TestClass> list = new List<TestClass>();
            //for (int i = 0; i < 10; i++)
            //{
            //    TestClass c = new TestClass
            //    {
            //        a = "a" + i.ToString(),
            //        b = "b" + i.ToString(),
            //        dic = new Dictionary<string, string>(),
            //    };
            //    c.dic["dic1"] = "dic1" + i.ToString();
            //    c.dic["dic2"] = "dic2" + i.ToString();
            //    c.dic["dic3"] = "dic3" + i.ToString();
            //    c.test = new List<TestClass>();
            //    c.test.Add(new TestClass { a = "aa" + i.ToString(), b = "bb" + i.ToString() });
            //    c.test.Add(new TestClass { a = "cc" + i.ToString(), b = "dd" + i.ToString() });
            //    list.Add(c);
            //}
            //watch.Start();
            //string strjson = JsonHelper.Serialize(list, false);
            //watch.Stop();
            //Console.WriteLine("序列化:{0}", watch.ElapsedMilliseconds);
            //watch.Reset();
            //watch.Start();
            //List<TestClass> list1 = JsonHelper.Deserialize<List<TestClass>>(strjson);
            //watch.Stop();
            //Console.WriteLine("反序列化:{0}", watch.ElapsedMilliseconds);
            //TestResponse re = JsonHelper.Deserialize<TestResponse>("{\"IsError\":false,\"Data\":[{\"InterfaceName\":\"SOAFramework.Service.Server.DefaultService.DiscoverService\"}]}");
            #endregion

            #region custom wcf binding
            //string baseAddress = "Http://localhost/Service";
            //ServiceHost host = new WebServiceHost(typeof(SOAService), new Uri(baseAddress));
            //host.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "soap");
            //WebHttpBinding webBinding = new WebHttpBinding();
            //webBinding.ContentTypeMapper = new MyRawMapper();
            //host.AddServiceEndpoint(typeof(IService), webBinding, "json").Behaviors.Add(new NewtonsoftJsonBehavior());
            //Console.WriteLine("Opening the host");
            //host.Open();

            //ChannelFactory<IService> factory = new ChannelFactory<IService>(new BasicHttpBinding(), new EndpointAddress(baseAddress + "/soap"));
            //IService proxy = factory.CreateChannel();
            //byte[] newdata;
            //TestClass c1 = new TestClass();
            //c1.a = "a";
            //List<TestClass> list1 = new List<TestClass>();
            //list1.Add(c1);
            //string strnewdata = JsonHelper.Serialize(list1);
            //newdata = Encoding.UTF8.GetBytes(strnewdata);
            //string newtestresult = HttpHelper.Post(@"http://localhost/Service/SOAFramework.Service.Server.DefaultService/DiscoverService", newdata);

            //Console.WriteLine("Now using the client formatter");
            //ChannelFactory<IService> newFactory = new ChannelFactory<IService>(webBinding, new EndpointAddress(baseAddress + "/json"));
            //newFactory.Endpoint.Behaviors.Add(new NewtonsoftJsonBehavior());
            //IService newProxy = newFactory.CreateChannel();

            //Console.WriteLine("Press ENTER to close");
            //Console.ReadLine();
            //host.Close();
            //Console.WriteLine("Host closed");
            #endregion

            #region wcf host
            WebServiceHost newhost = new WebServiceHost(typeof(SOAService));
            newhost.Open();
            newhost.Ping();
            #endregion

            #region zip tester
            string zip    = "i am a string, to be zipped!";
            string zipped = ZipHelper.Zip(zip, System.Text.Encoding.Default);
            zip = ZipHelper.UnZip(zipped);
            #endregion

            #region orm
            //string abc = Model.Users.Mapping.ColumnsMapping["PK_UserID"].ToString();
            //a c = new a();
            //c.b = "haha ";
            //c.t = new a();
            //c.t.b = "aaaaaa";
            //string str1 = JsonHelper.Serialize(c);

            //c = JsonHelper.Deserialize<a>(str1);

            //FTPClient f = new FTPClient();
            //f.FtpUrl = "ftp://localhost/";
            //f.FileName = "ha.txt";
            //f.UserName = "******";
            //f.Password = "******";
            //f.BufferSize = 10;
            //f.LocalFilePath = "e:";
            //f.Download();

            //sw.Stop();
            //Console.WriteLine("linq:" + sw.ElapsedTicks);
            //Model.Users objUser = new Model.Users();
            //Hashtable htArgs = new Hashtable();
            //htArgs["str"] = "ok";
            //WebServiceCaller wsCaller = new WebServiceCaller();
            //wsCaller.Action = "PostTest";
            //wsCaller.Args = htArgs;
            //wsCaller.Action = "GetTest";
            //wsCaller.WSUrl = @"http://*****:*****@"F:\TestOut.docx";
            //List<MethodArg> lstArg = new List<MethodArg>();
            //lstArg.Add(new MethodArg("there"));
            //cr.RequestData.MethodArgs = lstArg.ToArray();
            //cr.RequestType = WSDataType.JSON;
            //string str = cr.GetRequestString();
            //cr.ResponseType = WSDataType.JSON;
            //string strReturn = cr.SendRequest();
            //ServerResponse response = cr.GetResponse();
            //byte[] bytTemp = response.ResponseData;
            //Stream sw = File.Open(strFileName, FileMode.OpenOrCreate, FileAccess.Write);
            //sw.Write(bytTemp, 0, bytTemp.Length);
            //sw.Close();

            //Model.Users u = new Model.Users();
            //Model.Customer_AutoIncrease t = new Model.Customer_AutoIncrease();
            #endregion

            #region soa tester

            //testresult = HttpUtility.Get("http://localhost/Service/GetTest");

            argslist.Add(new SOAFramework.Service.SDK.Core.PostArgItem {
                Key = "url", Value = "http://localhost/"
            });
            //argslist.Add(new PostArgItem { Key = "usage", Value = "1.00" });
            strData = JsonHelper.Serialize("http://localhost/");
            //strData = "\"" + strData + "\"";
            data       = System.Text.Encoding.UTF8.GetBytes(strData);
            testresult = HttpHelper.Post(@"http://*****:*****@"http://localhost/Service/Execute/SOAFramework.Service.Server.DefaultService/DiscoverService", data);
            testresult = ZipHelper.UnZip(testresult);
            watch.Stop();
            Console.WriteLine("发现服务测试耗时{0}", watch.ElapsedMilliseconds);


            watch.Restart();
            argslist.Clear();
            strData    = JsonHelper.Serialize(argslist);
            data       = System.Text.Encoding.UTF8.GetBytes(strData);
            testresult = HttpHelper.Post(@"http://localhost/Service/Execute/SOAFramework.Service.Server.DefaultService/BigDataTest", data);
            watch.Stop();
            Console.WriteLine("大数据测试耗时{0}", watch.ElapsedMilliseconds);

            watch.Restart();
            //download test
            string filename = "预付款类型批量导入.xls";
            testresult = HttpHelper.Get(@"http://localhost/Service/Download/" + filename);
            //testresult = ZipHelper.UnZip(testresult);
            testresult.ToFile("D:\\" + filename);
            watch.Stop();
            Console.WriteLine("下载测试耗时{0}", watch.ElapsedMilliseconds);

            watch.Restart();
            //uploadtest
            string   uploadFileName = "D:\\预付款类型批量导入.xls";
            FileInfo file           = new FileInfo(uploadFileName);
            string   fileString     = file.FileToString();
            data       = System.Text.Encoding.UTF8.GetBytes(fileString);
            testresult = HttpHelper.Post(@"http://localhost/Service/Upload/" + file.Name, data);
            watch.Stop();
            Console.WriteLine("上传测试耗时{0}", watch.ElapsedMilliseconds);

            watch.Restart();
            int count = 10000;
            //for (int i = 0; i < count; i++)
            //{
            //    List<SOAFramework.Service.SDK.Core.PostArgItem> list = new List<SOAFramework.Service.SDK.Core.PostArgItem>();
            //    list.Add(new SOAFramework.Service.SDK.Core.PostArgItem { Key = "a", Value = JsonHelper.Serialize("hello world") });
            //    list.Add(new SOAFramework.Service.SDK.Core.PostArgItem { Key = "b", Value = JsonHelper.Serialize(new TestClass { a = "a", b = "b" }) });
            //    //list.Add(new PostArgItem { Key = "a", Value = "hello world" });
            //    //list.Add(new PostArgItem { Key = "b", Value = new TestClass { a = "a", b = "b" } });
            //    strData = JsonHelper.Serialize(list);
            //    data = System.Text.Encoding.UTF8.GetBytes(strData);
            //    //testresult = HttpHelper.Post(@"http://localhost/Service/Execute/SOAFramework.Service.Server.SOAService/Test", data);
            //    testresult = ZipHelper.UnZip(testresult);

            //    PerformanceRequest prequest = new PerformanceRequest();
            //    prequest.a = "hello world";
            //    prequest.b = new TestClass { a = "a", b = "b" };
            //    PerformanceResponse presponse = SDKFactory.Client.Execute(prequest);
            //}
            watch.Stop();
            Console.WriteLine("{1}次测试耗时{0}", watch.ElapsedMilliseconds, count);
            #endregion

            #region sdk testing
            //TestRequest request = new TestRequest();
            //TestResponse reseponse = SDKFactory.Client.Execute(request);
            #endregion

            Console.ReadLine();
        }
Exemple #54
0
        /// <summary>
        /// Listens for any requests and responds with the game server's config values
        /// </summary>
        private static void ProcessRequests()
        {
            while (_listener.IsListening)
            {
                try
                {
                    HttpListenerContext  context  = _listener.GetContext();
                    HttpListenerRequest  request  = context.Request;
                    HttpListenerResponse response = context.Response;

                    string requestMessage = $"HTTP:Received {request.Headers.ToString()}";
                    LogMessage(requestMessage);

                    IDictionary <string, string> config = null;

                    // For each request, "add" a connected player, but limit player count to 20.
                    const int maxPlayers = 20;
                    if (players.Count < maxPlayers)
                    {
                        players.Add(new ConnectedPlayer("gamer" + requestCount));
                    }
                    else
                    {
                        LogMessage($"Player not added since max of {maxPlayers} is reached. Current request count: {requestCount}.");
                    }

                    requestCount++;
                    GameserverSDK.UpdateConnectedPlayers(players);

                    config = GameserverSDK.getConfigSettings() ?? new Dictionary <string, string>();

                    config.Add("isActivated", _isActivated.ToString());
                    config.Add("assetFileText", _assetFileText);
                    config.Add("logsDirectory", GameserverSDK.GetLogsDirectory());
                    config.Add("installedCertThumbprint", _installedCertThumbprint);

                    if (_nextMaintenance != DateTimeOffset.MinValue)
                    {
                        config.Add("nextMaintenance", _nextMaintenance.ToLocalTime().ToString());
                    }

                    string content = JsonConvert.SerializeObject(config, Formatting.Indented);

                    response.AddHeader("Content-Type", "application/json");
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(content);
                    response.ContentLength64 = buffer.Length;
                    using (System.IO.Stream output = response.OutputStream)
                    {
                        output.Write(buffer, 0, buffer.Length);
                    }
                }
                catch (HttpListenerException httpEx)
                {
                    // This one is expected if we stopped the listener because we were asked to shutdown
                    LogMessage($"Got HttpListenerException: {httpEx.ToString()}, we are being shut down.");
                }
                catch (Exception ex)
                {
                    LogMessage($"Got Exception: {ex.ToString()}");
                }
            }
        }
        public static void UploadFile(string _FileName, string _UploadPath, string _FTPUser, string _FTPPass)
        {
            System.IO.FileInfo _FileInfo = new System.IO.FileInfo(_FileName);

            // Create FtpWebRequest object from the Uri provided
            System.Net.FtpWebRequest _FtpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(_UploadPath));

            // Provide the WebPermission Credentials
            _FtpWebRequest.Credentials = new System.Net.NetworkCredential(_FTPUser, _FTPPass);
            _FtpWebRequest.Proxy       = null;
            //_FtpWebRequest.ConnectionGroupName = _FileName;
            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            _FtpWebRequest.KeepAlive = false;

            // set timeout for 20 seconds
            _FtpWebRequest.Timeout = 30000;

            // Specify the command to be executed.
            _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            _FtpWebRequest.UseBinary = true;

            // Notify the server about the size of the uploaded file
            _FtpWebRequest.ContentLength = _FileInfo.Length;

            // The buffer size is set to 2kb
            int buffLength = 1024 * 4;

            byte[] buff = new byte[buffLength];

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            System.IO.FileStream _FileStream = _FileInfo.OpenRead();

            // Stream to which the file to be upload is written
            System.IO.Stream _Stream = _FtpWebRequest.GetRequestStream();

            try
            {
                // Read from the file stream 2kb at a time
                int contentLen = _FileStream.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    _Stream.Write(buff, 0, contentLen);
                    contentLen = _FileStream.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                _Stream.Close();
                _Stream.Dispose();
                _FileStream.Close();
                _FileStream.Dispose();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (_Stream != null)
                {
                    _Stream.Close();
                    _Stream.Dispose();
                }
                if (_FileStream != null)
                {
                    _FileStream.Close();
                    _FileStream.Dispose();
                }
                _FtpWebRequest = null;
            }
        }
Exemple #56
0
 private void UploadPacketToHandler(byte[] fileData, System.IO.Stream outputStream)
 {
     // Pipe the packet into the Steam to the Server
     outputStream.Write(fileData, 0, fileData.Length);
     outputStream.Close();
 }
Exemple #57
0
        private static void Main(string[] args)
        {
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("A more recent Windows version is required to use the HttpListener class.");
                return;
            }

            // Create a listener.
            HttpListener listener = new HttpListener();

            // Trap Ctrl-C and exit
            Console.CancelKeyPress += delegate
            {
                listener.Stop();
                System.Environment.Exit(0);
            };

            // Add the prefixes.
            if (args.Length != 0)
            {
                foreach (string s in args)
                {
                    listener.Prefixes.Add(s);
                    // don't forget to authorize access to the TCP/IP addresses localhost:xxxx and localhost:yyyy
                    // with netsh http add urlacl url=http://localhost:xxxx/ user="******"
                    // and netsh http add urlacl url=http://localhost:yyyy/ user="******"
                    // user="******" is language dependent, use user=Everyone in english
                }
            }
            else
            {
                Console.WriteLine("Syntax error: the call must contain at least one web server url as argument");
            }
            listener.Start();
            foreach (string s in args)
            {
                Console.WriteLine("Listening for connections on " + s);
            }

            while (true)
            {
                // Note: The GetContext method blocks while waiting for a request.
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request = context.Request;

                Header header = new Header((WebHeaderCollection)request.Headers);
                Console.WriteLine(header);

                string documentContents;
                using (Stream receiveStream = request.InputStream)
                {
                    using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                    {
                        documentContents = readStream.ReadToEnd();
                    }
                }
                Console.WriteLine($"Received request for {request.Url}");
                Console.WriteLine(documentContents);

                // Obtain a response object.
                HttpListenerResponse response = context.Response;

                // Construct a response.
                string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
                byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);
                // Get a response stream and write the response to it.
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                // You must close the output stream.
                output.Close();
            }
            // Httplistener neither stop ...
            // listener.Stop();
        }
Exemple #58
0
        internal void ExecuteQuery()
        {
            try
            {
                if (this.requestContentStream != null && this.requestContentStream.Stream != null)
                {
                    this.Request.SetRequestStream(this.requestContentStream);
                }
#if false
                if ((null != requestContent) && (0 < requestContent.Length))
                {
                    using (System.IO.Stream stream = Util.NullCheck(this.Request.GetRequestStream(), InternalError.InvalidGetRequestStream))
                    {
                        byte[] buffer       = requestContent.GetBuffer();
                        int    bufferOffset = checked ((int)requestContent.Position);
                        int    bufferLength = checked ((int)requestContent.Length) - bufferOffset;

                        // the following is useful in the debugging Immediate Window
                        // string x = System.Text.Encoding.UTF8.GetString(buffer, bufferOffset, bufferLength);
                        stream.Write(buffer, bufferOffset, bufferLength);
                    }
                }
#endif
                IODataResponseMessage response = null;
                response = this.RequestInfo.GetSyncronousResponse(this.Request, true);
                this.SetHttpWebResponse(Util.NullCheck(response, InternalError.InvalidGetResponse));

                if (HttpStatusCode.NoContent != this.StatusCode)
                {
                    using (Stream stream = this.responseMessage.GetStream())
                    {
                        if (null != stream)
                        {
                            Stream copy = this.GetAsyncResponseStreamCopy();
                            this.outputResponseStream = copy;

                            Byte[] buffer = this.GetAsyncResponseStreamCopyBuffer();

                            long copied = WebUtil.CopyStream(stream, copy, ref buffer);
                            if (this.responseStreamOwner)
                            {
                                if (0 == copied)
                                {
                                    this.outputResponseStream = null;
                                }
                                else if (copy.Position < copy.Length)
                                {   // In Silverlight, generally 3 bytes less than advertised by ContentLength are read
                                    ((MemoryStream)copy).SetLength(copy.Position);
                                }
                            }

                            this.PutAsyncResponseStreamCopyBuffer(buffer);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                this.HandleFailure(e);
                throw;
            }
            finally
            {
                this.SetCompleted();
                this.CompletedRequest();
            }

            if (null != this.Failure)
            {
                throw this.Failure;
            }
        }
Exemple #59
0
        private static void Main(string[] args)
        {
            //if HttpListener is not supported by the Framework
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("A more recent Windows version is required to use the HttpListener class.");
                return;
            }

            // Create a listener.
            HttpListener listener = new HttpListener();

            // Add the prefixes.
            if (args.Length != 0)
            {
                foreach (string s in args)
                {
                    listener.Prefixes.Add(s);
                    // don't forget to authorize access to the TCP/IP addresses localhost:xxxx and localhost:yyyy
                    // with netsh http add urlacl url=http://localhost:xxxx/ user="******"
                    // and netsh http add urlacl url=http://localhost:yyyy/ user="******"
                    // user="******" is language dependent, use user=Everyone in english
                }
            }
            else
            {
                Console.WriteLine("Syntax error: the call must contain at least one web server url as argument");
            }
            listener.Start();

            // get args
            foreach (string s in args)
            {
                Console.WriteLine("Listening for connections on " + s);
            }

            // Trap Ctrl-C on console to exit
            Console.CancelKeyPress += delegate {
                // call methods to close socket and exit
                listener.Stop();
                listener.Close();
                Environment.Exit(0);
            };


            while (true)
            {
                // Note: The GetContext method blocks while waiting for a request.
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request = context.Request;

                string documentContents;
                using (Stream receiveStream = request.InputStream)
                {
                    using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                    {
                        documentContents = readStream.ReadToEnd();
                    }
                }

                // get url
                Console.WriteLine($"Received request for {request.Url}");

                //get url protocol
                Console.WriteLine(request.Url.Scheme);
                //get user in url
                Console.WriteLine(request.Url.UserInfo);
                //get host in url
                Console.WriteLine(request.Url.Host);
                //get port in url
                Console.WriteLine(request.Url.Port);
                //get path in url
                Console.WriteLine(request.Url.LocalPath);

                // parse path in url
                foreach (string str in request.Url.Segments)
                {
                    Console.WriteLine(str);
                }

                //get params un url. After ? and between &

                Console.WriteLine(request.Url.Query);

                //parse params in url
                Console.WriteLine("param1 = " + HttpUtility.ParseQueryString(request.Url.Query).Get("param1"));
                Console.WriteLine("param2 = " + HttpUtility.ParseQueryString(request.Url.Query).Get("param2"));
                Console.WriteLine("param3 = " + HttpUtility.ParseQueryString(request.Url.Query).Get("param3"));
                Console.WriteLine("param4 = " + HttpUtility.ParseQueryString(request.Url.Query).Get("param4"));

                string responseString;

                try
                {
                    if (request.Url.Segments.GetValue(1).Equals("cgi/"))
                    {
                        responseString = (
                            MyMethods.mymethodCGI(
                                HttpUtility.ParseQueryString(request.Url.Query).Get("param3"),
                                HttpUtility.ParseQueryString(request.Url.Query).Get("param4")));
                    }

                    else if (request.Url.Segments.GetValue(1).Equals("mymethod/"))
                    {
                        responseString = (
                            MyMethods.mymethod(
                                HttpUtility.ParseQueryString(request.Url.Query).Get("param1"),
                                HttpUtility.ParseQueryString(request.Url.Query).Get("param2")));
                    }

                    else
                    {
                        responseString = (
                            MyMethods.mymethodReflection(
                                request.Url.Segments.GetValue(1).ToString(),
                                HttpUtility.ParseQueryString(request.Url.Query).Get("param1"),
                                HttpUtility.ParseQueryString(request.Url.Query).Get("param2")));
                    }
                }

                catch (Exception e)
                {
                    responseString = (
                        MyMethods.mymethod(HttpUtility.ParseQueryString(
                                               request.Url.Query).Get("param1"),
                                           HttpUtility.ParseQueryString(request.Url.Query).Get("param2")));
                }

                Console.WriteLine(BasicWebServer.MyMethods.mymethod(
                                      HttpUtility.ParseQueryString(request.Url.Query).Get("param1"),
                                      HttpUtility.ParseQueryString(request.Url.Query).Get("param2")));

                //
                Console.WriteLine(documentContents);

                // Obtain a response object.
                HttpListenerResponse response = context.Response;

                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                // Get a response stream and write the response to it.
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                // You must close the output stream.
                output.Close();
            }
            // Httplistener neither stop ... But Ctrl-C do that ...
            // listener.Stop();
        }
Exemple #60
0
        internal void Execute()
        {
            try
            {
#if false
                if ((null != requestContent) && (0 < requestContent.Length))
                {
                    using (System.IO.Stream stream = Util.NullCheck(this.Request.GetRequestStream(), InternalError.InvalidGetRequestStream))
                    {
                        byte[] buffer       = requestContent.GetBuffer();
                        int    bufferOffset = checked ((int)requestContent.Position);
                        int    bufferLength = checked ((int)requestContent.Length) - bufferOffset;

                        stream.Write(buffer, bufferOffset, bufferLength);
                    }
                }
#endif

                HttpWebResponse response = null;
                try
                {
                    response = (HttpWebResponse)this.Request.GetResponse();
                }
                catch (WebException ex)
                {
                    response = (HttpWebResponse)ex.Response;
                    if (null == response)
                    {
                        throw;
                    }
                }

                this.SetHttpWebResponse(Util.NullCheck(response, InternalError.InvalidGetResponse));

                if (HttpStatusCode.NoContent != this.StatusCode)
                {
                    using (Stream stream = this.httpWebResponse.GetResponseStream())
                    {
                        if (null != stream)
                        {
                            Stream copy = this.GetAsyncResponseStreamCopy();
                            this.responseStream = copy;

                            Byte[] buffer = this.GetAsyncResponseStreamCopyBuffer();

                            long copied = WebUtil.CopyStream(stream, copy, ref buffer);
                            if (this.responseStreamOwner)
                            {
                                if (0 == copied)
                                {
                                    this.responseStream = null;
                                }
                                else if (copy.Position < copy.Length)
                                {
                                    ((MemoryStream)copy).SetLength(copy.Position);
                                }
                            }

                            this.PutAsyncResponseStreamCopyBuffer(buffer);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                this.HandleFailure(e);
                throw;
            }
            finally
            {
                this.SetCompleted();
                this.CompletedRequest();
            }

            if (null != this.Failure)
            {
                throw this.Failure;
            }
        }