public static void Load(string xml, Document doc) { var sp =new StreamParser(); sp.OnStreamStart += (sender, node) => doc.ChildNodes.Add(node); sp.OnStreamElement += (sender, node) => doc.RootElement.ChildNodes.Add(node); byte[] b = System.Text.Encoding.UTF8.GetBytes(xml); sp.Push(b, 0, b.Length); }
public DomLoader(string xml, Document d) { doc = d; sp = new StreamParser(); sp.OnStreamStart += new StreamHandler(sp_OnStreamStart); sp.OnStreamElement += new StreamHandler(sp_OnStreamElement); sp.OnStreamEnd += new StreamHandler(sp_OnStreamEnd); byte[] b = System.Text.Encoding.UTF8.GetBytes(xml); sp.Push(b, 0, b.Length); }
public static Dictionary<string, DiscoInfo> GetCapsCache() { Dictionary<string, DiscoInfo> capsCache = new Dictionary<string, DiscoInfo>(24); try { using (SQLiteCommand command = _connection.CreateCommand()) { command.CommandText = "SELECT * FROM [CapsCache]"; SQLiteDataReader reader = command.ExecuteReader(); while (reader.Read()) { Document document = new Document(); document.LoadXml((string)reader["Features"]); DiscoInfo info = document.RootElement as DiscoInfo; if (info != null) { capsCache.Add((string) reader["Caps"], info); } } reader.Close(); } } catch (Exception e) { Events.Instance.OnEvent(e, new EventError(e.Message, null)); } return capsCache; }
/// <summary> /// Send a document, await the response and return it /// </summary> /// <param name="document">Document</param> /// <param name="timeout">Timeout for waiting on the response, if this passes a timeout exception is thrown</param> /// <returns>IQ response</returns> private async Task<IQ> RequestResponseAsync(Document document, int timeout = 2000) { // Check if the login was made, this blocks until there is a state // And throws an exception if the login failed. await _loginTaskCompletionSource.Task.ConfigureAwait(false); // Create the IQ to send var iqToSend = GenerateIq(document); // Prepate the TaskCompletionSource, which is used to await the result var resultTaskCompletionSource = new TaskCompletionSource<IQ>(); _resultTaskCompletionSources[iqToSend.Id] = resultTaskCompletionSource; Debug.WriteLine("Sending:"); Debug.WriteLine(iqToSend.ToString()); // Create the action which is called when a timeout occurs Action timeoutAction = () => { // Remove the registration, it is no longer needed _resultTaskCompletionSources.Remove(iqToSend.Id); // Pass the timeout exception to the await resultTaskCompletionSource.TrySetException(new TimeoutException($"Timeout while waiting on response {iqToSend.Id} after {timeout}")); }; // Start the sending _xmpp.Send(iqToSend); // Setup the timeout handling var cancellationTokenSource = new CancellationTokenSource(timeout); using (cancellationTokenSource.Token.Register(timeoutAction)) { // Await / block until an reply arrives or the timeout happens return await resultTaskCompletionSource.Task.ConfigureAwait(false); } }
/// <summary> /// Generate an IQ for the supplied Document /// </summary> /// <param name="document">Document</param> /// <returns>IQ</returns> private static IQ GenerateIq(Document document) { // Create the IQ to send var iqToSend = new IQ { Type = IqType.get, Namespace = "", From = "1", To = "guest" }; // Add the real content for the Harmony iqToSend.AddChild(document); // Generate an unique ID, this is used to correlate the reply to the request iqToSend.GenerateId(); return iqToSend; }
/// <summary> /// Send a document, ignore the response (but wait shortly for a possible error) /// </summary> /// <param name="document">Document</param> /// <param name="waitTimeout">the time to wait for a possible error, if this is too small errors are ignored.</param> /// <returns>Task to await on</returns> private async Task FireAndForgetAsync(Document document, int waitTimeout = 50) { // Check if the login was made, this blocks until there is a state // And throws an exception if the login failed. await _loginTaskCompletionSource.Task.ConfigureAwait(false); // Create the IQ to send var iqToSend = GenerateIq(document); // Prepate the TaskCompletionSource, which is used to await the result var resultTaskCompletionSource = new TaskCompletionSource<IQ>(); _resultTaskCompletionSources[iqToSend.Id] = resultTaskCompletionSource; Debug.WriteLine("Sending (ignoring response):"); Debug.WriteLine(iqToSend.ToString()); // Start the sending _xmpp.Send(iqToSend); // Await, to make sure there wasn't an error var task = await Task.WhenAny(resultTaskCompletionSource.Task, Task.Delay(waitTimeout)).ConfigureAwait(false); // Remove the result task, as we no longer need it. _resultTaskCompletionSources.Remove(iqToSend.Id); // This makes sure the exception, if there was one, is unwrapped await task; }
private void OnGetSessionRequestResponse(IAsyncResult result) { // grab the custom state object WebRequestState state = (WebRequestState)result.AsyncState; HttpWebRequest request = (HttpWebRequest)state.WebRequest; //state.TimeOutTimer.Dispose(); // get the Response HttpWebResponse resp = (HttpWebResponse)request.EndGetResponse(result); // The server must always return a 200 response code, // sending any session errors as specially-formatted identifiers. if (resp.StatusCode != HttpStatusCode.OK) { //FireOnError(new PollSocketException("unexpected status code " + resp.StatusCode.ToString())); return; } Stream rs = resp.GetResponseStream(); int readlen; byte[] readbuf = new byte[1024]; MemoryStream ms = new MemoryStream(); while ((readlen = rs.Read(readbuf, 0, readbuf.Length)) > 0) { ms.Write(readbuf, 0, readlen); } byte[] recv = ms.ToArray(); if (recv.Length > 0) { string body = null; string stanzas = null; string res = Encoding.UTF8.GetString(recv, 0, recv.Length); ParseResponse(res, ref body, ref stanzas); Document doc = new Document(); doc.LoadXml(body); Body boshBody = doc.RootElement as Body; sid = boshBody.Sid; polling = boshBody.Polling; m_MaxPause = boshBody.MaxPause; byte[] bin = Encoding.UTF8.GetBytes(DummyStreamHeader + stanzas); base.FireOnReceive(bin, bin.Length); // cleanup webrequest resources ms.Close(); rs.Close(); resp.Close(); waitingRequests--; if (waitingRequests == 0) StartWebRequest(); } }
private Message ToMessage(string messageXml) { Document doc = new Document(); doc.LoadXml(messageXml); return (Message)doc.RootElement; }
public static void Load(StreamReader sr, Document doc) { Load(sr.ReadToEnd(), doc); }
public DomLoader(StreamReader sr, Document d) : this(sr.ReadToEnd(), d) { }
private void OnGetResponse(IAsyncResult ar) { try { requestIsTerminating = true; // grab the custom state object WebRequestState state = (WebRequestState)ar.AsyncState; HttpWebRequest request = (HttpWebRequest)state.WebRequest; HttpWebResponse resp = null; if (request.HaveResponse) { // TODO, its crashing mostly here // get the Response try { resp = (HttpWebResponse) request.EndGetResponse(ar); } catch (WebException ex) { activeRequests--; requestIsTerminating = false; if (ex.Response == null) { StartWebRequest(); } else { HttpWebResponse res = ex.Response as HttpWebResponse; if (res.StatusCode == HttpStatusCode.NotFound) { TerminateBoshSession(); } } return; } // The server must always return a 200 response code, // sending any session errors as specially-formatted identifiers. if (resp.StatusCode != HttpStatusCode.OK) { activeRequests--; requestIsTerminating = false; if (resp.StatusCode == HttpStatusCode.NotFound) { //Console.WriteLine("Not Found"); TerminateBoshSession(); } return; } } else { //Console.WriteLine("No response"); } Stream rs = resp.GetResponseStream(); int readlen; byte[] readbuf = new byte[1024]; MemoryStream ms = new MemoryStream(); while ((readlen = rs.Read(readbuf, 0, readbuf.Length)) > 0) { ms.Write(readbuf, 0, readlen); } byte[] recv = ms.ToArray(); if (recv.Length > 0) { string sbody = null; string stanzas = null; ParseResponse(Encoding.UTF8.GetString(recv, 0, recv.Length), ref sbody, ref stanzas); if (stanzas != null) { byte[] bStanzas = Encoding.UTF8.GetBytes(stanzas); base.FireOnReceive(bStanzas, bStanzas.Length); } else { if (sbody != null) { var doc = new Document(); doc.LoadXml(sbody); if (doc.RootElement != null) { var body = doc.RootElement as Body; if (body.Type == BoshType.terminate) TerminateBoshSession(); } } if (terminate && !terminated) { // empty teminate response TerminateBoshSession(); } } } // cleanup webrequest resources ms.Close(); rs.Close(); resp.Close(); activeRequests--; requestIsTerminating = false; //if (activeRequests == 0 && !terminated) if ( (activeRequests == 0 && !terminated) || (activeRequests == 1 && m_SendQueue.Count > 0) ) { StartWebRequest(); } } catch (Exception ex) { } }
/// <summary> /// Create a "pair" document, this is a bit different from the others /// </summary> /// <param name="token">Token</param> /// <returns>Document</returns> public static Document LogitechPairDocument(string token) { var document = new Document { Namespace = Namespace }; var element = new Element("oa"); element.Attributes.Add("xmlns", "connect.logitech.com"); element.Attributes.Add("mime", "vnd.logitech.connect/vnd.logitech.pair"); element.Value = $"token={token}:name=foo#iOS6.0.1#iPhone"; document.AddChild(element); return document; }
/// <summary> /// Create a simple document for the command /// </summary> /// <param name="command">Command to call</param> /// <param name="elementValue">The value of the OA element, if one is needed</param> /// <returns>Document</returns> private static Document CreateDocument(HarmonyCommands command, string elementValue = null) { var document = new Document { Namespace = Namespace }; var element = CreateOaElement(command); if (elementValue != null) { element.Value = elementValue; } document.AddChild(element); return document; }