public async Task <int> addAsync(SubscriberModel subsciberModel, float height) { try { var exists = await _context.Subscribers.FirstOrDefaultAsync(s => s.email == subsciberModel.email); if (exists == null) { //SubscriberEntity newSunscriber = _mapper.Map<SubscriberEntity>(subsciber); //await _weightWatchersContext.AddAsync(newSunscriber); subsciberModel.id = Guid.NewGuid(); Subscriber s = _mapper.Map <Subscriber>(subsciberModel); await _context.Subscribers.AddAsync(s); await _context.Cards.AddAsync(new Card() { BMI = 0, subscriberId = subsciberModel.id, height = height, openDate = DateTime.Today }); return(await _context.SaveChangesAsync()); } } catch (Exception e) { throw new Exception("register failed"); } return(-1); }
public ActionOutput SubmitSubscriberEmail(SubscriberModel SubscriberModel) { var existingSubscriber = Context.Subscribers.Where(z => z.IsDeleted == false && z.EmailID == SubscriberModel.EmailID).FirstOrDefault(); if (existingSubscriber != null) { return(new ActionOutput { Status = ActionStatus.Error, Message = "This Subscriber email already exists and is also not marked as deleted." }); } else { var Subscriber = Context.Subscribers.Create(); Subscriber.AddedOn = DateTime.UtcNow; Subscriber.IsDeleted = false; Subscriber.EmailID = SubscriberModel.EmailID; Context.Subscribers.Add(Subscriber); Context.SaveChanges(); MailChimpService.AddOrUpdateListMember(subscriberEmail: SubscriberModel.EmailID, listId: System.Configuration.ConfigurationManager.AppSettings["SubListId"]); return(new ActionOutput { Status = ActionStatus.Successfull, Message = "Subscriber Details Added Successfully." }); } }
public async Task <IActionResult> UpdateSubscriber([FromBody] SubscriberModel subscriberModel) { try { //Получаем пользователя var user = GetUser(); var subscriber = _context.Subscribers.FirstOrDefault(s => s.Id == subscriberModel.Id); if (subscriber != null) { subscriber.Address = subscriberModel.Address; subscriber.FIOHead = subscriberModel.FIOHead; subscriber.FullName = subscriberModel.FullName; subscriber.INN = subscriberModel.INN; subscriber.Phones = subscriberModel.Phones; subscriber.RepresentativePhones = subscriberModel.RepresentativePhones; subscriber.ShortName = subscriberModel.ShortName; subscriber.SubscriberRepresentative = subscriberModel.SubscriberRepresentative; _context.Entry(subscriber).State = Microsoft.EntityFrameworkCore.EntityState.Modified; await _context.SaveChangesAsync(); _log.LogInformation($"Обновление абонента с идентификатором {subscriberModel.Id}"); return(Ok()); } return(BadRequest(new JsonResult("Запись с абонентом не найдена"))); } catch (Exception ex) { _log.LogInformation($"Ошибка при обновлении абонента с идентификатором {subscriberModel.Id}: {ex.Message}"); return(BadRequest(new { message = ex.Message })); } }
public ActionResult Edit(int?id) { if (!id.HasValue) { return(RedirectToAction("List")); } var subscriber = subscriberService.GetById(id.Value); if (subscriber == null) { this.NotifyError("Item not found."); return(RedirectToAction("List")); } var model = new SubscriberModel { Id = subscriber.Id, IsActive = subscriber.IsActive, FullName = subscriber.FullName, Email = subscriber.Email, SubscribeDate = subscriber.SubscribeDateUtc, UnsubscribeDate = subscriber.UnSubscribeDateUtc }; return(View(model)); }
public ActionResult Edit(SubscriberModel model) { if (model == null) { return(RedirectToAction("List")); } var subscriber = subscriberService.GetById(model.Id); if (subscriber == null) { this.NotifyError("Item not found."); return(RedirectToAction("List")); } else { subscriber.IsActive = model.IsActive; subscriber.Email = model.Email; subscriber.FullName = model.FullName; var result = subscriberService.Save(subscriber); if (result) { this.NotifySuccess("Successfully saved."); } else { this.NotifyError("Item can not saved!"); } } return(View(model)); }
public async Task <IActionResult> Create([FromBody] SubscribeViewModel record) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } SubscriberModel subscriberModel = new SubscriberModel { Code = record.Code, Name = record.Name, Emails = record.Emails, Remarks = record.Remarks }; try { var createdRecord = (await this._AppService.Create(subscriberModel)); return(Created($"api/[controller]/{ createdRecord.Id }", createdRecord)); } catch (ApplicationException ex) { return(new BadRequestObjectResult(ex)); } }
public SingleSubscriberModel(SubscriberModel model) { Category = model.Category; AllCategories = model.AllCategories; UserID = model.Author; SubscribeDate = model._DCDateCreated; }
void DeleteSubscriber(string publicKey) { try { using (var db = new SubscriberModel()) { var subtoremove = db.Subscribers.SingleOrDefault(x => x.PublicKey == publicKey); //returns a single item. if (subtoremove != null) { db.Subscribers.Remove(subtoremove); db.SaveChanges(); } } } catch (DbEntityValidationException ex) { foreach (var errors in ex.EntityValidationErrors) { foreach (var validationError in errors.ValidationErrors) { // get the error message string errorMessage = validationError.ErrorMessage; } } } }
public IActionResult SubscribeToTournament(Guid id, [FromBody] SubscribeToTournamentModel subscribeToTournamentModel) { if (ModelState.IsValid == false) { return(BadRequest()); } Tournament tournament = this.TournamentRepository.Get(id); if (tournament == null) { return(NotFound()); } Subscriber subscriber = Mapper.Map <SubscribeToTournamentModel, Subscriber>(subscribeToTournamentModel); subscriber.TournamentId = id; Subscriber newSubscriber = this.TournamentRepository.AddSubscriber(subscriber); SubscriberModel tournamentSubscriberModel = Mapper.Map <Subscriber, SubscriberModel>(newSubscriber); // If no game exists create one bool doesGameExist = this.TournamentRepository.HasGame(id); if (doesGameExist == false) { var newGame = this.GameLogic.BuildGame(id, tournament.CluesPerGame); var game = this.TournamentRepository.UpdateGame(newGame); } return(CreatedAtRoute("TournamentSubscriber", new { tournamentid = id, id = newSubscriber.Id }, tournamentSubscriberModel)); }
private async Task PublishToSubscriber(SubscriberModel subscriber, MarketEventModel model) { using (var client = _httpClientFactory.CreateClient()) { await client.PostAsync(subscriber.Url, new JsonContent <MarketEventModel>(model)); } }
public void AddAsync_WithEmailAlreadyExist_ThrowException() { SubscriberModel subscriberModel = new SubscriberModel(); var mockUoW = new Mock <IUnitOfWork>(); SubscriberService subscriberService = new SubscriberService(mockUoW.Object); subscriberService.AddAsync }
public async Task <long> AddSubscriberAsync(SubscriberModel subscriberModel) { var response = await _client.PostAsync("/subscribers", subscriberModel).ConfigureAwait(false); return(long.TryParse(response.GetIdFromLocationHeader(), out var id) ? id : default(long)); }
/// <summary> /// Creates a new subscription /// </summary> /// <param name="model">Suscription data</param> /// <returns>Updated record</returns> public async Task <SubscriberModel> Create(SubscriberModel model) { var collection = _SettingsModel.GetCollection <SubscriberModel>(collectionName); await collection.InsertOneAsync(model); return(model); }
public void ShouldCorrectlyResolveIsActive(bool isActive, bool neverExpire, int days, bool result) { var model = new SubscriberModel { IsActive = isActive, DefaultNeverExpire = neverExpire, ExpirationDate = DateTime.UtcNow.AddDays(days) }; var clientContent = model.ToDynamic(); Assert.AreEqual(clientContent.IsAlive, result); }
private bool IsValidSubscriber(SubscriberModel subscriber) { if (string.IsNullOrWhiteSpace(subscriber.EmailAddress) || string.IsNullOrWhiteSpace(subscriber.FirstName) || string.IsNullOrWhiteSpace(subscriber.LastName)) { return(false); } return(true); }
public IActionResult Subscribe([FromBody] SubscriberModel subscribers) { subscribers.Id = Guid.NewGuid(); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } subscribersList.Add(subscribers); return(Ok(new { massage = "Успешно подписанны" })); }
public Subscriber GetSubscriberData(string publicKey) { SubscriberModel db = new SubscriberModel(); var subdata = (from subscribers in db.Subscribers where subscribers.PublicKey.Equals(publicKey) select subscribers).SingleOrDefault(); return(subdata); }
public async Task <bool> RegisterAsync(SubscriberModel subscriberModel) { bool isEmailValid = await _subscriberRepository.IsEmailValiAsync(subscriberModel.Email); if (isEmailValid) { return(await _subscriberRepository.RegisterAsync(subscriberModel)); } return(false); }
public void SubscriptionRemoved(SubscriberModel model) { if (model != null) { StorageMethod.SubscriberRemoved(model); _cache.Remove(_cacheKey + model.Key); _cache.Remove(_cacheAppId + model.ApplicationId); } }
public async Task <ActionResult <bool> > RegisterAsync([FromBody] SubscriberDTO subscriber) { SubscriberModel subscriberModel = _mapper.Map <SubscriberModel>(subscriber); var response = await _subscriberService.RegisterAsync(subscriberModel); if (response) { return(Ok(response)); } return(BadRequest(false)); }
public void AddOrUpdateSubscriber(SubscriberModel model) { var config = GetConfiguration(); var expirationTicks = config?.Company?.CacheTimeoutTicks; var expiration = expirationTicks != null ? new TimeSpan?(new TimeSpan(expirationTicks.Value)) : null; var stringModel = JsonConvert.SerializeObject(model); _database.StringSet(GetRedisKeyForAppId(model.ApplicationId), stringModel, expiration); _database.StringSet(GetRedisKeyForKey(model.Key), stringModel, expiration); _database.HashSet(SUBSCRIO_ALL_KEY, GetRedisKeyForKey(model.Key), stringModel); }
public void SubscriberRemoved(SubscriberModel model) { var stringModel = JsonConvert.SerializeObject(model); // set expiration to 1 second, anything lower than that seems to throw an exception var expiration = new TimeSpan(10000000); _database.StringSet(GetRedisKeyForAppId(model.ApplicationId), stringModel, expiration); _database.StringSet(GetRedisKeyForKey(model.Key), stringModel, expiration); // expire the get all subscribers call _database.StringSet(HASH_EXPIRATION, DateTime.UtcNow.Ticks); }
public async Task <bool> AddAsync(SubscriberModel subsciber, float height) { var isExsits = _subscriberRepository.IsEmailExistsAsync(subsciber.email); if (isExsits.Result == false) { await _subscriberRepository.AddAsync(subsciber, height); return(true); } throw new Exception("this email exists, try another"); }
public void SubscriptionUpdated(SubscriberModel model) { if (model != null) { StorageMethod.AddOrUpdateSubscriber(model); _cache.Remove(_cacheKey + model.Key); _cache.Remove(_cacheAppId + model.ApplicationId); _cache.Add(_cacheAppId + model.ApplicationId, model, MyCachePriority.Default); _cache.Add(_cacheKey + model.Key, model, MyCachePriority.Default); } }
public void ShouldStoreAndRetrieveSubscriber() { var model = new SubscriberModel { ApplicationId = "AppTuttle", Key = "KeyTuttle", }; _redis.AddOrUpdateSubscriber(model); var result = _redis.GetByApplicationId("AppTuttle"); Assert.IsNotNull(result); result = _redis.GetByKey("KeyTuttle"); Assert.IsNotNull(result); }
public void SendNotificationManager([FromBody] int subID) { using (var db = new SubscriberModel()) { var query = from st in db.Subscribers where st.ID == subID select st; var sub = query.FirstOrDefault <Subscriber>(); if (sub != null) { sendPushNotificationClient(sub.Endpoint, sub.PublicKey, sub.PrivateKey, "", sub.URL); } } }
public SubscriberModel EditSubscriber(SubscriberModel model) { IRepository<Subscriber> subscriberRepo = UnitOfWork.Repository<Subscriber>(); Subscriber subscriber = subscriberRepo.FindById(model.Id); if (subscriber == null) { return null; } subscriber.Name = model.Name; subscriber.Surname = model.Surname; subscriber.Email = model.Email; return subscriberRepo.Update(subscriber) != null ? model : null; }
public void ShouldHaveExpiredAndReturnNull() { var model = new SubscriberModel { ApplicationId = "AppTuttle", Key = "KeyTuttle", }; _redis.AddOrUpdateSubscriber(model); System.Threading.Thread.Sleep(6000); var result = _redis.GetByApplicationId("AppTuttle"); Assert.IsNull(result); result = _redis.GetByKey("KeyTuttle"); Assert.IsNull(result); }
/// <summary> /// Создание модели для нового абонента для добавления его базу данных /// </summary> /// <param name="subscriberModel"></param> /// <returns></returns> private Subscriber NewSubscriber(SubscriberModel subscriberModel) { var subscriber = new Subscriber() { Address = subscriberModel.Address, FIOHead = subscriberModel.FIOHead, FullName = subscriberModel.FullName, INN = subscriberModel.INN, Phones = subscriberModel.Phones, RepresentativePhones = subscriberModel.RepresentativePhones, ShortName = subscriberModel.ShortName, SubscriberRepresentative = subscriberModel.SubscriberRepresentative }; return(subscriber); }
public static dynamic ToDynamic(this SubscriberModel subscriber) { var dic = subscriber.Features.ToDictionary(ft => ft.PropertyName, GetDerivedValue); dic.Add("SubscriptionTypeId", subscriber.SubscriptionTypeId); dic.Add("Id", subscriber.Id); dic.Add("Name", subscriber.Name); dic.Add("ApplicationId", subscriber.ApplicationId); dic.Add("Key", subscriber.Key); dic.Add("ExpirationDate", subscriber.ExpirationDate); dic.Add("BillingSystemIdentifier", subscriber.BillingSystemIdentifier); dic.Add("BillingSystemType", subscriber.BillingSystemType); dic.Add("IsExpired", !subscriber.DefaultNeverExpire && (subscriber.ExpirationDate.AddDays(subscriber.DefaultGracePeriod) < DateTime.UtcNow)); dic.Add("IsAlive", subscriber.IsActive && ((subscriber.ExpirationDate.AddDays(subscriber.DefaultGracePeriod) > DateTime.UtcNow) || subscriber.DefaultNeverExpire)); return(new DynamicDictionary(dic)); }
public dynamic CreateSubscription(int subscriptionTypeId, string applicationIdentifier, string name = null, int?billingSystemType = null, string billingSystemIdentifier = null) { var config = GetConfiguration(); if (config?.SubscriptionTypes == null || config.SubscriptionTypes.Count == 0) { throw new Exception("Missing configuration or subscription types, no subscription types found"); } var subscriptionType = config.SubscriptionTypes.FirstOrDefault(x => x.Id == subscriptionTypeId); if (subscriptionType == null) { throw new Exception($"Subscription type with id of: {subscriptionTypeId} was not found"); } var model = new SubscriberModel { ApplicationId = applicationIdentifier, BillingSystemType = billingSystemType ?? subscriptionType.BillingSystemType, BillingSystemIdentifier = billingSystemIdentifier, CompanyId = config.Company.Id, DefaultGracePeriod = subscriptionType.DefaultGracePeriod, DefaultNeverExpire = subscriptionType.DefaultNeverExpire, DefaultResetFeaturesOnRenewal = subscriptionType.DefaultResetFeaturesOnRenewal, DefaultRevertOnExpiration = subscriptionType.DefaultRevertOnExpiration, DefaultRevertTo = subscriptionType.DefaultRevertTo, Name = name, Version = VersionNumber, IsActive = true, SubscriptionTypeId = subscriptionType.Id, Features = subscriptionType.Features, ExpirationDate = DateTime.UtcNow.AddTicks(subscriptionType.TimeToExpireTicks.GetValueOrDefault()) }; var result = _webClientService.CreateSubscription(model); var newSubscriber = JsonConvert.DeserializeObject <SubscriberModel>(result); if (newSubscriber == null) { return(null); } StorageMethod.AddOrUpdateSubscriber(newSubscriber); _cache.Add(_cacheAppId + newSubscriber.ApplicationId, newSubscriber, MyCachePriority.Default); _cache.Add(_cacheKey + newSubscriber.Key, newSubscriber, MyCachePriority.Default); return(newSubscriber.ToDynamic()); }
public void AddVideoDevice_DeviceIdDoesNotExist_Failed() { // Set current subscriber const string subId = "SUBIDWITHANYVALUE"; const string locId = "LOCIDWITHANYVALUE"; var compositeSubscriber = new CompositeSubscriber { SubscriberTriad = new SubscriberDto { ID = subId, Accounts = new List<AccountDto> {new AccountDto {Location = new LocationDto {ID = locId}}} } }; var subscriberModel = new SubscriberModel { SubDetailsModel = new SubscriberDetailsModel{USI = subId}, SubLocationModel = new SubscriberLocationModel{LocationID = locId} }; CurrentSubscriber.SetInstance(compositeSubscriber, subscriberModel); // DeviceId to be added const string deviceId = "DEVICEIDDOESNOTEXIST"; // Expected Result var expectedErrorMesasge = string.Format("Error adding device [{0}]: Activation is not allowed, device [{0}] does not exist", deviceId); var expectedResult = new { status = "error", errorMessage = expectedErrorMesasge }; // Call AddVideoDevice action method var actualResult = RgController.AddVideoDevice(deviceId) as JsonResult; // Test results validation Assert.IsTrue(actualResult != null && actualResult.Data != null); Assert.AreEqual(expectedResult.ToJSON(), actualResult.Data.ToJSON()); }
public void AddVideoDevice_SubHasVideoDevices_Success() { // Restore subscriber test data var sub = TestData.Data.UVerseSub1WithActiveStb(); Assert.IsTrue(sub.Accounts != null && sub.Accounts.Any() && sub.Accounts.First().Location != null); // Set current subscriber var subId = sub.ID; var locId = sub.Accounts.First().Location.ID; var compositeSubscriber = new CompositeSubscriber { SubscriberTriad = new SubscriberDto { ID = subId, Accounts = new List<AccountDto> { new AccountDto { Location = new LocationDto { ID = locId } } } } }; var subscriberModel = new SubscriberModel { SubDetailsModel = new SubscriberDetailsModel { USI = subId }, SubLocationModel = new SubscriberLocationModel { LocationID = locId } }; CurrentSubscriber.SetInstance(compositeSubscriber, subscriberModel); // Restore device test data var device = TestData.Data.UVerseStb1InHeadend(); // Call AddVideoDevice action method var result = RgController.AddVideoDevice(device.SerialNumber) as JsonResult; // Validate returned results Assert.IsNotNull(result, "ActionResult is null"); Assert.IsNotNull(result.Data, "Data is null"); dynamic actualResult = result.Data; Assert.AreEqual("200", actualResult.code); Assert.AreEqual("valid", actualResult.status); }
public void SubscriberModel_As_Instantiated_References_And_State() { // Arrange - nothing to do here... // Act - not much to do here var model = new SubscriberModel(); // Assert - lots to do here // Verify instantiation of nested model objects Assert.IsNotNull(model.SubDetailsModel); Assert.IsNotNull(model.SubLocationModel); Assert.IsNotNull(model.SubServicesModel); Assert.IsNotNull(model.SubEquipmentModel); Assert.IsNotNull(model.ActionResponse); Assert.IsNotNull(model.ActionResponse.Code); Assert.AreEqual("200", model.ActionResponse.Code); Assert.IsNotNull(model.ActionResponse.Message); // Verify as instantiated state and behavior properties of class SubscriberDetailsModel var detailsModel = model.SubDetailsModel; Assert.IsFalse(detailsModel.HasName); Assert.IsFalse(detailsModel.HasBtn); Assert.IsNotNull(detailsModel.ActionResponse); Assert.AreEqual("200", detailsModel.ActionResponse.Code); Assert.IsNotNull(detailsModel.ActionResponse.Message); // Verify as instantiated state and behavior properties of class SubscriberLocationModel var locationModel = model.SubLocationModel; Assert.IsNotNull(locationModel.LoadedDeviceID); Assert.IsNotNull(locationModel.ActionResponse); Assert.IsNotNull(locationModel.ActionResponse.Code); Assert.AreEqual("200", locationModel.ActionResponse.Code); Assert.IsFalse(locationModel.HasServiceAddress); Assert.IsFalse(locationModel.HasAddress2); Assert.IsFalse(locationModel.HasCityStateZip); Assert.IsFalse(locationModel.IsInventoryLocation); Assert.IsFalse(locationModel.LocationIDIsValid); Assert.IsFalse(locationModel.HasSubscriber); // Verify as instantiated state and behavior properties of class SubscriberServicesModel var servicesModel = model.SubServicesModel; Assert.IsNotNull(servicesModel.ProvisionedServicesList as IList<SIMPL.DAL.DataTransfer.Provisioning.ServiceDto>); Assert.AreEqual(0, servicesModel.ProvisionedServicesList.Count); Assert.IsNotNull(servicesModel.BilledServicesList); Assert.IsNotNull(servicesModel.ActionResponse); Assert.IsNotNull(servicesModel.ActionResponse.Code); Assert.AreEqual("200", servicesModel.ActionResponse.Code); Assert.IsNotNull(servicesModel.ActionResponse.Message); // Verify as instantiated state and behavior properties of class SubscriberEquipmentModel var equipmentModel = model.SubEquipmentModel; Assert.IsNotNull(equipmentModel.ONTList as IList<ONT>); Assert.IsNotNull(equipmentModel.VideoDeviceList as IList<SerializableVideoDevice>); }
public ActionResult Edit(SubscriberModel model) { if (ModelState.IsValid) { SubscriberModel editedSubscriber = SubscriberService.EditSubscriber(model); if (editedSubscriber != null) { return RedirectToAction("Index", "Subscribers"); } } return View(model); }