static async void GraphCallback(SDK.CoreKit.GraphRequestConnection connection, NSObject result, NSError error) { if (error == null) { var data = new JObject(); foreach (var item in (NSDictionary)result) { data.Add(item.Key.ToString(), new JValue(item.Value.ToString())); } if (IsLoginCall) { CurrentUser = new User(data) { AccessToken = CurrentAccessToken }; await OnSuccess.Raise(CurrentUser); } else { await UserInfoFetched.Raise(data); } } else { await OnSuccess.Raise(null); } }
public async Task <bool> Send(ISmsMessage smsItem) { if (smsItem.Retries > MaximumRetries) { return(false); } if (smsItem.IsNew) { await Database.Save(smsItem); } try { await Dispatcher.Dispatch(smsItem); await Database.Update(smsItem, o => o.DateSent = LocalTime.Now); return(true); } catch (Exception ex) { await SendError.Raise(new SmsSendingEventArgs(smsItem) { Error = ex }); Log.Error(ex, "Can not send the SMS queue item."); await RecordFailedAttempt(smsItem); return(false); } }
public virtual async Task RecordSave(IEntity entity, SaveMode saveMode) { if (!LogEventsAttribute.ShouldLog(entity.GetType())) { return; } var eventInfo = CreateApplicationEvent(); if (eventInfo == null) { return; } eventInfo.ItemType = entity.GetType().FullName; eventInfo.ItemKey = entity.GetId().ToString(); eventInfo.Event = saveMode.ToString(); eventInfo.IP = GetCurrentUserIP(); eventInfo.UserId = GetCurrentUserId(); if (saveMode == SaveMode.Update) { var changes = await GetChangesXml(entity); if (changes.IsEmpty()) // No changes have happened, ignore recording the action: { return; } eventInfo.Data = changes; } else { if (!ShouldSkipInsertData) { eventInfo.Data = GetDataXml(entity); } } if (OnRecordingSave.IsHandled()) { var args = new AuditSaveEventArgs { SaveMode = saveMode, ApplicationEvent = eventInfo, Entity = entity }; await OnRecordingSave.Raise(args); if (args.Cancel) { return; } } await Save(eventInfo); ProcessContext <UndoContext> .Current.Perform(c => c.Append(eventInfo, entity)); }
internal async Task OnSaved(ReplicateDataMessage message, IEntity entity, SaveMode mode) { if (Saved.IsHandled()) { await Saved.Raise(new ReplicationSaveMessageProcessedEventArgs(message, entity, mode)); } }
public override async Task OnInitializing() { await base.OnInitializing(); Text = "Back"; Tapped.Handle(() => buttonTapped.Raise()); }
static async Task <bool> SendViaSmtp(IEmailMessage mailItem, MailMessage mail) { using (var smtpClient = new SmtpClient()) { smtpClient.EnableSsl = mailItem.EnableSsl ?? Config.GetOrThrow("Email:EnableSsl").To <bool>(); smtpClient.Port = mailItem.SmtpPort ?? Config.GetOrThrow("Email:SmtpPort").To <int>(); smtpClient.Host = mailItem.SmtpHost.OrNullIfEmpty() ?? Config.GetOrThrow("Email:SmtpHost"); var userName = mailItem.Username.OrNullIfEmpty() ?? Config.GetOrThrow("Email:Username"); var password = mailItem.Password.OrNullIfEmpty() ?? Config.GetOrThrow("Email:Password"); smtpClient.Credentials = new NetworkCredential(userName, password); await Sending.Raise(new EmailSendingEventArgs(mailItem, mail)); await smtpClient.SendMailAsync(mail); if (!mailItem.IsNew) { await Entity.Database.Delete(mailItem); } await Sent.Raise(new EmailSendingEventArgs(mailItem, mail)); } return(true); }
internal async Task OnDeleted(ReplicateDataMessage message, IEntity entity) { if (Deleted.IsHandled()) { await Deleted.Raise(new ReplicationDeleteMessageProcessedEventArgs(message, entity)); } }
/// <summary> /// Will try to send the specified email and returns true for successful sending. /// </summary> public static async Task <bool> Send(IEmailMessage mailItem) { if (mailItem == null) { throw new ArgumentNullException(nameof(mailItem)); } if (mailItem.Retries >= MaximumRetries) { return(false); } MailMessage mail = null; try { using (mail = await CreateMailMessage(mailItem)) { if (mail == null) { return(false); } return(await EmailDispatcher(mailItem, mail)); } } catch (Exception ex) { await SendError.Raise(new EmailSendingEventArgs(mailItem, mail) { Error = ex }); await mailItem.RecordRetry(); Log.Error($"Error in sending an email for this EmailQueueItem of '{mailItem.GetId()}'", ex); return(false); } }
async Task InitializeFacebook() { var browser = new WebView(RequestedUrl).Size(100.Percent()); browser.BrowserNavigated.Handle(() => { var uri = browser.Url.AsUri(); if (uri.AbsolutePath.EndsWith("/login_success.html")) { var token = uri.Fragment.OrEmpty().TrimStart("#").Split('&') .FirstOrDefault(x => x.StartsWith("access_token="))?.TrimStart("access_token="); Succeeded.Raise(token); this.Visible(value: false); return(Task.CompletedTask); } else { return(Task.CompletedTask); } }); await Container.Add(browser); }
private YearsView(DateTime start) { MainGrid = YearsGrid.CreateInstance(start); YearTapped = new AsyncEvent <DateTime>(); MainGrid.YearTapped.Handle(date => YearTapped.Raise(date)); StartDate = start; Add(MainGrid); }
/// <summary> /// Raises the <see cref = "E:Saved"/> event. /// </summary> /// <param name = "e">The <see cref = "SaveEventArgs"/> instance containing the event data.</param> protected internal virtual async Task OnSaved(SaveEventArgs e) { InvalidateCachedReferences(); await Saved.Raise(e); await EntityManager.RaiseStaticOnSaved(e); InvalidateCachedReferences(); }
public async Task NotifyExternalLoginAuthenticated(ExternalLoginInfo info) { if (!ExternalLoginAuthenticated.IsHandled()) { throw new InvalidOperationException("ExternalLogin requested but no handler found for ExternalLoginAuthenticated event"); } await ExternalLoginAuthenticated.Raise(info); }
public async Task ToggleMenu() { if (Animating) { return; } Animating = true; IsToggling = true; if (IsExpanded) { await HideMenu(); } else { await ShowMenu(); } IsToggling = false; Animating = false; await Toggled.Raise(); }
internal async Task <bool> OnDeleting(ReplicateDataMessage message, IEntity entity) { if (!Deleting.IsHandled()) { return(true); } var args = new ReplicationDeleteMessageReceivedEventArgs(message, entity); await Deleting.Raise(args); return(!args.Cancel); }
internal async Task <bool> OnSaving(ReplicateDataMessage message, IEntity entity, SaveMode mode) { if (!Saving.IsHandled()) { return(true); } var args = new ReplicationSaveMessageReceivedEventArgs(message, entity, mode); await Saving.Raise(args); return(!args.Cancel); }
public static async Task RaiseOnValidating(IEntity record, EventArgs args) { if (record == null) { throw new ArgumentNullException(nameof(record)); } await InstanceValidating.Raise(args); await(record as Entity).OnValidating(args); }
public async Task ExceptionHandlerTest(bool shouldThrow) { int threw = 0; List <Tuple <Exception, object, EventArgs> > logged = new List <Tuple <Exception, object, EventArgs> >(); Func <object, EventArgs, Task> thrower = async(x, y) => await Task.Run(() => { threw++; throw new InvalidOperationException(); }); Func <Exception, object, EventArgs, Task <bool> > exceptionHandler = async(x, y, z) => { await Task.Run(() => { logged.Add(new Tuple <Exception, object, EventArgs>(x, y, z)); }); return(shouldThrow); }; AsyncEvent <object, EventArgs> myEvent = new AsyncEvent <object, EventArgs>(); myEvent += thrower; bool didThrow = false; int aggregateCount = 0; try { await myEvent.Raise(this, null, exceptionHandler); } catch (Exception ex) { didThrow = true; var notAggregate = ex; while (notAggregate is AggregateException) { aggregateCount++; notAggregate = notAggregate.InnerException; } Assert.True(notAggregate is InvalidOperationException); Assert.True(ex is AggregateException); } int expectedCount = shouldThrow ? 1 : 0; Assert.Equal(shouldThrow, didThrow); Assert.Equal(expectedCount, aggregateCount); Assert.Equal(1, threw); Assert.Single(logged); Assert.True(logged[0].Item1 is InvalidOperationException); Assert.True(logged[0].Item2 is AsyncEventGenericTests); Assert.Null(logged[0].Item3); }
internal void Load() { Download(); var jsonProvider = new JsonConfigurationProvider(SecretString); jsonProvider.Load(); foreach (var item in jsonProvider.GetData()) { Config[item.Key] = this[item.Key] = item.Value; } Loaded.Raise(this); }
public static async Task RaiseOnDeleting(IEntity record, CancelEventArgs args) { if (record == null) { throw new ArgumentNullException(nameof(record)); } await InstanceDeleting.Raise(args); if (args.Cancel) { return; } await(record as Entity).OnDeleting(args); }
public static async Task RaiseOnSaving(IEntity record, CancelEventArgs e) { if (record == null) { throw new ArgumentNullException(nameof(record)); } await InstanceSaving.Raise(e); if (e.Cancel) { return; } await(record as Entity).OnSaving(e); }
async Task Update() { for (var row = 0; row < 4; row++) { for (var column = 0; column < 3; column++) { var button = new Calendar.ItemButton { Text = DateTimeFormatInfo.CurrentInfo.MonthNames[(row * 3) + column], Date = new DateTime(startDate.Year, (row * 3) + column + 1, 1), Id = "Month" }; button.Tapped.HandleWith(() => MonthTapped.Raise(button.Date.Value)); await Add(button); } } }
/// <summary> /// Will try to send the specified email and returns true for successful sending. /// </summary> public static async Task <bool> Send(IEmailMessage mailItem) { if (mailItem == null) { throw new ArgumentNullException(nameof(mailItem)); } if (mailItem.Retries >= MaximumRetries) { return(false); } MailMessage mail = null; try { using (mail = await CreateMailMessage(mailItem)) { if (mail == null) { return(false); } await Sending.Raise(new EmailSendingEventArgs(mailItem, mail)); var dispatcher = Context.Current.GetOptionalService <IEmailDispatcher>() ?? new DefaultEmailDispatcher(); var result = await dispatcher.Dispatch(mailItem, mail); await Sent.Raise(new EmailSendingEventArgs(mailItem, mail)); return(result); } } catch (Exception ex) { await SendError.Raise(new EmailSendingEventArgs(mailItem, mail) { Error = ex }); await mailItem.RecordRetry(); Log.For(typeof(EmailService)) .Error(ex, $"Error in sending an email for this EmailQueueItem of '{mailItem.GetId()}'"); return(false); } }
public async Task LoggingActionTest() { int threw = 0; List <Exception> logged = new List <Exception>(); Func <object, EventArgs, Task> thrower = async(x, y) => await Task.Run(() => { threw++; throw new InvalidOperationException(); }); Func <Exception, Task> logger = async(ex) => await Task.Run(() => { logged.Add(ex); }); AsyncEvent <object, EventArgs> myEvent = new AsyncEvent <object, EventArgs>(logger); myEvent += thrower; bool didThrow = false; int aggregateCount = 0; try { await myEvent.Raise(this, null); } catch (Exception ex) { didThrow = true; var notAggregate = ex; while (notAggregate is AggregateException) { aggregateCount++; notAggregate = notAggregate.InnerException; } Assert.True(notAggregate is InvalidOperationException); Assert.Equal(logged.Single(), notAggregate); Assert.True(ex is AggregateException); // we don't log the aggregate // Assert.Equal(logged.Last(), ex); } Assert.True(didThrow); Assert.Equal(1, aggregateCount); Assert.Single(logged); Assert.Equal(threw, logged.Count); }
static async Task <bool> SendViaSmtp(IEmailQueueItem mailItem, MailMessage mail) { // Developer note: Web.config setting for SSL is designed to take priority over the specific setting of the email. // If in your application you want the email item's setting to take priority, do this: // 1. Remove the 'Email->Enable.Ssl' setting from appsettings.json totally. // 2. If you need a default value, use your application's Global Settings object and use that value everywhere you create an EmailQueueItem. using (var smtpClient = new SmtpClient { EnableSsl = Config.Get("Email:Enable.Ssl", mailItem.EnableSsl) }) { smtpClient.Configure(); if (mailItem.SmtpHost.HasValue()) { smtpClient.Host = mailItem.SmtpHost; } if (mailItem.SmtpPort.HasValue) { smtpClient.Port = mailItem.SmtpPort.Value; } if (mailItem.Username.HasValue()) { smtpClient.Credentials = new NetworkCredential(mailItem.Username, mailItem.Password.Or((smtpClient.Credentials as NetworkCredential).Get(c => c.Password))); } if (Config.IsDefined("Email:Random.Usernames")) { var userName = Config.Get("Email:Random.Usernames").Split(',').Trim().PickRandom(); smtpClient.Credentials = new NetworkCredential(userName, Config.Get("Email:Password")); } await Sending.Raise(new EmailSendingEventArgs(mailItem, mail)); await smtpClient.SendMailAsync(mail); await Sent.Raise(new EmailSendingEventArgs(mailItem, mail)); } return(true); }
async Task Update() { YearButtons.Clear(); for (var row = 0; row < YearRows; row++) { for (var column = 0; column < YearColumns; column++) { var temp = (row * YearColumns) + column + 1; var button = new Calendar.ItemButton { Text = $"{startDate.Year + (temp - (YearColumns * YearRows / 2))}", Date = new DateTime(startDate.Year + (temp - (YearColumns * YearRows / 2)), startDate.Month, 1), Id = "Year" }; button.Tapped.HandleWith(() => YearTapped.Raise(button.Date.Value)); YearButtons.Add(button); await Add(button); } } }
public virtual async Task RecordDelete(IEntity entity) { if (!LogEventsAttribute.ShouldLog(entity.GetType())) { return; } var eventInfo = CreateApplicationEvent(); if (eventInfo == null) { return; } eventInfo.ItemType = entity.GetType().FullName; eventInfo.ItemKey = entity.GetId().ToString(); eventInfo.Event = "Delete"; eventInfo.IP = GetCurrentUserIP(); eventInfo.UserId = GetCurrentUserId(); var changes = Entity.Database.GetProvider(entity.GetType()).GetUpdatedValues(entity, null); eventInfo.Data = ToChangeXml(changes); if (OnRecordingDelete.IsHandled()) { var args = new AuditDeleteEventArgs { ApplicationEvent = eventInfo, Entity = entity }; await OnRecordingDelete.Raise(args); if (args.Cancel) { return; } } await Save(eventInfo); ProcessContext <UndoContext> .Current.Perform(c => c.Append(eventInfo, entity)); }
/// <summary> /// Sends the specified SMS item. /// It will try several times to deliver the message. The number of retries can be specified in AppConfig of "SMS:MaximumRetries". /// If it is not declared in web.config, then 3 retires will be used. /// Note: The actual SMS Sender component must be implemented as a public type that implements ISMSSender interface. /// The assembly qualified name of that component, must be specified in AppConfig of "SMS:SenderType". /// </summary> public static async Task <bool> Send(ISmsQueueItem smsItem) { if (smsItem.Retries > Config.Get("SMS:MaximumRetries", 3)) { return(false); } try { ISMSSender sender; try { sender = Activator.CreateInstance(Type.GetType(Config.GetOrThrow("SMS:SenderType"))) as ISMSSender; if (sender == null) { throw new Exception("Type is not defined, or it does not implement ISMSSender"); } } catch (Exception ex) { Log.For(typeof(SmsService)).Error(ex, "Can not instantiate the sms sender from App config of " + Config.Get("SMS:SenderType")); return(false); } sender.Deliver(smsItem); await Database.Update(smsItem, o => o.DateSent = LocalTime.Now); return(true); } catch (Exception ex) { await SendError.Raise(new SmsSendingEventArgs(smsItem) { Error = ex }); Log.For(typeof(SmsService)).Error(ex, "Can not send the SMS queue item."); await smsItem.RecordRetry(); return(false); } }
static async void RequestTokenHandler(SDK.LoginKit.LoginManagerLoginResult result, NSError error) { if (error != null) { Log.For(typeof(Facebook)).Error("An error occurred in Facebook :[" + error + "]"); await OnError.Raise(error.ToString()); } else if (result?.IsCancelled ?? true) { await OnCancel.Raise(); } else { try { var er = result.ToString(); var accessToken = result.Token; if (accessToken.IsExpired) { accessToken = await RefreshAccessToken(); } CurrentAccessToken = new AccessToken { TokenString = accessToken.TokenString, AppId = accessToken.AppId, UserId = accessToken.UserId }; var param = NSDictionary.FromObjectAndKey(CurrentParameters.ToString(",").ToNs(), "fields".ToNs()); var request = new SDK.CoreKit.GraphRequest("me", param, accessToken.TokenString, null, "GET"); request.Start(new SDK.CoreKit.GraphRequestBlockHandler(GraphCallback)); } catch (Exception e) { Log.For(typeof(Facebook)).Error(e); throw; } } }
static async Task <Tuple <bool, string> > TryTranslateUsingTheEvent(string phraseInDefaultLanguage, ILanguage language) { if (TranslationRequested.IsHandled()) { var args = new TranslationRequestedEventArgs { PhraseInDefaultLanguage = phraseInDefaultLanguage, Language = language }; await TranslationRequested.Raise(args); if (args.Cancel) { return(Tuple.Create(true, phraseInDefaultLanguage)); } if (args.TranslationProvider != null) { return(Tuple.Create(true, args.TranslationProvider())); } } return(Tuple.Create(false, default(string))); }
void Authenticator_Completed(object sender, AuthenticatorCompletedEventArgs e) { AuthCompleted.Raise(new AuthCompletedEventArgs { Account = (OAuthAccount)e.Account, IsAuthenticated = e.IsAuthenticated }); }