private void ConfigureAndDisplayMainView() { //Cache the ApplicationShell export as the MainWindow this.MainWindow = Container.RetrieveExportedValue <Window>("ApplicationShell"); //Finish configuring MainWindow and show this.MainWindow.DataContext = this.PosApplication.ApplicationViewModel; ChangeShutdownMode(Current); Current.MainWindow = MainWindow; //Perform authentication MainWindow.Loaded += (sender, e) => { if (this.SplashScreen != null) { this.SplashScreen.Close(); } }; MainWindow.Show(); var beforeMainViewLoadMessage = new PosBeforeMainViewLoadEventData(PosApplication, Current); MessagingService.SendPosEventMessage(beforeMainViewLoadMessage); SystemEvents.DisplaySettingsChanged += FixWin8SizeChanged; if (beforeMainViewLoadMessage.PreventSignIn) { return; } PosApplication.CommandService.ExecuteCommand(CorePosCommands.ShowSignInViewCommand); }
public async Task <IHttpActionResult> PutMessage(int id, Message message) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != message.Id) { return(BadRequest()); } try { await MessagingService.UpdateMessage(message); } catch (InvalidOperationException) { if (!MessageExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public Fixture() { this.Message = new TestMessage() { Id = Guid.NewGuid(), Description = "Test Message Text", Name = "Test Message Name", MessageDate = DateTime.UtcNow, }; string messageBody = JsonConvert.SerializeObject(this.Message); this.MessageBytes = Encoding.UTF8.GetBytes(messageBody); this.Outbox = new Outbox <ApplicationDbContext>(new OutboxSettings() { BatchSize = 5, MaxConcurrency = 1, MaxTries = 3, SqlConnectionString = ConnectionString, DisableTransientDispatch = true, RetryStrategy = new ConstantRetryStrategy(0.5) }); var handlerFactory = A.Fake <IServiceFactory>(); this.MessagingService = new MessagingService(this.Outbox, handlerFactory); }
void OnTouchReleased(TouchEndEventArgs eventArgs) { currentScreenLayout.OnTouchReleased(Input, eventArgs); // Return if this is not our original tap finger if (eventArgs.TouchID != tapTouchID) { return; } // Get delta time float dt = Time.ElapsedTime - tapTimeStamp; // If it is lesser than our tap margin, it is a tap! if (dt < tapTimeMargin) { // Notify CameraPageViewModel of a tap. This is used to hide // the settings drawer MessagingService.Send(this, MessageSubject.URHO_SURFACE_TAPPED); // Are we in grid mode? Test for camera selection if (currentScreenLayout.GetType() == typeof(GridScreenLayout)) { CastTouchRay(eventArgs.X, eventArgs.Y); } } }
public void Should_send_message() { //Arrange var basicProperties = _basicProperties.Object; _model.Setup(x => x.CreateBasicProperties()) .Returns(basicProperties); var model = _model.Object; _connection.Setup(x => x.CreateModel()) .Returns(model); var queue = "test"; _queueSettingsService.SetupGet(x => x.Queue) .Returns(queue); var messageBody = Encoding.UTF8.GetBytes("test"); var Sut = new MessagingService(_connection.Object, _queueSettingsService.Object); //Act Sut.SendMessage(messageBody); //Assert _model.Verify(x => x.QueueDeclare(queue, It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >())); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser() { UserName = model.UserName, Region = model.Region }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var request = new UserRequest() { UserName = user.UserName }; var message = MessagingService.CreateSaveUserMessage(request, user.Region); var messagingService = new MessagingService(); messagingService.Send(message); await SignInAsync(user, isPersistent : false); return(RedirectToAction("Index", "Home")); } else { AddErrors(result); } } // If we got this far, something failed, redisplay form return(View(model)); }
public override void OnCreate() { base.OnCreate(); // Optionally, initialize the intercepting service (ViewPump) before initializing the messaging service. // Useful for if you're using ViewPump for other purposes (for example: providing a custom IInterceptingService). //InterceptingService.Init(); // Initialize the messaging service, passing in the current Application context. // Overflow initializer methods are available for more advanced use cases. MessagingService.Init(this); // Provide the messaging service with a custom messaging delegate. // This allows us to be notified when specific dialogs are requested meaning that we can alter // the configuration, or even deny the dialog showing. MessagingService.Delegate = new MessagingDelegate(); // Assign defaults to certain dialogs, as we would like these to be persistant throughout. // These values can be overwritten, and will already have been applied to the dialog configuration // object by the time it reaches the messaging delegate. AlertConfigDefaults.Cancelable = true; AlertConfigDefaults.LayoutResID = Resource.Layout.dialog_alert; AlertConfigDefaults.StyleResID = Resource.Style.AppTheme_Dialog_Alert; SnackbarConfigDefaults.ActionButtonTextColor = Color.White; SnackbarConfigDefaults.Duration = Snackbar.LengthLong; SnackbarConfigDefaults.MessageTextColor = Color.White; }
public void EnqueueTenTimesTest() { var deviceId = MessagingService.Initialize(Identity.Next()); for (int i = 1; i <= 10; i++) { MessagingService.Enqueue(new EnqueueMessagesDto { Messages = new List <EnqueueMessageDto> { new EnqueueMessageDto { DeviceId = deviceId, Payload = Encoding.UTF8.GetBytes("Message no. " + i), TimeStamp = DateTime.UtcNow, SenderDeviceId = Identity.Next() } } }); } var deviceEntry = DeviceEntryRegistry.Instance.Get(deviceId); Assert.AreEqual(0, deviceEntry.DequeueIndex); Assert.AreEqual(10, deviceEntry.EnqueueIndex); Assert.AreEqual(10, deviceEntry.Version); }
public static void Main(string[] args) { Console.WriteLine("Listening for new messages..."); var messageingService = new MessagingService(); using (var context = new CheckoutContext()) { context.Database.EnsureCreated(); messageingService.ActivateMessageListener(ConfigurationDefaults.RABBITMQ_HOST, ConfigurationDefaults.RABBITMQ_EXCHANGENAME, (nav) => { var navObject = JsonConvert.DeserializeObject <Navigation>(nav); context.Navigations.Add(navObject); context.SaveChanges(); Console.WriteLine($"MSG: {navObject.ToString()}"); }); while (Console.Read() != 13) { } messageingService.DeactivateMessageListener(); } }
public Fixture() { this.Message = new TestMessage() { Id = Guid.NewGuid(), Description = "Test Message Text", Name = "Test Message Name", MessageDate = DateTime.UtcNow, }; this.MessageMetaData = new MessageMetaData(delay: TimeSpan.FromSeconds(10), correlationId: this.Message.Id.ToString(), messageId: this.Message.Id.ToString(), skipTransient: true); string messageBody = JsonConvert.SerializeObject(this.Message); this.SerializedMessageMetaData = this.MessageMetaData != null?JsonConvert.SerializeObject(this.MessageMetaData) : null; this.MessageBytes = Encoding.UTF8.GetBytes(messageBody); this.Outbox = new Outbox <ApplicationDbContext>(new OutboxSettings() { BatchSize = 10, MaxConcurrency = 1, MaxTries = 10, SqlConnectionString = ConnectionString, DisableTransientDispatch = false, }); var handlerFactory = A.Fake <IServiceFactory>(); this.MessagingService = new MessagingService(this.Outbox, handlerFactory); }
public HttpResponseMessage CancelShift(Guid Id, ShiftChangeActionDTO shiftCancelDTO) { var shift = db.Shifts.Find(Id); if (shift == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Shift not found")); } //Only the staff member assigned to the shift can request to cancel the shift if (ClaimsAuthorization.CheckAccess("Get", "BusinessId", shift.Roster.BusinessLocation.Business.Id.ToString()) || shift.Employee.UserProfile.Email != User.Identity.Name) { if (shiftCancelDTO.Reason == String.Empty) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Reason cannot be blank")); } //Check to see if there is already a pending cancellation request var shiftCancelRequest = db.ShiftChangeRequests.Where(sc => sc.Type == ShiftRequestType.Cancel && sc.Shift.Id == Id && sc.Status == RequestStatus.Pending); if (shiftCancelRequest.Count() > 0) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Existing cancellation request already for shift id:" + Id.ToString())); } ShiftChangeRequest shiftChangeRequest = new ShiftChangeRequest { Id = Guid.NewGuid(), Reason = shiftCancelDTO.Reason, Shift = shift, Type = ShiftRequestType.Cancel, Status = RequestStatus.Pending, CreatedDate = WebUI.Common.Common.DateTimeNowLocal(), CreatedBy = shift.Employee }; //Get all managers for this busiess location var managers = db.Employees.Where(m => m.IsAdmin == true && m.BusinessLocation.Id == shift.Roster.BusinessLocation.Id); foreach (var mgr in managers) { if (mgr.UserProfile != null) { //Send notifications to managers of the affected business location information that the employee has requested to cancel a shift MessagingService.ShiftCancelRequest(mgr.UserProfile.Email, mgr.UserProfile.FirstName, shift.Employee.UserProfile.FirstName + ' ' + shift.Employee.UserProfile.LastName, shift.InternalLocation.BusinessLocation.Name, shift.StartTime, shift.FinishTime); } } db.ShiftChangeRequests.Add(shiftChangeRequest); db.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.Created, shiftChangeRequest.Id)); } else { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized)); } }
public async Task GetChannelOwner_ChannelOwner_RetrievedChannelOwner(int ChannelId, int UserId, int OwnerId, string ChannelName, int NewUserId) { ChannelModel model = new ChannelModel(); model.OwnerId = OwnerId; model.Name = ChannelName; IDataGateway dataGateway = new SQLServerGateway(); IConnectionStringData connectionString = new ConnectionStringData(); IMessagesRepo messagesRepo = new MessagesRepo(dataGateway, connectionString); IChannelsRepo channelsRepo = new ChannelsRepo(dataGateway, connectionString); IUserAccountRepository userAccountRepository = new UserAccountRepository(dataGateway, connectionString); IUserChannelsRepo userChannelsRepo = new UserChannelsRepo(dataGateway, connectionString); IMessagingService messagingService = new MessagingService(messagesRepo, channelsRepo, userChannelsRepo, userAccountRepository); await messagingService.CreateChannelAsync(model); try { int ownerId = await messagingService.GetChannelOwnerAsync(ChannelId); if (ownerId == 1) { Assert.IsTrue(true); } else { Assert.IsTrue(false); } } catch { Assert.IsTrue(false); } }
public void TestInitialize() { mockSerialiser = new Mock<ISerialiser>(); mockRestClient = new Mock<IRestClient>(); service = new MessagingService(mockRestClient.Object, mockSerialiser.Object, false); }
public void Refer(string refName, string refEmail) { var firstName = ClaimsHelper.GetClaimValue(WebUI.Common.Common.GetToken(System.Web.HttpContext.Current), Constants.ClaimFirstName); var lastName = ClaimsHelper.GetClaimValue(WebUI.Common.Common.GetToken(System.Web.HttpContext.Current), Constants.ClaimLastName); MessagingService.Referral(refEmail, refName, firstName + " " + lastName); }
public void TryEnqueueSameDeviceTest() { var deviceId = MessagingService.Initialize(Identity.Next()); MessagingService.Enqueue(new EnqueueMessagesDto { Messages = new List <EnqueueMessageDto> { new EnqueueMessageDto { DeviceId = deviceId, Payload = Encoding.UTF8.GetBytes("Message no. 1"), TimeStamp = DateTime.UtcNow, SenderDeviceId = Identity.Next() }, new EnqueueMessageDto { DeviceId = deviceId, Payload = Encoding.UTF8.GetBytes("Message no. 2"), TimeStamp = DateTime.UtcNow, SenderDeviceId = Identity.Next() } } }); }
/// <summary> /// Handles refreshing after adding. /// </summary> void HandleContributionAddMessage(MessagingService obj, Contribution contribution) { State = LayoutState.Loading; Contributions.Add(contribution); Contributions = new ObservableCollection <Contribution>(Contributions.OrderByDescending(x => x.StartDate).ToList()); State = LayoutState.None; }
public void EnqueueOneTest() { var deviceId = MessagingService.Initialize(Identity.Next()); var result = MessagingService.Enqueue(new EnqueueMessagesDto { Messages = new List <EnqueueMessageDto> { new EnqueueMessageDto { DeviceId = deviceId, Payload = Encoding.UTF8.GetBytes("Message no. 1"), TimeStamp = DateTime.UtcNow, SenderDeviceId = Identity.Next() } } }); Assert.AreEqual(1, result.DeviceIds.Count); Assert.AreEqual(deviceId, result.DeviceIds[0]); var deviceEntry = DeviceEntryRegistry.Instance.Get(deviceId); Assert.AreEqual(deviceId, deviceEntry.Id); Assert.AreEqual(0, deviceEntry.DequeueIndex); Assert.AreEqual(1, deviceEntry.EnqueueIndex); Assert.AreEqual(1, deviceEntry.Version); }
public async Task <IHttpActionResult> PutUser(string id, User user) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != user.Username) { return(BadRequest()); } if (!UserExists(id)) { return(NotFound()); } try { await MessagingService.UpdateUser(user); } catch (Exception) { return(InternalServerError()); } return(StatusCode(HttpStatusCode.NoContent)); }
public AccountController( IHostingEnvironment environment, IIdentityServerInteractionService interaction, UserManager userManager, SignInManager signInManager, MessagingService messagingService, ILoggerFactory loggerFactory, ICypher cypher, IHttpContextAccessor httpContextAccessor, AegisTenantResolver aegisTenantResolver, DirectoryManager directoryManager ) { _logger = loggerFactory.CreateLogger <AccountController>(); _environment = environment; _interaction = interaction; _userManager = userManager; _signInManager = signInManager; _messaging = messagingService; _cypher = cypher; _httpContextAccessor = httpContextAccessor; _aegisTenantResolver = aegisTenantResolver; _directoryManager = directoryManager; }
public async Task <IActionResult> PostAds([FromForm] int userId, [FromForm] string ads) { var postedAds = JsonConvert.DeserializeObject <List <Ad> >(ads); var addedList = new List <AdModel>(); foreach (var item in postedAds) { var result = await _dbContext .Ads .Where(ad => ad.ProviderAdId == item.ProviderAdId && ad.OwnerId == item.OwnerId && ad.AdSource == item.AdSource) .FirstOrDefaultAsync(); if (result is null) { _dbContext.Ads.Add(item); addedList.Add((AdModel)item); } } var user = await _dbContext.Users.FindAsync(userId); if (addedList.Count == 0) { return(Ok()); } var task = MessagingService.SendPushNotificationWithData($"({addedList.Count()}) нових авто.", "", new Random().Next(1, 9999999), user.MobileAppToken, _firebaseServerApiKey); _dbContext.SaveChanges(); await Task.WhenAll(task); return(Ok()); }
public void Initialize() { var persistentStorage = PoorMansContainerResolver(); _messageCache = new MessageCache(); MessagingService = new MessagingService(_messageCache, persistentStorage); }
public void DeclareExchangeFailWithEmptyName() { var messagingService = new MessagingService(); Assert.Throws <ArgumentNullException>(() => messagingService.DeclareExchange(null)); Assert.Throws <ArgumentNullException>(() => messagingService.DeclareExchange(" ")); }
public void TestInitialize() { mockSerialiser = new Mock <ISerialiser>(); mockRestClient = new Mock <IRestClient>(); service = new MessagingService(mockRestClient.Object, mockSerialiser.Object, false); }
public void CommitOutgoingMessageRealTest() { var environmentFactory = EnvironmentFactoryFactory.Create(); MessagingWorkers.Start(new TestBatchParameters(), environmentFactory.MessagingEnvironment.MessagingServiceClient); var pltDeviceOperations = environmentFactory.ManagementEnvironment.ObjDeviceOperations; var messagingService = new MessagingService(new MessagingOperations(), pltDeviceOperations); messagingService.RecordOutgoingMessage(_deviceId, _deviceId, "32412341243"); var msg = messagingService.Peek(_deviceId); Assert.AreEqual(OutgoingState.Ok, msg.State); Assert.AreEqual(_deviceId, msg.Message.DeviceId); Assert.AreEqual("32412341243", msg.Message.Payload); Assert.AreEqual(_deviceId, msg.Message.SenderDeviceId); var state = messagingService.Commit(_deviceId); Assert.AreEqual(OutgoingState.Ok, state); var state2 = messagingService.Commit(_deviceId); Assert.AreEqual(OutgoingState.Ok, state2); MessagingWorkers.Stop(); }
//// DELETE api/shiftapi/5 public HttpResponseMessage Delete(Guid id) { var shift = db.Shifts.Find(id); if (shift == null) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } //If published, send notification to staff member to tell them shift is cancelled if (shift.IsPublished && shift.Employee != null && shift.Employee.UserProfile != null) { MessagingService.ShiftCancelled(shift.Employee.UserProfile.Email, shift.Employee.UserProfile.FirstName, shift.InternalLocation.BusinessLocation.Name, shift.StartTime, shift.FinishTime); } db.ShiftChangeRequests.RemoveRange(shift.ShiftChangeRequests); db.Shifts.Remove(shift); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex)); } return(Request.CreateResponse(HttpStatusCode.OK)); }
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { Logger.Log.Error("Unhandled exception", e.Exception); MessagingService.ShowErrorMessage(Common.Resources.Strings.Resources.UnhandledException, e.Exception.ToString(), false); e.Handled = true; }
public void PeekTwiceOutgoingMessageTest() { var messagingOperations = Substitute.For <IMessagingOperations>(); var pltDeviceOperations = Substitute.For <IDeviceOperations>(); pltDeviceOperations.Get("1234").Returns(TestDataCreator.Device("1234", "1234", "12345", "123456", "1234567", 1)); messagingOperations.Peek(1) .Returns(new OutgoingMessageToStoreWithState(new OutgoingMessageToStore(1, new byte[] { 48, 49, 50 }, 1, DateTime.UtcNow, "sender"), OutgoingState.Ok)); var messagingService = new MessagingService(messagingOperations, pltDeviceOperations); var msg = messagingService.Peek("1234"); Assert.IsNotNull(msg); Assert.AreEqual(OutgoingState.Ok, msg.State); Assert.AreEqual("1234", msg.Message.DeviceId); Assert.AreEqual("012", msg.Message.Payload); Assert.AreEqual("sender", msg.Message.SenderDeviceId); msg = messagingService.Peek("1234"); Assert.IsNotNull(msg); Assert.AreEqual(OutgoingState.Ok, msg.State); Assert.AreEqual("1234", msg.Message.DeviceId); Assert.AreEqual("012", msg.Message.Payload); Assert.AreEqual("sender", msg.Message.SenderDeviceId); }
public void PeekKickCacheTest() { var deviceId = MessagingService.Initialize(Identity.Next()); string senderDeviceId = Identity.Next(); MessagingService.Enqueue(new EnqueueMessagesDto { Messages = new List <EnqueueMessageDto> { new EnqueueMessageDto { DeviceId = deviceId, Payload = Encoding.UTF8.GetBytes("Message no. 1"), TimeStamp = DateTime.UtcNow, SenderDeviceId = senderDeviceId } } }); RemoveCacheItem(deviceId, 0); var result = MessagingService.Peek(new DeviceListDto { DeviceIds = new List <long> { deviceId } }); Assert.AreEqual(1, result.Messages.Count); Assert.AreEqual(deviceId, result.Messages[0].DeviceId); Assert.IsTrue(Encoding.UTF8.GetBytes("Message no. 1").SequenceEqual(result.Messages[0].Payload)); Assert.AreEqual(senderDeviceId, result.Messages[0].SenderDeviceId); }
public App() { //Required designer call this.InitializeComponent(); Current.ShutdownMode = ShutdownMode.OnExplicitShutdown; //RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly; //Wire-up additional exception handling this.Dispatcher.UnhandledException += ((sender, e) => { if ((e != null) && (e.Exception != null)) { //Log the exception MessagingService?.SendLogMessage("Unhandled exception", e.Exception.ToString(), CloudRetailerTraceLevel.Critical); var isCritical = IsCritical(e.Exception); var message = isCritical ? "Unexpected critical exception occurred: " + e.Exception.Message + ". The application will now close." : "Unexpected exception occurred: " + e.Exception.Message + ". \n<b>If you experience further problems, please restart the application and contact system administrator.</b>"; if (!e.Exception.Message.Contains("DependencySource")) { PromptUser(message); } if (!isCritical) { e.Handled = true; } } }); }
public void SendToSuccessTest() { var connection = Substitute.For <IPersistentConnection>(); var deviceAuthenticator = Substitute.For <IDeviceAuthenticator>(); var deviceOperations = Substitute.For <IDeviceOperations>(); var dateTimeProvider = Substitute.For <IDateTimeProvider>(); var messagingOperations = Substitute.For <IMessagingOperations>(); dateTimeProvider.UtcNow.Returns(DateTime.UtcNow); var pusherRegistry = new PusherRegistry(dateTimeProvider); var connectionRegistry = new ConnectionRegistry(pusherRegistry, null); var deviceId = Identity.Next(); connection.ConnectionId.Returns(Guid.NewGuid()); deviceAuthenticator.Authenticate(null).ReturnsForAnyArgs(true); deviceOperations.Get(null).ReturnsForAnyArgs(TestDataCreator.Device(deviceId, "1234", "2345", "3456", "4567", 1)); connectionRegistry.RegisterInitiatedConnection(connection); var msgService = new MessagingService(messagingOperations, deviceOperations); var commandExecutor = new CommandExecutor(pusherRegistry, connectionRegistry, null, deviceAuthenticator, deviceOperations, msgService, null); commandExecutor.Execute(connection, new LoginCommand(deviceId + " " + Identity.Next())); dateTimeProvider.UtcNow.Returns(DateTime.UtcNow); commandExecutor.Execute(connection, new SendToCommand("{\"Temperature\": 24, \"Time\":" + DateTime.UtcNow.Ticks + "}")); connection.Received(1).Reply("sendto ack"); }
public static IMessagingService GetMessagingServiceInstance() { if (null == _messagingServiceInstance) { lock (_syncObject) { if (null == _messagingServiceInstance) { _messagingServiceInstance = new MessagingService(); } } } return _messagingServiceInstance; }
public void DefaultConstructor() { // Arrange bool ensureMessageIdsInResult = false; EsendexCredentials credentials = new EsendexCredentials("username", "password"); // Act MessagingService serviceInstance = new MessagingService(ensureMessageIdsInResult, credentials); // Assert Assert.That(serviceInstance.RestClient, Is.InstanceOf<RestClient>()); Assert.That(serviceInstance.Serialiser, Is.InstanceOf<XmlSerialiser>()); Assert.IsFalse(serviceInstance.EnsureMessageIdsInResult); }
public ActionResult Send(string toScreenName, string message) { var success = new MessagingService(Token).SendDirectMessage(toScreenName, message); if (success) { Flash("Direct Message sent to " + toScreenName); } else { Flash("Unable to send direct message to " + toScreenName); } return RedirectToAction("Sent"); }
public OperationResult Post(GenerateSantaResource generate) { var contacts = _provider.Get<Contact>(); var restrictions = _provider.Get<Restriction>(); bool finished = false; while (!finished) { try { var result = _generator.GenerateSantaList(contacts.ToList(), restrictions.ToList()); finished = true; var appDir = AppDomain.CurrentDomain.BaseDirectory; var appDataDir = "App_Data"; var stamp = DateTime.UtcNow.Ticks; var filenameEncoded = string.Format("encoded_{0}_at_{1}.txt",result.Id, stamp); var filenameDecoded = string.Format("decoded_{0}_at_{1}.txt", result.Id, stamp); var encodedFile = Path.Combine(appDir,appDataDir, filenameEncoded); var decodedFile = Path.Combine(appDir, appDataDir, filenameDecoded); SaveDecodedResultTo(decodedFile, result); SaveEncodedResultTo(encodedFile, result); if (generate.SendRealMessages) { var creds = new EsendexCredentials(generate.Username, generate.Password); var messagingService = new MessagingService(true, creds); var texter = new Texter(messagingService); texter.SendMessagesToSantas(result.SantaEntries, generate.Template, generate.Originator, generate.Account); } return new OperationResult.SeeOther { RedirectLocation = typeof(SantaList).CreateUri() }; } catch(Exception ex) { Console.WriteLine("Error creating, trying again...{0}", ex); } } return new OperationResult.InternalServerError(); }
/// <summary> /// Inicializa una nueva instancia de la clase <see cref="MainPage"/> /// </summary> public MainPage() { InitializeComponent(); #if WINDOWS_PHONE_APP var statusBar = StatusBar.GetForCurrentView(); statusBar.BackgroundColor = (Color)Application.Current.Resources["BrandColor"]; statusBar.BackgroundOpacity = 1; statusBar.ForegroundColor = (Color)Application.Current.Resources["BrandForegroundColor"]; var ignoreResult = statusBar.ShowAsync(); var progressIndicator = statusBar.ProgressIndicator; progressIndicator.Text = "SUDOKU"; progressIndicator.ProgressValue = 0; ignoreResult = progressIndicator.ShowAsync(); #endif messagingService = (Application.Current.Resources["Locator"] as ServiceLocator).MessagingService; }
public void DefaultDIConstructor() { // Arrange Uri uri = new Uri("http://tempuri.org"); EsendexCredentials credentials = new EsendexCredentials("username", "password"); IHttpRequestHelper httpRequestHelper = new HttpRequestHelper(); IHttpResponseHelper httpResponseHelper = new HttpResponseHelper(); IHttpClient httpClient = new HttpClient(credentials, uri, httpRequestHelper, httpResponseHelper); IRestClient restClient = new RestClient(httpClient); ISerialiser serialiser = new XmlSerialiser(); // Act MessagingService serviceInstance = new MessagingService(restClient, serialiser, true); // Assert Assert.That(serviceInstance.RestClient, Is.InstanceOf<RestClient>()); Assert.That(serviceInstance.Serialiser, Is.InstanceOf<XmlSerialiser>()); Assert.IsTrue(serviceInstance.EnsureMessageIdsInResult); }
/// <summary> /// Inicializa una nueva instancia de la clase <see cref="MainViewModel"/> /// </summary> /// <param name="navigationService">El servicio de navegación</param> /// <param name="sudokuService">El servicio de la API REST de Sudokus</param> /// <param name="messagingService">El servicio de mensajería</param> public MainViewModel( INavigationService navigationService, SudokuService sudokuService, MessagingService messagingService) { this.navigationService = navigationService; this.sudokuService = sudokuService; this.messagingService = messagingService; NewGameCommand = new RelayCommand(NewGame, () => PlayingGame && !Thinking); PlayGameCommand = new RelayCommand(PlayGame, () => !PlayingGame && !Thinking); VerifyValidGameCommand = new RelayCommand(VerifyValidGame, () => PlayingGame && !Thinking); ShowHelpCommand = new RelayCommand(ShowHelp); cells = new Cell[9][]; for (int row = 0; row < 9; row++) { cells[row] = new Cell[9]; for (int column = 0; column < 9; column++) { cells[row][column] = new Cell(); } } }
public ActionResult GetRecievedMessages(int? page) { var service = new MessagingService(Token); return StandardJsonResult(service, s => s.GetInbox(page)); }
public ActionResult GetSentMessages(int? page) { var service = new MessagingService(Token); return StandardJsonResult(service, s => s.GetSent(page)); }
private static void SendMessageExample(EsendexCredentials credentials) { var message = new SmsMessage(_sendTo, "This is a test message from the .Net SDK...", _accountReference); var messagingService = new MessagingService(true, credentials); try { var messageResult = messagingService.SendMessage(message); Console.WriteLine("\tMessage Batch Id: {0}", messageResult.BatchId); foreach (var messageId in messageResult.MessageIds) { Console.WriteLine("\t\tMessage Uri: {0}", messageId.Uri); } } catch (WebException ex) { Console.Write(ex.Message); } }
public void TestInitialize() { mocks = new MockFactory(MockBehavior.Strict); mockSerialiser = mocks.Create<ISerialiser>(); mockRestClient = mocks.Create<IRestClient>(); service = new MessagingService(mockRestClient.Object, mockSerialiser.Object, false); }
protected SupportRequestsNotificationScheduledTask( InitializationConfiguration configuration, Func <Task <SqlConnection> > openSupportRequestSqlConnectionAsync, ILoggerFactory loggerFactory) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } var serializer = new ServiceBusMessageSerializer(); var topicClient = new TopicClientWrapper(configuration.EmailPublisherConnectionString, configuration.EmailPublisherTopicName); var enqueuer = new EmailMessageEnqueuer(topicClient, serializer, loggerFactory.CreateLogger <EmailMessageEnqueuer>()); var messageService = new AsynchronousEmailMessageService( enqueuer, loggerFactory.CreateLogger <AsynchronousEmailMessageService>(), configuration); _messagingService = new MessagingService(messageService, loggerFactory.CreateLogger <MessagingService>()); _supportRequestRepository = new SupportRequestRepository(loggerFactory, openSupportRequestSqlConnectionAsync); }
private static void SendMessageExample() { SmsMessage message = new SmsMessage("07000000000", "This is a test...", accountReference); MessagingService messagingService = new MessagingService(true, Credentials); try { MessagingResult messageResult = messagingService.SendMessage(message); Console.WriteLine("Message Batch Id: {0}", messageResult.BatchId); foreach (ResourceLink messageId in messageResult.MessageIds) { Console.WriteLine("Message Uri: {0}", messageId.Uri); } } catch (WebException ex) { Console.Write(ex.Message); } }