private static string ReadStream(Stream stream)
{
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
public static IncomingTransportMessage Deserialize(string messageId, Stream inputStream)
{
var headers = new Dictionary<string, string>();
var serializedMessageData = "";
using (var reader = new XmlTextReader(inputStream))
{
reader.WhitespaceHandling = WhitespaceHandling.None;
reader.Read(); // read <root>
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
var elementName = reader.Name;
reader.Read(); // read the child;
while (reader.NodeType == XmlNodeType.Element)
{
// likely an empty header element node
headers.Add(elementName, reader.Value);
elementName = reader.Name;
reader.Read(); // read the child;
}
if (string.Equals(elementName, "body", StringComparison.InvariantCultureIgnoreCase) && reader.NodeType == XmlNodeType.CDATA)
{
serializedMessageData = reader.Value;
}
else if (reader.NodeType == XmlNodeType.Text)
{
headers.Add(elementName, reader.Value);
}
}
}
}
return new IncomingTransportMessage(messageId, headers, serializedMessageData);
}
static Map LoadHeaderInternal( Stream stream ) {
BinaryReader bs = new BinaryReader( stream );
byte version = bs.ReadByte();
if( version != 1 && version != 2 ) throw new MapFormatException();
Position spawn = new Position();
// Read in the spawn location
spawn.X = (short)(IPAddress.NetworkToHostOrder( bs.ReadInt16() ) * 32);
spawn.H = (short)(IPAddress.NetworkToHostOrder( bs.ReadInt16() ) * 32);
spawn.Y = (short)(IPAddress.NetworkToHostOrder( bs.ReadInt16() ) * 32);
// Read in the spawn orientation
spawn.R = bs.ReadByte();
spawn.L = bs.ReadByte();
// Read in the map dimesions
int widthX = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
int widthY = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
int height = IPAddress.NetworkToHostOrder( bs.ReadInt16() );
Map map = new Map( null, widthX, widthY, height, false );
map.SetSpawn( spawn );
return map;
}
/// <inheritdoc/>
public async Task<Uri> UploadMessageAsync(Stream content, DateTime expirationUtc, string contentType, string contentEncoding, IProgress<int> bytesCopiedProgress, CancellationToken cancellationToken = default(CancellationToken))
{
Requires.NotNull(content, "content");
Requires.Range(expirationUtc > DateTime.UtcNow, "expirationUtc");
string blobName = Utilities.CreateRandomWebSafeName(DesktopUtilities.BlobNameLength);
if (expirationUtc < DateTime.MaxValue)
{
DateTime roundedUp = expirationUtc - expirationUtc.TimeOfDay + TimeSpan.FromDays(1);
blobName = roundedUp.ToString("yyyy.MM.dd") + "/" + blobName;
}
var blob = this.container.GetBlockBlobReference(blobName);
// Set metadata with the precise expiration time, although for efficiency we also put the blob into a directory
// for efficient deletion based on approximate expiration date.
if (expirationUtc < DateTime.MaxValue)
{
blob.Metadata["DeleteAfter"] = expirationUtc.ToString(CultureInfo.InvariantCulture);
}
blob.Properties.ContentType = contentType;
blob.Properties.ContentEncoding = contentEncoding;
await blob.UploadFromStreamAsync(content.ReadStreamWithProgress(bytesCopiedProgress), cancellationToken);
return blob.Uri;
}
public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
{
Mixin.CheckModule (module);
Mixin.CheckStream (symbolStream);
return new PdbReader (Disposable.NotOwned (symbolStream));
}
private UnzipCode UnzipFileHandler(string fileName, Stream fileStream)
{
fileName = fileName.ToLower();
if (fileName.EndsWith(".cfg") ||
fileName.EndsWith("local.ip") ||
fileName.EndsWith("password") ||
fileName.EndsWith(".bat") ||
fileName.EndsWith(".settings"))
{
if (this.NeedUpdateConfigFiles)
{
if (fileStream != null)
{
WriteFile(fileStream, this.destPath + "\\" + fileName);
}
return UnzipCode.Compare;
}
return UnzipCode.Ignore;
}
if (fileName.EndsWith("scada.update.exe") ||
(fileName.EndsWith("scada.watch.exe") && this.UpdateByWatch) ||
fileName.EndsWith("icsharpcode.sharpziplib.dll"))
{
Console.WriteLine("File <" + fileName + "> In use:!");
UpdateLog.Instance().AddName(fileName + " <iu>");
return UnzipCode.Ignore;
}
return UnzipCode.None;
}
private static S3File UploadImage(string key, Stream inputStream)
{
var s3Config = new AmazonS3Config() { ServiceURL = "http://" + _s3_bucket_region };
using (var cli = new AmazonS3Client(
_s3_access_key,
_s3_secret_access_key,
s3Config))
{
PutObjectRequest req = new PutObjectRequest()
{
BucketName = _s3_bucket_name,
ContentType = "image/jpg",
InputStream = inputStream,
Key = key,
CannedACL = S3CannedACL.PublicRead
};
var response = cli.PutObject(req);
if (response.HttpStatusCode != System.Net.HttpStatusCode.OK)
{
throw new Exception("s3: upload failed.");
}
else
{
return new S3File()
{
Key = key,
Url = HttpUtility.HtmlEncode(
String.Format("http://{0}.{1}/{2}", _s3_bucket_name, _s3_bucket_region, key))
};
}
}
}
public override int Read(byte[] buffer, int offset, int count)
{
if (current == null && streams.Count == 0)
{
return -1;
}
if (current == null)
{
current = streams.Dequeue();
}
int totalRead = 0;
while (totalRead < count)
{
int read = current.Read(buffer, offset + totalRead, count - totalRead);
if (read <= 0)
{
if (streams.Count == 0)
{
return totalRead;
}
else
{
current = streams.Dequeue();
}
}
totalRead += read;
}
return totalRead;
}
// called before MediaOpened is raised, and when the Media pipeline is building a topology
protected override void OnAcquireLicense(Stream licenseChallenge, Uri licenseServerUri)
{
StreamReader objStreamReader = new StreamReader(licenseChallenge);
challengeString = objStreamReader.ReadToEnd();
// set License Server URL, based on whether there is an override
Uri resolvedLicenseServerUri;
if (LicenseServerUriOverride == null)
resolvedLicenseServerUri = licenseServerUri;
else
resolvedLicenseServerUri = LicenseServerUriOverride;
//SMFPlayer bug: converting & to & in query string parameters. This line fixes it.
resolvedLicenseServerUri = new Uri(System.Windows.Browser.HttpUtility.HtmlDecode(resolvedLicenseServerUri.AbsoluteUri));
//construct HttpWebRequest to license server
HttpWebRequest objHttpWebRequest = WebRequest.Create(resolvedLicenseServerUri) as HttpWebRequest;
objHttpWebRequest.Method = "POST";
objHttpWebRequest.ContentType = "application/xml";
//The headers below are necessary so that error handling and redirects are handled properly via the Silverlight client.
objHttpWebRequest.Headers["msprdrm_server_redirect_compat"] = "false";
objHttpWebRequest.Headers["msprdrm_server_exception_compat"] = "false";
if (AddAuthorizationToken)
{
string token = Token;
objHttpWebRequest.Headers["Authorization"] = token; //e.g.: Bearer=urn:microsoft:azure:mediaservices:contentkeyidentifier=42b3ddc1-2b93-4813-b50b-af1ec3c9c771&urn%3aServiceAccessible=service&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fnimbusvoddev.accesscontrol.windows.net%2f&Audience=urn%3atest&ExpiresOn=1406385025&Issuer=http://testacs.com&HMACSHA256=kr1fHp0chSNaMcRimmENpk1E8LaS1ufknb8mR3xQhx4%3d
}
// Initiate getting request stream
IAsyncResult objIAsyncResult = objHttpWebRequest.BeginGetRequestStream(new AsyncCallback(RequestStreamCallback), objHttpWebRequest);
}
private string CheckMetaCharSetAndReEncode(Stream memStream, string html)
{
Match m = new Regex(@"<meta\s+.*?charset\s*=\s*(?<charset>[A-Za-z0-9_-]+)", RegexOptions.Singleline | RegexOptions.IgnoreCase).Match(html);
if (m.Success)
{
string charset = m.Groups["charset"].Value.ToLower() ?? "iso-8859-1";
if ((charset == "unicode") || (charset == "utf-16"))
{
charset = "utf-8";
}
try
{
Encoding metaEncoding = Encoding.GetEncoding(charset);
if (Encoding != metaEncoding)
{
memStream.Position = 0L;
StreamReader recodeReader = new StreamReader(memStream, metaEncoding);
html = recodeReader.ReadToEnd().Trim();
recodeReader.Close();
}
}
catch (ArgumentException)
{
}
}
return html;
}
void IExtension.EndAppend(Stream stream, bool commit)
{
using (stream)
{
int len;
if (commit && (len = (int)stream.Length) > 0)
{
MemoryStream ms = (MemoryStream)stream;
if (buffer == null)
{ // allocate new buffer
buffer = ms.ToArray();
}
else
{ // resize and copy the data
// note: Array.Resize not available on CF
int offset = buffer.Length;
byte[] tmp = new byte[offset + len];
Buffer.BlockCopy(buffer, 0, tmp, 0, offset);
Buffer.BlockCopy(ms.GetBuffer(), 0, tmp, offset, len);
buffer = tmp;
}
}
}
}
public LogWriter(Stream stream, bool ownsStream)
{
_stream = stream;
_ownsStream = ownsStream;
BlockHelper.WriteBlock(_stream, BlockType.MagicBytes, new ArraySegment<byte>(Encoding.ASCII.GetBytes("TeraConnectionLog")));
BlockHelper.WriteBlock(_stream, BlockType.Start, new ArraySegment<byte>(new byte[0]));
}
/// <inheritdoc/>
public Object Read(Stream mask0)
{
var result = new TrainingContinuation();
var ins0 = new EncogReadHelper(mask0);
EncogFileSection section;
while ((section = ins0.ReadNextSection()) != null)
{
if (section.SectionName.Equals("CONT")
&& section.SubSectionName.Equals("PARAMS"))
{
IDictionary<String, String> paras = section.ParseParams();
foreach (String key in paras.Keys)
{
if (key.Equals("type", StringComparison.InvariantCultureIgnoreCase))
{
result.TrainingType = paras[key];
}
else
{
double[] list = EncogFileSection
.ParseDoubleArray(paras, key);
result.Put(key, list);
}
}
}
}
return result;
}
public static void SaveDrawing(Drawing drawing, Stream stream)
{
using (var writer = XmlWriter.Create(stream, XmlSettings))
{
SaveDrawing(drawing, writer);
}
}
private static void WriteInt(Stream stream, int value)
{
stream.WriteByte((byte)(value));
stream.WriteByte((byte)(value >> 8));
stream.WriteByte((byte)(value >> 16));
stream.WriteByte((byte)(value >> 24));
}
private void UpdateMainListFromStream(Stream s)
{
using (s)
{
_mainList = ParserFactory.ParseMainListData(s);
}
}
protected int ReadByteAfterWhitespace(Stream s)
{
int buff = s.ReadByte();
while (buff >= 0 && IsWhitespace(buff))
buff = s.ReadByte();
return buff;
}
public void SerializeRequest(Stream stm, XmlRpcRequest request)
{
var xtw = XmlRpcXmlWriter.Create(stm, XmlRpcFormatSettings);
xtw.WriteStartDocument();
xtw.WriteStartElement(string.Empty, "methodCall", string.Empty);
{
var mappingActions = new MappingActions();
mappingActions = GetTypeMappings(request.Mi, mappingActions);
mappingActions = GetMappingActions(request.Mi, mappingActions);
WriteFullElementString(xtw, "methodName", request.Method);
if (request.Args.Length > 0 || UseEmptyParamsTag)
{
xtw.WriteStartElement("params");
try
{
if (!IsStructParamsMethod(request.Mi))
SerializeParams(xtw, request, mappingActions);
else
SerializeStructParams(xtw, request, mappingActions);
}
catch (XmlRpcUnsupportedTypeException ex)
{
throw new XmlRpcUnsupportedTypeException(
ex.UnsupportedType,
string.Format(
"A parameter is of, or contains an instance of, type {0} which cannot be mapped to an XML-RPC type",
ex.UnsupportedType));
}
WriteFullEndElement(xtw);
}
}
WriteFullEndElement(xtw);
xtw.Flush();
}
/// <summary>
/// Initializes a new instance of the BZip2DecoderStream class.
/// </summary>
/// <param name="stream">The compressed input stream.</param>
/// <param name="ownsStream">Whether ownership of stream passes to the new instance.</param>
public BZip2DecoderStream(Stream stream, Ownership ownsStream)
{
_compressedStream = stream;
_ownsCompressed = ownsStream;
_bitstream = new BigEndianBitStream(new BufferedStream(stream));
// The Magic BZh
byte[] magic = new byte[3];
magic[0] = (byte)_bitstream.Read(8);
magic[1] = (byte)_bitstream.Read(8);
magic[2] = (byte)_bitstream.Read(8);
if (magic[0] != 0x42 || magic[1] != 0x5A || magic[2] != 0x68)
{
throw new InvalidDataException("Bad magic at start of stream");
}
// The size of the decompression blocks in multiples of 100,000
int blockSize = (int)_bitstream.Read(8) - 0x30;
if (blockSize < 1 || blockSize > 9)
{
throw new InvalidDataException("Unexpected block size in header: " + blockSize);
}
blockSize *= 100000;
_rleStream = new BZip2RleStream();
_blockDecoder = new BZip2BlockDecoder(blockSize);
_blockBuffer = new byte[blockSize];
if (ReadBlock() == 0)
{
_eof = true;
}
}
/// <summary>
/// Creates texture atlas from stream.
/// </summary>
/// <param name="device"></param>
public TextureAtlas ( RenderSystem rs, Stream stream, bool useSRgb = false )
{
var device = rs.Game.GraphicsDevice;
using ( var br = new BinaryReader(stream) ) {
br.ExpectFourCC("ATLS", "texture atlas");
int count = br.ReadInt32();
for ( int i=0; i<count; i++ ) {
var element = new Element();
element.Index = i;
element.Name = br.ReadString();
element.X = br.ReadInt32();
element.Y = br.ReadInt32();
element.Width = br.ReadInt32();
element.Height = br.ReadInt32();
elements.Add( element );
}
int ddsFileLength = br.ReadInt32();
var ddsImageBytes = br.ReadBytes( ddsFileLength );
texture = new UserTexture( rs, ddsImageBytes, useSRgb );
}
dictionary = elements.ToDictionary( e => e.Name );
}
private static object Load(Stream stream)
{
var pc = new ParserContext();
MethodInfo loadBamlMethod = typeof (XamlReader).GetMethod("LoadBaml",
BindingFlags.NonPublic | BindingFlags.Static);
return loadBamlMethod.Invoke(null, new object[] {stream, pc, null, false});
}
public override byte[] Handle(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
// path = /wifi/...
//m_log.DebugFormat("[Wifi]: path = {0}", path);
//m_log.DebugFormat("[Wifi]: ip address = {0}", httpRequest.RemoteIPEndPoint);
//foreach (object o in httpRequest.Query.Keys)
// m_log.DebugFormat(" >> {0}={1}", o, httpRequest.Query[o]);
string result = string.Empty;
try
{
Request request = RequestFactory.CreateRequest(string.Empty, httpRequest, Localization.GetLanguageInfo(httpRequest.Headers.Get("accept-language")));
Environment env = new Environment(request);
result = m_WebApp.Services.LogoutRequest(env);
httpResponse.ContentType = "text/html";
}
catch (Exception e)
{
m_log.DebugFormat("[LOGOUT HANDLER]: Exception {0}: {1}", e.Message, e.StackTrace);
}
return WebAppUtils.StringToBytes(result);
}
public BoundedStream(Stream stream, long offset, long length)
{
mStream = stream;
mOffset = offset;
mLength = length;
mPosition = 0;
}
/// <summary>
/// Creates a new instance of <see cref="MockClientHttpResponse"/>.
/// </summary>
/// <param name="body">The body of the response as a stream.</param>
/// <param name="headers">The response headers.</param>
/// <param name="statusCode">The response status code.</param>
/// <param name="statusDescription">The response status description.</param>
public MockClientHttpResponse(Stream body, HttpHeaders headers, HttpStatusCode statusCode, string statusDescription)
{
this.body = body;
this.headers = headers;
this.statusCode = statusCode;
this.statusDescription = statusDescription;
}
public virtual void Write(
Stream zOut)
{
Stream inStr = Read();
Streams.PipeAll(inStr, zOut);
inStr.Close();
}
public static int IntPtrCopy(IntPtr source, Stream dest, int length)
{
var buffer = new Byte[length];
Marshal.Copy(source, buffer, 0, length);
dest.Write(buffer, 0, length);
return length;
}
public override void Handle(string requested, Stream stream)
{
uint photo_id = uint.Parse (requested);
Photo photo = App.Instance.Database.Photos.Get (photo_id);
SendImage (photo, stream);
}
public KinectReader(Stream fileStream, int width, int height)
{
this.Width = width;
this.Height = height;
this.reader = new BinaryReader(fileStream);
this.createIndexes();
}
public void Send(string remoteUrl, IDictionary<string, string> headers, Stream data)
{
var request = WebRequest.Create(remoteUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers = Encode(headers);
request.UseDefaultCredentials = true;
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
data.CopyTo(stream);
}
HttpStatusCode statusCode;
//todo make the receiver send the md5 back so that we can double check that the transmission went ok
using (var response = (HttpWebResponse) request.GetResponse())
{
statusCode = response.StatusCode;
}
Logger.Debug("Got HTTP response with status code " + statusCode);
if (statusCode != HttpStatusCode.OK)
{
Logger.Warn("Message not transferred successfully. Trying again...");
throw new Exception("Retrying");
}
}
public static void TransformFile(byte[] key, byte[] iv, Stream dstfs, Stream srcfs, long offset, long length)
{
var aes = new Aes128Ctr(key, iv);
var counter = BitConverter.ToUInt64(aes._iv.Reverse().ToArray(), 0); //get the nonce
byte[] buffer;
long buffersize = 1024 * 1024 * 4;
while (offset > 0)
{
buffersize = offset > buffersize ? buffersize : offset;
buffer = new byte[buffersize];
srcfs.Read(buffer, 0, (int)buffersize);
counter = aes.TransformBlock(buffer, counter);
offset -= buffersize;
}
buffersize = 1024 * 1024 * 4;
while (length > 0)
{
buffersize = length > buffersize ? buffersize : length;
buffer = new byte[buffersize];
srcfs.Read(buffer, 0, (int)buffersize);
counter = aes.TransformBlock(buffer, counter);
dstfs.Write(buffer, 0, (int)buffersize);
length -= buffersize;
}
}