public void LoadExisting(Stream existing, byte[] masterKey) { if (existing == null) throw new ArgumentNullException("existing"); if (masterKey == null) throw new ArgumentNullException("masterKey"); var reader = new BinaryReader(existing); if (!FileFormat.Sign(reader)) { throw new FormatException( "Invalid format detected"); } _version = FileFormat .ReadVersion(reader); _masterKey = masterKey; _headers = FileFormat .ReadHeaders(existing); _xmlWriter = new XmlWriter(); using (var decrypt = FileFormat.Decrypt( existing, _headers, masterKey)) { _xmlWriter.Load(decrypt); var crypto = CryptoSerializer .Create(_headers); _xmlWriter.Decrypt(crypto); } }
public void Write(Headers headers, Version version) { if (headers == null) throw new ArgumentNullException("headers"); // Signature _writer.Write(FileFormat.SIGNATURE); // Database version _writer.Write((short)version.Minor); _writer.Write((short)version.Major); // Headers Write(headers, HeaderFields.CipherID); Write(headers, HeaderFields.CompressionFlags); Write(headers, HeaderFields.MasterSeed); Write(headers, HeaderFields.TransformSeed); Write(headers, HeaderFields.TransformRounds); Write(headers, HeaderFields.EncryptionIV); Write(headers, HeaderFields.ProtectedStreamKey); Write(headers, HeaderFields.StreamStartBytes); Write(headers, HeaderFields.InnerRandomStreamID); Write(headers, HeaderFields.EndOfHeader); _writer.Flush(); }
public static Stream Decrypt(Stream source, Headers headers, byte[] masterKey) { byte[] easKey; using (var buffer = new MemoryStream()) { var masterSeed = headers.MasterSeed; buffer.Write(masterSeed, 0, masterSeed.Length); buffer.Write(masterKey, 0, masterKey.Length); easKey = BufferEx.GetHash(buffer.ToArray()); } var eas = new AesManaged { KeySize = 256, Key = BufferEx.Clone(easKey), IV = BufferEx.Clone(headers.EncryptionIV) }; Stream stream = new CryptoStream(source, eas.CreateDecryptor(), CryptoStreamMode.Read); if (!VerifyStartBytes(headers, stream)) return null; stream = new HashedBlockStream(stream, true); return headers.Compression == Compressions.GZip ? new GZipInputStream(stream) : stream; }
public static void ReadBody(Stream inputStream, Stream output, Headers headers, bool strict, ref float progress) { // Read Body byte[] buffer = new byte[8192]; int contentLength = 0; if (int.TryParse (headers.Get ("Content-Length"), out contentLength)) { if (contentLength > 0) { var remaining = contentLength; while (remaining > 0) { var count = inputStream.Read (buffer, 0, buffer.Length); if (count == 0) { break; } remaining -= count; output.Write (buffer, 0, count); progress = Mathf.Clamp01 (1.0f - ((float)remaining / (float)contentLength)); } } } else { if (!strict) { var count = inputStream.Read (buffer, 0, buffer.Length); while (count > 0) { output.Write (buffer, 0, count); count = inputStream.Read (buffer, 0, buffer.Length); } } progress = 1; } }
public HeadersResponse Get(Headers request) { HeadersResponse response = new HeadersResponse(); List<Bm2s.Data.Common.BLL.Trade.Header> items = new List<Data.Common.BLL.Trade.Header>(); if (!request.Ids.Any()) { items.AddRange(Datas.Instance.DataStorage.Headers.Where(item => (request.ActivityId == 0 || item.ActivityId == request.ActivityId) && (!request.Date.HasValue || (request.Date >= item.Date && (!item.EndingDate.HasValue || request.Date < item.EndingDate.Value))) && (string.IsNullOrWhiteSpace(request.Description) || item.Description.ToLower().Contains(request.Description.ToLower())) && (request.HeaderStatusId == 0 || item.HeaderStatusId == request.HeaderStatusId) && (!request.IsSell || item.IsSell) && (!request.IsPurchase || item.IsPurchase) && (string.IsNullOrWhiteSpace(request.Reference) || item.Reference.ToLower().Contains(request.Reference.ToLower())) && (request.UserId == 0 || item.UserId == request.UserId) )); } else { items.AddRange(Datas.Instance.DataStorage.Headers.Where(item => request.Ids.Contains(item.Id))); } var collection = (from item in items select new Bm2s.Poco.Common.Trade.Header() { Activity = new ActivitiesService().Get(new Activities() { Ids = new List<int>() { item.ActivityId } }).Activities.FirstOrDefault(), Date = item.Date, DeliveryObservation = item.DeliveryObservation, Description = item.Description, EndingDate = item.EndingDate, FooterDiscount = Convert.ToDecimal(item.FooterDiscount), HeaderStatus = new HeaderStatusesService().Get(new HeaderStatuses() { Ids = new List<int>() { item.HeaderStatusId } }).HeaderStatuses.FirstOrDefault(), Id = item.Id, IsPurchase = item.IsPurchase, IsSell = item.IsSell, Reference = item.Reference, User = new UsersService().Get(new Users() { Ids = new List<int>() { item.UserId } }).Users.FirstOrDefault() }).AsQueryable().OrderBy(request.Order, !request.DescendingOrder); response.ItemsCount = collection.Count(); if (request.PageSize > 0) { response.Headers.AddRange(collection.Skip((request.CurrentPage - 1) * request.PageSize).Take(request.PageSize)); } else { response.Headers.AddRange(collection); } try { response.PagesCount = collection.Count() / response.Headers.Count + (collection.Count() % response.Headers.Count > 0 ? 1 : 0); } catch { response.PagesCount = 1; } return response; }
protected override IEnumerable<KeyValuePair<string, string>> GetResult(string methodName, Headers methodParams) { var deviceId = "test"; var user = _user; if (string.Equals(methodName, "GetSearchCapabilities", StringComparison.OrdinalIgnoreCase)) return HandleGetSearchCapabilities(); if (string.Equals(methodName, "GetSortCapabilities", StringComparison.OrdinalIgnoreCase)) return HandleGetSortCapabilities(); if (string.Equals(methodName, "GetSortExtensionCapabilities", StringComparison.OrdinalIgnoreCase)) return HandleGetSortExtensionCapabilities(); if (string.Equals(methodName, "GetSystemUpdateID", StringComparison.OrdinalIgnoreCase)) return HandleGetSystemUpdateID(); if (string.Equals(methodName, "Browse", StringComparison.OrdinalIgnoreCase)) return HandleBrowse(methodParams, user, deviceId).Result; if (string.Equals(methodName, "X_GetFeatureList", StringComparison.OrdinalIgnoreCase)) return HandleXGetFeatureList(); if (string.Equals(methodName, "GetFeatureList", StringComparison.OrdinalIgnoreCase)) return HandleGetFeatureList(); if (string.Equals(methodName, "X_SetBookmark", StringComparison.OrdinalIgnoreCase)) return HandleXSetBookmark(methodParams, user); if (string.Equals(methodName, "Search", StringComparison.OrdinalIgnoreCase)) return HandleSearch(methodParams, user, deviceId).Result; throw new ResourceNotFoundException("Unexpected control request name: " + methodName); }
public void test() { Headers headers = new Headers(); headers.username = "******"; headers.password = "******"; service.HeadersValue = headers; Assert.AreEqual("hello user", service.say_hello()); }
public override Navigation.NavigationContainer Create(RlViewer.Files.FileProperties properties, Headers.Abstract.LocatorFileHeader header) { var rHeader = header as RlViewer.Headers.Concrete.R.RHeader; if (rHeader == null) throw new ArgumentException("rHeader"); return new RNavigationContainer(properties.FilePath, rHeader.HeaderStruct.synthesisHeader.initialRange, 0, (int)rHeader.HeaderStruct.lineInfoHeader.lineLength, rHeader.HeaderStruct.synthesisHeader.dx, rHeader.HeaderStruct.synthesisHeader.sideObservation, rHeader.FileHeaderLength, (int)rHeader.HeaderStruct.lineInfoHeader.lineLength * rHeader.BytesPerSample); }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="request"></param> /// <param name="status"></param> public IOResponse(IORequest request, IOStatus status) { Contract.Requires<ArgumentNullException>(request != null); this.request = request; this.status = status; this.headers = new Headers(); }
public override Navigation.NavigationContainer Create(RlViewer.Files.FileProperties properties, Headers.Abstract.LocatorFileHeader header) { var brl4header = header as RlViewer.Headers.Concrete.Brl4.Brl4Header; if (brl4header == null) throw new ArgumentException("brl4header"); return new Brl4NavigationContainer(properties.FilePath, brl4header.HeaderStruct.synthParams.D0, brl4header.HeaderStruct.rlParams.flipType, brl4header.HeaderStruct.rlParams.width, brl4header.HeaderStruct.rlParams.dx, brl4header.HeaderStruct.synthParams.board, brl4header.FileHeaderLength, brl4header.HeaderStruct.rlParams.width * brl4header.BytesPerSample, brl4header.HeaderStruct.rlParams.sx, brl4header.HeaderStruct.rlParams.sy); }
private void Write(Headers header, HeaderFields field) { var bytes = header[field]; _writer.Write((byte)field); _writer.Write((short)bytes.Length); _writer.Write(bytes, 0, bytes.Length); }
public override Navigation.NavigationContainer Create(RlViewer.Files.FileProperties properties, Headers.Abstract.LocatorFileHeader header) { var kHeader = header as RlViewer.Headers.Concrete.K.KHeader; if (kHeader == null) throw new ArgumentException("kHeader"); return new KNavigationContainer(properties.FilePath, kHeader.HeaderStruct.synchronizerHeader.initialRange, 0, 0, 0, (byte)kHeader.HeaderStruct.synchronizerHeader.board, header.FileHeaderLength, (int)kHeader.HeaderStruct.lineInfoHeader.lineLength * header.BytesPerSample); }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="request"></param> public ModelResponse(ModelRequest request, ModelResponseStatus status, XDocument body) { Contract.Requires<ArgumentNullException>(request != null); this.request = request; this.status = status; this.body = body; this.headers = new Headers(); }
protected override IEnumerable<KeyValuePair<string, string>> GetResult(string methodName, Headers methodParams) { if (string.Equals(methodName, "IsAuthorized", StringComparison.OrdinalIgnoreCase)) return HandleIsAuthorized(); if (string.Equals(methodName, "IsValidated", StringComparison.OrdinalIgnoreCase)) return HandleIsValidated(); throw new ResourceNotFoundException("Unexpected control request name: " + methodName); }
public KSizeCalculator(Headers.Abstract.LocatorFileHeader header) { var fileHead = header as Headers.Concrete.K.KHeader; _dx = 300 / (2 * fileHead.HeaderStruct.adcHeader.adcFreq); _dy = _dx; //_freq = fileHead.HeaderStruct.adcHeader.adcFreq; //_impulseLength = fileHead.HeaderStruct }
protected override IEnumerable<KeyValuePair<string, string>> GetResult(string methodName, Headers methodParams) { if (string.Equals(methodName, "GetProtocolInfo", StringComparison.OrdinalIgnoreCase)) { return HandleGetProtocolInfo(); } throw new ResourceNotFoundException("Unexpected control request name: " + methodName); }
private ControlResponse ProcessControlRequestInternal(ControlRequest request) { var soap = new XmlDocument(); soap.LoadXml(request.InputXml); var sparams = new Headers(); var body = soap.GetElementsByTagName("Body", NS_SOAPENV).Item(0); var method = body.FirstChild; foreach (var p in method.ChildNodes) { var e = p as XmlElement; if (e == null) { continue; } sparams.Add(e.LocalName, e.InnerText.Trim()); } Logger.Debug("Received control request {0}", method.LocalName); var result = GetResult(method.LocalName, sparams); var env = new XmlDocument(); env.AppendChild(env.CreateXmlDeclaration("1.0", "utf-8", string.Empty)); var envelope = env.CreateElement("SOAP-ENV", "Envelope", NS_SOAPENV); env.AppendChild(envelope); envelope.SetAttribute("encodingStyle", NS_SOAPENV, "http://schemas.xmlsoap.org/soap/encoding/"); var rbody = env.CreateElement("SOAP-ENV:Body", NS_SOAPENV); env.DocumentElement.AppendChild(rbody); var response = env.CreateElement(String.Format("u:{0}Response", method.LocalName), method.NamespaceURI); rbody.AppendChild(response); foreach (var i in result) { var ri = env.CreateElement(i.Key); ri.InnerText = i.Value; response.AppendChild(ri); } var xml = env.OuterXml.Replace("xmlns:m=", "xmlns:u="); var controlResponse = new ControlResponse { Xml = xml, IsSuccessful = true }; //Logger.Debug(xml); controlResponse.Headers.Add("EXT", string.Empty); return controlResponse; }
public HeadersResponse Delete(Headers request) { Bm2s.Data.Common.BLL.Trade.Header item = Datas.Instance.DataStorage.Headers[request.Header.Id]; item.EndingDate = DateTime.Now; Datas.Instance.DataStorage.Headers[item.Id] = item; HeadersResponse response = new HeadersResponse(); response.Headers.Add(request.Header); return response; }
public static void CollectHeaders(Stream inputStream, Headers headers) { while (true) { // Collect Headers string[] parts = ReadKeyValue (inputStream); if (parts == null) { break; } headers.Add (parts [0], parts [1]); } }
public static byte[] Serialize(Headers headers) { using (var buffer = new MemoryStream()) { var writer = new BinaryWriter(buffer); writer.Write((byte)headers.CrsAlgorithm); writer.Write(headers.ProtectedStreamKey); return buffer.ToArray(); } }
public ZendeskDefaultConfiguration(string username, string token) { Headers = new Headers(); var auth = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}/token:{1}", username, token))); Headers.AddHeader(AcceptCharset, "utf-8"); Headers.AddHeader(Authorization, string.Format("Basic {0}", auth)); Headers.AddHeader(AcceptKey, "application/json"); Headers.AddHeader(ContentTypeKey, "application/json"); }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="resourceUri"></param> /// <param name="method"></param> public IORequest( Uri resourceUri, IOMethod method) { Contract.Requires<ArgumentNullException>(resourceUri != null); Contract.Requires<ArgumentException>(resourceUri.IsAbsoluteUri); this.resourceUri = resourceUri; this.method = method; this.headers = new Headers(); this.context = new DynamicDictionary(); }
protected override byte[] ConvertToDestStrHeaderBytes(Headers.Abstract.IStrHeader sourceHeader) { switch (SourceFile.Properties.Type) { case FileType.k: return StructIO.WriteStruct<Headers.Concrete.Brl4.Brl4StrHeaderStruct>(((Headers.Concrete.K.KStrHeaderStruct)sourceHeader).ToBrl4StrHeader()); case FileType.ba: return StructIO.WriteStruct<Headers.Concrete.Brl4.Brl4StrHeaderStruct>(((Headers.Concrete.Ba.BaStrHeader)sourceHeader).ToBrl4StrHeader()); default: throw new ArgumentException("SourceFile type"); } }
public void test_exception() { Headers headers = new Headers(); headers.username = "******"; headers.password = "******"; service.HeadersValue = headers; try { service.say_hello(); } catch(Exception e) { Assert.AreEqual("Access denied for user fake", e.Message); return; } Assert.True(false, "Exception hasn't been thrown"); }
public static Headers ReadHeaders(Stream stream) { HeaderFields field; var fields = new Headers(); var reader = new BinaryReader(stream); do { field = (HeaderFields)reader.ReadByte(); var size = reader.ReadInt16(); fields.Add(field, reader.ReadBytes(size)); } while (field != HeaderFields.EndOfHeader); return fields; }
public override NavigationString[] ConvertToCommonNavigation(Headers.Abstract.IStrHeader[] strCollection) { RlViewer.Headers.Concrete.Brl4.Brl4StrHeaderStruct[] rStrColl = strCollection.Select(x => (RlViewer.Headers.Concrete.Brl4.Brl4StrHeaderStruct)x).ToArray(); IEnumerable<NavigationString> naviStrings; try { naviStrings = rStrColl.Select (x => new NavigationString((float)x.longtitude, (float)x.latitude, (float)x.H, (float)x.a, _board, x.time[0] == 0 ? default(DateTime) : x.time.ToDateTime())); } catch (ArgumentNullException) { throw; } return naviStrings.ToArray(); }
public override NavigationString[] ConvertToCommonNavigation(Headers.Abstract.IStrHeader[] strCollection) { RlViewer.Headers.Concrete.R.RStrHeaderStruct[] rStrColl = strCollection.Select(x => (RlViewer.Headers.Concrete.R.RStrHeaderStruct)x).ToArray(); IEnumerable<NavigationString> naviStrings; try { naviStrings = rStrColl.Select (x => new NavigationString((float)(x.navigationHeader.longtitudeInsSns / 180f * Math.PI), (float)(x.navigationHeader.latitudeInsSns / 180f * Math.PI), (float)x.navigationHeader.heightInsSns, (float)(x.navigationHeader.realTraceInsSns / 180f * Math.PI), _board, new DateTime().AddYears(1970).AddMilliseconds(x.navigationHeader.timeArm))); } catch (ArgumentNullException) { throw; } return naviStrings.ToArray(); }
/// <summary> /// Gets the header with the specified key as a string if possible, otherwise null /// </summary> public string GetStringHeader(string key) { return(Headers.ContainsKey(key) && Headers[key] is string?(string)Headers[key] : null); }
/// <summary> /// Adds or updates an HTTP header with the specified name and value in /// the headers for the response. /// </summary> /// <param name="name"> /// A <see cref="string"/> that specifies the name of the header to set. /// </param> /// <param name="value"> /// A <see cref="string"/> that specifies the value of the header to set. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="name"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="name"/> is an empty string. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="name"/> is a string of spaces. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="name"/> contains an invalid character. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="value"/> contains an invalid character. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="name"/> is a restricted header name. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 /// characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current headers do not allow the header. /// </exception> public void SetHeader(string name, string value) { Headers.Set(name, value); }
public void AddHeader(string name, string value) { Headers.Add(name, value); request.AddHeader(name, value); }
private void OnRequestHandlerHeaders(object o, WebHeadersEventArgs webInjectEventArgs) { Headers?.Invoke(this, webInjectEventArgs); }
private RequestData(HttpMethod method, PostData data, ITransportConfigurationValues global, IRequestConfiguration local, IMemoryStreamFactory memoryStreamFactory ) { ConnectionSettings = global; MemoryStreamFactory = memoryStreamFactory; Method = method; PostData = data; if (data != null) { data.DisableDirectStreaming = local?.DisableDirectStreaming ?? global.DisableDirectStreaming; } Pipelined = local?.EnableHttpPipelining ?? global.HttpPipeliningEnabled; HttpCompression = global.EnableHttpCompression; RequestMimeType = local?.ContentType ?? MimeType; Accept = local?.Accept ?? MimeType; if (global.Headers != null) { Headers = new NameValueCollection(global.Headers); } if (local?.Headers != null) { Headers ??= new NameValueCollection(); foreach (var key in local.Headers.AllKeys) { Headers[key] = local.Headers[key]; } } if (!string.IsNullOrEmpty(local?.OpaqueId)) { Headers ??= new NameValueCollection(); Headers.Add(OpaqueIdHeader, local.OpaqueId); } RunAs = local?.RunAs; SkipDeserializationForStatusCodes = global.SkipDeserializationForStatusCodes; ThrowExceptions = local?.ThrowExceptions ?? global.ThrowExceptions; RequestTimeout = local?.RequestTimeout ?? global.RequestTimeout; PingTimeout = local?.PingTimeout ?? global.PingTimeout ?? (global.ConnectionPool.UsingSsl ? TransportConfiguration.DefaultPingTimeoutOnSsl : TransportConfiguration.DefaultPingTimeout); KeepAliveInterval = (int)(global.KeepAliveInterval?.TotalMilliseconds ?? 2000); KeepAliveTime = (int)(global.KeepAliveTime?.TotalMilliseconds ?? 2000); DnsRefreshTimeout = global.DnsRefreshTimeout; ProxyAddress = global.ProxyAddress; ProxyUsername = global.ProxyUsername; ProxyPassword = global.ProxyPassword; DisableAutomaticProxyDetection = global.DisableAutomaticProxyDetection; AuthenticationHeader = local?.AuthenticationHeader ?? global.AuthenticationHeader; AllowedStatusCodes = local?.AllowedStatusCodes ?? EmptyReadOnly <int> .Collection; ClientCertificates = local?.ClientCertificates ?? global.ClientCertificates; UserAgent = global.UserAgent; TransferEncodingChunked = local?.TransferEncodingChunked ?? global.TransferEncodingChunked; TcpStats = local?.EnableTcpStats ?? global.EnableTcpStats; ThreadPoolStats = local?.EnableThreadPoolStats ?? global.EnableThreadPoolStats; }
/// <summary> /// Initializes a new instance of the <see cref="HttpMultipartFileContent" /> class. /// </summary> /// <param name="boundary">The boundary string for file content.</param> public HttpMultipartFileContent(string boundary) { this.boundaryString = boundary; Headers.TryAddWithoutValidation("Content-Type", $"multipart/form-data; boundary={this.boundaryString}"); }
/// <summary> /// Create a new SerializationContext object instance. /// </summary> /// <param name="component"> /// The component of the message the serialization operation relates to. /// </param> /// <param name="topic"> /// The topic the data is being written to or read from. /// </param> /// <param name="headers"> /// The collection of message headers (or null). Specifying null or an /// empty list are equivalent. The order of headers is maintained, and /// duplicate header keys are allowed. /// </param> public SerializationContext(MessageComponentType component, string topic, Headers headers = null) { Component = component; Topic = topic; Headers = headers; }
private void process() { PacketReader pr = new PacketReader(_buffer); //Create our packet reader. Headers header = (Headers)pr.ReadByte(); //Read and cast our header. switch (header) { case Headers.Queue: { //Read the ID, Filename and length of the file (For progress) from the packet. int id = pr.ReadInt32(); //string Shortname = pr.ReadString(); string type = pr.ReadString(); string fileName = pr.ReadString(); long length = pr.ReadInt64(); //Create our queueload queue. queue queue = queue.CreateDownloadQueue(this, id, type, Path.Combine(OutputFolder, fileName), length); //Add it to our transfer list. _transfers.Add(id, queue); // Call queued. if (Queued != null) { Queued(this, queue); } } break; case Headers.Start: { //Read the ID int id = pr.ReadInt32(); //Start the upload. if (_transfers.ContainsKey(id)) { _transfers[id].Start(); } } break; //case Headers.Stop: // { // //Read the ID // int id = pr.ReadInt32(); // if (_transfers.ContainsKey(id)) // { // //Get the queue. // TransferQueue queue = _transfers[id]; // //Stop and close the queue // queue.Stop(); // queue.Close(); // //Call the stopped event. // if (Stopped != null) // Stopped(this, queue); // //Remove the queue // _transfers.Remove(id); // } // } // break; //case Headers.Pause: // { // int id = pr.ReadInt32(); // //Pause the upload. // if (_transfers.ContainsKey(id)) // { // _transfers[id].Pause(); // } // } // break; case Headers.Chunk: { //Read the ID, index, size and buffer from the packet. int id = pr.ReadInt32(); long index = pr.ReadInt64(); int size = pr.ReadInt32(); byte[] buffer = pr.ReadBytes(size); //Get the queue. queue queue = _transfers[id]; //Write the newly transferred bytes to the queue based on the write index. queue.Write(buffer, index); //Get the progress of the current transfer with the formula //(AMOUNT_TRANSFERRED * 100) / COMPLETE SIZE queue.Progress = (int)((queue.Transferred * 100) / queue.Length); //This will prevent the us from calling progress changed multiple times. /* Such as * 2, 2, 2, 2, 2, 2 (Since the actual progress minus the decimals will be the same for a bit * It will be * 1, 2, 3, 4, 5, 6 * Instead*/ if (queue.LastProgress < queue.Progress) { queue.LastProgress = queue.Progress; if (ProgressChanged != null) { ProgressChanged(this, queue); } //If the transfer is complete, call the event. if (queue.Progress == 100) { queue.Close(); if (Complete != null) { Complete(this, queue); } } } } break; } pr.Dispose(); //Dispose the reader. }
/// <summary> /// Gets the value of header with <paramref name="name"/>. /// </summary> /// <remarks><typeparamref name="T"/> must contain a TryParse method with the signature <c>public static bool TryParse(string, out T)</c>.</remarks> /// <typeparam name="T">The type of the header. /// The given type must have a static TryParse method.</typeparam> /// <param name="name">The name of the header to retrieve.</param> /// <returns>The value of the header.</returns> public T?Get <T>(string name) { return(Headers.Get <T>(name)); }
private void SetTimeoutHeaders(object toSend) { Headers.SetMessageHeader(toSend, Headers.SagaId, Data.Id.ToString()); Headers.SetMessageHeader(toSend, Headers.IsSagaTimeoutMessage, Boolean.TrueString); Headers.SetMessageHeader(toSend, Headers.SagaType, GetType().AssemblyQualifiedName); }
/// <summary> /// Sets the request body to a binary stream. /// </summary> /// <param name="content">The binary stream to set as a body.</param> public void SetStreamContent(Stream content) { Content = content; Headers.Add(contentTypeHeader, binaryContentType); }
/// <summary> /// Gets the header. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns></returns> public T GetHeader <T>(string key, T defaultValue = default(T)) { return(Headers != null && Headers.ContainsKey(key) ? (T)Headers[key] : defaultValue); }
public void RemoveHeader(string name) { var knownHeader = Headers.SingleOrDefault(h => string.Equals(h.Name, name, StringComparison.OrdinalIgnoreCase)); _headers.Remove(knownHeader); }
public abstract LocatorFile Create(FileProperties properties, Headers.Abstract.LocatorFileHeader header, RlViewer.Navigation.NavigationContainer navi);
public void AddHeader(HttpHeader header) { CoreValidator.ThrowIfNull(header, nameof(header)); Headers.Add(header); }
internal void PrepareHeaders(bool sendEnvelope, bool allowUnicode) { string headerName; if (_headersEncoding == null) { _headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet); } //ContentType is written directly to the stream so remove potential user duplicate Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentType) !); Headers[MailHeaderInfo.GetString(MailHeaderID.MimeVersion)] = "1.0"; // add sender to headers first so that it is written first to allow the IIS smtp svc to // send MAIL FROM with the sender if both sender and from are present headerName = MailHeaderInfo.GetString(MailHeaderID.Sender) !; if (Sender != null) { Headers.InternalAdd(headerName, Sender.Encode(headerName.Length, allowUnicode)); } else { Headers.Remove(headerName); } headerName = MailHeaderInfo.GetString(MailHeaderID.From) !; Headers.InternalAdd(headerName, From !.Encode(headerName.Length, allowUnicode)); headerName = MailHeaderInfo.GetString(MailHeaderID.To) !; if (To.Count > 0) { Headers.InternalAdd(headerName, To.Encode(headerName.Length, allowUnicode)); } else { Headers.Remove(headerName); } headerName = MailHeaderInfo.GetString(MailHeaderID.Cc) !; if (CC.Count > 0) { Headers.InternalAdd(headerName, CC.Encode(headerName.Length, allowUnicode)); } else { Headers.Remove(headerName); } headerName = MailHeaderInfo.GetString(MailHeaderID.ReplyTo) !; if (ReplyTo != null) { Headers.InternalAdd(headerName, ReplyTo.Encode(headerName.Length, allowUnicode)); } else if (ReplyToList.Count > 0) { Headers.InternalAdd(headerName, ReplyToList.Encode(headerName.Length, allowUnicode)); } else { Headers.Remove(headerName); } Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Bcc) !); if (_priority == MailPriority.High) { Headers[MailHeaderInfo.GetString(MailHeaderID.XPriority)] = "1"; Headers[MailHeaderInfo.GetString(MailHeaderID.Priority)] = "urgent"; Headers[MailHeaderInfo.GetString(MailHeaderID.Importance)] = "high"; } else if (_priority == MailPriority.Low) { Headers[MailHeaderInfo.GetString(MailHeaderID.XPriority)] = "5"; Headers[MailHeaderInfo.GetString(MailHeaderID.Priority)] = "non-urgent"; Headers[MailHeaderInfo.GetString(MailHeaderID.Importance)] = "low"; } //if the priority was never set, allow the app to set the headers directly. else if (((int)_priority) != -1) { Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.XPriority) !); Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Priority) !); Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Importance) !); } Headers.InternalAdd(MailHeaderInfo.GetString(MailHeaderID.Date) !, MailBnfHelper.GetDateTimeString(DateTime.Now, null) !); headerName = MailHeaderInfo.GetString(MailHeaderID.Subject) !; if (!string.IsNullOrEmpty(_subject)) { if (allowUnicode) { Headers.InternalAdd(headerName, _subject); } else { Headers.InternalAdd(headerName, MimeBasePart.EncodeHeaderValue(_subject, _subjectEncoding, MimeBasePart.ShouldUseBase64Encoding(_subjectEncoding), headerName.Length)); } } else { Headers.Remove(headerName); } EncodeHeaders(_headers !, allowUnicode); }
public RedirectResult(string location) : base(HttpResponseStatusCode.SeeOther) { Headers.AddHeader(new HttpHeader(Constants.LocationHeaderKey, location)); }
public RedirectResult(string location) : base(HttpResponseStatusCode.SeeOther) { Headers.AddHeader(new HTTP.Headers.HttpHeader("Location", location)); }
private void SetHeadersAndResponseContent(byte[] responseMessage) { if (responseMessage == null || responseMessage.Length < 4) { return; } var headers = string.Empty; // get headers part; var headerEnd = 0; for (; headerEnd < responseMessage.Length - 3; headerEnd++) { if (responseMessage[headerEnd] == 13 && responseMessage[headerEnd + 1] == 10 && responseMessage[headerEnd + 2] == 13 && responseMessage[headerEnd + 3] == 10) { headers = Encoding.ASCII.GetString(responseMessage, 0, headerEnd); break; } } if (string.IsNullOrEmpty(headers)) { return; } var headerValues = headers.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); // ignore the first line in the header since it is the HTTP response code for (var i = 1; i < headerValues.Length; i++) { var headerEntry = headerValues[i].Split(':'); Headers.Add(headerEntry[0], headerEntry[1]); } var statusRegex = new System.Text.RegularExpressions.Regex(@"^HTTP/\d+\.\d+ (\d+)(.*)$"); var matches = statusRegex.Match(headerValues[0]); if (matches.Groups.Count < 3) { throw new InvalidDataException(); } StatusCode = (HttpStatusCode)int.Parse(matches.Groups[1].Value); StatusDescription = matches.Groups[2].Value; ResponseContent = new byte[responseMessage.Length - headerEnd - 4]; Array.Copy(responseMessage, headerEnd + 4, ResponseContent, 0, ResponseContent.Length); string transferEncoding = Headers["Transfer-Encoding"]; switch (transferEncoding) { case "chunked": DechunkContent(); break; } string contentEncoding = Headers["Content-Encoding"]; switch (contentEncoding) { case "gzip": ResponseContent = Decompress(ResponseContent) ?? ResponseContent; break; } }
public HttpRequest header(string name, string value) { Headers.Add(name, value); return(this); }
public int Prompt(string message = "", ConsoleColor?color = null, bool allowEmpty = false, bool clearConsole = true) { if (Contents?.Any() == false) { return(-1); } var prevRenderOptionChoice = RenderOptions.IncludeChoices; RenderOptions.IncludeChoices = true; int selection = -1; do { Write(clearConsole); if (!string.IsNullOrEmpty(message)) { Consoul.Write("HELP ME!", Console.BackgroundColor); Consoul.Write(message, color ?? ConsoulLibrary.RenderOptions.PromptColor); } if (allowEmpty) { Consoul.Write("Press Enter to continue", ConsoulLibrary.RenderOptions.SubnoteColor); } string input = Consoul.Read(); if (string.IsNullOrEmpty(input) && allowEmpty) { selection = Contents.Count + 1; break; } if (input.Contains("=")) { Dictionary <int, List <int> > matches = new Dictionary <int, List <int> >(); string[] queries = input.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); foreach (string queryInput in queries) { string[] queryParts = queryInput.Split('='); if (queryParts.Length == 2) { int columnIndex = Headers.IndexOf(queryParts[0]); if (columnIndex >= 0) { if (!matches.ContainsKey(columnIndex)) { matches.Add(columnIndex, new List <int>()); } for (int i = 0; i < Contents.Count; i++) { if (Contents[i][columnIndex] == queryParts[1]) { matches[columnIndex].Add(i); } } } else { raiseQueryYieldsNoResults($"Invalid Header reference! Could not find Header '{queryParts[0]}'.", input); } } else { raiseQueryYieldsNoResults("Query-based selection not formatted correctly. Must be in {Header Name}={Value} format", input); } } List <int> results = new List <int>(); for (int i = 0; i < Contents.Count; i++) { if (matches.All(o => o.Value.Contains(i))) { results.Add(i); } } if (results.Count == 1) { selection = results.First() + 1; // selection is expected as one-based } else if (results.Count > 1) { raiseQueryYieldsNoResults("Invalid Query! Query yielded multiple results. Try a more refined search.", input); } else if (results.Count == 0) { raiseQueryYieldsNoResults("Invalid Query! Query yielded no results.", input); } } else if (!int.TryParse(input, out selection) || selection <= 0 || selection > Contents.Count) { Consoul.Write("Invalid selection!", ConsoleColor.Red); Consoul.Wait(); selection = -1; } } while (selection < 0); if (selection > Contents.Count) { selection = 0; } RenderOptions.IncludeChoices = prevRenderOptionChoice; return(selection - 1); }
public void RemoveHeader(string name) { Headers.Remove(name); }
private bool ProcessContentLengthHeader() { // Read the content. string contentLengthHeader; if (Headers.TryGetValue("Content-Length", out contentLengthHeader)) { int contentLength; if (!int.TryParse(contentLengthHeader, out contentLength)) { throw new ProtocolException(String.Format("Could not parse Content-Length header '{0}'", contentLengthHeader)); } string contentTypeHeader; string contentType = null; string contentTypeExtra = null; if (Headers.TryGetValue("Content-Type", out contentTypeHeader)) { string[] parts = contentTypeHeader.Split(new[] { ';' }, 2); contentType = parts[0].Trim().ToLowerInvariant(); contentTypeExtra = parts.Length == 2 ? parts[1].Trim() : null; } if (_parser != null) { _parser.Dispose(); _parser = null; } switch (contentType) { case "application/x-www-form-urlencoded": _parser = new HttpUrlEncodedRequestParser(this, contentLength); break; case "multipart/form-data": string boundary = null; if (contentTypeExtra != null) { string[] parts = contentTypeExtra.Split(new[] { '=' }, 2); if ( parts.Length == 2 && String.Equals(parts[0], "boundary", StringComparison.OrdinalIgnoreCase) ) { boundary = parts[1]; } } if (boundary == null) { throw new ProtocolException("Expected boundary with multipart content type"); } _parser = new HttpMultiPartRequestParser(this, contentLength, boundary); break; case "application/json": _parser = new HttpJsonRequestParser(this, contentLength); break; default: _parser = new HttpUnknownRequestParser(this, contentLength); break; } // We've made a parser available. Recurs back to start processing // with the parser. ProcessContent(); return(true); } return(false); }
public void AddHeader(string key, double value) { Headers.Add(key, value); }
public void Handle(CampaignCreatedEvent @event, Headers headers) { string name = @event.Name; string aggId = headers.GetAggregateId(); }
/// <summary> /// Gets the values of header with <paramref name="name"/>. /// </summary> /// <remarks><typeparamref name="T"/> must contain a TryParseList method with the signature <c>public static bool TryParseList(IList<string>, out IList<T>)</c>.</remarks> /// <typeparam name="T">The type of the header. /// The given type must have a static TryParseList method.</typeparam> /// <param name="name">The name of the header to retrieve.</param> /// <returns>List of values of the header.</returns> public IList <T> GetList <T>(string name) { return(Headers.GetList <T>(name)); }
/// <summary> /// Appends an HTTP header with the specified name and value to /// the headers for the response. /// </summary> /// <param name="name"> /// A <see cref="string"/> that specifies the name of the header to /// append. /// </param> /// <param name="value"> /// A <see cref="string"/> that specifies the value of the header to /// append. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="name"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="name"/> is an empty string. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="name"/> is a string of spaces. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="name"/> contains an invalid character. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="value"/> contains an invalid character. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="name"/> is a restricted header name. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 /// characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current headers do not allow the header. /// </exception> public void AppendHeader(string name, string value) { Headers.Add(name, value); }
public virtual HttpRequestBuilder SetHeader(string name, string value) { Headers.Set(name, value); return(this); }
/// <summary> /// Appends the header name and it's values. /// </summary> /// <param name="name">The header name.</param> /// <param name="values">The header values.</param> public void AppendList <T>(string name, IList <T> values) { Headers.AppendList <T>(name, values); }
internal static Stream Encrypt(Stream source, Headers headers, byte[] masterKey) { byte[] easKey; using (var buffer = new MemoryStream()) { var masterSeed = headers.MasterSeed; buffer.Write(masterSeed, 0, masterSeed.Length); buffer.Write(masterKey, 0, masterKey.Length); easKey = BufferEx.GetHash(buffer.ToArray()); } var eas = new AesManaged { KeySize = 256, Key = BufferEx.Clone(easKey), IV = BufferEx.Clone(headers.EncryptionIV) }; Stream stream = new CryptoStream(source, eas.CreateEncryptor(), CryptoStreamMode.Write); stream.Write(headers.StreamStartBytes, 0, headers.StreamStartBytes.Length); stream = new HashedBlockStream(stream, false); return headers.Compression == Compressions.GZip ? new GZipOutputStream(stream) : stream; }
public bool Download(MessageFetchMode mode = MessageFetchMode.ClientDefault, bool reloadHeaders = false) { if (mode == MessageFetchMode.ClientDefault) { mode = _client.Behavior.MessageFetchMode; } if (mode == MessageFetchMode.None) { return(true); } var fetchParts = new StringBuilder(); if (mode.HasFlag(MessageFetchMode.Flags) && !_downloadProgress.HasFlag(MessageFetchMode.Flags)) { fetchParts.Append("FLAGS "); } if (mode.HasFlag(MessageFetchMode.InternalDate) && !_downloadProgress.HasFlag(MessageFetchMode.InternalDate)) { fetchParts.Append("INTERNALDATE "); } if (mode.HasFlag(MessageFetchMode.Size) && !_downloadProgress.HasFlag(MessageFetchMode.Size)) { fetchParts.Append("RFC822.SIZE "); } if (mode.HasFlag(MessageFetchMode.Headers) && (!_downloadProgress.HasFlag(MessageFetchMode.Headers) || reloadHeaders)) { Headers.Clear(); if (_client.Behavior.RequestedHeaders == null || _client.Behavior.RequestedHeaders.Length == 0) { fetchParts.Append("BODY.PEEK[HEADER] "); } else { fetchParts.Append("BODY.PEEK[HEADER.FIELDS (" + string.Join(" ", _client.Behavior.RequestedHeaders.Where(_ => !string.IsNullOrEmpty(_)) .Select(_ => _.ToUpper()) .ToArray()) + ")] "); } } if (mode.HasFlag(MessageFetchMode.BodyStructure) && !_downloadProgress.HasFlag(MessageFetchMode.BodyStructure)) { fetchParts.Append("BODYSTRUCTURE "); } if (_client.Capabilities.XGMExt1) { if (mode.HasFlag(MessageFetchMode.GMailMessageId) && !_downloadProgress.HasFlag(MessageFetchMode.GMailMessageId)) { fetchParts.Append("X-GM-MSGID "); } if (mode.HasFlag(MessageFetchMode.GMailThreads) && !_downloadProgress.HasFlag(MessageFetchMode.GMailThreads)) { fetchParts.Append("X-GM-THRID "); } if (mode.HasFlag(MessageFetchMode.GMailLabels) && !_downloadProgress.HasFlag(MessageFetchMode.GMailLabels)) { fetchParts.Append("X-GM-LABELS "); } } IList <string> data = new List <string>(); if (fetchParts.Length > 0 && !_client.SendAndReceive(string.Format(ImapCommands.Fetch, UId, fetchParts.ToString().Trim()), ref data)) { return(false); } else { NormalizeAndProcessFetchResult(data); } BindHeadersToFields(); if (!mode.HasFlag(MessageFetchMode.Body) || BodyParts == null) { return(true); } foreach (MessageContent bodyPart in BodyParts) { if (mode.HasFlag(MessageFetchMode.Full) || (bodyPart.ContentDisposition == null && bodyPart.ContentType != null && (bodyPart.ContentType.MediaType == "text/plain" || bodyPart.ContentType.MediaType == "text/html"))) { bodyPart.Download(); } } return(true); }
public override LocatorFile Create(FileProperties properties, Headers.Abstract.LocatorFileHeader header, RlViewer.Navigation.NavigationContainer navi) { return new K(properties, header, navi); }
public List <string> GetHeadersList() { return(Headers.Split(',').ToList()); }