Пример #1
0
        public Entity(Stream stream, int id, int type, ISymbolTable symbolTable, IonLoader loader)
        {
            using var reader = new BinaryReader(stream, Encoding.UTF8, true);
            Signature        = Encoding.ASCII.GetString(reader.ReadBytes(4));
            if (Signature != EntitySignature)
            {
                throw new Exception("Invalid signature");
            }

            Version = reader.ReadUInt16();
            if (!_allowedVersions.Contains(Version))
            {
                throw new Exception($"Version not supported ({Version})");
            }

            Length = reader.ReadUInt32();
            if (Length < MinHeaderLength)
            {
                throw new Exception("Header too short");
            }

            // Duplicated in KfxContainer
            // 10 = number of bytes read so far
            var containerInfoData = new MemoryStream(stream.ReadBytes((int)Length - 10));
            var entityInfo        = loader.LoadSingle <IonStruct>(containerInfoData);

            if (entityInfo == null)
            {
                throw new Exception("Bad container or something");
            }

            var compressionType = entityInfo.GetField(KfxSymbols.BcComprType).IntValue;

            if (compressionType != KfxContainer.DefaultCompressionType)
            {
                throw new Exception($"Unexpected bcComprType ({compressionType})");
            }

            var drmScheme = entityInfo.GetField(KfxSymbols.BcDrmScheme).IntValue;

            if (drmScheme != KfxContainer.DefaultDrmScheme)
            {
                throw new Exception($"Unexpected bcDRMScheme ({drmScheme})");
            }

            FragmentId   = symbolTable.FindKnownSymbol(id);
            FragmentType = symbolTable.FindKnownSymbol(type);

            Value = RawFragmentTypes.Contains(FragmentType)
                ? new IonBlob(new ReadOnlySpan <byte>(stream.ReadToEnd()))
                : ((IonDatagram)loader.Load(stream.ReadToEnd())).Single();

            // Skipping annotation handling for now

            //if ftype == fid and ftype in ROOT_FRAGMENT_TYPES and not self.pure:

            //fid = "$348"

            //return YJFragment(fid = fid if fid != "$348" else None, ftype = ftype, value = self.value)
        }
Пример #2
0
        public void Load(Stream reader, bool headersOnly = false, int maxLength = 0)
        {
            _HeadersOnly = headersOnly;
            Headers      = null;
            Body         = null;

            if (headersOnly)
            {
                RawHeaders = reader.ReadToEnd(maxLength, _DefaultEncoding);
            }
            else
            {
                var entireMessage = reader.ReadToEnd(maxLength, _DefaultEncoding).Split('\n');
                var index         = 0;
                var headers       = entireMessage
                                    .TakeWhile((x, i) => x.Trim().Length > 0 && (index = i) >= 0);
                RawHeaders = String.Join(Environment.NewLine, headers);

                string boundary = Headers.GetBoundary();
                if (!string.IsNullOrEmpty(boundary))
                {
                    //else this is a multipart Mime Message
                    //using (var subreader = new StringReader(line + Environment.NewLine + reader.ReadToEnd()))
                    ParseMime(String.Join(Environment.NewLine, entireMessage.SkipWhile((x, i) => i <= index || x.Trim().Length == 0)), boundary);
                }
                else
                {
                    SetBody(String.Join(Environment.NewLine, entireMessage.SkipWhile((x, i) => i <= index || x.Trim().Length == 0)));
                }
            }

            if (string.IsNullOrWhiteSpace(Body) && AlternateViews.Count > 0)
            {
                var att = AlternateViews.FirstOrDefault(x => x.ContentType.Is("text/plain"));
                if (att == null)
                {
                    att = AlternateViews.FirstOrDefault(x => x.ContentType.Contains("html"));
                }

                if (att != null)
                {
                    Body = att.Body;
                    ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
                    ContentType             = att.Headers["Content-Type"].RawValue;
                }
            }

            Date      = Headers.GetDate();
            To        = Headers.GetAddresses("To").ToList();
            Cc        = Headers.GetAddresses("Cc").ToList();
            Bcc       = Headers.GetAddresses("Bcc").ToList();
            Sender    = Headers.GetAddresses("Sender").FirstOrDefault();
            ReplyTo   = Headers.GetAddresses("Reply-To").ToList();
            From      = Headers.GetAddresses("From").FirstOrDefault();
            MessageID = Headers["Message-ID"].RawValue;

            Importance = Headers.GetEnum <MailPriority>("Importance");
            Subject    = Headers["Subject"].RawValue;
        }
Пример #3
0
        public static object GetDataOrException(this IDataObject source, string format, bool ConvertToString = false)
        {
            var value = default(object);

            try
            {
                value = source.GetData(format);

                if (ConvertToString)
                {
                    (value as MemoryStream).With(
                        Stream =>
                    {
                        value = Encoding.UTF8.GetString(Stream.ReadToEnd()).TakeUntilIfAny("\0");
                    }
                        );
                }
            }
            catch (Exception exc)
            {
                value = exc;
            }

            return(value);
        }
Пример #4
0
 public static string FromMessageBody(this Stream messageBody)
 {
     using (messageBody)
     {
         return(messageBody.ReadToEnd().FromMessageBody());
     }
 }
Пример #5
0
        private OAuthResponseData GetResponse(Stream httpResponse)
        {
            try
            {
                var response = httpResponse.ReadToEnd();

                return(new OAuthResponseData()
                {
                    Auth = JsonConvert.DeserializeObject <OAuthData>(response),
                });
            }
            catch (WebException ex)
            {
                using (var errorResponse = ex.Response)
                {
                    var response = errorResponse.GetResponseStream().ReadToEnd();

                    return(new OAuthResponseData()
                    {
                        ErrorData = JsonConvert.DeserializeObject <OAuthErrorData>(response),
                    });
                }
            }
            catch (Exception ex)
            {
                return(new OAuthResponseData()
                {
                    ErrorData = new OAuthErrorData()
                    {
                        Error = ex.Message,
                    },
                });
            }
        }
Пример #6
0
 public OutputInfoModel PostStream1(Stream stream)
 {
     return(new OutputInfoModel
     {
         Data = stream.ReadToEnd(Encoding.UTF8)
     });
 }
            public void Download_Test()
            {
                //Arange
                //load the user
                UserBean user = _bundledocsApi.Users.Me();

                //find a brief to load
                Brief briefToLoad = user.Briefs.Where(k => k.PartitionKey == user.RowKey).FirstOrDefault();

                //load the brief
                BriefBean loadedBrief = _bundledocsApi.Bundles.Get(briefToLoad.PartitionKey, briefToLoad.RowKey);

                //Act
                //Download the bundle
                Stream myStream = _bundledocsApi.Bundles.Download(loadedBrief.PartitionKey, loadedBrief.RowKey);

                //write the downloaded bundle to disk
                byte[] myFile      = myStream.ReadToEnd();
                string newFilePath = $@"{App.Default.TempFolder}{Guid.NewGuid().ToString("n")}.pdf";

                File.WriteAllBytes(newFilePath, myFile);

                //Assert
                Assert.IsTrue(File.Exists(newFilePath));

                //open the downloaded bundle
                Process.Start(newFilePath);
            }
Пример #8
0
        private void OnPublishPackageCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            var state = (PublishState)e.UserState;

            if (e.Error != null)
            {
                Exception error = e.Error;

                WebException webException = e.Error as WebException;
                if (webException != null)
                {
                    // real error message is contained inside the response body
                    using (Stream stream = webException.Response.GetResponseStream()) {
                        string errorMessage = stream.ReadToEnd();
                        error = new WebException(errorMessage, webException, webException.Status, webException.Response);
                    }
                }

                state.ProgressObserver.OnError(error);
            }
            else if (!e.Cancelled)
            {
                state.ProgressObserver.OnCompleted();
            }

            var client = (WebClient)sender;

            client.Dispose();
        }
            public void Download_Test()
            {
                //Arrange
                //load the user
                UserBean user = _bundledocsApi.Users.Me();

                //find a brief to load
                Brief parentBrief = user.Briefs.Where(k => k.PartitionKey == user.RowKey).FirstOrDefault();

                //load the brief
                BriefBean loadedBrief = _bundledocsApi.Bundles.Get(parentBrief.PartitionKey, parentBrief.RowKey);

                //load the brief documents
                BriefDocument documentToDownload = _bundledocsApi.Bundles.Tree(loadedBrief.PartitionKey, loadedBrief.RowKey).Where(k => k.Type == "HEADER").FirstOrDefault().Children.Where(k => k.Type == "DOCUMENT").FirstOrDefault();

                //Act
                //download the document
                Stream myStream = _bundledocsApi.Documents.Download(documentToDownload.PartitionKey, documentToDownload.RowKey);

                //write the downloaded bundle to disk
                byte[] myFile      = myStream.ReadToEnd();
                string newFilePath = $@"{App.Default.TempFolder}{Guid.NewGuid().ToString("n")}.pdf";

                File.WriteAllBytes(newFilePath, myFile);

                //Assert
                Assert.IsTrue(File.Exists(newFilePath));

                //open the downloaded bundle
                Process.Start(newFilePath);
            }
            public void Download_Test()
            {
                //Arrange
                //load the user
                UserBean user = _bundledocsApi.Users.Me();

                //find a brief to load
                Brief parentBrief = user.Briefs.Where(k => k.PartitionKey == user.RowKey).FirstOrDefault();

                //load the brief
                BriefBean loadedBrief = _bundledocsApi.Bundles.Get(parentBrief.PartitionKey, parentBrief.RowKey);

                //load the brief receipts
                IList <BriefReceipt> briefReceipts = _bundledocsApi.Bundles.Receipts(loadedBrief.PartitionKey, loadedBrief.RowKey);

                //load the latest brief receipt
                BriefReceipt briefReceiptToDownload = briefReceipts.FirstOrDefault();

                //download the brief receipt
                Stream briefReceiptStream = _bundledocsApi.Receipts.Download(briefReceiptToDownload.PartitionKey, briefReceiptToDownload.RowKey);

                //write the downloaded stream to disk
                byte[] myFile      = briefReceiptStream.ReadToEnd();
                string newFilePath = $@"{App.Default.TempFolder}{Guid.NewGuid().ToString("n")}.pdf";

                File.WriteAllBytes(newFilePath, myFile);

                //Assert
                Assert.IsTrue(File.Exists(newFilePath));

                //open the downloaded bundle
                Process.Start(newFilePath);
            }
Пример #11
0
        public static string Process(Stream stream, IPropertyProvider propertyProvider, bool throwIfNotFound = true)
        {
            string text = stream.ReadToEnd();
            var tokenizer = new Tokenizer(text);
            StringBuilder result = new StringBuilder();
            for (; ; )
            {
                Token token = tokenizer.Read();
                if (token == null)
                {
                    break;
                }

                if (token.Category == TokenCategory.Variable)
                {
                    var replaced = ReplaceToken(token.Value, propertyProvider, throwIfNotFound);
                    result.Append(replaced);
                }
                else
                {
                    result.Append(token.Value);
                }
            }

            return result.ToString();
        }
Пример #12
0
        public static string Process(Stream stream, IPropertyProvider propertyProvider, bool throwIfNotFound = true)
        {
            string        text      = stream.ReadToEnd();
            var           tokenizer = new Tokenizer(text);
            StringBuilder result    = new StringBuilder();

            for (; ;)
            {
                Token token = tokenizer.Read();
                if (token == null)
                {
                    break;
                }

                if (token.Category == TokenCategory.Variable)
                {
                    var replaced = ReplaceToken(token.Value, propertyProvider, throwIfNotFound);
                    result.Append(replaced);
                }
                else
                {
                    result.Append(token.Value);
                }
            }

            return(result.ToString());
        }
Пример #13
0
        public static object ReadFromJson(this Stream stream, string messageType)
        {
            var type = Type.GetType(messageType);
            var json = stream.ReadToEnd();

            return(JsonConvert.DeserializeObject(json, type));
        }
Пример #14
0
        public Shader CreateShader(Shader.Stage ShaderStage, Stream InputStream)
        {
            Shader s = CreateShader(ShaderStage);

            s.Data = InputStream.ReadToEnd();
            return(s);
        }
        public Float1Texture Parse()
        {
            if (inputStream.Length > int.MaxValue)
            {
                throw new IOException(
                          $"[{nameof(R32Parser)}] Streams with more then {int.MaxValue} bytes of data are unsupported");
            }

            int byteCount = (int)inputStream.Length;

            if (byteCount % sizeof(float) != 0)
            {
                throw new Exception($"[[{nameof(R32Parser)}]] Data corrupt");
            }

            //Allocate a array for the pixels;
            int pixelCount = byteCount / sizeof(float);

            float[] pixels = new float[pixelCount];

            //Read from the stream directly into the pixels array
            inputStream.ReadToEnd <float>(pixels);

            //Because the format contains no header we have no way of determining the dimensions if
            //we don't assume a power-of-two
            int?size = IntUtils.TryPerfectSquareRoot(pixelCount);

            if (size == null)
            {
                throw new Exception($"[[{nameof(R32Parser)}]] Only power-of-two texture are supported");
            }

            return(new Float1Texture(pixels, (size.Value, size.Value)));
        }
        public ITransformFixtureInputSetup Message <TSchema>(Stream message, XmlSchemaContentProcessing contentProcessing)
            where TSchema : SchemaBase, new()
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            var partCount           = Messages.Count;
            var validatingXmlReader = XmlReader.Create(
                message,
                Be.Stateless.Xml.ValidatingXmlReaderSettings.Create(
                    contentProcessing,
                    (sender, args) => {
                throw new XmlSchemaValidationException(
                    string.Format(
                        "Transform's input message #{0} failed '{1}' schema validation for the following reason:{2}{3}: {4}{2}{2}The message's content is:{2}{5}{2}",
                        partCount + 1,
                        typeof(TSchema).Name,
                        Environment.NewLine,
                        args.Severity,
                        args.Message,
                        message.ReadToEnd()),
                    args.Exception);
            },
                    new TSchema().CreateResolvedSchema()));

            Messages.Add(validatingXmlReader.AsStream());
            return(this);
        }
Пример #17
0
 public StreamInfoModel PostStream1(Stream stream)
 {
     return(new StreamInfoModel
     {
         Data = stream.ReadToEnd()
     });
 }
Пример #18
0
        private async Task DownloadBackupAsync()
        {
            DateTime backupDate = await GetBackupDateAsync();

            if (settingsFacade.LastDatabaseUpdate > backupDate)
            {
                return;
            }

            List <string> backups = await cloudBackupService.GetFileNamesAsync();

            if (backups.Contains(DatabaseConstants.BACKUP_NAME))
            {
                using (Stream backupStream = await cloudBackupService.RestoreAsync(DatabaseConstants.BACKUP_NAME,
                                                                                   DatabaseConstants.BACKUP_NAME))
                {
                    fileStore.WriteFile(DatabaseConstants.BACKUP_NAME, backupStream.ReadToEnd());
                }

                bool moveSucceed = fileStore.TryMove(DatabaseConstants.BACKUP_NAME,
                                                     DatabasePathHelper.GetDbPath(),
                                                     true);

                if (!moveSucceed)
                {
                    throw new BackupException("Error Moving downloaded backup file");
                }
                contextAdapter.RecreateContext();
            }
        }
Пример #19
0
        /// <summary> Загрузить задание </summary>
        private TaskPoco UploadTaskInternal(Stream stream, bool appendTimestamp)
        {
            var info = _xapProcessor.Parse(stream);

            if (info == null)
            {
                throw new ArgumentException("Не удалось распознать модуль-задание.");
            }

            var name = appendTimestamp
                ? $"{info.Name} ({DateTime.Now:u})"
                : info.Name;

            var sameTaskExists = _query.OfEntities <Task>().Any(t => t.Name == name && t.Version == info.Version);

            if (!sameTaskExists)
            {
                var newTask = new TaskPoco
                {
                    Name             = name,
                    Sections         = info.Sections,
                    VariantGenerator = null,
                    Note             = null,
                    Version          = info.Version,
                    Xap = stream.ReadToEnd()
                };

                return(newTask);
            }
            else
            {
                //TODO: здесь кидать исключение о дубликате (лучше ResultOrError)
                return(null);
            }
        }
Пример #20
0
        public Stream Modify(Stream openStream)
        {
            var content = openStream.ReadToEnd();
            content = minifier.Minify(content);

            return content.ToStream();
        }
Пример #21
0
 private static DateTime GetBuildTime(Stream assembly)
 {
     using (var memoryStream = new MemoryStream(assembly.ReadToEnd()))
     {
         var header = PE.PeHeader.ReadFrom(memoryStream);
         return(header.TimeStamp);
     }
 }
 protected override void Reader()
 {
     try {
         result = Stream.ReadToEnd();
     } catch (Exception ex) { // can't let any exceptions kill the thread or the program will crash
         result = ex.ToString();
     }
 }
Пример #23
0
        public EncryptedStream Encrypt(Stream clearStream)
        {
            byte[] clearBytes  = clearStream.ReadToEnd();
            byte[] iv          = GenerateIv();
            byte[] cipherBytes = ProtectedData.Protect(clearBytes, iv, DataProtectionScope.LocalMachine);
            var    result      = new EncryptedStream(cipherBytes, iv);

            return(result);
        }
Пример #24
0
        public static void ReadExactly(this Stream stream, byte[] buffer, int offset, int count)
        {
            var read = stream.ReadToEnd(buffer, offset, count);

            if (read < count)
            {
                throw new EndOfStreamException();
            }
        }
Пример #25
0
        public static T ReadFromJson <T>(this Stream stream)
        {
            var json = stream.ReadToEnd();

            return(JsonConvert.DeserializeObject <T>(json, new JsonSerializerSettings
            {
                ContractResolver = new PrivateSetterContractResolver()
            }));
        }
Пример #26
0
 internal BsonDocument GetById(string _collectionName, string _id)
 {
     using (Stream stream = S3Helper.ReadDocument(m_S3Client, DataBucket, Database, _collectionName, _id))
     {
         byte[]       data = stream.ReadToEnd();
         BsonDocument doc  = BsonSerializer.Deserialize(data);
         return(doc);
     }
 }
Пример #27
0
        public static string ToUtf8String(this Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            return(stream.ReadToEnd());
        }
Пример #28
0
        public PacCredentialInfo(byte[] info)
            : base(info)
        {
            Version = Stream.ReadInt();

            EncryptionType = (EncryptionType)Stream.ReadInt();

            SerializedData = Stream.ReadToEnd();
        }
Пример #29
0
        /// <summary>
        /// 参见 <see cref="EmbededFilesFinder.FindAvailableModules"/> 方法。
        /// </summary>
        public IEnumerable <ModuleDescriptor> FindAvailableModules()
        {
            ConcurrentDictionary <String, ModuleDescriptor> modules =
                new ConcurrentDictionary <string, ModuleDescriptor>();

            IEnumerable <string> folders = this.GetFolders().Where(f => Directory.Exists(f));

            Parallel.ForEach(folders, (f) =>
            {
                var files = Directory.EnumerateFiles(f, "*.dll", SearchOption.TopDirectoryOnly)
                            .Where(file =>
                {
                    string name = Path.GetFileName(file);
                    return
                    (!name.StartsWith("system.", StringComparison.OrdinalIgnoreCase) &&
                     !name.StartsWith("microsoft.", StringComparison.OrdinalIgnoreCase) &&
                     !name.StartsWith("schubert.framework", StringComparison.OrdinalIgnoreCase));
                }).ToArray();
                foreach (var file in files)
                {
                    Assembly assembly = null;
                    try
                    {
                        assembly = _reader.ReadFile(file);
                    }
                    catch (BadImageFormatException)
                    {
                        continue;
                    }
                    var resourceNames = assembly.GetManifestResourceNames();
                    foreach (string r in resourceNames)
                    {
                        string resourceFile = GetResourceFileName(assembly, r);
                        foreach (IModuleHarvester harverter in _moduleHarvesters)
                        {
                            if (harverter.CanHarvest(resourceFile))
                            {
                                _logger.WriteDebug($"尝试加载模块嵌入式清单文件 {file} , 资源路径:{r}。");
                                using (Stream stream = assembly.GetManifestResourceStream(r))
                                {
                                    string content        = stream.ReadToEnd(System.Text.Encoding.UTF8);
                                    ModuleDescriptor desc = null;
                                    if (harverter.TryHarvestModule(content, out desc))
                                    {
                                        desc.RootDirectory  = f;
                                        desc.LibraryPath    = file;
                                        desc.ModuleManifest = GetResourceFileName(assembly, r, desc.RootNamespce);
                                        modules.GetOrAdd(desc.Name, desc);
                                    }
                                }
                            }
                        }
                    }
                }
            });
            return(modules.Values.ToArray());
        }
        public void Can_download_Poco_response_as_Stream(IRestClient client)
        {
            Stream response = client.Get <Stream>("/poco/Test");

            using (response)
            {
                Assert.That(response.ReadToEnd(), Does.Contain("Hello, Test"));
            }
        }
Пример #31
0
        public static object ReadFromJson(this Stream stream, string messageType)
        {
            var type = Type.GetType(messageType);
            var json = stream.ReadToEnd();

            return(JsonConvert.DeserializeObject(json, type, new JsonSerializerSettings
            {
                ContractResolver = new PrivateSetterContractResolver()
            }));
        }
Пример #32
0
        public static byte[] LoadResource(this Type tp, string name)
        {
            Stream s = tp.FindResource(name);

            if (s?.CanRead == true)
            {
                return(s.ReadToEnd());
            }
            return(null);
        }
Пример #33
0
        internal static AzureContext CreateFrom(Stream configStream, ContextSettings settings)
        {
            if (configStream == null)
                throw new ArgumentNullException("configStream");

            if (settings == null)
                throw new ArgumentNullException("settings");

            _config = configStream.ReadToEnd().FromJsonToObject<HostConfig>();
            _current = new AzureContext(_config, settings);
            return _current;
        }
Пример #34
0
 public static void AssertAreEqual(Stream expected, Stream found, int tolerance)
 {
     var expectedByteArray = expected.ReadToEnd();
     var foundByteArray = found.ReadToEnd();
     Assert.AreEqual(expectedByteArray.Length, foundByteArray.Length, "Lengths do not match");
     for (int i = 0; i < expectedByteArray.Length; i++)
     {
         if (Math.Abs(expectedByteArray[i] - foundByteArray[i]) > tolerance)
         {
             Assert.AreEqual(expectedByteArray[i], foundByteArray[i], "Data mismatch at location " + i);
         }
     }
 }
Пример #35
0
 internal static string Process(Stream stream, IPropertyProvider propertyProvider)
 {
     string text = stream.ReadToEnd();
     return _tokenRegex.Replace(text, match => ReplaceToken(match, propertyProvider));
 }
Пример #36
0
        public virtual void Load(Stream reader,  Scope scope, int maxLength, char? termChar = null)
        {
            Scope = scope;
            Headers = null;
            Body = null;

            var headers = new StringBuilder();
            string line;
            while ((line = reader.ReadLine(ref maxLength, _DefaultEncoding, termChar)) != null)
            {
                if (line.Trim().Length == 0)
                    if (headers.Length == 0)
                        continue;
                    else
                        break;
                headers.AppendLine(line);
            }
            RawHeaders = headers.ToString();

            if (Scope > Scope.Headers)
            {
                string boundary = Headers.GetBoundary();
                if (!string.IsNullOrEmpty(boundary))
                {
                    var atts = new List<Attachment>();
                    // Read the mime structure anyways, but the body might be empty.
                    var body = ParseMime(reader, boundary, ref maxLength, atts, Encoding, termChar, scope);
                    if (Scope > Scope.HeadersAndMime && !string.IsNullOrEmpty(body))
                    {
                        SetBody(body);
                    }

                    foreach (var att in atts)
                    {
                        Add(att);
                    }

                    if (maxLength > 0)
                        reader.ReadToEnd(maxLength, Encoding);
                }
                else if (Scope > Scope.HeadersAndMime)
                {
                    //	sometimes when email doesn't have a body, we get here with maxLength == 0 and we shouldn't read any further
                    string body = String.Empty;
                    if (maxLength > 0)
                        body = reader.ReadToEnd(maxLength, Encoding);

                    SetBody(body);
                }
            }

            Date = Headers.GetDate();
            To = Headers.GetMailAddresses("To").ToList();
            Cc = Headers.GetMailAddresses("Cc").ToList();
            Bcc = Headers.GetMailAddresses("Bcc").ToList();
            Sender = Headers.GetMailAddresses("Sender").FirstOrDefault();
            ReplyTo = Headers.GetMailAddresses("Reply-To").ToList();
            From = Headers.GetMailAddresses("From").FirstOrDefault();
            MessageID = Headers["Message-ID"].RawValue;

            Importance = Headers.GetEnum<MailPriority>("Importance");
            Subject = Headers["Subject"].RawValue;
        }
Пример #37
0
        public virtual void Load(Stream reader, bool headersOnly = false, int maxLength = 0, char? termChar = null)
        {
            _HeadersOnly = headersOnly;
            Headers = null;
            Body = null;

            if (headersOnly) {
                RawHeaders = reader.ReadToEnd(maxLength, _DefaultEncoding);
            } else {
                var headers = new StringBuilder();
                string line;
                while ((line = reader.ReadLine(ref maxLength, _DefaultEncoding, termChar)) != null) {
                    if (line.Trim().Length == 0)
                        if (headers.Length == 0)
                            continue;
                        else
                            break;
                    headers.AppendLine(line);
                }
                RawHeaders = headers.ToString();

                string boundary = Headers.GetBoundary();
                if (!string.IsNullOrEmpty(boundary)) {
                    //else this is a multipart Mime Message
                    //using (var subreader = new StringReader(line + Environment.NewLine + reader.ReadToEnd()))
                    var atts = new List<Attachment>();
                    ParseMime(reader, boundary, ref maxLength, atts, Encoding, termChar);
                    foreach (var att in atts)
                        (att.IsAttachment ? Attachments : AlternateViews).Add(att);

                    if (maxLength > 0)
                        reader.ReadToEnd(maxLength, Encoding);
                } else {
                    SetBody(reader.ReadToEnd(maxLength, Encoding).Trim());
                }
            }

            if (string.IsNullOrWhiteSpace(Body) && AlternateViews.Count > 0) {
                var att = AlternateViews.FirstOrDefault(x => x.ContentType.Is("text/plain"));
                if (att == null) {
                    att = AlternateViews.FirstOrDefault(x => x.ContentType.Contains("html"));
                }

                if (att != null) {
                    Body = att.Body;
                    ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
                    ContentType = att.Headers["Content-Type"].RawValue;
                }
            }

            Date = Headers.GetDate();
            To = Headers.GetAddresses("To").ToList();
            Cc = Headers.GetAddresses("Cc").ToList();
            Bcc = Headers.GetAddresses("Bcc").ToList();
            Sender = Headers.GetAddresses("Sender").FirstOrDefault();
            ReplyTo = Headers.GetAddresses("Reply-To").ToList();
            From = Headers.GetAddresses("From").FirstOrDefault();
            MessageID = Headers["Message-ID"].RawValue;

            Importance = Headers.GetEnum<MailPriority>("Importance");
            Subject = Headers["Subject"].RawValue;
        }
Пример #38
0
        static object GetDeserializedObject(Stream inputStream)
        {
            string body = inputStream.ReadToEnd().ToUtf8String();
            if (body.IsEmpty())
                return null;

            return new JavaScriptSerializer().DeserializeObject(body);
        }
Пример #39
0
        private void ParseMime(Stream reader, string boundary, int maxLength)
        {
            var maxLengthSpecified = maxLength > 0;
              string data,
            bounderInner = "--" + boundary,
            bounderOuter = bounderInner + "--";

              do {
            data = reader.ReadLine(ref maxLength, Encoding);
              } while (data != null && !data.StartsWith(bounderInner));

              while (data != null && !data.StartsWith(bounderOuter) && (maxLength > 0 || !maxLengthSpecified)) {
            data = reader.ReadLine(ref maxLength, Encoding);
            var a = new Attachment { Encoding = Encoding };

            var part = new StringBuilder();
            // read part header
            while (!data.StartsWith(bounderInner) && data != string.Empty) {
              part.AppendLine(data);
              data = reader.ReadLine(ref maxLength, Encoding);
            }
            a.RawHeaders = part.ToString();
            // header body

            data = reader.ReadLine(ref maxLength, Encoding);
            var body = new StringBuilder();
            while (data != string.Empty && !data.StartsWith(bounderInner)) {
              body.AppendLine(data);
              data = reader.ReadLine(ref maxLength, Encoding);
            }
            // check for nested part
            string nestedboundary = a.Headers.GetBoundary();
            if (!string.IsNullOrEmpty(nestedboundary)) {
              ParseMime(body.ToString(), nestedboundary);

            } else { // nested
              a.SetBody(body.ToString());
              (a.IsAttachment ? Attachments : AlternateViews).Add(a);
            }
              }

              if (maxLength > 0)
            data = reader.ReadToEnd(maxLength, Encoding);
        }
Пример #40
0
 internal static string Process(Stream stream, IPropertyProvider propertyProvider, bool throwIfNotFound = true)
 {
     string text = stream.ReadToEnd();
     return _tokenRegex.Replace(text, match => ReplaceToken(match, propertyProvider, throwIfNotFound));
 }
Пример #41
0
 private void LocalAfterRequestCompleted(Stream stream)
 {
     LogInstance.LogInfo("Call complete to {0} in {1:#.000} seconds", this.Url, CallTimer.Stop());
     this.ResponseText = stream.ReadToEnd().TrimEnd();
     AfterRequestCompleted(this.ResponseText);
 }
Пример #42
0
		public virtual void Load(Stream reader, bool headersOnly = false, int maxLength = 0, char? termChar = null)
		{
			_HeadersOnly = headersOnly;
			Headers = null;
			Body = null;
			if (maxLength == 0)
				return;


			var headers = new StringBuilder();
			string line;
			while ((line = reader.ReadLine(ref maxLength, _DefaultEncoding, termChar)) != null) {
				if (line.Length == 0)
					if (headers.Length == 0)
						continue;
					else
						break;
				headers.AppendLine(line);
			}
			RawHeaders = headers.ToString();

			if (!headersOnly) {
				string boundary = Headers.GetBoundary();
				if (!string.IsNullOrEmpty(boundary)) {
					var atts = new List<Attachment>();
					var body = ParseMime(reader, boundary, ref maxLength, atts, Encoding, termChar);
					if (!string.IsNullOrEmpty(body))
						SetBody(body);

					foreach (var att in atts)
						(att.IsAttachment ? Attachments : AlternateViews).Add(att);

					if (maxLength > 0)
						reader.ReadToEnd(maxLength, Encoding);
				} else {
					//	sometimes when email doesn't have a body, we get here with maxLength == 0 and we shouldn't read any further
					string body = String.Empty;
					if (maxLength > 0)
						body = reader.ReadToEnd(maxLength, Encoding);

					SetBody(body);
				}
			}
			else if (maxLength > 0)
				reader.ReadToEnd(maxLength, Encoding);

			if ((string.IsNullOrWhiteSpace(Body) || ContentType.StartsWith("multipart/")) && AlternateViews.Count > 0) {
				var att = AlternateViews.GetTextView() ?? AlternateViews.GetHtmlView();
				if (att != null) {
					Body = att.Body;
					ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
					ContentType = att.Headers["Content-Type"].RawValue;
				}
			}

			Date = Headers.GetDate();
			To = Headers.GetMailAddresses("To").ToList();
			Cc = Headers.GetMailAddresses("Cc").ToList();
			Bcc = Headers.GetMailAddresses("Bcc").ToList();
			Sender = Headers.GetMailAddresses("Sender").FirstOrDefault();
			ReplyTo = Headers.GetMailAddresses("Reply-To").ToList();
			From = Headers.GetMailAddresses("From").FirstOrDefault();
			MessageID = Headers["Message-ID"].RawValue;

			Importance = Headers.GetEnum<MailPriority>("Importance");
			Subject = Headers["Subject"].RawValue;
		}