internal Connection(System.Net.ConnectionGroup connectionGroup) : base(null) { this.m_IISVersion = -1; this.m_Free = true; this.m_Idle = true; this.m_KeepAlive = true; this.m_MaximumUnauthorizedUploadLength = SettingsSectionInternal.Section.MaximumUnauthorizedUploadLength; if (this.m_MaximumUnauthorizedUploadLength > 0L) { this.m_MaximumUnauthorizedUploadLength *= 0x400L; } this.m_ResponseData = new CoreResponseData(); this.m_ConnectionGroup = connectionGroup; this.m_ReadBuffer = new byte[0x1000]; this.m_ReadState = ReadState.Start; this.m_WaitList = new List<WaitListItem>(); this.m_WriteList = new ArrayList(); this.m_AbortDelegate = new HttpAbortDelegate(this.AbortOrDisassociate); this.m_ConnectionUnlock = new UnlockConnectionDelegate(this.UnlockRequest); this.m_StatusLineValues = new StatusLineValues(); this.m_RecycleTimer = this.ConnectionGroup.ServicePoint.ConnectionLeaseTimerQueue.CreateTimer(); this.ConnectionGroup.Associate(this); this.m_ReadDone = true; this.m_WriteDone = true; this.m_Error = WebExceptionStatus.Success; }
internal void BeginRead() { NetworkStream netstream = _tcp.GetStream(); int bufferSize = _tcp.ReceiveBufferSize; var state = new ReadState(netstream, bufferSize); netstream.BeginRead(state.Buffer, 0, state.Buffer.Length, ReadCallback, state); }
public void Poll() { while (_stream.DataAvailable) { switch (_readState) { case ReadState.ReadLength: _bufInt32Offset += _stream.Read(_bufInt32, _bufInt32Offset, 4 - _bufInt32Offset); if (_bufInt32Offset == 4) { _readState = ReadState.ReadType; _bufInt32Offset = 0; _intConverter.FromBytes(_bufInt32, 0); _payload = new byte[_intConverter.intdata]; } break; case ReadState.ReadType: _bufInt32Offset += _stream.Read (_bufInt32, _bufInt32Offset, 4 - _bufInt32Offset); if (_bufInt32Offset == 4) { _readState = ReadState.ReadPayload; _bufInt32Offset = 0; _intConverter.FromBytes(_bufInt32, 0); _type = (PacketType)_intConverter.intdata; } break; case ReadState.ReadPayload: _payloadOffset += _stream.Read(_payload, _payloadOffset, _payload.Length - _payloadOffset); if (_payloadOffset == _payload.Length) { _readState = ReadState.ReadLength; _payloadOffset = 0; if (OnResponse != null) { OnResponse(new Packet(){ type = _type, payload = _payload }); } } break; } } }
internal CommState() { idle_tick = new Timer( CheckIdle, null, 30000, 30000 ); readstate = ReadState.getLength; buffer = new MemoryStream( 1024 ); send_buffer = new MemoryStream( 1024 ); }
void ReadComplete( IAsyncResult iar ) { int toread = 4; int bytes = 0; try { bytes = socket.EndReceive( iar ); } catch( Exception ) { socket.Close(); disconnected = true; return; } switch( state ) { case ReadState.readLength: toread = BitConverter.ToInt32( buffer.GetBuffer(), 0 ); state = ReadState.readData; break; case ReadState.readData: state = ReadState.readLength; Protocol.Message msgId = (Protocol.Message)BitConverter.ToInt32( buffer.GetBuffer(), 0 ); switch( msgId ) { default: Log.log( "Received unhandled message: {0}", msgId ); break; //case Protocol.Message. } break; } buffer.SetLength( toread ); socket.BeginReceive( buffer.GetBuffer(), 0, toread, SocketFlags.None, ReadComplete, null ); }
public RilList Get(ReadState state, DateTime? since, int? count, int? page, bool myAppOnly, bool tags) { var list = new RilList(); list.Items = new Dictionary<string, RilListItem>(); list.Items.Add("12345", new RilListItem() { Title = "Website 1", Url = "www.web1.com" }); list.Items.Add("23456", new RilListItem() { Title = "Website 2", Url = "www.web2.com" }); list.Items.Add("34567", new RilListItem() { Title = "Website 3", Url = "www.web3.com", Tags = "existing-tag" }); return list; }
public ChunkParser(Connection connection,ArraySegment<byte> initialBuffer, int initialBufferOffset, int initialBufferCount) { _connection = connection; _buffer = initialBuffer; _bufferCurrentPos = initialBufferOffset; _bufferSize = initialBufferOffset + initialBufferCount; _readState = ReadState.ChunkLength; _currentChunkLength = -1; }
public TextIncludingReader(Uri includeLocation, string encoding, string accept, string acceptLanguage, bool exposeCDATA) { _includeLocation = includeLocation; _href = includeLocation.AbsoluteUri; _encoding = encoding; _state = ReadState.Initial; _accept = accept; _acceptLanguage = acceptLanguage; _exposeCDATA = exposeCDATA; }
internal MasterServerConnection( TcpClient client) { this.tcpClient = client; socket = client.Client; state = ReadState.readLength; socket.NoDelay = true; buffer.SetLength( 4 ); // makes ure buffer has a buffer socket.BeginReceive( buffer.GetBuffer(), 0, 4, SocketFlags.None, ReadComplete, client ); SendHello(); }
private void ResetForNewResponse() { if (_errorDecoder != null) { _errorDecoder.Dispose(); _errorDecoder = null; } _readState = new ReadState(); _currentReadState = ReadResponseHeader; }
public static IHandler Create(WebSocketHttpRequest request, Action<string> onMessage, Action onClose) { var readState = new ReadState(); return new ComposableHandler { Handshake = () => Hybi13Handler.BuildHandshake(request), Frame = s => Hybi13Handler.FrameData(Encoding.UTF8.GetBytes(s), FrameType.Text), Close = i => Hybi13Handler.FrameData(i.ToBigEndianBytes<ushort>(), FrameType.Close), RecieveData = d => Hybi13Handler.ReceiveData(d, readState, (op, data) => Hybi13Handler.ProcessFrame(op, data, onMessage, onClose)) }; }
internal static string Read(Record record, int lengthBits, ref int continueIndex, ref ushort offset) { string text = string.Empty; ReadState state = new ReadState(record, lengthBits, continueIndex, offset); Read(state); continueIndex = state.ContinueIndex; offset = state.Offset; return new string(state.CharactersRead.ToArray()); }
public static IHandler Create(WebSocketHttpRequest request, Action<string> onMessage, Fleck2Extensions.Action onClose, Action<byte[]> onBinary) { var readState = new ReadState(); return new ComposableHandler { Handshake = () => BuildHandshake(request), TextFrame = data => FrameData(Encoding.UTF8.GetBytes(data), FrameType.Text), BinaryFrame = data => FrameData(data, FrameType.Binary), CloseFrame = i => FrameData(i.ToBigEndianBytes<ushort>(), FrameType.Close), ReceiveData = bytes => ReceiveData(bytes, readState, (op, data) => ProcessFrame(op, data, onMessage, onClose, onBinary)) }; }
private bool BufferEnd() { if (this.maxOffset != 0) { return false; } if ((this.readState != ReadState.ReadWS) && (this.readState != ReadState.ReadValue)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MimeReaderMalformedHeader"))); } this.readState = ReadState.EOF; return true; }
public override bool Read() { switch (readState) { case ReadState.Initial: readState = ReadState.Interactive; return ReadCurrentPosition(); case ReadState.Interactive: objectIterator.MoveInto(); return ReadCurrentPosition(); default: return false; } }
public XmlMicrodataReader(HtmlAgilityPack.HtmlNode rootEntity) { this.readState = System.Xml.ReadState.Initial; this.rootEntity = new Item(rootEntity); this.nodeType = XmlNodeType.None; var typeAttr = rootEntity.GetAttributeItemType(); if (typeAttr != null) { Uri type; Uri.TryCreate(typeAttr.Value, UriKind.Absolute, out type); this.Type = type; } }
public static IHandler Create(WebSocketHttpRequest request, Action<string> onMessage, Action onClose, Action<byte[]> onBinary, Action<byte[]> onPing, Action<byte[]> onPong) { var readState = new ReadState(); return new ComposableHandler { Handshake = sub => Hybi13Handler.BuildHandshake(request, sub), TextFrame = s => Hybi13Handler.FrameData(Encoding.UTF8.GetBytes(s), FrameType.Text), BinaryFrame = s => Hybi13Handler.FrameData(s, FrameType.Binary), PingFrame = s => Hybi13Handler.FrameData(s, FrameType.Ping), PongFrame = s => Hybi13Handler.FrameData(s, FrameType.Pong), CloseFrame = i => Hybi13Handler.FrameData(i.ToBigEndianBytes<ushort>(), FrameType.Close), ReceiveData = d => Hybi13Handler.ReceiveData(d, readState, (op, data) => Hybi13Handler.ProcessFrame(op, data, onMessage, onClose, onBinary, onPing, onPong)) }; }
private static void BeginRead(ReadState rs, Action callback) { AsyncCallback asyncCallback = ar => { int count = rs.Stream.EndRead(ar); rs.Offset += count; rs.Count -= count; if(rs.Count > 0) { BeginRead(rs, callback); } else { callback(); } }; rs.Stream.BeginRead(rs.Buffer, rs.Offset, rs.Count, asyncCallback, rs); }
/// <summary> /// See <see cref="XmlReader.Read"/>. /// </summary> public override bool Read() { if (state == ReadState.Initial) { state = ReadState.Interactive; isRoot = true; nodeType = XmlNodeType.Element; return true; } else if (state == ReadState.EndOfFile) { return false; } bool read = base.Read(); if (isRoot) { if (!read) { isRoot = false; nodeType = XmlNodeType.None; state = ReadState.EndOfFile; } else { isRoot = false; } } else { if (!read) { isRoot = true; nodeType = XmlNodeType.EndElement; return true; } } return read; }
private void ReadNewLine(byte[] buffer, int startIndex, int lastIndex, bool beforeContentDisposition) { _readState = beforeContentDisposition ? ReadState.ReadBeforeContentDisposition : ReadState.ReadAfterContentDisposition; for (int i = startIndex; i < lastIndex; ++i) { if (!beforeContentDisposition) { _contentDisposition.Add(buffer[i]); } if (buffer[i] == _newLine[_newLineIndex]) { _newLineIndex++; if (_newLineIndex == 2) { _newLineIndex = 0; if (beforeContentDisposition) { // found a new line character here. now start parsing the content-disposition _contentDisposition.Clear(); ReadNewLine(buffer, i + 1, lastIndex, false); } else { // reach the end of content-disposition. extract the filename out of it _currentFileName = ParseContentDisposition(_contentDisposition.ToArray()); SearchForBoundary(buffer, i + 1, lastIndex); } return; } } else { _newLineIndex = 0; } } }
// Constructor. public XmlNodeReader(XmlNode node) { startNode = currentNode = node; if(node.NodeType == XmlNodeType.Document) { doc = (XmlDocument) (node); } else { doc = node.OwnerDocument; } if(node.NodeType == XmlNodeType.Attribute) { this.isAttributeReader = true; } if(node.NodeType != XmlNodeType.Document && node.NodeType != XmlNodeType.DocumentFragment) { skipThisNode = false; } this.readState = ReadState.Initial; }
// a bit detailed version public static void AssertReadXml(DataSet ds, string label, string xml, XmlReadMode readMode, XmlReadMode resultMode, string datasetName, int tableCount, ReadState state, string readerLocalName, string readerNS) { XmlReader xtr = new XmlTextReader(xml, XmlNodeType.Element, null); Assert.Equal(resultMode, ds.ReadXml(xtr, readMode)); AssertDataSet(label + ".dataset", ds, datasetName, tableCount, -1); Assert.Equal(state, xtr.ReadState); if (readerLocalName != null) { Assert.Equal(readerLocalName, xtr.LocalName); } if (readerNS != null) { Assert.Equal(readerNS, xtr.NamespaceURI); } }
public static List <VKMessage> GetVKMessages(string[] data) { List <VKMessage> vKMessages = new List <VKMessage>(); DateTime dateTime = new DateTime(); List <VKMessage> forwardedMessages = new List <VKMessage>(); List <string> forwardedStr = new List <string>(); List <string> attachments = new List <string>(); string author = ""; string vkID = ""; string message = ""; string line = ""; ReadState state = ReadState.Header; for (int i = 0; i < data.Length; i++) { if (data[i] == "") { continue; } line = data[i]; if (state == ReadState.Attachments && line != "]") { attachments.Add(line); continue; } else if (line == "]") { state = ReadState.NotStated; } else if (state == ReadState.Forwarded && line[0] != '\t') { forwardedMessages = GetVKMessages(forwardedStr.ToArray()); } if (IsHeader(line)) { state = ReadState.Header; } else if (line == "Attachments:[") { state = ReadState.Attachments; } else if (line[0] == '\t') { state = ReadState.Forwarded; } else { state = ReadState.Message; } switch (state) { case ReadState.Header: if (vKMessages.Count > 0) { vKMessages.Add(new VKMessage(author, vkID, message, dateTime, forwardedMessages, attachments)); } var splitLine = line.Split(' ', '(', ')'); author = splitLine[0] + " " + splitLine[1]; vkID = splitLine[2]; vkID = vkID.Remove(vkID.IndexOf('['), 1); vkID = vkID.Remove(vkID.IndexOf(']'), 1); var time = splitLine[4].Split(':'); var date = splitLine[6].Split('/'); dateTime = new DateTime(Convert.ToInt32(date[2]), Convert.ToInt32(date[1]), Convert.ToInt32(date[0]), Convert.ToInt32(time[0]), Convert.ToInt32(time[1]), Convert.ToInt32(time[2]) ); break; case ReadState.Message: message += line; break; case ReadState.Forwarded: forwardedStr.Add(line.Remove(0, 1)); break; case ReadState.Attachments: break; } } vKMessages.Add(new VKMessage(author, vkID, message, dateTime, forwardedMessages, attachments)); return(vKMessages); }
bool ReadContent() { if (ReadState == ReadState.Initial) { current = startNode; state = ReadState.Interactive; // when startNode is document or fragment if (ignoreStartNode) { current = startNode.FirstChild; } if (current == null) { state = ReadState.Error; return(false); } else { return(true); } } MoveToElement(); // don't step into EntityReference's children. Also // avoid re-entering children of already-consumed // element (i.e. when it is regarded as EndElement). XmlNode firstChild = !isEndElement && current.NodeType != XmlNodeType.EntityReference ? current.FirstChild : null; if (firstChild != null) { isEndElement = false; current = firstChild; depth++; return(true); } if (current == startNode) // Currently it is on the start node. { if (IsEmptyElement || isEndElement) { // The start node is already consumed. isEndElement = false; current = null; state = ReadState.EndOfFile; return(false); } else { // The start node is the only element // which should be processed. Now it // is set as EndElement. isEndElement = true; return(true); } } if (!isEndElement && !IsEmptyElement && current.NodeType == XmlNodeType.Element) { // element, currently not EndElement, and has // no child. (such as <foo></foo>, which // should become EndElement). isEndElement = true; return(true); } // If NextSibling is available, move to there. XmlNode next = current.NextSibling; if (next != null) { isEndElement = false; current = next; return(true); } // Otherwise, parent. XmlNode parent = current.ParentNode; if (parent == null || parent == startNode && ignoreStartNode) { // Parent is not available, or reached to // the start node. This reader never sets // startNode as current if it was originally // ignored (e.g. startNode is XmlDocument). isEndElement = false; current = null; state = ReadState.EndOfFile; return(false); } else { // Parent was available, so return it as // EndElement. current = parent; depth--; isEndElement = true; return(true); } }
// ****************************************************************** // ****************************************************************** // Close the underlying reader public override void Close() { m_dataReader.Close(); m_readState = ReadState.Closed; }
public override bool Read() { if (_nodeType == XmlNodeType.Attribute && MoveToNextAttribute()) { return(true); } MoveNext(_element.dataNode); switch (_internalNodeType) { case ExtensionDataNodeType.Element: case ExtensionDataNodeType.ReferencedElement: case ExtensionDataNodeType.NullElement: PushElement(); SetElement(); break; case ExtensionDataNodeType.Text: _nodeType = XmlNodeType.Text; _prefix = String.Empty; _ns = String.Empty; _localName = String.Empty; _attributeCount = 0; _attributeIndex = -1; break; case ExtensionDataNodeType.EndElement: _nodeType = XmlNodeType.EndElement; _prefix = String.Empty; _ns = String.Empty; _localName = String.Empty; _value = String.Empty; _attributeCount = 0; _attributeIndex = -1; PopElement(); break; case ExtensionDataNodeType.None: if (_depth != 0) { throw new XmlException(SR.InvalidXmlDeserializingExtensionData); } _nodeType = XmlNodeType.None; _prefix = String.Empty; _ns = String.Empty; _localName = String.Empty; _value = String.Empty; _attributeCount = 0; _readState = ReadState.EndOfFile; return(false); case ExtensionDataNodeType.Xml: // do nothing break; default: Fx.Assert("ExtensionDataReader in invalid state"); throw new SerializationException(SR.InvalidStateInExtensionDataReader); } _readState = ReadState.Interactive; return(true); }
int GetResponse(byte [] buffer, int max) { int pos = 0; string line = null; bool lineok = false; bool isContinue = false; bool emptyFirstLine = false; do { if (readState == ReadState.None) { lineok = ReadLine(buffer, ref pos, max, ref line); if (!lineok) { return(0); } if (line == null) { emptyFirstLine = true; continue; } emptyFirstLine = false; readState = ReadState.Status; string [] parts = line.Split(' '); if (parts.Length < 2) { return(-1); } if (String.Compare(parts [0], "HTTP/1.1", true) == 0) { Data.Version = HttpVersion.Version11; sPoint.SetVersion(HttpVersion.Version11); } else { Data.Version = HttpVersion.Version10; sPoint.SetVersion(HttpVersion.Version10); } Data.StatusCode = (int)UInt32.Parse(parts [1]); if (parts.Length >= 3) { Data.StatusDescription = String.Join(" ", parts, 2, parts.Length - 2); } else { Data.StatusDescription = ""; } if (pos >= max) { return(pos); } } emptyFirstLine = false; if (readState == ReadState.Status) { readState = ReadState.Headers; Data.Headers = new WebHeaderCollection(); ArrayList headers = new ArrayList(); bool finished = false; while (!finished) { if (ReadLine(buffer, ref pos, max, ref line) == false) { break; } if (line == null) { // Empty line: end of headers finished = true; continue; } if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) { int count = headers.Count - 1; if (count < 0) { break; } string prev = (string)headers [count] + line; headers [count] = prev; } else { headers.Add(line); } } if (!finished) { return(0); } foreach (string s in headers) { Data.Headers.SetInternal(s); } if (Data.StatusCode == (int)HttpStatusCode.Continue) { sPoint.SendContinue = true; if (pos >= max) { return(pos); } if (Data.request.ExpectContinue) { Data.request.DoContinueDelegate(Data.StatusCode, Data.Headers); // Prevent double calls when getting the // headers in several packets. Data.request.ExpectContinue = false; } readState = ReadState.None; isContinue = true; } else { readState = ReadState.Content; return(pos); } } } while (emptyFirstLine || isContinue); return(-1); }
bool ReadCurrentPosition() { attributes = null; attributeIndex = -1; inAttributeValue = false; while (true) { var obj = objectIterator.CurrentObject; if (obj == null) { readState = ReadState.EndOfFile; elementNodeType = XmlNodeType.None; return false; } else if (objectIterator.IsAtElementEnd) { elementNodeType = XmlNodeType.EndElement; return true; } else if (obj is InternalElement) { // element start elementNodeType = XmlNodeType.Element; InternalTag startTag = ((InternalTag)obj.NestedObjects[0]); if (startTag.NestedObjects != null) attributes = startTag.NestedObjects.OfType<InternalAttribute>().ToList(); return true; } else if (obj is InternalText) { InternalText text = (InternalText)obj; if (text.ContainsOnlyWhitespace) { elementNodeType = XmlNodeType.Whitespace; } else { elementNodeType = XmlNodeType.Text; } return true; } else if (obj is InternalTag) { // start/end tags can be skipped as the parent InternalElement already handles them, // TODO all other tags (xml decl, comments, ...) } else { throw new NotSupportedException(); } objectIterator.MoveInto(); } }
/// <summary> /// Make a List of SimpleChannels from a List of GuildChannels /// </summary> /// <param name="channels">List of GuildChannels</param> /// <returns>List of SimpleChannels</returns> public static List <SimpleChannel> OrderChannels(List <LocalModels.GuildChannel> channels) { // Create return list List <SimpleChannel> returnChannels = new List <SimpleChannel>(); // For each channel foreach (var channel in channels) { // Create basic SimpleChannel SimpleChannel sc = new SimpleChannel(); sc.Id = channel.raw.Id; sc.Name = channel.raw.Name; sc.Type = channel.raw.Type; sc.Position = channel.raw.Position; sc.ParentId = channel.raw.ParentId; sc.Nsfw = channel.raw.NSFW; switch (channel.raw.Type) { // Text Channel case 0: // Determine muted sc.IsMuted = LocalState.GuildSettings.ContainsKey(channel.raw.GuildId) && (LocalState.GuildSettings[channel.raw.GuildId].channelOverrides.ContainsKey(channel.raw.Id) && LocalState.GuildSettings[channel.raw.GuildId].channelOverrides[channel.raw.Id].Muted); // Determine Unread and Notification status if (LocalState.RPC.ContainsKey(sc.Id)) { ReadState readstate = LocalState.RPC[sc.Id]; sc.NotificationCount = readstate.MentionCount; var storageChannel = LocalState.CurrentGuild.channels[sc.Id]; sc.IsUnread = storageChannel?.raw.LastMessageId != null && readstate.LastMessageId != storageChannel.raw.LastMessageId; } // Detemine if user has read permissions sc.HavePermissions = LocalState.CurrentGuild.channels[sc.Id].permissions.ReadMessages || App.CurrentGuildId == sc.Id; // Determine if user should see channel if (!(sc.IsMuted && Storage.Settings.HideMutedChannels) && (sc.HavePermissions || Storage.Settings.ShowNoPermissionChannels)) { returnChannels.Add(sc); } break; // Voice Channel case 2: // Determine if user has Connect permissions sc.HavePermissions = LocalState.CurrentGuild.channels[sc.Id].permissions.Connect || App.CurrentGuildId == sc.Id; // Determine if user should see channel if (!(sc.IsMuted && Storage.Settings.HideMutedChannels) && (sc.HavePermissions || Storage.Settings.ShowNoPermissionChannels)) { returnChannels.Add(sc); } break; // Category case 4: sc.HavePermissions = LocalState.CurrentGuild.channels[sc.Id].permissions.ReadMessages || LocalState.CurrentGuild.channels[sc.Id].permissions.Connect; sc.Name = sc.Name.ToUpper(); if (!(sc.IsMuted && Storage.Settings.HideMutedChannels) && (sc.HavePermissions || Storage.Settings.ShowNoPermissionChannels)) { returnChannels.Add(sc); } break; } } var Categorized = returnChannels.Where(x => x.ParentId != null && x.Type != 4).OrderBy(x => x.Type).ThenBy(x => x.Position); var Categories = returnChannels.Where(x => x.Type == 4).OrderBy(x => x.Position).ToList(); List <SimpleChannel> Sorted = new List <SimpleChannel>(); foreach (var noId in returnChannels.Where(x => x.ParentId == null && x.Type != 4).OrderBy(x => x.Type).ThenBy(x => x.Position)) { Sorted.Add(noId); } foreach (var categ in Categories) { if (Categorized.Where(x => x.ParentId == categ.Id).Count() > 0) { Sorted.Add(categ); foreach (var item in Categorized.Where(x => x.ParentId == categ.Id)) { Sorted.Add(item); } } } return(Sorted); }
bool ReadCurrentPosition() { attributes = null; attributeIndex = -1; inAttributeValue = false; while (true) { var obj = objectIterator.CurrentObject; if (obj == null) { readState = ReadState.EndOfFile; elementNodeType = XmlNodeType.None; return false; } else if (objectIterator.IsAtElementEnd) { if (IsEmptyElement) { // Don't report EndElement for empty elements nsManager.PopScope(); } else { elementNodeType = XmlNodeType.EndElement; return true; } } else if (obj is InternalElement) { // element start elementNodeType = XmlNodeType.Element; InternalTag startTag = ((InternalTag)obj.NestedObjects[0]); nsManager.PushScope(); if (startTag.NestedObjects != null) { attributes = startTag.NestedObjects.OfType<InternalAttribute>().ToList(); for (int i = 0; i < attributes.Count; i++) { var attr = attributes[i]; if (attr.Name.StartsWith("xmlns:", StringComparison.Ordinal)) nsManager.AddNamespace(AXmlObject.GetLocalName(attr.Name), attr.Value); else if (attr.Name == "xmlns") nsManager.AddNamespace(string.Empty, attr.Value); } } return true; } else if (obj is InternalText) { InternalText text = (InternalText)obj; if (text.ContainsOnlyWhitespace) { elementNodeType = XmlNodeType.Whitespace; } else { elementNodeType = XmlNodeType.Text; } return true; } else if (obj is InternalTag) { InternalTag tag = (InternalTag)obj; if (tag.IsStartOrEmptyTag || tag.IsEndTag) { // start/end tags can be skipped as the parent InternalElement already handles them } else if (tag.IsComment && !settings.IgnoreComments) { elementNodeType = XmlNodeType.Comment; return true; } else if (tag.IsProcessingInstruction && !settings.IgnoreProcessingInstructions) { if (tag.Name == "xml") { elementNodeType = XmlNodeType.XmlDeclaration; attributes = tag.NestedObjects.OfType<InternalAttribute>().ToList(); } else { elementNodeType = XmlNodeType.ProcessingInstruction; } return true; } else if (tag.IsCData) { elementNodeType = XmlNodeType.CDATA; return true; } else { // TODO all other tags } } else { throw new NotSupportedException(); } objectIterator.MoveInto(); } }
protected XmlTextNode(XmlNodeType nodeType, PrefixHandle prefix, StringHandle localName, ValueHandle value, XmlNodeFlags nodeFlags, ReadState readState, XmlAttributeTextNode attributeTextNode, int depthDelta) : base(nodeType, prefix, localName, value, nodeFlags, readState, attributeTextNode, depthDelta) { }
public WebConnectionData() { _readState = ReadState.None; }
protected bool Read <TElement>(out Array result) { switch (_readState) { case ReadState.ReadNothing: if (_buf.ReadBytesLeft < 12) { result = null; return(false); } _dimensions = _buf.ReadInt32(); var hasNulls = _buf.ReadInt32(); // Not populated by PG? var elementOID = _buf.ReadUInt32(); Contract.Assume(elementOID == ElementHandler.OID); _dimLengths = new int[_dimensions]; if (_dimensions > 1) { _indices = new int[_dimensions]; } _index = 0; goto case ReadState.ReadHeader; case ReadState.ReadHeader: if (_buf.ReadBytesLeft < _dimensions * 8) { result = null; return(false); } for (var i = 0; i < _dimensions; i++) { _dimLengths[i] = _buf.ReadInt32(); _buf.ReadInt32(); // We don't care about the lower bounds } if (_dimensions == 0) { result = new TElement[0]; _readState = ReadState.NeedPrepare; return(true); } _readValue = Array.CreateInstance(typeof(TElement), _dimLengths); _readState = ReadState.ReadingElements; goto case ReadState.ReadingElements; case ReadState.ReadingElements: var completed = _readValue is TElement[] ? ReadElementsOneDimensional <TElement>() : ReadElementsMultidimensional <TElement>(); if (!completed) { result = null; return(false); } result = _readValue; _readValue = null; _buf = null; _fieldDescription = null; _readState = ReadState.NeedPrepare; return(true); default: throw new ArgumentOutOfRangeException(); } }
internal bool ReadRow() { // currentChar is the first char after newlines int currentChar = SkipAllNewLine(); if (currentChar < 0) { // nothing else to read return(false); } ReadState currentState = ReadState.TokenStart; _columns = new ArrayList(); StringBuilder buffer = new StringBuilder(); while (currentState != ReadState.LineEnd) { switch (currentState) { // start of a token case ReadState.TokenStart: { if (currentChar == _delimiter) { // it is the end of the token when we see a delimeter // Store token, and reset state. and ignore this char StoreTokenAndResetState(ref buffer, ref currentState); } else if (currentChar == '\"') { // jump to Quoted content if it token starts with a quote. // and also ignore this quote currentState = ReadState.QuotedContent; } else if (currentChar == '\n' || (currentChar == '\r' && _reader.Peek() == '\n')) { // we see a '\n' or '\r\n' sequence. Go to LineEnd // ignore these chars currentState = ReadState.LineEnd; } else { // safe to say that this is part of a unquoted content buffer.Append((Char)currentChar); currentState = ReadState.UnQuotedContent; } break; } // inside of an unquoted content case ReadState.UnQuotedContent: { if (currentChar == _delimiter) { // It is then end of a toekn. // Store the token value and reset state // igore this char as well StoreTokenAndResetState(ref buffer, ref currentState); } else if (currentChar == '\n' || (currentChar == '\r' && _reader.Peek() == '\n')) { // see a new line // igorne these chars and jump to LineEnd currentState = ReadState.LineEnd; } else { // we are good. store this char // notice, even we see a '\"', we will just treat it like // a normal char buffer.Append((Char)currentChar); } break; } // inside of a quoted content case ReadState.QuotedContent: { if (currentChar == '\"') { // now it depends on whether the next char is quote also if (_reader.Peek() == '\"') { // we will ignore the next quote. currentChar = _reader.Read(); buffer.Append((Char)currentChar); } else { // we have a single quote. We fall back to unquoted content state // and igorne the curernt quote currentState = ReadState.UnQuotedContent; } } else { // we are still inside of a quote, anything is accepted buffer.Append((Char)currentChar); } break; } } // read in the next char currentChar = _reader.Read(); if (currentChar < 0) { // break out of the state machine if we reach the end of the file break; } } // we got to here either we are at LineEnd, or we are end of file if (buffer.Length > 0) { _columns.Add(buffer.ToString()); } return(true); }
/// <summary> /// Make SimpleChannel from DMChannel /// </summary> /// <param name="channel">DMChannel</param> /// <returns>SimpleChannel</returns> public static SimpleChannel MakeChannel(DirectMessageChannel channel) { // Create basic SimpleChannel SimpleChannel sc = new SimpleChannel(); sc.Id = channel.Id; sc.Type = channel.Type; switch (channel.Type) { // DM case 1: // Assign basic DM info sc.Name = "@" + channel.Users.FirstOrDefault().Username; sc.LastMessageId = channel.LastMessageId; sc.ImageURL = "https://cdn.discordapp.com/avatars/" + channel.Users.FirstOrDefault().Id + "/" + channel.Users.FirstOrDefault().Avatar + ".png?size=64"; // Add members sc.Members = new Dictionary <string, User>(); foreach (User user in channel.Users) { sc.Members.Add(user.Id, user); } // Determine presence if (LocalState.PresenceDict.ContainsKey(channel.Users.FirstOrDefault().Id)) { sc.UserStatus = LocalState.PresenceDict[channel.Users.FirstOrDefault().Id]; sc.Playing = LocalState.PresenceDict[channel.Users.FirstOrDefault().Id].Game; if (LocalState.PresenceDict[channel.Users.FirstOrDefault().Id].Game != null) { sc.Playing = new Game() { Name = LocalState.PresenceDict[channel.Users.FirstOrDefault().Id].Game .Name, Type = LocalState.PresenceDict[channel.Users.FirstOrDefault().Id].Game.Type, Url = LocalState.PresenceDict[channel.Users.FirstOrDefault().Id].Game.Url }; } } else { sc.UserStatus = new Presence() { Status = "offline" }; } //sc.IsMuted = LocalState.GuildSettings.ContainsKey(channel.raw.GuildId) ? (LocalState.GuildSettings[channel.raw.GuildId].channelOverrides.ContainsKey(channel.raw.Id) ? LocalState.GuildSettings[channel.raw.GuildId].channelOverrides[channel.raw.Id].Muted : false) : false; if (LocalState.RPC.ContainsKey(sc.Id)) { ReadState readstate = LocalState.RPC[sc.Id]; sc.NotificationCount = readstate.MentionCount; var StorageChannel = LocalState.DMs[sc.Id]; if (StorageChannel.LastMessageId != null && readstate.LastMessageId != StorageChannel.LastMessageId) { sc.IsUnread = true; } else { sc.IsUnread = false; } } return(sc); // Group DM case 3: // Assign basic Group DM info sc.Name = channel.Name; sc.LastMessageId = channel.LastMessageId; sc.Subtitle = App.GetString("/Main/members").Replace("<count>", (channel.Users.Count() + 1).ToString()); sc.Icon = channel.Icon; // Override null name if (!string.IsNullOrEmpty(channel.Name)) { sc.Name = channel.Name; } else { List <string> channelMembers = new List <string>(); foreach (var d in channel.Users) { channelMembers.Add(d.Username); } sc.Name = string.Join(", ", channelMembers); } // Determine Unread and Notification status if (LocalState.RPC.ContainsKey(sc.Id)) { ReadState readstate = LocalState.RPC[sc.Id]; sc.NotificationCount = readstate.MentionCount; var StorageChannel = LocalState.DMs[sc.Id]; if (StorageChannel.LastMessageId != null && readstate.LastMessageId != StorageChannel.LastMessageId) { sc.IsUnread = true; } else { sc.IsUnread = false; } } // Show SimpleChannel sc.HavePermissions = true; return(sc); } return(null); }
void InitConnection (object state) { HttpWebRequest request = (HttpWebRequest) state; request.WebConnection = this; if (request.Aborted) return; keepAlive = request.KeepAlive; Data = new WebConnectionData (request); retry: Connect (request); if (request.Aborted) return; if (status != WebExceptionStatus.Success) { if (!request.Aborted) { request.SetWriteStreamError (status, connect_exception); Close (true); } return; } if (!CreateStream (request)) { if (request.Aborted) return; WebExceptionStatus st = status; if (Data.Challenge != null) goto retry; Exception cnc_exc = connect_exception; connect_exception = null; request.SetWriteStreamError (st, cnc_exc); Close (true); return; } readState = ReadState.None; request.SetWriteStream (new WebConnectionStream (this, request)); }
/// <summary> /// Make SimpleChannel based on GuildChannel /// </summary> /// <param name="channel">GuildChannel</param> /// <returns>SimpleChannel</returns> public static SimpleChannel MakeChannel(LocalModels.GuildChannel channel) { // Create basic SimpleChannel SimpleChannel sc = new SimpleChannel { Id = channel.raw.Id, Name = channel.raw.Name, Type = channel.raw.Type, Nsfw = channel.raw.NSFW, Position = channel.raw.Position, ParentId = channel.raw.ParentId, Icon = channel.raw.Icon }; switch (channel.raw.Type) { // Text Channel case 0: // Determine muted status sc.IsMuted = LocalState.GuildSettings.ContainsKey(channel.raw.GuildId) && (LocalState.GuildSettings[channel.raw.GuildId].channelOverrides .ContainsKey(channel.raw.Id) && LocalState.GuildSettings[channel.raw.GuildId] .channelOverrides[channel.raw.Id].Muted); // Determine is unread and notification count if (LocalState.RPC.ContainsKey(sc.Id)) { ReadState readstate = LocalState.RPC[sc.Id]; sc.NotificationCount = readstate.MentionCount; var StorageChannel = LocalState.Guilds[App.CurrentGuildId].channels[sc.Id]; sc.IsUnread = StorageChannel?.raw.LastMessageId != null && readstate.LastMessageId != StorageChannel.raw.LastMessageId; } // Assing if user has read permissions sc.HavePermissions = LocalState.Guilds[App.CurrentGuildId].channels[sc.Id].permissions.ReadMessages || App.CurrentGuildId == sc.Id; // Determine if SimpleChannel should be shown if (!(sc.IsMuted && Storage.Settings.HideMutedChannels) && (sc.HavePermissions || Storage.Settings.ShowNoPermissionChannels)) { return(sc); } break; // Voice channel case 2: sc.HavePermissions = LocalState.Guilds[App.CurrentGuildId].channels[sc.Id].permissions.Connect || App.CurrentGuildId == sc.Id; if (!(sc.IsMuted && Storage.Settings.HideMutedChannels) && (sc.HavePermissions || Storage.Settings.ShowNoPermissionChannels)) { return(sc); } break; // Category channel case 4: //TODO: Categories break; } return(null); }
public override void Close() => _readState = ReadState.Closed;
/// <summary> /// Create a List of SimpleChannels from a List of DirectMessageChannels /// </summary> /// <param name="channels">List of DirectMessageChannels</param> /// <returns>List of SimpleChannels</returns> public static List <SimpleChannel> OrderChannels(List <DirectMessageChannel> channels) { // Create return list List <SimpleChannel> returnChannels = new List <SimpleChannel>(); foreach (var channel in channels) { SimpleChannel sc = new SimpleChannel(); sc.Id = channel.Id; sc.Type = channel.Type; switch (channel.Type) { // DM case 1: // Assign basic DM info sc.Name = "@" + channel.Users.FirstOrDefault().Username; sc.UserId = channel.Users.FirstOrDefault().Id; sc.LastMessageId = channel.LastMessageId; sc.ImageURL = "https://cdn.discordapp.com/avatars/" + channel.Users.FirstOrDefault().Id + "/" + channel.Users.FirstOrDefault().Avatar + ".png?size=64"; // Add members sc.Members = new Dictionary <string, User>(); foreach (User user in channel.Users) { sc.Members.Add(user.Id, user); } // Determine presence if (LocalState.PresenceDict.ContainsKey(channel.Users.FirstOrDefault().Id)) { sc.UserStatus = LocalState.PresenceDict[channel.Users.FirstOrDefault().Id]; sc.Playing = LocalState.PresenceDict[channel.Users.FirstOrDefault().Id].Game; if (LocalState.PresenceDict[channel.Users.FirstOrDefault().Id].Game != null) { sc.Playing = new Game() { Name = LocalState.PresenceDict[channel.Users.FirstOrDefault().Id].Game .Name, Type = LocalState.PresenceDict[channel.Users.FirstOrDefault().Id].Game.Type, Url = LocalState.PresenceDict[channel.Users.FirstOrDefault().Id].Game.Url }; } } else { sc.UserStatus = new Presence() { Status = "offline" }; } // Determine unread and notifcation status if (LocalState.RPC.ContainsKey(sc.Id)) { ReadState readstate = LocalState.RPC[sc.Id]; sc.NotificationCount = readstate.MentionCount; var StorageChannel = LocalState.DMs[sc.Id]; if (StorageChannel.LastMessageId != null && readstate.LastMessageId != StorageChannel.LastMessageId) { sc.IsUnread = true; } else { sc.IsUnread = false; } } // Add to return channel list sc.HavePermissions = true; returnChannels.Add(sc); break; // Group DM case 3: // Assign basic Group info sc.Name = channel.Name; sc.LastMessageId = channel.LastMessageId; sc.Subtitle = App.GetString("/Main/members").Replace("<count>", (channel.Users.Count() + 1).ToString()); sc.Icon = channel.Icon; // Override group name if (channel.Name != null && channel.Name != "") { sc.Name = channel.Name; } else { List <string> channelMembers = new List <string>(); foreach (var d in channel.Users) { channelMembers.Add(d.Username); } sc.Name = string.Join(", ", channelMembers); } // Determine unread and notification status if (LocalState.RPC.ContainsKey(sc.Id)) { ReadState readstate = LocalState.RPC[sc.Id]; sc.NotificationCount = readstate.MentionCount; var StorageChannel = LocalState.DMs[sc.Id]; if (StorageChannel.LastMessageId != null && readstate.LastMessageId != StorageChannel.LastMessageId) { sc.IsUnread = true; } else { sc.IsUnread = false; } } // Add channel to return list sc.HavePermissions = true; returnChannels.Add(sc); break; } } // Order by LastMessageId return(returnChannels.OrderByDescending(x => x.LastMessageId).ToList()); }
public override void Close() { _state = ReadState.Closed; }
public static void ReceiveData(List <byte> data, ReadState readState, Action <FrameType, byte[]> processFrame) { while (data.Count >= 2) { var isFinal = (data[0] & 128) != 0; var reservedBits = (data[0] & 112); var frameType = (FrameType)(data[0] & 15); var isMasked = (data[1] & 128) != 0; var length = (data[1] & 127); if (!isMasked || !Enum.IsDefined(typeof(FrameType), frameType) || reservedBits != 0 || //Must be zero per spec 5.2 (frameType == FrameType.Continuation && !readState.FrameType.HasValue)) { throw new WebSocketException(WebSocketStatusCodes.ProtocolError); } var index = 2; int payloadLength; if (length == 127) { if (data.Count < index + 8) { return; //Not complete } payloadLength = data.Skip(index).Take(8).ToArray().ToLittleEndianInt(); index += 8; } else if (length == 126) { if (data.Count < index + 2) { return; //Not complete } payloadLength = data.Skip(index).Take(2).ToArray().ToLittleEndianInt(); index += 2; } else { payloadLength = length; } if (data.Count < index + 4) { return; //Not complete } var maskBytes = data.Skip(index).Take(4).ToArray(); index += 4; if (data.Count < index + payloadLength) { return; //Not complete } var payload = data .Skip(index) .Take(payloadLength) .Select((x, i) => (byte)(x ^ maskBytes[i % 4])); readState.Data.AddRange(payload); data.RemoveRange(0, index + payloadLength); if (frameType != FrameType.Continuation) { readState.FrameType = frameType; } if (isFinal && readState.FrameType.HasValue) { var stateData = readState.Data.ToArray(); var stateFrameType = readState.FrameType; readState.Clear(); processFrame(stateFrameType.Value, stateData); } } }
public override bool Read() { switch (_state) { case ReadState.Initial: if (_value == null) { WebResponse wRes; Stream stream = XIncludingReader.GetResource(_includeLocation.AbsoluteUri, _accept, _acceptLanguage, out wRes); StreamReader reader; /* According to the spec, encoding should be determined as follows: * external encoding information, if available, otherwise * if the media type of the resource is text/xml, application/xml, * or matches the conventions text/*+xml or application/*+xml as * described in XML Media Types [IETF RFC 3023], the encoding is * recognized as specified in XML 1.0, otherwise * the value of the encoding attribute if one exists, otherwise * UTF-8. */ try { //TODO: try to get "content-encoding" from wRes.Headers collection? //If mime type is xml-aware, get resource encoding as per XML 1.0 string contentType = wRes.ContentType.ToLower(); if (contentType == "text/xml" || contentType == "application/xml" || contentType.StartsWith("text/") && contentType.EndsWith("+xml") || contentType.StartsWith("application/") && contentType.EndsWith("+xml")) { //Yes, that's xml, let's read encoding from the xml declaration reader = new StreamReader(stream, GetEncodingFromXMLDecl(_href)); } else if (_encoding != null) { //Try to use user-specified encoding Encoding enc; try { enc = Encoding.GetEncoding(_encoding); } catch (Exception e) { throw new ResourceException(SR.GetString("NotSupportedEncoding", _encoding), e); } reader = new StreamReader(stream, enc); } else { //Fallback to UTF-8 reader = new StreamReader(stream, Encoding.UTF8); } _value = reader.ReadToEnd(); TextUtils.CheckForNonXmlChars(_value); } catch (ResourceException re) { throw re; } catch (OutOfMemoryException oome) { //Crazy include - memory is out //TODO: what about reading by chunks? throw new ResourceException(SR.GetString("OutOfMemoryWhileFetchingResource", _href), oome); } catch (IOException ioe) { throw new ResourceException(SR.GetString("IOErrorWhileFetchingResource", _href), ioe); } } _state = ReadState.Interactive; return(true); case ReadState.Interactive: //No more input _state = ReadState.EndOfFile; return(false); default: return(false); } } // Read()
public override void Close() { current = null; state = ReadState.Closed; }
public TextContentReader(Uri uri, string content) { BaseURI = uri.ToString(); _readState = ReadState.Initial; _content = content; }
private bool TryReadMessageHeaders() { int scanOffset = this.readOffset; // Scan for the final double-newline that marks the end of the header lines while (scanOffset + 3 < this.bufferEndOffset && (this.messageBuffer[scanOffset] != CR || this.messageBuffer[scanOffset + 1] != LF || this.messageBuffer[scanOffset + 2] != CR || this.messageBuffer[scanOffset + 3] != LF)) { scanOffset++; } // Make sure we haven't reached the end of the buffer without finding a separator (e.g CRLFCRLF) if (scanOffset + 3 >= this.bufferEndOffset) { return(false); } // Convert the header block into a array of lines var headers = Encoding.ASCII.GetString(this.messageBuffer, this.readOffset, scanOffset) .Split(NewLineDelimiters, StringSplitOptions.RemoveEmptyEntries); try { // Read each header and store it in the dictionary this.messageHeaders = new Dictionary <string, string>(); foreach (var header in headers) { int currentLength = header.IndexOf(':'); if (currentLength == -1) { throw new ArgumentException(SR.HostingHeaderMissingColon); } var key = header.Substring(0, currentLength); var value = header.Substring(currentLength + 1).Trim(); this.messageHeaders[key] = value; } // Parse out the content length as an int string contentLengthString; if (!this.messageHeaders.TryGetValue("Content-Length", out contentLengthString)) { throw new MessageParseException("", SR.HostingHeaderMissingContentLengthHeader); } // Parse the content length to an integer if (!int.TryParse(contentLengthString, out this.expectedContentLength)) { throw new MessageParseException("", SR.HostingHeaderMissingContentLengthValue); } } catch (Exception) { // The content length was invalid or missing. Trash the buffer we've read ShiftBufferBytesAndShrink(scanOffset + 4); throw; } // Skip past the headers plus the newline characters this.readOffset += scanOffset + 4; // Done reading headers, now read content this.readState = ReadState.Content; return(true); }
bool GetResponse(BufferOffsetSize buffer, ref int pos, ref ReadState state) { string line = null; bool lineok = false; bool isContinue = false; bool emptyFirstLine = false; do { if (state == ReadState.Aborted) { throw GetReadException(WebExceptionStatus.RequestCanceled, null, "GetResponse"); } if (state == ReadState.None) { lineok = WebConnection.ReadLine(buffer.Buffer, ref pos, buffer.Offset, ref line); if (!lineok) { return(false); } if (line == null) { emptyFirstLine = true; continue; } emptyFirstLine = false; state = ReadState.Status; string[] parts = line.Split(' '); if (parts.Length < 2) { throw GetReadException(WebExceptionStatus.ServerProtocolViolation, null, "GetResponse"); } if (String.Compare(parts[0], "HTTP/1.1", true) == 0) { Version = HttpVersion.Version11; ServicePoint.SetVersion(HttpVersion.Version11); } else { Version = HttpVersion.Version10; ServicePoint.SetVersion(HttpVersion.Version10); } StatusCode = (HttpStatusCode)UInt32.Parse(parts[1]); if (parts.Length >= 3) { StatusDescription = String.Join(" ", parts, 2, parts.Length - 2); } else { StatusDescription = string.Empty; } if (pos >= buffer.Offset) { return(true); } } emptyFirstLine = false; if (state == ReadState.Status) { state = ReadState.Headers; Headers = new WebHeaderCollection(); var headerList = new List <string> (); bool finished = false; while (!finished) { if (WebConnection.ReadLine(buffer.Buffer, ref pos, buffer.Offset, ref line) == false) { break; } if (line == null) { // Empty line: end of headers finished = true; continue; } if (line.Length > 0 && (line[0] == ' ' || line[0] == '\t')) { int count = headerList.Count - 1; if (count < 0) { break; } string prev = headerList[count] + line; headerList[count] = prev; } else { headerList.Add(line); } } if (!finished) { return(false); } // .NET uses ParseHeaders or ParseHeadersStrict which is much better foreach (string s in headerList) { int pos_s = s.IndexOf(':'); if (pos_s == -1) { throw new ArgumentException("no colon found", "header"); } var header = s.Substring(0, pos_s); var value = s.Substring(pos_s + 1).Trim(); if (WebHeaderCollection.AllowMultiValues(header)) { Headers.AddInternal(header, value); } else { Headers.SetInternal(header, value); } } if (StatusCode == HttpStatusCode.Continue) { ServicePoint.SendContinue = true; if (pos >= buffer.Offset) { return(true); } if (Request.ExpectContinue) { Request.DoContinueDelegate((int)StatusCode, Headers); // Prevent double calls when getting the // headers in several packets. Request.ExpectContinue = false; } state = ReadState.None; isContinue = true; } else { state = ReadState.Content; return(true); } } } while (emptyFirstLine || isContinue); throw GetReadException(WebExceptionStatus.ServerProtocolViolation, null, "GetResponse"); }
public static void AssertReadXml(DataSet ds, string label, string xml, XmlReadMode readMode, XmlReadMode resultMode, string datasetName, int tableCount, ReadState state) { DataSetAssertion.AssertReadXml(ds, label, xml, readMode, resultMode, datasetName, tableCount, state, null, null); }
public override bool Read() { if (this.EOF) { return(false); } if (this.readState == ReadState.Initial) { this.readState = ReadState.Interactive; this.xmlState = XmlReadState.Table; if (!String.IsNullOrEmpty(this.tableName.Namespace)) { AddAttribute("", "xmlns", this.tableName.Namespace); } if (this.xsiNil || this.xsiType) { AddAttribute("xmlns", xsiPrefix, xsiNamespace); } if (this.xsiType) { AddAttribute("xmlns", xsPrefix, "http://www.w3.org/2001/XMLSchema"); } return(true); } this.attribs.Clear(); if (this.multipartClose > 0) { this.multipartClose--; this.multipartNameIndex--; this.depth--; if (this.multipartClose == 0) { this.xmlState = XmlReadState.Field; if (this.multipartNameIndex == this.name.Length - 1) { ReadValue(); } } return(true); } switch (this.xmlState) { case XmlReadState.Table: if (MoveNextRow()) { this.depth++; } else { this.xmlState = XmlReadState.EndTable; } break; case XmlReadState.Row: if (this.fieldCount == 0) { this.xmlState = XmlReadState.EndRow; Debug.Assert(this.depth == 2); } else { if (this.xsiNil) { this.ordinal = 0; } else { for (int i = 0; i < this.fieldCount; i++) { if (!this.record.IsDBNull(i)) { this.ordinal = i; break; } } } if (this.ordinal == -1) { this.xmlState = XmlReadState.EndRow; Debug.Assert(this.depth == 2); } else { this.xmlState = XmlReadState.Field; this.depth++; ReadField(); if (this.multipartNameIndex == this.name.Length - 1) { ReadValue(); } } } break; case XmlReadState.Field: if (this.IsEmptyElement) { this.xmlState = XmlReadState.EndField; goto case XmlReadState.EndField; } else { this.depth++; if (this.multipartNameIndex < this.name.Length - 1) { this.multipartNameIndex++; if (this.multipartNameIndex == this.name.Length - 1) { ReadValue(); } break; } this.xmlState = XmlReadState.Value; } break; case XmlReadState.Value: this.depth--; this.xmlState = XmlReadState.EndField; break; case XmlReadState.EndField: int nextOrdinal = this.ordinal + 1; this.ordinal = -1; if (nextOrdinal > 0) { if (this.xsiNil) { this.ordinal = nextOrdinal; } else { for (int i = nextOrdinal; i < this.fieldCount; i++) { if (!this.record.IsDBNull(i)) { this.ordinal = i; break; } } } } if (this.ordinal == -1 || this.ordinal + 1 > this.fieldCount) { this.depth--; if (this.multipartNameIndex > 0) { this.multipartNameIndex--; break; } this.ordinal = -1; this.xmlState = XmlReadState.EndRow; } else { ReadField(); if (this.multipartNameIndex > 0) { // e.g. // prevName: A$B$C // name: A$D$E$F // close C, B -> open D, E, F int i = 0; for (; i < this.name.Length - 1; i++) { if (i > this.prevName.Length - 1 || this.name[i] != this.prevName[i]) { break; } } this.multipartClose = this.prevName.Length - i - 1; if (this.multipartClose > 0) { break; } } this.xmlState = XmlReadState.Field; if (this.multipartNameIndex == this.name.Length - 1) { ReadValue(); } } break; case XmlReadState.EndRow: if (!MoveNextRow()) { this.xmlState = XmlReadState.EndTable; this.depth--; } break; case XmlReadState.EndTable: this.eof = true; Debug.Assert(this.depth == 0); return(false); } return(true); }
public TextIncludingReader(string value, bool exposeCDATA) { _state = ReadState.Initial; _exposeCDATA = exposeCDATA; _value = value; }
public override bool Read() { switch (read_state) { case ReadState.EndOfFile: case ReadState.Closed: case ReadState.Error: return(false); case ReadState.Initial: read_state = ReadState.Interactive; next_element = "root"; current_node = XmlNodeType.Element; break; } MoveToElement(); if (content_stored) { if (current_node == XmlNodeType.Element) { if (elements.Peek().Type == "null") { // since null is not consumed as text content, it skips Text state. current_node = XmlNodeType.EndElement; content_stored = false; } else { current_node = XmlNodeType.Text; } return(true); } else if (current_node == XmlNodeType.Text) { current_node = XmlNodeType.EndElement; content_stored = false; return(true); } } else if (current_node == XmlNodeType.EndElement) { // clear EndElement state elements.Pop(); if (elements.Count > 0) { elements.Peek().HasContent = true; } else { finished = true; } } SkipWhitespaces(); attr_state = AttributeState.None; // Default. May be overriden only as EndElement or None. current_node = XmlNodeType.Element; if (!ReadContent(false)) { return(false); } if (finished) { throw XmlError("Multiple top-level content is not allowed"); } return(true); }
public override void Close() { readState = ReadState.Closed; offsetToTextLocation = null; }
public override ValueTask <int> ReadAsync(Memory <byte> buffer, CancellationToken cancellationToken = default) { CheckDisposed(); EventSourceTrace("Buffer: {0}", buffer.Length); // Check for cancellation if (cancellationToken.IsCancellationRequested) { EventSourceTrace("Canceled"); return(new ValueTask <int>(Task.FromCanceled <int>(cancellationToken))); } lock (_lockObject) { VerifyInvariants(); // If there's currently a pending read, fail this read, as we don't support concurrent reads. if (_pendingReadRequest != null) { EventSourceTrace("Failing due to existing pending read; concurrent reads not supported."); return(new ValueTask <int>(Task.FromException <int>(new InvalidOperationException(SR.net_http_content_no_concurrent_reads)))); } // If the stream was already completed with failure, complete the read as a failure. if (_completed != null && _completed != s_completionSentinel) { EventSourceTrace("Failing read with error: {0}", _completed); OperationCanceledException oce = _completed as OperationCanceledException; return(new ValueTask <int>((oce != null && oce.CancellationToken.IsCancellationRequested) ? Task.FromCanceled <int>(oce.CancellationToken) : Task.FromException <int>(MapToReadWriteIOException(_completed, isRead: true)))); } // Quick check for if no data was actually requested. We do this after the check // for errors so that we can still fail the read and transfer the exception if we should. if (buffer.Length == 0) { return(new ValueTask <int>(0)); } // If there's any data left over from a previous call, grab as much as we can. if (_remainingDataCount > 0) { int bytesToCopy = Math.Min(buffer.Length, _remainingDataCount); new Span <byte>(_remainingData, _remainingDataOffset, bytesToCopy).CopyTo(buffer.Span); _remainingDataOffset += bytesToCopy; _remainingDataCount -= bytesToCopy; Debug.Assert(_remainingDataCount >= 0, "The remaining count should never go negative"); Debug.Assert(_remainingDataOffset <= _remainingData.Length, "The remaining offset should never exceed the buffer size"); EventSourceTrace("Read {0} bytes", bytesToCopy); return(new ValueTask <int>(bytesToCopy)); } // If the stream has already been completed, complete the read immediately. if (_completed == s_completionSentinel) { EventSourceTrace("Stream already completed"); return(new ValueTask <int>(0)); } // Finally, the stream is still alive, and we want to read some data, but there's no data // in the buffer so we need to register ourself to get the next write. if (cancellationToken.CanBeCanceled) { // If the cancellation token is cancelable, then we need to register for cancellation. // We create a special CancelableReadState that carries with it additional info: // the cancellation token and the registration with that token. When cancellation // is requested, we schedule a work item that tries to remove the read state // from being pending, canceling it in the process. This needs to happen under the // lock, which is why we schedule the operation to run asynchronously: if it ran // synchronously, it could deadlock due to code on another thread holding the lock // and calling Dispose on the registration concurrently with the call to Cancel // the cancellation token. Dispose on the registration won't return until the action // associated with the registration has completed, but if that action is currently // executing and is blocked on the lock that's held while calling Dispose... deadlock. var crs = new CancelableReadState(buffer, this, cancellationToken); crs._registration = cancellationToken.Register(s1 => { ((CancelableReadState)s1)._stream.EventSourceTrace("Cancellation invoked. Queueing work item to cancel read state"); Task.Factory.StartNew(s2 => { var crsRef = (CancelableReadState)s2; lock (crsRef._stream._lockObject) { Debug.Assert(crsRef._token.IsCancellationRequested, "We should only be here if cancellation was requested."); if (crsRef._stream._pendingReadRequest == crsRef) { crsRef._stream.EventSourceTrace("Canceling"); crsRef.TrySetCanceled(crsRef._token); crsRef._stream.ClearPendingReadRequest(); } } }, s1, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); }, crs); _pendingReadRequest = crs; } else { // The token isn't cancelable. Just create a normal read state. _pendingReadRequest = new ReadState(buffer); } _easy._associatedMultiAgent.RequestUnpause(_easy); _easy._selfStrongToWeakReference.MakeStrong(); // convert from a weak to a strong ref to keep the easy alive during the read return(new ValueTask <int>(_pendingReadRequest.Task)); } }
protected XmlNode(XmlNodeType nodeType, PrefixHandle prefix, StringHandle localName, ValueHandle value, XmlNodeFlags nodeFlags, ReadState readState, XmlAttributeTextNode attributeTextNode, int depthDelta) { _nodeType = nodeType; _prefix = prefix; _localName = localName; _value = value; _ns = NamespaceManager.EmptyNamespace; _hasValue = ((nodeFlags & XmlNodeFlags.HasValue) != 0); _canGetAttribute = ((nodeFlags & XmlNodeFlags.CanGetAttribute) != 0); _canMoveToElement = ((nodeFlags & XmlNodeFlags.CanMoveToElement) != 0); _isAtomicValue = ((nodeFlags & XmlNodeFlags.AtomicValue) != 0); _skipValue = ((nodeFlags & XmlNodeFlags.SkipValue) != 0); _hasContent = ((nodeFlags & XmlNodeFlags.HasContent) != 0); _readState = readState; _attributeTextNode = attributeTextNode; _exitScope = (nodeType == XmlNodeType.EndElement); _depthDelta = depthDelta; _isEmptyElement = false; _quoteChar = '"'; _qnameType = QNameType.Normal; }
public void Reset() { _readState = ReadState.AccumulatingLength; _readBytes = 0; _messageLength = 0; }
public override void Close() { readState = ReadState.Closed; }
// Moving through the Stream public override bool Read() { Debug.Assert(this.processor != null || this.state == ReadState.Closed); if (this.state != ReadState.Interactive) { if (this.state == ReadState.Initial) { state = ReadState.Interactive; } else { return(false); } } while (true) // while -- to ignor empty whitespace nodes. { if (this.haveRecord) { this.processor.ResetOutput(); this.haveRecord = false; } this.processor.Execute(); if (this.haveRecord) { CheckCurrentInfo(); // check text nodes on whitespaces; switch (this.NodeType) { case XmlNodeType.Text: if (XmlCharType.IsOnlyWhitespace(this.Value)) { this.currentInfo.NodeType = XmlNodeType.Whitespace; goto case XmlNodeType.Whitespace; } Debug.Assert(this.Value.Length != 0, "It whould be Whitespace in this case"); break; case XmlNodeType.Whitespace: if (this.Value.Length == 0) { continue; // ignoring emty text nodes } if (this.XmlSpace == XmlSpace.Preserve) { this.currentInfo.NodeType = XmlNodeType.SignificantWhitespace; } break; } } else { Debug.Assert(this.processor.ExecutionDone); this.state = ReadState.EndOfFile; Reset(); } return(this.haveRecord); } }
int GetResponse (byte [] buffer, int max) { int pos = 0; string line = null; bool lineok = false; bool isContinue = false; bool emptyFirstLine = false; do { if (readState == ReadState.None) { lineok = ReadLine (buffer, ref pos, max, ref line); if (!lineok) return 0; if (line == null) { emptyFirstLine = true; continue; } emptyFirstLine = false; readState = ReadState.Status; string [] parts = line.Split (' '); if (parts.Length < 2) return -1; if (String.Compare (parts [0], "HTTP/1.1", true) == 0) { Data.Version = HttpVersion.Version11; sPoint.SetVersion (HttpVersion.Version11); } else { Data.Version = HttpVersion.Version10; sPoint.SetVersion (HttpVersion.Version10); } Data.StatusCode = (int) UInt32.Parse (parts [1]); if (parts.Length >= 3) Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2); else Data.StatusDescription = ""; if (pos >= max) return pos; } emptyFirstLine = false; if (readState == ReadState.Status) { readState = ReadState.Headers; Data.Headers = new WebHeaderCollection (); ArrayList headers = new ArrayList (); bool finished = false; while (!finished) { if (ReadLine (buffer, ref pos, max, ref line) == false) break; if (line == null) { // Empty line: end of headers finished = true; continue; } if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) { int count = headers.Count - 1; if (count < 0) break; string prev = (string) headers [count] + line; headers [count] = prev; } else { headers.Add (line); } } if (!finished) return 0; foreach (string s in headers) Data.Headers.SetInternal (s); if (Data.StatusCode == (int) HttpStatusCode.Continue) { sPoint.SendContinue = true; if (pos >= max) return pos; if (Data.request.ExpectContinue) { Data.request.DoContinueDelegate (Data.StatusCode, Data.Headers); // Prevent double calls when getting the // headers in several packets. Data.request.ExpectContinue = false; } readState = ReadState.None; isContinue = true; } else { readState = ReadState.Content; return pos; } } } while (emptyFirstLine || isContinue); return -1; }
public override void Close() { this.processor = null; this.state = ReadState.Closed; Reset(); }
public WebConnection (WebConnectionGroup group, ServicePoint sPoint) { this.sPoint = sPoint; buffer = new byte [4096]; readState = ReadState.None; Data = new WebConnectionData (); initConn = new WaitCallback (state => { try { InitConnection (state); } catch {} }); queue = group.Queue; abortHelper = new AbortHelper (); abortHelper.Connection = this; abortHandler = new EventHandler (abortHelper.Abort); }
bool ReadToEnd() { state = ReadState.EndOfFile; return(false); }