public void GetLivestreams(int page, AsyncCallback callback) { new Thread(new ThreadStart(() => { var List = new List <Livestream>(); GangOSClient.Trace("Getting official stream if live..."); //Get official Stream JObject query = JsonApiHelper.GetJson(string.Format("{0}streams/gangsofspace", p_APIUrl)); if (query == null) { GangOSClient.Trace(ErrorConsts.JSONDownloadError); callback.Invoke(new ListAsyncResult(List)); } if (query["stream"].HasValues) { List.Add(new Livestream(query["stream"])); GangOSClient.Trace("Official stream is live."); } else { GangOSClient.Trace("Official stream is offline."); } GangOSClient.Trace(string.Format("Getting {0} livestreams from page {1}", 10 - List.Count, page)); //Get streams playing Gangs of Space live query = JsonApiHelper.GetJson(string.Format("{0}streams?game={1}&limit={2}&offset={3}", p_APIUrl, "Gangs%20of%20Space", 10 - List.Count, page)); if (query == null) { GangOSClient.Trace(ErrorConsts.JSONDownloadError); callback.Invoke(new ListAsyncResult(List)); } GangOSClient.Trace("JSON Downloaded, parsing..."); var results = query["streams"]; foreach (var k in results) { List.Add(new Livestream(k)); GangOSClient.Trace(string.Format("Added livestream {0} with {1} viewers", List.Last().Username, List.Last().Viewers)); } GangOSClient.Trace(string.Format("Livestream fetch complete, {0} streams returned.", List.Count)); callback.Invoke(new ListAsyncResult(List)); })).Start(); }
//------------------------------------------------------------------------- private void ThreadWorker() { while (!_cancel) { _eventWait.WaitOne(); bool hasWork = true; while (hasWork) { hasWork = false; AsyncCallback callback = null; lock (_callbacks) { if (_callbacks.Count > 0) { callback = _callbacks.Dequeue(); hasWork = (_callbacks.Count > 0); } } if (null != callback) { try { callback.Invoke(null); } catch (Exception ex) { Console.WriteLine(ex); Debug.Assert(false); } } } } }
private void WriteToResponse(TransportClassMainAshx oTransportClassMainAshx, ErrorTypes eError, List <string> aUrls, NameValueCollection aNameValueCollection) { HttpContext oHttpContext = oTransportClassMainAshx.m_oHttpContext; AsyncCallback oAsyncCallback = oTransportClassMainAshx.m_oAsyncCallback; OutputCommand oOutputCommand = new OutputCommand(); if (null != aNameValueCollection) { for (int i = 0, length = aNameValueCollection.Count; i < length; ++i) { oOutputCommand.input.Add(aNameValueCollection.GetKey(i), aNameValueCollection.Get(i)); } } oOutputCommand.urls = aUrls; oOutputCommand.error = (int)eError; oOutputCommand.type = (int)PostMessageType.UploadImage; JavaScriptSerializer serializer = new JavaScriptSerializer(); StringBuilder sb = new StringBuilder(); serializer.Serialize(oOutputCommand, sb); string sJson = sb.ToString(); oHttpContext.Response.Write("<html><head><script type=\"text/javascript\">function load(){ parent.postMessage(\"" + sJson.Replace("\"", "\\\"") + "\", '*'); }</script></head><body onload='load()'></body></html>"); oAsyncCallback.Invoke(new AsyncOperationData(null)); }
private static void InvokeCallback(AsyncCallback callback, IAsyncResult result) { if (callback != null) { callback.Invoke(result); } }
public void TestProcessCallbackContainsStreamOnResponse() { Stream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); sw.Write("testing"); sw.Flush(); ms.Seek(0, SeekOrigin.Begin); webResponseMock.Setup((r) => r.Headers).Returns(new WebHeaderCollection()); webResponseMock.Setup((r) => r.GetResponseStream()).Returns(ms); Mutex requestMutex = new Mutex(); RequestWrapper req = new RequestWrapper(); AsyncCallback cb = req.ProcessCallback((headers, stream) => { StreamReader sr = new StreamReader(stream); String contents = sr.ReadToEnd(); Assert.AreEqual("testing", contents); requestMutex.ReleaseMutex(); }, (webex) => { Assert.Fail(); }); requestMutex.WaitOne(); cb.Invoke(result); }
private void FireCallback() { if (null != m_fAsyncCallback) { m_fAsyncCallback.Invoke(new AsyncOperationData(m_oParam)); } }
public static Task ToApm(this Task task, AsyncCallback?callback, object?state) { Requires.NotNull(task, nameof(task)); if (task.AsyncState == state) { if (callback is object) { task.ContinueWith( (t, cb) => ((AsyncCallback)cb !)(t), callback, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); } return(task); } var tcs = new TaskCompletionSource <object?>(state); task.ContinueWith( t => { ApplyCompletedTaskResultTo(t, tcs, null); callback?.Invoke(tcs.Task); }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); return(tcs.Task); }
private void WriteOutputCommand(TransportClassMainAshx oTransportClassMainAshx, OutputCommand oOutputCommand) { HttpContext oHttpContext = oTransportClassMainAshx.m_oHttpContext; AsyncCallback fAsyncCallback = oTransportClassMainAshx.m_oAsyncCallback; oHttpContext.Response.ContentType = "text/xml"; oHttpContext.Response.Charset = "UTF-8"; string sXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><FileResult>"; if (null != oOutputCommand.m_sFileUrl) { sXml += string.Format("<FileUrl>{0}</FileUrl>", HttpUtility.HtmlEncode(oOutputCommand.m_sFileUrl)); } if (null != oOutputCommand.m_sPercent) { sXml += string.Format("<Percent>{0}</Percent>", oOutputCommand.m_sPercent); } if (true == oOutputCommand.m_bIsEndConvert.HasValue) { sXml += string.Format("<EndConvert>{0}</EndConvert>", oOutputCommand.m_bIsEndConvert.Value.ToString()); } if (ErrorTypes.NoError != oOutputCommand.m_eError) { sXml += string.Format("<Error>{0}</Error>", Utils.mapAscServerErrorToOldError(oOutputCommand.m_eError).ToString()); } sXml += "</FileResult>"; oHttpContext.Response.Write(sXml); fAsyncCallback.Invoke(new AsyncOperationData(null)); }
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { var result = new DataUriAsyncResult(state); callback.Invoke(result); return(result); }
public override IAsyncResult BeginDownloadXml(Uri feeduri, AsyncCallback callback) { #if !WINDOWS_PHONE if (!IsolatedStorageFile.IsEnabled) throw new MissingFeedException("IsolatedStorage is not enabled! Cannot access files from IsolatedStorage!"); #endif try { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { if(!PingFeed(feeduri, store)) throw new MissingFeedException(string.Format("Could not find feed at location {0}", feeduri)); using (var stream = new IsolatedStorageFileStream(feeduri.OriginalString, FileMode.Open, FileAccess.Read, store)) { using(var reader = new StreamReader(stream)) { var strOutput = reader.ReadToEnd(); //Fake the async result var result = new AsyncResult<FeedTuple>(callback, new FeedTuple { FeedContent = strOutput, FeedUri = feeduri }, true); if (callback != null) callback.Invoke(result); return result; } } } } catch (IsolatedStorageException ex) { throw new MissingFeedException(string.Format("Unable to open feed at {0}", feeduri), ex); } }
public void UnStar(AsyncCallback callback) { this.connector.UnStarBookmark(this, delegate(IAsyncResult res){ this.Starred = false; callback.Invoke(res); }); }
internal void SetCompleted() { Debug.Assert(!isCompleted); isCompleted = true; callback?.Invoke(this); waitHandle?.Set(); }
protected virtual void ReceivedResult(IAsyncResult result) { int messageLength = 0; Socket receivedSocket = (Socket)result.AsyncState; try { messageLength = receivedSocket.EndReceive(result); } catch (Exception e) { if (e.GetType() != typeof(System.ObjectDisposedException)) { Trace.Warn("Receiver Error: {0}", e.ToString()); } } if (messageLength > 0) { _resultBuffer = new byte[messageLength]; Array.Copy(_receiverBuffer, _resultBuffer, messageLength); } if (!Running) { return; } SocketListen(); if (_callback != null && messageLength > 0) { _callback.Invoke(new SocketResult(_resultBuffer)); } }
private void BeginHandlerRunner(TcpClient server, Logger logger, AsyncCallback acb, object state) { server.LingerState = new LingerOption(true, 10); logger.LogMessage(String.Format("Listener - Connection established with {0}.", server.Client.RemoteEndPoint)); new Handler(server.GetStream(), logger, cts).Run(); acb.Invoke(null); }
private unsafe void completionCallback(uint errorCode, uint numBytes, NativeOverlapped *pOVERLAP) { try { if (errorCode != 0) { System.Diagnostics.Trace.TraceError("OverlappedStream GetQueuedCompletionStatus error: {0}", errorCode); } lock (_eventHandle) { System.Diagnostics.Debug.Assert(!_completed); _errorCode = errorCode; _numberOfBytesTransferred = numBytes; _completed = true; if (_callback != null) { _callback.Invoke(this); } Monitor.Pulse(_eventHandle); } } catch (Exception ex) { System.Diagnostics.Trace.TraceError("OverlappedStream.completionCallback error, {0}", ex.Message); } finally { this.Dispose(); } }
public void GetBookmarks(Folder folder, AsyncCallback callback) { String url = "https://www.instapaper.com/api/1/bookmarks/list"; String[] scriptParams = { url, "folder_id", folder.Id }; callApi(url, scriptParams, new AsyncCallback(delegate(IAsyncResult res) { String respResult = readResult(); List <Bookmark> bookmarks = new List <Bookmark>(); JsonParser parser = new JsonParser(respResult); var parsedBookmarksResult = parser.Decode(); ArrayList bookmarkArray = parsedBookmarksResult as ArrayList; foreach (Dictionary <String, Object> bookmark in bookmarkArray) { if ((bookmark["type"] as String).Equals("bookmark")) { Bookmark current = new Bookmark(this); current.Id = (String)bookmark["bookmark_id"]; current.Title = (String)bookmark["title"]; current.Url = (String)bookmark["url"]; current.Starred = ((String)bookmark["starred"]).Equals("1"); bookmarks.Add(current); } } folder.Bookmarks = bookmarks; callback.Invoke(res); })); }
public void ExecuteAsyncOperation(object param) { lock (_opLock) { try { _start.Invoke(param); if (_successCallback != null) { _successCallback.Invoke(null); } } catch (Exception ex) { SdkSettings.Instance.Logger.Log(TraceLevel.Error, ex.Message); if (_handler != null) { _handler.Show(ex.Message); } if (_errorCallback != null) { _errorCallback.Invoke(null); } } finally { ; } } }
void BTR_TransferStatusChanged(object sender, BackgroundTransferEventArgs e) { if (e.Request.TransferStatus == TransferStatus.Completed) { Uploading = false; if (e.Request.StatusCode == 200) { using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) { if (iso.FileExists(SAVE_RESPONSE_LOCATION)) { IsolatedStorageFileStream fs = new IsolatedStorageFileStream(SAVE_RESPONSE_LOCATION, System.IO.FileMode.Open, iso); //byte[] buffer = new byte[fs.Length]; //fs.Read(buffer, 0, (int)fs.Length); StreamReader str = new StreamReader(fs); string resp = str.ReadToEnd(); fs.Close(); JsonObject jobj = (JsonObject)SimpleJson.DeserializeObject(resp); string userid; IsolatedStorageSettings.ApplicationSettings.TryGetValue("userid", out userid); if (userid != null) { _heroku.AddBackup(jobj["key"].ToString(), jobj["url"].ToString(), userid); } iso.DeleteFile(SAVE_RESPONSE_LOCATION); _uploadCallback.Invoke(new AsyncCallbackEvent("success")); } } } BackgroundTransferService.Remove(e.Request); } Debug.WriteLine(e.Request.TransferStatus); }
public static void GetJson(string url, AsyncCallback callback) { new Thread(new ThreadStart(() => { callback.Invoke(new JsonAsyncResult(GetJson(url))); })).Start(); }
public static IAsyncResult BeginReadUInt64(this Stream stream, AsyncCallback callback, object state) { var task = Task.Run(() => ReadUInt64(stream)); callback.Invoke(task); return(task); }
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback?callback, object?state) { return(_innerStream.BeginWrite(buffer, offset, count, ar => { callback?.Invoke(ar); _writeAction?.Invoke(count); }, state)); }
public void TryComplete() { if (!(_callback is null) && Interlocked.Increment(ref _completions) == 1) { IsCompleted = true; _callback.Invoke(this); } }
public static IAsyncResult BeginReadCharacter(this Stream stream, Encoding encoding, AsyncCallback callback, object state) { var task = Task.Run(() => ReadCharacter(stream, encoding)); callback.Invoke(task); return(task); }
public static IAsyncResult BeginWriteCharacterArray(this Stream stream, char[] value, Encoding encoding, AsyncCallback callback, object state) { var task = Task.Run(() => WriteCharacterArray(stream, value, encoding)); callback.Invoke(task); return(task); }
internal static IAsyncResult Create(AsyncCallback ac) { var result = new LocalAsyncResult(); Task.Delay(100).Wait(); ac.Invoke(result); return(result); }
public static IAsyncResult BeginWriteString(this Stream stream, string value, Encoding encoding, AsyncCallback callback, object state) { var task = Task.Run(() => WriteString(stream, value, encoding)); callback.Invoke(task); return(task); }
public void GetPlayerData(string auth, AsyncCallback callback) { new Thread(new ThreadStart(() => { string url = string.Format("{0}{1}?token={2}", p_apiURL, p_player, auth); GangOSClient.Trace(string.Format("Downloading JSON Data from {0}", url)); callback.Invoke(new JsonAsyncResult(JsonApiHelper.GetJson(url), auth)); })).Start(); }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { var task = ReadAsync(buffer, offset, count, CancellationToken.None, state); if (callback != null) { task.ContinueWith(t => callback.Invoke(t)); } return task; }
public void GetBookmarkText(Bookmark bookmark, AsyncCallback callback) { String url = "https://www.instapaper.com/api/1/bookmarks/get_text"; String[] scriptParams = { url, "bookmark_id", bookmark.Id }; callApi(url, scriptParams, new AsyncCallback(delegate(IAsyncResult res) { bookmark.HtmlText = readResult(); callback.Invoke(res); })); }
static IAsyncResult BeginAsync(int input, out int result, AsyncCallback callback, object state) { result = input; _current = input * 2; if (callback != null) { callback.Invoke(new MyAsyncResult(state)); } return(null); }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { var task = ReadAsync(buffer, offset, count, CancellationToken.None, state); if (callback != null) { task.ContinueWith(t => callback.Invoke(t)); } return(task); }
public override void GET_Method_CallBack(IAsyncResult res) { HttpWebRequest wr = (HttpWebRequest)res.AsyncState; HttpWebResponse wrsp = (HttpWebResponse)wr.EndGetResponse(res); StreamReader strm = new StreamReader(wrsp.GetResponseStream()); string response = strm.ReadToEnd(); GetBackupCallBack.Invoke(new AsyncCallbackEvent(response)); //JsonObject jobj = (JsonObject)SimpleJson.DeserializeObject(response); }
public void UnStarBookmark(Bookmark bookmark, AsyncCallback callback) { String url = "https://www.instapaper.com/api/1/bookmarks/unstar"; String[] scriptParams = { url, "bookmark_id", bookmark.Id }; callApi(url, scriptParams, new AsyncCallback(delegate(IAsyncResult res) { bookmark.Starred = false; callback.Invoke(res); })); }
public void GetFolderList(User user, AsyncCallback callback) { String url = "https://www.instapaper.com/api/1/folders/list"; String[] scriptParams = { url }; callApi(url, scriptParams, delegate(IAsyncResult result){ String respResult = readResult(); List<Folder> folders = new List<Folder>(); // manually add the predefined folders Folder unread = new Folder(this); unread.Id = Folder.UNREAD; unread.Title = "Unread"; Folder starred = new Folder(this); starred.Id = Folder.STARRED; starred.Title = "Starred"; Folder archive = new Folder(this); archive.Id = Folder.ARCHIVE; archive.Title = "Archive"; folders.Add(unread); folders.Add(starred); folders.Add(archive); JsonParser parser = new JsonParser(respResult); var parsedFolderResult = parser.Decode(); ArrayList folderArray = parsedFolderResult as ArrayList; foreach (Dictionary<String, Object> folder in folderArray) { Folder current = new Folder(this); current.Id = folder["folder_id"] as String; current.Title = folder["title"] as String; folders.Add(current); } user.Folders = folders; callback.Invoke(result); }); }
protected override IAsyncResult BeginQueryCore(EntityQuery query, AsyncCallback callback, object userState) { // load test data and get query result IEnumerable<Entity> entities = GetQueryResult(query.QueryName, query.Parameters); if (query.Query != null) { entities = RebaseQuery(entities.AsQueryable(), query.Query).Cast<Entity>(); } MockAsyncResult ar = new MockAsyncResult(entities, userState, null); callback.Invoke(ar); return ar; }
public void GetBookmarks(Folder folder, AsyncCallback callback) { String url = "https://www.instapaper.com/api/1/bookmarks/list"; String[] scriptParams = { url, "folder_id", folder.Id }; callApi(url, scriptParams, new AsyncCallback(delegate(IAsyncResult res) { String respResult = readResult(); List<Bookmark> bookmarks = new List<Bookmark>(); JsonParser parser = new JsonParser(respResult); var parsedBookmarksResult = parser.Decode(); ArrayList bookmarkArray = parsedBookmarksResult as ArrayList; foreach (Dictionary<String, Object> bookmark in bookmarkArray) { if ((bookmark["type"] as String).Equals("bookmark")) { Bookmark current = new Bookmark(this); current.Id = (String)bookmark["bookmark_id"]; current.Title = (String)bookmark["title"]; current.Url = (String)bookmark["url"]; current.Starred = ((String)bookmark["starred"]).Equals("1"); bookmarks.Add(current); } } folder.Bookmarks = bookmarks; callback.Invoke(res); })); }
protected override IAsyncResult BeginSubmitCore(EntityChangeSet changeSet, AsyncCallback callback, object userState) { IEnumerable<ChangeSetEntry> submitOperations = changeSet.GetChangeSetEntries(); MockAsyncResult ar = new MockAsyncResult(null, userState, new object[] { changeSet, submitOperations, userState }); // perform mock submit operations callback.Invoke(ar); return ar; }
public override ICancellableAsyncResult BeginCommit(AsyncCallback callback, object state) { Commit(); ICancellableAsyncResult result = new CompletedCancellableAsyncResult(state); if (callback != null) { callback.Invoke(result); } return result; }
protected override IAsyncResult BeginInvokeCore(InvokeArgs invokeArgs, AsyncCallback callback, object userState) { MockAsyncResult ar = new MockAsyncResult(null, userState, new object[] { invokeArgs.OperationName, invokeArgs.ReturnType, invokeArgs.Parameters, userState }); // do the invoke and get the return value if (invokeArgs.OperationName == "Echo") { ar.ReturnValue = "Echo: " + (string)invokeArgs.Parameters.Values.First(); } callback.Invoke(ar); return ar; }
public IAsyncResult BeginReceiveFrom(byte[] buffer, ref EndPoint remoteEndPoint, AsyncCallback asynCallback, object state) { var ar = new MockedAsyncResult(state); Encoding.ASCII.GetBytes(MessageString).CopyTo(buffer, 0); asynCallback.Invoke(ar); return ar; }
public void ReadContextBegin(Stream oStream, AsyncCallback fCallback, object oParam) { ErrorTypes eError = ErrorTypes.NoError; try { m_oStream = oStream; m_fAsyncCallback = fCallback; m_oParam = oParam; m_oStream.BeginRead(m_aBuffer, 0, m_aBuffer.Length, ClearCacheTaskResultCallback, null); } catch { eError = ErrorTypes.ReadRequestStream; } if (ErrorTypes.NoError != eError) { m_eError = eError; fCallback.Invoke(new AsyncOperationData(oParam)); } }
public async void updateRequierdData(int days, AsyncCallback callback, AsyncCallback failCallback) { DateTime today= DateTime.Now; LocalWeatherInput weatherInput = new LocalWeatherInput(); weatherInput.num_of_days = days.ToString(); callback.Invoke(new Task((object obj) => { }, string.Format(" {0} place will be updated!", places.Count))); try { foreach (string langName in VoiceCommandInfo.AvailableLanguages) { if (VoiceCommandService.InstalledCommandSets.ContainsKey(langName)) { VoiceCommandSet widgetVcs = VoiceCommandService.InstalledCommandSets[langName]; widgetVcs.UpdatePhraseListAsync("place", places.Keys); } } } catch (Exception e) { BugReporter.GetInstance().report(e); } foreach (KeyValuePair<string, Place> dictionaryEntry in places) { Place place = dictionaryEntry.Value; if (place.LastUpdateTime > DateTime.Now.AddHours(-2) && !Settings.GetInstance().APIKey.Any()) { callback.Invoke(new Task((object obj) => { }, "current weather data for " + place.Name + " is not outdated yet!")); continue; } if (place._useName) weatherInput.query = place.Name; else weatherInput.query = place.Latitude + "," + place.Longitude; SaveWeatherDataClass saver = new SaveWeatherDataClass(place.Name,callback); new FreeAPI().GetLocalWeather(weatherInput,saver.SaveWeatherData, failCallback); Thread.Sleep(1000); } }
public void ReadContextBegin(Stream oStream, AsyncCallback fCallback, object oParam) { try { m_oStream = oStream; m_oParam = oParam; int nInputLength = (int)m_oStream.Length; m_aBuffer = new byte[nInputLength]; m_oStream.BeginRead(m_aBuffer, 0, nInputLength, fCallback, oParam); } catch { m_eError = ErrorTypes.ReadRequestStream; } if (ErrorTypes.NoError != m_eError) fCallback.Invoke(new AsyncOperationData(oParam)); }