private void InitializeServiceAsync(System.Action callback) { Debug.WriteLine("[CallInProgressAgentImpl {0}] _mtProtoService == null {1}", GetHashCode(), _mtProtoService == null); if (MTProtoService == null) { var deviceInfoService = new Telegram.Api.Services.DeviceInfo.DeviceInfoService(GetInitConnection(), true, "BackgroundDifferenceLoader", 1); var cacheService = new MockupCacheService(); var updatesService = new MockupUpdatesService(); _transportService = new TransportService(); var connectionService = new ConnectionService(deviceInfoService); var publicConfigService = new MockupPublicConfigService(); var mtProtoService = new MTProtoService(deviceInfoService, updatesService, cacheService, _transportService, connectionService, publicConfigService); mtProtoService.Initialized += (o, e) => { //Log(string.Format("[MTProtoUpdater {0}] Initialized", GetHashCode())); Thread.Sleep(1000); callback.SafeInvoke(); }; mtProtoService.InitializationFailed += (o, e) => { //Log(string.Format("[MTProtoUpdater {0}] InitializationFailed", GetHashCode())); }; mtProtoService.Initialize(); MTProtoService = mtProtoService; } else { callback.SafeInvoke(); } }
public void GetContactsAsync(System.Action callback) { var savedCount = TLUtils.OpenObjectFromMTProtoFile <TLInt>(_savedCountSyncRoot, Constants.SavedCountFileName); var hash = TLUtils.GetContactsHash(savedCount, CacheService.GetContacts().Where(x => x.IsContact).OrderBy(x => x.Index).ToList()); IsWorking = true; MTProtoService.GetContactsAsync(new TLInt(hash), result => Execute.BeginOnUIThread(() => { Execute.ShowDebugMessage(result.ToString()); IsWorking = false; var contacts = result as TLContacts71; if (contacts != null) { TLUtils.SaveObjectToMTProtoFile(_savedCountSyncRoot, Constants.SavedCountFileName, contacts.SavedCount); InsertContacts(contacts.Users); } var contactsNotModified = result as TLContactsNotModified; if (contactsNotModified != null) { } callback.SafeInvoke(); }), error => Execute.BeginOnUIThread(() => { IsWorking = false; Execute.ShowDebugMessage("contacts.getContacts error: " + error); callback.SafeInvoke(); })); }
public void EditChannelAboutAsync(TLChannel channel, TLString about, System.Action callback) { if (TLString.Equals(about, channel.About, StringComparison.Ordinal)) { callback.SafeInvoke(); return; } IsWorking = true; MTProtoService.EditAboutAsync(channel, about, statedMessage => Execute.BeginOnUIThread(() => { IsWorking = false; channel.About = about; CacheService.Commit(); callback.SafeInvoke(); }), error => Execute.BeginOnUIThread(() => { Execute.ShowDebugMessage("channels.editAbout error " + error); IsWorking = false; if (error.CodeEquals(ErrorCode.BAD_REQUEST) && error.TypeEquals(ErrorType.CHAT_ABOUT_NOT_MODIFIED)) { } callback.SafeInvoke(); })); }
private void HorizontalItem_OnTap(object sender, GestureEventArgs e) { var frameworkElement = sender as FrameworkElement; if (frameworkElement == null) { return; } var with = frameworkElement.DataContext as TLObject; if (with == null) { return; } ClosePivotAction.SafeInvoke(Visibility.Visible); ViewModel.StateService.CollapseSearchControl = true; Execute.BeginOnUIThread(() => { if (!ViewModel.OpenDialogDetails(with, false)) { return; } }); }
public void ProcessAsync(Action <IList <DialogItem> > callback) { if (Results != null) { IsCanceled = false; callback.SafeInvoke(Results); return; } var dialogsSource = DialogsSource; Execute.BeginOnThreadPool(() => { var useFastSearch = !Text.Contains(" "); var results = new List <DialogItem>(dialogsSource.Count); foreach (var dialogItem in dialogsSource) { var dialog = dialogItem.Dialog; var user = dialog.With as TLUser; var chat = dialog.With as TLChatBase; if (user != null) { if (IsUserValid(user, Text) || IsUserValid(user, TransliterateText) || IsUsernameValid(user, Text)) { results.Add(dialogItem); } } else if (chat != null) { if (IsChatValid(chat, Text, useFastSearch) || IsChatValid(chat, TransliterateText, useFastSearch) || IsUsernameValid(chat as IUserName, Text)) { var channelForbidden = chat as TLChannelForbidden; if (channelForbidden != null) { continue; } var chat41 = chat as TLChat41; if (chat41 != null && chat41.IsMigrated) { continue; } results.Add(dialogItem); } } } Results = results; Execute.BeginOnUIThread(() => callback.SafeInvoke(Results)); }); }
private void ConnectAsync(Action callback, Action <TcpTransportResult> faultCallback) { WRITE_LOG(string.Format("Socket.ConnectAsync[#3] {0} ({1}:{2})", Id, Host, Port)); TLSocks5Proxy socks5Proxy = ProxyConfig != null && ProxyConfig.IsEnabled.Value && !ProxyConfig.IsEmpty ? ProxyConfig.GetProxy() as TLSocks5Proxy : null; if (socks5Proxy != null) { try { ActualHost = StaticHost; ActualPort = StaticPort; RaiseConnectingAsync(); SocksProxy.ConnectToSocks5Proxy(_socket, socks5Proxy.Server.ToString(), (ushort)socks5Proxy.Port.Value, StaticHost, (ushort)StaticPort, socks5Proxy.Username.ToString(), socks5Proxy.Password.ToString()); OnConnected(new SocketAsyncEventArgs { SocketError = SocketError.Success }, callback, faultCallback); } catch (Exception ex) { faultCallback.SafeInvoke(new TcpTransportResult(SocketAsyncOperation.Connect, ex)); WRITE_LOG("Socket.ConnectAsync[#3]", ex); } } else { System.Diagnostics.Debug.WriteLine(" Connecting mtproto=[server={0} port={1}]", Host, Port); var args = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(_address, Port) }; args.Completed += (o, e) => OnConnected(e, callback, faultCallback); try { ActualHost = Host; ActualPort = Port; RaiseConnectingAsync(); _socket.ConnectAsync(args); } catch (Exception ex) { faultCallback.SafeInvoke(new TcpTransportResult(SocketAsyncOperation.Connect, ex)); WRITE_LOG("Socket.ConnectAsync[#3]", ex); } } }
private void StopLiveLocation(TLMessage70 message, System.Action callback) { if (message == null) { return; } var mediaGeoLive = message.Media as TLMessageMediaGeoLive; if (mediaGeoLive == null) { return; } var geoPoint = mediaGeoLive.Geo as TLGeoPoint; if (geoPoint == null) { return; } var newGeoPoint = new TLGeoPointEmpty(); var liveLocationsService = IoC.Get <ILiveLocationService>(); liveLocationsService.UpdateAsync(message, newGeoPoint, result => Execute.BeginOnUIThread(() => { LiveLocationBadge = null; NotifyOfPropertyChange(() => LiveLocationBadge); mediaGeoLive.Date = message.Date; mediaGeoLive.EditDate = message.EditDate; mediaGeoLive.NotifyOfPropertyChange(() => mediaGeoLive.Geo); mediaGeoLive.NotifyOfPropertyChange(() => mediaGeoLive.EditDate); mediaGeoLive.NotifyOfPropertyChange(() => mediaGeoLive.Active); callback.SafeInvoke(); }), error => Execute.BeginOnUIThread(() => { if (error == null || error.CodeEquals(ErrorCode.BAD_REQUEST)) { LiveLocationBadge = null; NotifyOfPropertyChange(() => LiveLocationBadge); mediaGeoLive.Date = message.Date; mediaGeoLive.EditDate = message.EditDate; mediaGeoLive.NotifyOfPropertyChange(() => mediaGeoLive.Geo); mediaGeoLive.NotifyOfPropertyChange(() => mediaGeoLive.EditDate); mediaGeoLive.NotifyOfPropertyChange(() => mediaGeoLive.Active); callback.SafeInvoke(); } })); }
public static void DeleteAndExitDialogCommon(TLChatBase chatBase, IMTProtoService mtProtoService, System.Action callback, Action <TLRPCError> faultCallback = null) { if (chatBase == null) { return; } var inputPeer = chatBase.ToInputPeer(); if (chatBase is TLChatForbidden) { DeleteHistoryAsync( mtProtoService, false, inputPeer, new TLInt(0), affectedHistory => callback.SafeInvoke(), faultCallback.SafeInvoke); } else { var chat = chatBase as TLChat; var chat41 = chatBase as TLChat41; if (chat != null) { if (chat.Left.Value || (chat41 != null && chat41.IsMigrated)) { DeleteHistoryAsync( mtProtoService, false, inputPeer, new TLInt(0), affectedHistory => callback.SafeInvoke(), faultCallback.SafeInvoke); } else { mtProtoService.DeleteChatUserAsync( chat.Id, new TLInputUserSelf(), statedMessage => DeleteHistoryAsync( mtProtoService, false, inputPeer, new TLInt(0), affectedHistory => callback.SafeInvoke(), faultCallback.SafeInvoke), faultCallback.SafeInvoke); } } } }
public static void Init() { _sheets.Clear(); _entriesByFullID.Clear(); _enums = new Enums(); var files = new DirectoryInfo(_mainJsonPath).EnumerateFiles().Where(f => _fileExtensions.Contains(f.Extension)); foreach (var file in files) { var db = new JsonDB(File.ReadAllText(file.FullName)); foreach (var dbSheet in db.Sheets) { if (!_sheets.TryGetValue(dbSheet.Key, out var sheet)) { sheet = new Dictionary <string, DataEntry>(); _sheets.Add(dbSheet.Key, sheet); } for (int i = 0; i < dbSheet.Value.Count; i++) { var entry = dbSheet.Value[i]; sheet.AddOrUpdate(entry.ID, entry); _entriesByFullID.AddOrUpdate(entry.FullID, entry); } } } _onInit.SafeInvoke(); }
private void UpdateUsers(List <TLUserBase> users, Action callback) { const int firstSliceCount = 3; var secondSlice = new List <TLUserBase>(); for (var i = 0; i < users.Count; i++) { if (i < firstSliceCount) { Items.Add(users[i]); } else { secondSlice.Add(users[i]); } } Execute.BeginOnUIThread(() => { foreach (var user in secondSlice) { Items.Add(user); } callback.SafeInvoke(); }); }
private void AddItemsChunk(int chunkSize, List <TLStickerSetBase> delayedItems, System.Action callback) { BeginOnUIThread(() => { for (var i = 0; i < delayedItems.Count && i < chunkSize; i++) { var stickerSet = delayedItems[i] as TLStickerSet; if (stickerSet != null) { stickerSet.IsSelected = StickerSet != null && TLString.Equals(StickerSet.ShortName, stickerSet.ShortName, StringComparison.OrdinalIgnoreCase); } Items.Add(delayedItems[0]); delayedItems.RemoveAt(0); } if (delayedItems.Count > 0) { AddItemsChunk(25, delayedItems, callback); } else { callback.SafeInvoke(); } }); }
public void SendPacketAsync(string caption, byte[] message, Action <bool> callback, Action <TcpTransportResult> faultCallback = null) { //var guid = Guid.NewGuid(); var stopwatch = Stopwatch.StartNew(); TLUtils.WriteLine(" HTTP: Send " + caption); var request = CreateRequest(message.Length, _host); request.BeginAsync(message, result => { TLUtils.WriteLine(); TLUtils.WriteLine(); TLUtils.WriteLine(" HTTP: Receive " + caption + " (" + stopwatch.Elapsed + ")"); RaiseGetBytes(result); ///callback(result); }, () => { TLUtils.WriteLine(); TLUtils.WriteLine(); TLUtils.WriteLine(" HTTP: Receive Falt " + caption + " (" + stopwatch.Elapsed + ")"); faultCallback.SafeInvoke(null); }); }
private void UpdateUsers(List <TLUserBase> users, System.Action callback) { const int firstSliceCount = 3; var secondSlice = new List <TLUserBase>(); for (var i = 0; i < users.Count; i++) { if (i < firstSliceCount) { Items.Add(users[i]); } else { secondSlice.Add(users[i]); } } Status = Items.Count > 0 ? string.Empty : AppResources.Loading; Execute.BeginOnUIThread(() => { foreach (var user in secondSlice) { Items.Add(user); } callback.SafeInvoke(); }); }
private static void TranscodeComplete(IAsyncActionWithProgress <double> asyncInfo, AsyncStatus asyncStatus, Action callback, Action <IAsyncActionWithProgress <double> > faultCallback) { asyncInfo.GetResults(); if (asyncInfo.Status == AsyncStatus.Completed) { callback.SafeInvoke(); } else if (asyncInfo.Status == AsyncStatus.Canceled) { Telegram.Api.Helpers.Execute.ShowDebugMessage("Transcode canceled result " + asyncInfo.Status); faultCallback.SafeInvoke(asyncInfo); } else { Telegram.Api.Helpers.Execute.ShowDebugMessage("Transcode error result=" + asyncInfo.Status + " exception \n" + asyncInfo.ErrorCode); faultCallback.SafeInvoke(asyncInfo); } }
public void OpenContact() { IsOpen = false; Execute.BeginOnUIThread(TimeSpan.FromSeconds(0.25), () => { _sendContactAction.SafeInvoke(); }); }
private void OnConnected(SocketAsyncEventArgs args, Action callback = null, Action <TcpTransportResult> faultCallback = null) { WRITE_LOG(string.Format("Socket.OnConnected[#4] {0} socketError={1}", Id, args.SocketError)); try { if (args.SocketError != SocketError.Success) { faultCallback.SafeInvoke(new TcpTransportResult(SocketAsyncOperation.Connect, args.SocketError)); } else { RaiseConnectedAsync(); ReceiveAsync(); try { lock (_encryptedStreamSyncRoot) { var buffer = GetInitBuffer(); var sendArgs = new SocketAsyncEventArgs(); sendArgs.SetBuffer(buffer, 0, buffer.Length); sendArgs.Completed += (o, e) => callback.SafeInvoke(); _socket.SendAsync(sendArgs); } } catch (Exception ex) { faultCallback.SafeInvoke(new TcpTransportResult(SocketAsyncOperation.Send, ex)); WRITE_LOG("Socket.OnConnected[#4]", ex); } } } catch (Exception ex) { faultCallback.SafeInvoke(new TcpTransportResult(SocketAsyncOperation.Connect, ex)); WRITE_LOG("Socket.OnConnected[#4] SendAsync", ex); } }
public void SlideRight(double velocity, System.Action callback = null) { if (velocity == 0.0) { velocity = 480.0 + 12.0; } var transform = ImagesGrid.RenderTransform as CompositeTransform; if (transform == null) { return; } var translationX = 480.0 + 12.0; var duration = PanAndZoomBehavior.Clamp((translationX - transform.TranslateX) / velocity, .15, .35); #if !NO_RIBBON Ribbon.ScrollPrevious(duration); #endif var storyboard = new Storyboard(); var translateAnimation = new DoubleAnimation(); translateAnimation.To = translationX; translateAnimation.Duration = new Duration(TimeSpan.FromSeconds(duration)); Storyboard.SetTarget(translateAnimation, transform); Storyboard.SetTargetProperty(translateAnimation, new PropertyPath("TranslateX")); storyboard.Children.Add(translateAnimation); storyboard.Begin(); //MainGrid.IsHitTestVisible = false; _slideAnimating = true; storyboard.Completed += (sender, args) => { //Deployment.Current.Dispatcher.BeginInvoke(() => // { //MainGrid.IsHitTestVisible = true; _slideAnimating = false; //}); //MainGrid.IsHitTestVisible = true; transform.TranslateX = 0.0; Grid.SetColumn(Item1, Grid.GetColumn(Item1) + 1 > 2 ? 0 : Grid.GetColumn(Item1) + 1); Grid.SetColumn(Item2, Grid.GetColumn(Item2) + 1 > 2 ? 0 : Grid.GetColumn(Item2) + 1); Grid.SetColumn(Item3, Grid.GetColumn(Item3) + 1 > 2 ? 0 : Grid.GetColumn(Item3) + 1); SetPanAndZoom(); //return; ViewModel.SlideRight(); //return; SetControlContent(0, ViewModel.PreviousItem); callback.SafeInvoke(); }; }
public void ShowBlockingPlaceholder(System.Action callback) { var updateAppControl = new UpdateAppControl(); updateAppControl.TapBottomMenu += (o, e) => { callback.SafeInvoke(); }; _blockingPlaceholder.Content = updateAppControl; _blockingPlaceholder.Visibility = Visibility.Visible; }
private void AppBarAction(System.Action action) { if (FocusManager.GetFocusedElement() == Caption) { Items.Focus(); Telegram.Api.Helpers.Execute.BeginOnUIThread(TimeSpan.FromSeconds(0.20), action.SafeInvoke); } else { action.SafeInvoke(); } }
private static async void GetCompressedFile(CompressingVideoFile file, Action <StorageFile, ulong> callback, Action <double> progressCallback, Action <IAsyncActionWithProgress <double> > faultCallback) { var fileName = Path.GetFileName(file.Source.Name); var videoParameters = string.Empty; if (file.EncodingProfile != null) { videoParameters = string.Format("{0}_{1}_{2}_{3}", file.EncodingProfile.Video.Width, file.EncodingProfile.Video.Height, file.EncodingProfile.Video.Bitrate, file.EncodingProfile.Video.FrameRate); } var audioParameters = string.Empty; if (file.EncodingProfile != null) { audioParameters = file.EncodingProfile.Audio != null?file.EncodingProfile.Audio.Bitrate.ToString() : "0"; } var hashString = string.Format("{0}_{1}_{2}_{3}", audioParameters, videoParameters, file.TrimStartTime, file.TrimStopTime); var transcodedFileName = string.Format("vid_{0}_{1}", hashString.GetHashCode(), fileName); //Telegram.Api.Helpers.Execute.ShowDebugMessage(transcodedFileName + Environment.NewLine + hashString); var fulltranscodedFileName = Path.Combine(KnownFolders.CameraRoll.Path, transcodedFileName); if (File.Exists(fulltranscodedFileName)) { StorageFile transcodedFile = null; ulong transcodedLength = 0; try { transcodedFile = await KnownFolders.CameraRoll.GetFileAsync(transcodedFileName); if (transcodedFile != null) { transcodedLength = (ulong)new FileInfo(fulltranscodedFileName).Length; } } catch (Exception ex) { Telegram.Api.Helpers.Execute.ShowDebugMessage("Get transcoded file ex: \n" + ex); } if (transcodedFile != null && transcodedLength > 0) { callback.SafeInvoke(transcodedFile, transcodedLength); return; } } var dest = await KnownFolders.CameraRoll.CreateFileAsync(transcodedFileName, CreationCollisionOption.ReplaceExisting); TranscodeFile(file.EncodingProfile, file.TrimStartTime, file.TrimStopTime, file.Source, dest, callback, progressCallback, faultCallback); }
public static void ImportContactsAsync(IFileManager fileManager, ContactsOperationToken token, IList <TLUserBase> contacts, Action <Telegram.Api.WindowsPhone.Tuple <int, int> > progressCallback, System.Action cancelCallback) { #if WP8 Execute.BeginOnThreadPool(async() => { //var contacts = _cacheService.GetContacts(); var totalCount = contacts.Count; if (totalCount == 0) { return; } var store = await ContactStore.CreateOrOpenAsync(); var importedCount = 0; var delayedContacts = new TLVector <TLInt>(); foreach (var contact in contacts) { if (token.IsCanceled) { cancelCallback.SafeInvoke(); return; } try { var delayedContact = await UpdateContactInternalAsync(contact, fileManager, store, true); if (delayedContact != null) { delayedContacts.Add(delayedContact.Id); } } catch (Exception ex) { // continue import after failed contact } //Thread.Sleep(100); importedCount++; progressCallback.SafeInvoke(new Telegram.Api.WindowsPhone.Tuple <int, int>(importedCount, totalCount)); //var duration = importedCount == totalCount ? 0.5 : 2.0; //_mtProtoService.SetMessageOnTime(duration, string.Format("Sync contacts ({0} of {1})...", importedCount, totalCount)); } var result = new TLVector <TLInt>(); foreach (var delayedContact in delayedContacts) { result.Add(delayedContact); } SaveDelayedContactsAsync(result); }); #endif }
public void EditChannelTitleAsync(TLChannel channel, TLString title, System.Action callback) { if (TLString.Equals(title, channel.Title, StringComparison.Ordinal)) { callback.SafeInvoke(); return; } IsWorking = true; MTProtoService.EditTitleAsync(channel, title, result => Execute.BeginOnUIThread(() => { IsWorking = false; var updates = result as TLUpdates; if (updates != null) { var updateNewMessage = updates.Updates.FirstOrDefault(x => x is TLUpdateNewChannelMessage) as TLUpdateNewChannelMessage; if (updateNewMessage != null) { EventAggregator.Publish(updateNewMessage.Message); } } callback.SafeInvoke(); }), error => Execute.BeginOnUIThread(() => { Execute.ShowDebugMessage("channels.editTitle error " + error); IsWorking = false; if (error.CodeEquals(ErrorCode.BAD_REQUEST) && error.TypeEquals(ErrorType.CHAT_NOT_MODIFIED)) { } callback.SafeInvoke(); })); }
private static SocketAsyncEventArgs CreateArgs(byte[] data, Action <bool> callback = null) { var packet = CreatePacket(data); var args = new SocketAsyncEventArgs(); args.SetBuffer(packet, 0, packet.Length); args.Completed += (sender, eventArgs) => { callback.SafeInvoke(eventArgs.SocketError == SocketError.Success); }; return(args); }
public void ShowCallPlaceholder(System.Action callback) { if (_callPlaceholder == null || _callPlaceholder.Content != null) { _returnToCallControl = new ReturnToCallControl(); _returnToCallControl.Tap += (o, e) => { callback.SafeInvoke(); }; return; } var returnToCallControl = new ReturnToCallControl(); returnToCallControl.Tap += (o, e) => { callback.SafeInvoke(); }; _callPlaceholder.Content = returnToCallControl; }
public static void DeleteDialogCommon(TLUserBase userBase, IMTProtoService mtProtoService, System.Action callback, Action <TLRPCError> faultCallback = null) { if (userBase == null) { return; } var inputPeer = userBase.ToInputPeer(); DeleteHistoryAsync(mtProtoService, false, inputPeer, new TLInt(0), result => callback.SafeInvoke(), faultCallback.SafeInvoke); }
private void OnConnected(SocketAsyncEventArgs args, Action callback = null, Action <TcpTransportResult> faultCallback = null) { WRITE_LOG(string.Format("Socket.OnConnected[#4] {0} socketError={1}", Id, args.SocketError)); try { if (args.SocketError != SocketError.Success) { faultCallback.SafeInvoke(new TcpTransportResult(SocketAsyncOperation.Connect, args.SocketError)); } else { ReceiveAsync(); var sendArgs = new SocketAsyncEventArgs(); sendArgs.SetBuffer(new byte[] { 0xef }, 0, 1); sendArgs.Completed += (o, e) => callback.SafeInvoke(); try { _socket.SendAsync(sendArgs); } catch (Exception ex) { faultCallback.SafeInvoke(new TcpTransportResult(SocketAsyncOperation.Send, ex)); WRITE_LOG("Socket.OnConnected[#4]", ex); } } } catch (Exception ex) { faultCallback.SafeInvoke(new TcpTransportResult(SocketAsyncOperation.Connect, ex)); WRITE_LOG("Socket.OnConnected[#4] SendAsync", ex); } }
private static async void TranscodeFile(MediaEncodingProfile profile, TimeSpan trimStartTime, TimeSpan trimStopTime, StorageFile srcFile, StorageFile destFile, Action <StorageFile, ulong> callback, Action <double> progressCallback, Action <IAsyncActionWithProgress <double> > faultCallback) { profile = profile ?? await MediaEncodingProfile.CreateFromFileAsync(srcFile); var transcoder = new MediaTranscoder { TrimStartTime = trimStartTime, TrimStopTime = trimStopTime }; var prepareOp = await transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile); //Telegram.Api.Helpers.Execute.ShowDebugMessage(string.Format("TranscodeFile\nvideo=[{0}x{1} {2}]\naudio=[{3}]\ntrim_start={4} trim_end={5}", profile.Video.Width, profile.Video.Height, profile.Video.Bitrate, profile.Audio != null ? profile.Audio.Bitrate : 0, trimStartTime, trimStopTime)); if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); transcodeOp.Progress += (result, progress) => { progressCallback.SafeInvoke(progress); }; transcodeOp.Completed += async(o, e) => { var properties = await destFile.GetBasicPropertiesAsync(); var size = properties.Size; TranscodeComplete(o, e, () => callback(destFile, size), faultCallback); }; } else { faultCallback.SafeInvoke(null); switch (prepareOp.FailureReason) { case TranscodeFailureReason.CodecNotFound: Telegram.Api.Helpers.Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.CodecWasNotFound, AppResources.Error, MessageBoxButton.OK)); break; case TranscodeFailureReason.InvalidProfile: Telegram.Api.Helpers.Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.ProfileIsInvalid, AppResources.Error, MessageBoxButton.OK)); break; default: Telegram.Api.Helpers.Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.UnknownFailure, AppResources.Error, MessageBoxButton.OK)); break; } } }
public void GetSendingQueueInfoAsync(Action <string> callback) { Helpers.Execute.BeginOnThreadPool(() => { var info = new StringBuilder(); lock (_sendingQueueSyncRoot) { var count = 0; foreach (var item in _sendingQueue) { var sendBeforeTimeString = item.SendBeforeTime.HasValue ? item.SendBeforeTime.Value.ToString("H:mm:ss.fff") : null; var message = string.Empty; try { var transportMessage = item.Message as TLContainerTransportMessage; if (transportMessage != null) { var sendMessage = transportMessage.MessageData as TLSendMessage; if (sendMessage != null) { message = string.Format("{0} {1}", sendMessage.Message, sendMessage.RandomId); } else { var invokeAfterMsg = transportMessage.MessageData as TLInvokeAfterMsg; if (invokeAfterMsg != null) { sendMessage = invokeAfterMsg.Object as TLSendMessage; if (sendMessage != null) { message = string.Format("{0} {1}", sendMessage.Message, sendMessage.RandomId); } } } } } catch (Exception ex) { } info.AppendLine(string.Format("{0} send={1} before={2} msg=[{3}] error=[{4}]", count++, item.SendTime.ToString("H:mm:ss.fff"), sendBeforeTimeString, message, item.LastError)); } } callback.SafeInvoke(info.ToString()); }); }
private SocketAsyncEventArgs CreateArgs(byte[] data, Action <bool> callback = null) { var packet = CreatePacket(data); #if TCP_OBFUSCATED_2 packet = Encrypt(packet); #endif var args = new SocketAsyncEventArgs(); args.SetBuffer(packet, 0, packet.Length); args.Completed += (sender, eventArgs) => { callback.SafeInvoke(eventArgs.SocketError == SocketError.Success); }; return(args); }
private static async void TranscodeFile(VideoEncodingQuality quality, StorageFile srcFile, StorageFile destFile, Action <StorageFile, ulong> callback, Action <IAsyncActionWithProgress <double> > faultCallback) { var profile = MediaEncodingProfile.CreateMp4(quality); profile.Video.Bitrate = 750000; profile.Audio.ChannelCount = 1; profile.Audio.Bitrate = 62000; var transcoder = new MediaTranscoder(); var prepareOp = await transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile); //message.PrepareTranscodeResult = prepareOp; if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); transcodeOp.Progress += TranscodeProgress; transcodeOp.Completed += async(o, e) => { var properties = await destFile.GetBasicPropertiesAsync(); var size = properties.Size; TranscodeComplete(o, e, () => callback(destFile, size), faultCallback); }; } else { faultCallback.SafeInvoke(null); switch (prepareOp.FailureReason) { case TranscodeFailureReason.CodecNotFound: Telegram.Api.Helpers.Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.CodecWasNotFound, AppResources.Error, MessageBoxButton.OK)); break; case TranscodeFailureReason.InvalidProfile: Telegram.Api.Helpers.Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.ProfileIsInvalid, AppResources.Error, MessageBoxButton.OK)); break; default: Telegram.Api.Helpers.Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.UnknownFailure, AppResources.Error, MessageBoxButton.OK)); break; } } }
public When_invoking_an_action() { action = () => { wasCalled = true; }; action.SafeInvoke(); }