public void KattisSolver_Should_WorkOnMultipleLinesOfInput() { // Arrange string result; using (var helper = new StreamHelper("5 3 8", "10 5 2", "5 15 3")) { // Act var kattisSolver = new KattisSolver(helper.InStream, helper.OutStream); kattisSolver.SolveOnStreams(); result = helper.ReadOut(); } // Assert Assert.That(result, Is.EqualTo("5+3=8\r\n10/5=2\r\n5=15/3\r\n")); }
public void KattisSolver_Should_WorkOnStreams() { // Arrange const string data = "5 3 8"; string result; using (var helper = new StreamHelper(data)) { // Act var kattisSolver = new KattisSolver(helper.InStream, helper.OutStream); kattisSolver.SolveOnStreams(); result = helper.ReadOut(); } // Assert Assert.That(result, Is.EqualTo("5+3=8\r\n")); }
public static Image GetQRCode(byte[] data, ErrorCorrectionLevel level = ErrorCorrectionLevel.M) { bool requires16BitLength = false; int maxBytesInVersion9Code = QRErrorCorrections.GetQRVersionInfo(9).GetCorrectionInfo(level).TotalDataBytes; if (maxBytesInVersion9Code - 2 < data.Length) { // This data requires a version 10 or higher code; will not fit in version 9 or lower. // Version 10 and higher codes require 16-bit data lengths. requires16BitLength = true; } StreamHelper sh = new StreamHelper(); sh.WriteNibble(0x04); // byte mode if (requires16BitLength) { sh.WriteWord((ushort)data.Length); } else { sh.WriteByte((byte)data.Length); } sh.WriteBytes(new ArraySegment<byte>(data)); sh.WriteNibble(0x00); // terminator byte[] binaryData = sh.ToArray(); int qrCodeVersion; ErrorCorrectionLevel errorCorrectionLevel; byte[] finalMessageSequence = QRErrorCorrections.GetMessageSequence(binaryData, level, out qrCodeVersion, out errorCorrectionLevel); SymbolTemplate template = SymbolTemplate.CreateTemplate(qrCodeVersion); template.ErrorCorrectionLevel = errorCorrectionLevel; template.PopulateData(finalMessageSequence); template.Complete(); return template.ToImage(); }
#pragma warning disable SA1009 // Doesn't like ValueTuples. public async Task <(string contents, string path)> GetDocumentationAsync() #pragma warning restore SA1009 // Doesn't like ValueTuples. { if (!string.IsNullOrWhiteSpace(_cachedDocumentation)) { return(_cachedDocumentation, _cachedPath); } var filepath = string.Empty; var filename = string.Empty; var localPath = string.Empty; var docRegex = new Regex("^" + _repoOnlineRoot + "(?<branch>.+?)/docs/(?<file>.+)"); var docMatch = docRegex.Match(DocumentationUrl); if (docMatch.Success) { filepath = docMatch.Groups["file"].Value; filename = Path.GetFileName(filepath); localPath = $"ms-appx:///docs/{Path.GetDirectoryName(filepath)}/"; } #if !DEBUG // use the docs repo in release mode string modifiedDocumentationUrl = $"{_docsOnlineRoot}master/docs/{filepath}"; _cachedPath = modifiedDocumentationUrl.Replace(filename, string.Empty); // Read from Cache if available. try { _cachedDocumentation = await StorageFileHelper.ReadTextFromLocalCacheFileAsync(filename); } catch (Exception) { } // Grab from docs repo if not. if (string.IsNullOrWhiteSpace(_cachedDocumentation)) { try { using (var request = new HttpRequestMessage(HttpMethod.Get, new Uri(modifiedDocumentationUrl))) { using (var response = await client.SendAsync(request).ConfigureAwait(false)) { if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); _cachedDocumentation = ProcessDocs(result); if (!string.IsNullOrWhiteSpace(_cachedDocumentation)) { await StorageFileHelper.WriteTextToLocalCacheFileAsync(_cachedDocumentation, filename); } } } } } catch (Exception) { } } #endif // Grab the local copy in Debug mode, allowing you to preview changes made. if (string.IsNullOrWhiteSpace(_cachedDocumentation)) { try { using (var localDocsStream = await StreamHelper.GetPackagedFileStreamAsync($"docs/{filepath}")) { var result = await localDocsStream.ReadTextAsync(); _cachedDocumentation = ProcessDocs(result); _cachedPath = localPath; } } catch (Exception) { } } return(_cachedDocumentation, _cachedPath); }
/// <summary> /// Reads the RequestType from the stream, creates the appropriate request object, populates it and executes the request (calls the handler) /// </summary> /// <param name="packet"></param> public virtual void HandlePacket(DataPacket packet) { _logger.DebugFormat("Handling request in '{0}'", SubsystemIdentifier); using (ByteStream src = new ByteStream(packet.Payload)) { TRequest requestTypeIdentifier = (TRequest)Enum.ToObject(typeof(TRequest), StreamHelper.ReadUInt16(src)); SubsystemRequest request = CreateRequestFromIdentifier(requestTypeIdentifier); request.Read(src); request.PacketIdentifier = new PacketIdentifier(packet.PacketNr); ExecuteRequest(requestTypeIdentifier, request); } }
public void LoadData(System.IO.BinaryReader reader) { name = StreamHelper.ReadString(reader); data = ScorItem.UnserializeDefaultToken(reader); }
private Task StartStreaming(string url, TaskCompletionSource <bool> openTaskCompletionSource, CancellationToken cancellationToken) { return(Task.Run(async() => { var isFirstAttempt = true; while (!cancellationToken.IsCancellationRequested) { try { using (var response = await _httpClient.SendAsync(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken, BufferContent = false, // Increase a little bit TimeoutMs = 30000 }, "GET").ConfigureAwait(false)) { _logger.Info("Opened HDHR stream from {0}", url); if (!cancellationToken.IsCancellationRequested) { _logger.Info("Beginning multicastStream.CopyUntilCancelled"); if (_enableFileBuffer) { FileSystem.CreateDirectory(FileSystem.GetDirectoryName(_tempFilePath)); using (var fileStream = FileSystem.GetFileStream(_tempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) { StreamHelper.CopyTo(response.Content, fileStream, 81920, () => Resolve(openTaskCompletionSource), cancellationToken); } } else { await _multicastStream.CopyUntilCancelled(response.Content, () => Resolve(openTaskCompletionSource), cancellationToken).ConfigureAwait(false); } } } } catch (OperationCanceledException) { break; } catch (Exception ex) { if (isFirstAttempt) { _logger.ErrorException("Error opening live stream:", ex); openTaskCompletionSource.TrySetException(ex); break; } _logger.ErrorException("Error copying live stream, will reopen", ex); } isFirstAttempt = false; } _liveStreamTaskCompletionSource.TrySetResult(true); //await DeleteTempFile(_tempFilePath).ConfigureAwait(false); })); }
public virtual void Write(Stream sink) { foreach (FieldInfo memberInfo in GetMembersToSerializeInOrder()) { Type curType = memberInfo.FieldType; if (curType.IsEnum) { curType = Enum.GetUnderlyingType(curType); } if (typeof(ITypedStreamSerializable).IsAssignableFrom(curType)) { StreamHelper.WriteTypedStreamSerializable((ITypedStreamSerializable)memberInfo.GetValue(this), sink); } else if (typeof(IStreamSerializable).IsAssignableFrom(curType)) { IStreamSerializable toSerialize = (IStreamSerializable)memberInfo.GetValue(this); if (toSerialize == null) { StreamHelper.WriteBool(false, sink); } else { StreamHelper.WriteBool(true, sink); toSerialize.Write(sink); } } else if (curType == typeof(byte)) { sink.WriteByte((byte)memberInfo.GetValue(this)); } else if (curType == typeof(byte[])) { StreamHelper.WriteBytesSafe((byte[])memberInfo.GetValue(this), sink); } else if (curType == typeof(byte[][])) { StreamHelper.WriteInt32(((byte[][])memberInfo.GetValue(this)).Length, sink); foreach (byte[] data in (byte[][])memberInfo.GetValue(this)) { StreamHelper.WriteBytesSafe(data, sink); } } else if (curType == typeof(int)) { StreamHelper.WriteInt32((int)memberInfo.GetValue(this), sink); } else if (curType == typeof(uint)) { StreamHelper.WriteUInt32((uint)memberInfo.GetValue(this), sink); } else if (curType == typeof(ushort)) { StreamHelper.WriteUInt16((ushort)memberInfo.GetValue(this), sink); } else if (curType == typeof(Stream)) { StreamHelper.WriteStream((Stream)memberInfo.GetValue(this), sink); } else { throw new ArgumentException(string.Format("Type '{0}' is not supported by AutoStreamSerializable", curType)); } } }
/// <summary>Open a file to be appended at the end.</summary> /// <remarks> /// <para>This method open and seek to the end the file.</para> /// <para> /// When you finish to append to the file you must call /// <b> /// <see cref="Close" /> /// </b> /// method. /// </para> /// </remarks> /// <param name="fileName">The file path to be opened to write at the end.</param> public void BeginAppendToFile(string fileName) { mAsyncWriter = StreamHelper.CreateFileAppender(fileName, mEncoding, false); mHeaderText = String.Empty; mFooterText = String.Empty; }
public virtual uint ReadUInt32() { StreamHelper.Receive(this.stream, this._buffer, 4); return(Adf.BaseDataConverter.ToUInt32(this._buffer, 0)); }
public virtual ushort ReadUInt16() { StreamHelper.Receive(this.stream, this._buffer, 2); return(Adf.BaseDataConverter.ToUInt16(this._buffer, 0)); }
public virtual bool ReadBoolean() { StreamHelper.Receive(this.stream, this._buffer, 1); return(this._buffer[0] == 1); }
/// <summary> /// Parses headers from message or mime entry. /// </summary> /// <param name="entryStrm">Stream from where to read headers.</param> /// <returns>Returns header lines.</returns> public static string ParseHeaders(Stream entryStrm) { /*3.1. GENERAL DESCRIPTION A message consists of header fields and, optionally, a body. The body is simply a sequence of lines containing ASCII charac- ters. It is separated from the headers by a null line (i.e., a line with nothing preceding the CRLF). */ byte[] crlf = new byte[] { (byte)'\r', (byte)'\n' }; MemoryStream msHeaders = new MemoryStream(); StreamHelper r = new StreamHelper(entryStrm, null); byte[] lineData = r.ReadLine(); while (lineData != null) { if (lineData.Length == 0) { break; } msHeaders.Write(lineData, 0, lineData.Length); msHeaders.Write(crlf, 0, crlf.Length); lineData = r.ReadLine(); } return System.Text.Encoding.Default.GetString(msHeaders.ToArray()); }
/// <summary> /// Parses mime entries. /// </summary> /// <param name="msgStrm"></param> /// <param name="pos"></param> /// <param name="boundaryID"></param> internal ArrayList ParseEntries(MemoryStream msgStrm, int pos, string boundaryID) { ArrayList entries = null; // Entries are already parsed if (m_Entries != null) { return m_Entries; } entries = new ArrayList(); // If message doesn't have entries and have 1 entry (simple text message or contains only attachment). if (this.ContentType.ToLower().IndexOf("multipart/") == -1) { entries.Add(new MimeEntry(msgStrm.ToArray(), this)); m_Entries = entries; return m_Entries; } msgStrm.Position = pos; if (boundaryID.Length > 0) { MemoryStream strmEntry = new MemoryStream(); StreamHelper reader = new StreamHelper(msgStrm, null); byte[] lineData = reader.ReadLine(); // Search first entry while (lineData != null) { string line = System.Text.Encoding.Default.GetString(lineData); if (line.StartsWith("--" + boundaryID)) { break; } lineData = reader.ReadLine(); } // Start reading entries while (lineData != null) { // Read entry data string line = System.Text.Encoding.Default.GetString(lineData); // Next boundary if (line.StartsWith("--" + boundaryID) && strmEntry.Length > 0) { // Add Entry entries.Add(new MimeEntry(strmEntry.ToArray(), this)); strmEntry.SetLength(0); } else { strmEntry.Write(lineData, 0, lineData.Length); strmEntry.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2); } lineData = reader.ReadLine(); } } return entries; }
public override void DoAfterPublishUploadWork(IFileUploadContext uploadContext) { FileAttachSettings attachSettings = new FileAttachSettings(uploadContext.Settings); if (attachSettings.AttachmentFileName == null) { CalculateUploadVariables(uploadContext.FormatFileName(uploadContext.PreferredFileName), attachSettings); } string listGuid = SharepointBlogIdToListGuid(uploadContext.BlogId); if (listGuid != null) { SharePointListsService listsServicesharePointLists = new SharePointListsService(attachSettings.UploadServiceUrl); listsServicesharePointLists.Credentials = GetHttpCredentials(); //The AddAttachment() call will throw an error if the attachment already exists, so we need to delete //the attachment first (if it exists). To delete the attachment, we must construct the attachment URL //that is typically generated internally by the server. //Sample URL: http://sharepoint/sites/writer/b2/blog/Lists/Posts/Attachments/13/Sunset_thumb1.jpg string attachDeleteUrl = String.Format(CultureInfo.InvariantCulture, "{0}{1}/Lists/Posts/Attachments/{2}/{3}", attachSettings.BaseUrl, attachSettings.BlogUrlPart, uploadContext.PostId, attachSettings.AttachmentFileName); try { listsServicesharePointLists.DeleteAttachment(listGuid, uploadContext.PostId, attachDeleteUrl); } catch (Exception) {} //Add the attachment using (Stream fileContents = uploadContext.GetContents()) listsServicesharePointLists.AddAttachment(listGuid, uploadContext.PostId, attachSettings.AttachmentFileName, Convert.ToBase64String(StreamHelper.AsBytes(fileContents))); uploadContext.Settings.SetString(uploadContext.PostId, FILE_ALREADY_UPLOADED); return; } throw new BlogClientFileUploadNotSupportedException(); }
public virtual ulong ReadUInt64() { StreamHelper.Receive(this.stream, this._buffer, 8); return(Adf.BaseDataConverter.ToUInt64(this._buffer, 0)); }
public string GetFileContent(string file) { return(StreamHelper.GetString(_archive.GetFileStream(file))); }
public virtual float ReadSingle() { StreamHelper.Receive(this.stream, this._buffer, 4); return(Adf.BaseDataConverter.ToSingle(this._buffer, 0)); }
/** * Save relationships into the part. * * @param rels * The relationships collection to marshall. * @param relPartName * Part name of the relationship part to marshall. * @param zos * Zip output stream in which to save the XML content of the * relationships serialization. */ public static bool MarshallRelationshipPart( PackageRelationshipCollection rels, PackagePartName relPartName, ZipOutputStream zos) { // Building xml XmlDocument xmlOutDoc = new XmlDocument(); // make something like <Relationships // xmlns="http://schemas.openxmlformats.org/package/2006/relationships"> System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xmlOutDoc.NameTable); xmlnsManager.AddNamespace("x", PackageNamespaces.RELATIONSHIPS); XmlNode root = xmlOutDoc.AppendChild(xmlOutDoc.CreateElement(PackageRelationship.RELATIONSHIPS_TAG_NAME, PackageNamespaces.RELATIONSHIPS)); // <Relationship // TargetMode="External" // Id="rIdx" // Target="http://www.custom.com/images/pic1.jpg" // Type="http://www.custom.com/external-resource"/> Uri sourcePartURI = PackagingUriHelper .GetSourcePartUriFromRelationshipPartUri(relPartName.URI); foreach (PackageRelationship rel in rels) { // the relationship element XmlElement relElem = xmlOutDoc.CreateElement(PackageRelationship.RELATIONSHIP_TAG_NAME, PackageNamespaces.RELATIONSHIPS); // the relationship ID relElem.SetAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel.Id); // the relationship Type relElem.SetAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel .RelationshipType); // the relationship Target String targetValue; Uri uri = rel.TargetUri; if (rel.TargetMode == TargetMode.External) { // Save the target as-is - we don't need to validate it, // alter it etc targetValue = uri.OriginalString; // add TargetMode attribute (as it is external link external) relElem.SetAttribute( PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME, "External"); } else { targetValue = PackagingUriHelper.RelativizeUri( sourcePartURI, rel.TargetUri, true).ToString(); } relElem.SetAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME, targetValue); xmlOutDoc.DocumentElement.AppendChild(relElem); } xmlOutDoc.Normalize(); // String schemaFilename = Configuration.getPathForXmlSchema()+ // File.separator + "opc-relationships.xsd"; // Save part in zip ZipEntry ctEntry = new ZipEntry(ZipHelper.GetZipURIFromOPCName( relPartName.URI.ToString()).OriginalString); try { zos.PutNextEntry(ctEntry); StreamHelper.SaveXmlInStream(xmlOutDoc, zos); zos.CloseEntry(); } catch (IOException e) { logger.Log(POILogger.ERROR, "Cannot create zip entry " + relPartName, e); return(false); } return(true); // success }
public override void Read(Stream src) { base.Read(src); _contained = StreamHelper.ReadBool(src); }
public virtual void Read(Stream src) { foreach (FieldInfo memberInfo in GetMembersToSerializeInOrder()) { Type curType = memberInfo.FieldType; if (curType.IsEnum) { curType = Enum.GetUnderlyingType(curType); } if (typeof(ITypedStreamSerializable).IsAssignableFrom(curType)) { memberInfo.SetValue(this, StreamHelper.ReadTypedStreamSerializable(src, this.GetType().Assembly)); } else if (typeof(IStreamSerializable).IsAssignableFrom(curType)) { ConstructorInfo defaultCtorInfo = curType.GetConstructor(new Type[] { }); ConstructorInfo ctorInfo = curType.GetConstructor(new Type[] { typeof(Stream) }); if (defaultCtorInfo == null && ctorInfo == null) { throw new ArgumentException(string.Format("'{0}' is not compatible with AutoStreamSerializable, no ctor(Stream) found!", curType)); } bool hasValue = StreamHelper.ReadBool(src); if (hasValue) { if (ctorInfo != null) { memberInfo.SetValue(this, ctorInfo.Invoke(new object[] { src })); } else { memberInfo.SetValue(this, defaultCtorInfo.Invoke(new object[] { })); ((IStreamSerializable)memberInfo.GetValue(this)).Read(src); } } else { memberInfo.SetValue(this, null); } } else if (curType == typeof(byte)) { memberInfo.SetValue(this, (byte)src.ReadByte()); } else if (curType == typeof(byte[])) { memberInfo.SetValue(this, StreamHelper.ReadBytesSafe(src)); } else if (curType == typeof(byte[][])) { int length = StreamHelper.ReadInt32(src); byte[][] val = new byte[length][]; for (int i = 0; i < length; i++) { val[i] = StreamHelper.ReadBytesSafe(src); } memberInfo.SetValue(this, val); } else if (curType == typeof(int)) { memberInfo.SetValue(this, StreamHelper.ReadInt32(src)); } else if (curType == typeof(uint)) { memberInfo.SetValue(this, StreamHelper.ReadUInt32(src)); } else if (curType == typeof(ushort)) { memberInfo.SetValue(this, StreamHelper.ReadUInt16(src)); } else if (curType == typeof(Stream)) { memberInfo.SetValue(this, StreamHelper.ReadStream(src)); } else { throw new ArgumentException(string.Format("Type '{0}' is not supported by AutoStreamSerializable", curType)); } } }
public override void Write(Stream sink) { base.Write(sink); StreamHelper.WriteBool(_contained, sink); }
/// <summary> /// See base class docs. /// </summary> /// <param name="server"></param> /// <param name="args"></param> /// <returns></returns> protected override bool DoHandleRequest(IWebServer server, RequestReceivedEventArgs args) { var requestFile = GetRequestFile(args.PathParts, args.File); var result = requestFile != null && !String.IsNullOrEmpty(requestFile.FileName) && File.Exists(requestFile.FileName); if(result) { var normalisedRequestPath = NormaliseRequestPath(args.PathAndFile); var extension = Path.GetExtension(requestFile.FileName); var isProtected = requestFile.Root.IsProtectedContent; var checksumEntry = isProtected ? requestFile.Root.FindChecksum(normalisedRequestPath, requestPathIsNormalised: true) : null; result = !isProtected || checksumEntry != null; if(result) { var isHtml = ".html".Equals(extension, StringComparison.OrdinalIgnoreCase) || ".htm".Equals(extension, StringComparison.OrdinalIgnoreCase); if(isProtected && !requestFile.Root.TestChecksum(checksumEntry, requestFile.FileName)) { Factory.Singleton.Resolve<ILog>().Singleton.WriteLine("Will not serve {0}, it has failed the checksum test", args.PathAndFile); if(!isHtml) { args.Response.StatusCode = HttpStatusCode.BadRequest; } else { Responder.SendText(args.Request, args.Response, "<HTML><HEAD><TITLE>No</TITLE></HEAD><BODY>VRS will not serve content that has been tampered with. Install the custom content plugin if you want to alter the site's files.</BODY></HTML>", Encoding.UTF8, MimeType.Html); args.Classification = ContentClassification.Html; } } else { if(isHtml) { ModifyAndSendContent(args, requestFile.FileName, extension, r => { var textContentArgs = new TextContentEventArgs(args.Request, args.PathAndFile, r.Content, r.Encoding); _WebSite.OnHtmlLoadedFromFile(textContentArgs); r.Content = textContentArgs.Content; _WebSite.InjectHtmlContent(args.PathAndFile, r); _WebSite.BundleHtml(args.PathAndFile, r); }); } else if(".js".Equals(extension, StringComparison.OrdinalIgnoreCase)) { ModifyAndSendContent(args, requestFile.FileName, extension, r => { _WebSite.InjectIntoJavaScript(args.PathAndFile, r); _WebSite.MinifyJavaScript(r); }); } else if(".css".Equals(extension, StringComparison.OrdinalIgnoreCase)) { ModifyAndSendContent(args, requestFile.FileName, extension, r => { _WebSite.MinifyCss(r); }); } else { args.Response.MimeType = MimeType.GetForExtension(extension); var enableCompression = true; if(args.Response.MimeType == MimeType.IconImage) enableCompression = false; else if(args.Response.MimeType.StartsWith("image/")) enableCompression = false; if(enableCompression) args.Response.EnableCompression(args.Request); args.Response.ContentLength = new FileInfo(requestFile.FileName).Length; args.Classification = MimeType.GetContentClassification(args.Response.MimeType); args.Response.StatusCode = HttpStatusCode.OK; using(var fileStream = new FileStream(requestFile.FileName, FileMode.Open, FileAccess.Read)) { StreamHelper.CopyStream(fileStream, args.Response.OutputStream, 4096); } } } } } return result; }
public override void Write(Stream sink) { base.Write(sink); StreamHelper.WriteString(_identifier, sink); }
/// <inheritdoc /> /// <summary> /// Generates output in Word Document Office Open XML. /// </summary> protected override void Execute() { var tempTemplate = FileHelper.GetUniqueTempRandomFile(); var originalTemplate = Provider.Input.Model.ResolveRelativePath(KnownRelativeFilePath.Template); File.Copy(originalTemplate, tempTemplate.OriginalString); var rows = GetRowData().ToList(); var sufix = Template.Writer.Settings.FieldSufix; var trimmode = Template.Writer.Settings.TrimMode; var prefix = Template.Writer.Settings.FieldPrefix; var trimField = Template.Writer.Settings.TrimFields == YesNo.Yes; foreach (var row in rows) { using (var stream = StreamHelper.AsMemoryStreamFromFile(tempTemplate.OriginalString)) { using (var document = DocX.Load(stream)) { var attributes = row.Attributes(); var templateField = new StringBuilder(); foreach (var attribute in attributes) { templateField.Clear(); templateField.Append(prefix); templateField.Append(attribute.Name); templateField.Append(sufix); var hasTables = document.Tables.Any(); var matches = document.FindUniqueByPattern(templateField.ToString(), RegexOptions.IgnoreCase); if (!matches.Any() && !hasTables) { continue; } var value = attribute.Value; if (trimField) { switch (trimmode) { case KnownTrimMode.All: value = value.Trim(); break; case KnownTrimMode.Start: value = value.TrimStart(); break; case KnownTrimMode.End: value = value.TrimEnd(); break; } } document.ReplaceText(templateField.ToString(), value); } var ms = new MemoryStream(); document.SaveAs(ms); Result.Add(ms.ToArray()); } } } File.Delete(tempTemplate.OriginalString); }
/// <summary> /// Converts stream to the file information parameter. /// </summary> /// <param name="stream">The stream.</param> /// <param name="paramName">Name of the parameter.</param> /// <returns>File information parameter.</returns> public FileInfo ToFileInfo(Stream stream, string paramName) { return(new FileInfo { Name = paramName, MimeType = "application/octet-stream", File = StreamHelper.ReadAsBytes(stream) }); }
public void SaveData(System.IO.BinaryWriter writer, bool last) { StreamHelper.WriteString(writer, name); writer.Write(data); ScorItem.SerializeDefaultToken(writer, last); }
/// <summary> /// Prepares the request. /// </summary> /// <param name="path">The path.</param> /// <param name="method">The method.</param> /// <param name="formParams">The form parameters.</param> /// <param name="headerParams">The header parameters.</param> /// <param name="body">The body.</param> /// <param name="contentType">Type of the content.</param> /// <returns>Prepared request.</returns> /// <exception cref="Aspose.Imaging.Cloud.Sdk.Client.ApiException">500 - unknown method type</exception> private WebRequest PrepareRequest(string path, string method, Dictionary <string, object> formParams, Dictionary <string, string> headerParams, string body, string contentType) { var client = WebRequest.Create(path.Replace(" ", "%20")); client.Method = method; Stream content = body == null ? null : new MemoryStream(Encoding.UTF8.GetBytes(body)); try { if (formParams.Count > 0) { content?.Dispose(); string formDataBoundary = "Somthing"; client.ContentType = "multipart/form-data; boundary=" + formDataBoundary; content = GetMultipartFormData(formParams, formDataBoundary); } else { client.ContentType = contentType; } foreach (var headerParamsItem in headerParams) { client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value); } foreach (var defaultHeaderMapItem in this.defaultHeaderMap) { if (!headerParams.ContainsKey(defaultHeaderMapItem.Key)) { client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); } } this.requestHandlers.ForEach(p => p.BeforeSend(client, content)); if (content != null) { client.ContentLength = content.Length; client.Timeout += (int)(content.Length / TimeoutDivisionIncreaseCoefficient); using (Stream requestStream = client.GetRequestStream()) { StreamHelper.CopyTo(content, requestStream); } } else { // TODO: change the behavior according to IMAGINGCLOUD-52 resolution client.ContentLength = 0; client.Timeout += 600000; } } finally { content?.Dispose(); } return(client); }
public override Stream Load(Context context) { return(StreamHelper.LoadMemoryStream(Data)); }
/// <summary> /// TestStepBase.Execute() implementation /// </summary> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public override void Execute(Context context) { var fi = new FileInfo(RuleStoreName); if (!fi.Exists) { throw new FileNotFoundException("RuleStoreName", RuleStoreName); } var ruleStore = new FileRuleStore(fi.FullName); var rsInfo = ruleStore.GetRuleSets(RuleSetInfoCollectionName, RuleStore.Filter.Latest); if (rsInfo.Count != 1) { // oops ... error throw new InvalidOperationException(string.Format("RuleStore {0} did not contain RuleSet {1}", RuleStoreName, RuleSetInfoCollectionName)); } var ruleset = ruleStore.GetRuleSet(rsInfo[0]); // load the facts into array var facts = new List <object>(FactsList.Count); // Create an instance of the Policy Tester class using (var policyTester = new PolicyTester(ruleset)) { foreach (var currentFact in FactsList) { switch (currentFact.GetType().ToString()) { case "ObjectFact": { var fact = currentFact as ObjectFact; object[] objectArgs = null; if (null != fact.Args) { objectArgs = fact.Args.Split(',').Cast <object>().ToArray(); } Type type; if (fact.AssemblyPath.Length > 0) { var asm = Assembly.Load(fact.AssemblyPath); if (asm == null) { // fail throw (new InvalidOperationException("failed to create type " + fact.Type)); } type = asm.GetType(fact.Type, true, false); } else { // must be in path type = Type.GetType(fact.Type); } facts.Add(Activator.CreateInstance(type, objectArgs)); break; } case "DocumentFact": { var fact = currentFact as DocumentFact; var xd1 = new XmlDocument(); xd1.Load(fact.InstanceDocument); var txd = new TypedXmlDocument(fact.SchemaType, xd1); facts.Add(txd); break; } case "DataConnectionFact": { var fact = currentFact as DataConnectionFact; var conn = new SqlConnection(fact.ConnectionString); conn.Open(); var dc = new DataConnection(fact.Dataset, fact.TableName, conn); facts.Add(dc); break; } case "dataTable": case "dataRow": { var fact = currentFact as DataTableFact; var conn = new SqlConnection(fact.ConnectionString); conn.Open(); var myCommand = new SqlCommand(fact.Command, conn) { CommandType = CommandType.Text }; var dAdapt = new SqlDataAdapter(); dAdapt.TableMappings.Add("Table", fact.TableName); dAdapt.SelectCommand = myCommand; var ds = new DataSet(fact.Dataset); dAdapt.Fill(ds); var tdt = new TypedDataTable(ds.Tables[fact.TableName]); if (fact.Type == "dataRow") { var tdr = new TypedDataRow(ds.Tables[fact.TableName].Rows[0], tdt); facts.Add(tdr); } else { facts.Add(tdt); } break; } } } // Create an instance of the DebugTrackingInterceptor using (var dti = new DebugTrackingInterceptor(DebugTracking)) { // Execute Policy Tester try { policyTester.Execute(facts.ToArray(), dti); } catch (Exception e) { context.LogException(e); throw; } } } // write out all document instances passed in foreach (var fact in facts) { switch (fact.GetType().Name) { case "TypedXmlDocument": { var txd = (TypedXmlDocument)fact; context.LogData("TypedXmlDocument result: ", txd.Document.OuterXml); using (var data = StreamHelper.LoadMemoryStream(txd.Document.OuterXml)) { if (txd.DocumentType == "UBS.CLAS.PoC.Schemas.INSERTS") { SubSteps.Aggregate(data, (current, subStep) => subStep.Execute(current, context)); } } break; } case "DataConnection": { var dc = (DataConnection)fact; dc.Update(); // persist any changes break; } case "TypedDataTable": { var tdt = (TypedDataTable)fact; tdt.DataTable.AcceptChanges(); break; } case "TypedDataRow": { var tdr = (TypedDataRow)fact; tdr.DataRow.AcceptChanges(); break; } } } }
public async Task PreparePropertyDescriptorAsync() { if (string.IsNullOrEmpty(XamlCodeFile)) { return; } if (_propertyDescriptor == null) { // Get Xaml code using (var codeStream = await StreamHelper.GetPackagedFileStreamAsync($"SamplePages/{Name}/{XamlCodeFile}")) { XamlCode = await codeStream.ReadTextAsync(Encoding.UTF8); // Look for @[] values and generate associated properties var regularExpression = new Regex(@"@\[(?<name>.+?)(:(?<type>.+?):(?<value>.+?)(:(?<parameters>.+?))?(:(?<options>.*))*)?\]@?"); _propertyDescriptor = new PropertyDescriptor { Expando = new ExpandoObject() }; var proxy = (IDictionary <string, object>)_propertyDescriptor.Expando; foreach (Match match in regularExpression.Matches(XamlCode)) { var label = match.Groups["name"].Value; var name = label.Replace(" ", string.Empty); // Allow us to have nicer display names, but create valid properties. var type = match.Groups["type"].Value; var value = match.Groups["value"].Value; var existingOption = _propertyDescriptor.Options.Where(o => o.Name == name).FirstOrDefault(); if (existingOption == null && string.IsNullOrWhiteSpace(type)) { throw new NotSupportedException($"Unrecognized short identifier '{name}'; Define type and parameters of property in first occurance in {XamlCodeFile}."); } if (Enum.TryParse(type, out PropertyKind kind)) { if (existingOption != null) { if (existingOption.Kind != kind) { throw new NotSupportedException($"Multiple options with same name but different type not supported: {XamlCodeFile}:{name}"); } continue; } PropertyOptions options; switch (kind) { case PropertyKind.Slider: case PropertyKind.DoubleSlider: try { var sliderOptions = new SliderPropertyOptions { DefaultValue = double.Parse(value, CultureInfo.InvariantCulture) }; var parameters = match.Groups["parameters"].Value; var split = parameters.Split('-'); int minIndex = 0; int minMultiplier = 1; if (string.IsNullOrEmpty(split[0])) { minIndex = 1; minMultiplier = -1; } sliderOptions.MinValue = minMultiplier * double.Parse(split[minIndex], CultureInfo.InvariantCulture); sliderOptions.MaxValue = double.Parse(split[minIndex + 1], CultureInfo.InvariantCulture); if (split.Length > 2 + minIndex) { sliderOptions.Step = double.Parse(split[split.Length - 1], CultureInfo.InvariantCulture); } options = sliderOptions; } catch (Exception ex) { Debug.WriteLine($"Unable to extract slider info from {value}({ex.Message})"); TrackingManager.TrackException(ex); continue; } break; case PropertyKind.TimeSpan: try { var sliderOptions = new SliderPropertyOptions { DefaultValue = TimeSpan.FromMilliseconds(double.Parse(value, CultureInfo.InvariantCulture)) }; var parameters = match.Groups["parameters"].Value; var split = parameters.Split('-'); int minIndex = 0; int minMultiplier = 1; if (string.IsNullOrEmpty(split[0])) { minIndex = 1; minMultiplier = -1; } sliderOptions.MinValue = minMultiplier * double.Parse(split[minIndex], CultureInfo.InvariantCulture); sliderOptions.MaxValue = double.Parse(split[minIndex + 1], CultureInfo.InvariantCulture); if (split.Length > 2 + minIndex) { sliderOptions.Step = double.Parse(split[split.Length - 1], CultureInfo.InvariantCulture); } options = sliderOptions; } catch (Exception ex) { Debug.WriteLine($"Unable to extract slider info from {value}({ex.Message})"); TrackingManager.TrackException(ex); continue; } break; case PropertyKind.Enum: try { options = new PropertyOptions(); var split = value.Split('.'); var typeName = string.Join(".", split.Take(split.Length - 1)); var enumType = LookForTypeByName(typeName); options.DefaultValue = Enum.Parse(enumType, split.Last()); } catch (Exception ex) { Debug.WriteLine($"Unable to parse enum from {value}({ex.Message})"); TrackingManager.TrackException(ex); continue; } break; case PropertyKind.Bool: try { options = new PropertyOptions { DefaultValue = bool.Parse(value) }; } catch (Exception ex) { Debug.WriteLine($"Unable to parse bool from {value}({ex.Message})"); continue; } break; case PropertyKind.Brush: try { options = new PropertyOptions { DefaultValue = value }; } catch (Exception ex) { Debug.WriteLine($"Unable to parse bool from {value}({ex.Message})"); TrackingManager.TrackException(ex); continue; } break; case PropertyKind.Thickness: try { var thicknessOptions = new ThicknessPropertyOptions { DefaultValue = value }; options = thicknessOptions; } catch (Exception ex) { Debug.WriteLine($"Unable to extract slider info from {value}({ex.Message})"); TrackingManager.TrackException(ex); continue; } break; default: options = new PropertyOptions { DefaultValue = value }; break; } options.Label = label; options.Name = name; options.OriginalString = match.Value; options.Kind = kind; options.IsTwoWayBinding = options.OriginalString.EndsWith("@"); proxy[name] = new ValueHolder(options.DefaultValue); _propertyDescriptor.Options.Add(options); } } } } }
public void TestOpenPackage() { FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestOpenPackageTMP.docx"); FileInfo inputFile = OpenXml4NetTestDataSamples.GetSampleFile("TestOpenPackageINPUT.docx"); FileInfo expectedFile = OpenXml4NetTestDataSamples.GetSampleFile("TestOpenPackageOUTPUT.docx"); // Copy the input file in the output directory FileHelper.CopyFile(inputFile.FullName, targetFile.FullName); // Create a namespace OPCPackage pkg = OPCPackage.Open(targetFile.FullName); // Modify core part PackagePartName corePartName = PackagingUriHelper .CreatePartName("/word/document.xml"); PackagePart corePart = pkg.GetPart(corePartName); // Delete some part to have a valid document foreach (PackageRelationship rel in corePart.Relationships) { corePart.RemoveRelationship(rel.Id); pkg.RemovePart(PackagingUriHelper.CreatePartName(PackagingUriHelper .ResolvePartUri(corePart.PartName.URI, rel .TargetUri))); } // Create a content XmlDocument doc = new XmlDocument(); XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable); string wuri = "http://schemas.openxmlformats.org/wordProcessingml/2006/main"; mgr.AddNamespace("w", wuri); XmlElement elDocument = doc.CreateElement("w:document", wuri); doc.AppendChild(elDocument); XmlElement elBody = doc.CreateElement("w:body", wuri); elDocument.AppendChild(elBody); XmlElement elParagraph = doc.CreateElement("w:p", wuri); elBody.AppendChild(elParagraph); XmlElement elRun = doc.CreateElement("w:r", wuri); elParagraph.AppendChild(elRun); XmlElement elText = doc.CreateElement("w:t", wuri); elRun.AppendChild(elText); elText.InnerText = ("Hello Open XML !"); StreamHelper.SaveXmlInStream(doc, corePart.GetOutputStream()); // Save and close try { pkg.Close(); } catch (IOException) { Assert.Fail(); } ZipFileAssert.AssertEqual(expectedFile, targetFile); File.Delete(targetFile.FullName); Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files."); }
public void AddFileContent(string content, string entryName) { AddFileContent(StreamHelper.Parse(content), entryName); }
/// <summary> /// Retrieve the resource with the specified timeout (in ms). /// </summary> /// <param name="timeoutMs">Timeout (in ms) for the request.</param> /// <returns>A stream representing the requested resource. Can return null /// if the CacheLevel is CacheOnly and the resource could not be found /// in the cache.</returns> public Stream GetResponse(int timeoutMs) { // always try to get the url from the cache first if (ReadFromCache) { Internet_Cache_Entry_Info cacheInfo; if (WinInet.GetUrlCacheEntryInfo(_requestUrl, out cacheInfo)) { if (File.Exists(cacheInfo.lpszLocalFileName)) { return(new FileStream(cacheInfo.lpszLocalFileName, FileMode.Open, FileAccess.Read)); } } } // if that didn't succeed then try to get the file from // the web as long as the user has requested we do this if (MakeRequest) { HttpWebResponse response = HttpRequestHelper.SendRequest(_requestUrl, delegate(HttpWebRequest request) { request.AllowAutoRedirect = AllowAutoRedirect; request.Timeout = timeoutMs; request.ContentType = ContentType; if (PostData != null) { request.Method = "POST"; using (Stream requestStream = request.GetRequestStream()) StreamHelper.Transfer(new MemoryStream(PostData), requestStream); } }); try { Stream responseStream = response.GetResponseStream(); if (responseStream != null) { if (WriteToCache) { return(WriteResponseToCache(responseStream)); } else { return(StreamHelper.CopyToMemoryStream(responseStream)); } } else { return(null); } } finally { response.Close(); } } else { // look only in the cache return(null); } }
public override void Read(Stream src) { base.Read(src); _parentIdentifier = StreamHelper.ReadString(src); }
private static string ConstructNonMultiPart(MimeEntry ent,bool bodystructure) { string str = "("; // contentType str += "\"" + ent.ContentType.Split('/')[0] + "\" "; // conentSubType if(ent.ContentType.Split('/').Length == 2){ str += "\"" + ent.ContentType.Split('/')[1].Replace(";","") + "\" "; } else{ str += "NIL "; } // conentTypeSubFields string longContentType = MimeParser.ParseHeaderField("Content-Type:",ent.Headers); if(longContentType.IndexOf(";") > -1){ str += "("; string[] fields = longContentType.Split(';'); for(int i=1;i<fields.Length;i++){ string[] nameValue = fields[i].Replace("\"","").Trim().Split(new char[]{'='},2); str += "\"" + nameValue[0] + "\" \"" + nameValue[1] + "\""; if(i < fields.Length - 1){ str += " "; } } str += ") "; } else{ // if content is attachment and content type name filed is missing, use filename for it string fileName = MimeParser.ParseHeaderFiledSubField("Content-Disposition:","filename",ent.Headers); if(fileName.Length > 0){ str += "(\"name\" \"" + fileName + "\") "; } else{ str += "NIL "; } } // contentID string contentID = MimeParser.ParseHeaderField("Content-ID:",ent.Headers); if(contentID.Length > 0){ str += "\"" + contentID + "\" "; } else{ str += "NIL "; } // contentDescription string contentDescription = MimeParser.ParseHeaderField("Content-Description:",ent.Headers); if(contentDescription.Length > 0){ str += "\"" + contentDescription + "\" "; } else{ str += "NIL "; } // contentEncoding str += "\"" + ent.ContentEncoding + "\" "; // contentSize str += ent.DataNonDecoded.Length + " "; // envelope NOTE: included only if contentType = "message" !!! // contentLines NOTE: included only if contentType = "text" !!! if(ent.ContentType.ToLower().IndexOf("text") > -1){ StreamHelper r = new StreamHelper(new MemoryStream(ent.DataNonDecoded), null); int nLines = 0; byte[] line = new byte[0]; while(line != null){ line = r.ReadLine(); nLines++; } str += nLines; } // Need to add extended fields if(bodystructure){ str += " "; // md5 str += "NIL "; // contentDisposition string contDispos = MimeParser.ParseHeaderField("Content-Disposition:",ent.Headers); if(contDispos.Length > 0){ str += "("; string[] fields = contDispos.Split(';'); str += "\"" + fields[0] + "\" "; if(fields.Length > 1){ str += "("; for(int i=1;i<fields.Length;i++){ string[] nameValue = fields[i].Replace("\"","").Trim().Split(new char[]{'='},2); str += "\"" + nameValue[0] + "\" \"" + nameValue[1] + "\""; if(i < fields.Length - 1){ str += " "; } } str += ")"; } else{ str += "NIL"; } str += ") "; } else{ str += "NIL "; } // contentLanguage str += "NIL"; } str += ")"; return str; }