public Task <IDataSourceResponse <ChannelViewModel> > ReadAsync(DataSourceRequest request) { var responseData = this.DbContext.Channel.Select(c => c); if (request.ServerFiltering != null) { } IDataSourceResponse <ChannelViewModel> response = new DataSourceResponse <ChannelViewModel> { TotalRowCount = responseData.Count() }; if (request.ServerPaging != null) { int skip = Math.Max(request.ServerPaging.PageSize * (request.ServerPaging.Page - 1), 0); responseData = responseData.OrderBy(p => p.Id).Skip(skip).Take(request.ServerPaging.PageSize); } var dataCollection = responseData.ToList(); foreach (var data in dataCollection) { response.DataCollection.Add(ChannelViewModel.NewInstance(data)); } return(Task.FromResult(response)); }
public ChannelListView() { InitializeComponent(); var viewModel = new ChannelViewModel(); this.DataContext = viewModel; }
public async Task <IActionResult> Create([FromBody] ChannelViewModel pvm) { try { CurrentUser cUser = new CurrentUser(HttpContext, _configuration); pvm.UserId = cUser.UserId; pvm.ReturnKey = 1; pvm.ChannelId = 0; pvm.Active = "Y"; var result = await ChannelRepo.SaveOrUpdate(pvm); await auditLogService.LogActivity(cUser.UserId, cUser.HostIP, cUser.SessionId, "Channel", "Channel Created."); return(Ok(result)); } catch (CustomException cex) { var returnObj = new EmaintenanceMessage(cex.Message, cex.Type, cex.IsException, cex.Exception?.ToString()); return(StatusCode(StatusCodes.Status500InternalServerError, returnObj)); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, new EmaintenanceMessage(ex.Message))); } }
public async Task <ChannelViewModel> GetChannel(string channelId) { PopulatePastChannelSearchesDict(); if (PastChannelSearchesDict.ContainsKey(channelId)) { return(PastChannelSearchesDict[channelId]); } else { ApiChannel apiChannel = await GetChannelDataFromApi(channelId); if (apiChannel.Items.Length > 0) { ChannelViewModel viewModel = ChannelViewModel.FromApiChannel(apiChannel); PastChannelSearchesDict.Add(channelId, viewModel); await WriteChannelViewModelToFile(viewModel); return(viewModel); } return(null); } }
public ICollection <ChannelViewModel> GetSuggestedChannels(string username) { this.GetTags(username, out var channelViewModels, out var userTags, out var notFollowedChannels); foreach (var channel in notFollowedChannels) { var tags = channel.Tags.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); var containsTag = false; for (var i = 0; i < tags.Length; i++) { if (userTags.Contains(tags[i])) { containsTag = true; } } if (containsTag) { var channelViewModel = new ChannelViewModel(); channelViewModel.Followers = this.context.UsersChannels.Count(uch => uch.ChannelId == channel.Id); channelViewModel.Name = channel.Name; channelViewModel.Type = channel.Type.ToString(); channelViewModel.Id = channel.Id; channelViewModels.Add(channelViewModel); } } return(channelViewModels); }
private async Task WriteChannelViewModelToFile(ChannelViewModel viewModel) { using (StreamWriter sw = new StreamWriter(UriHelper.PAST_CHANNEL_SEARCHES_FILE_URI, true)) { await sw.WriteLineAsync(ChannelViewModel.SerializeObject(viewModel)); } }
public async Task <Dictionary <string, ChannelViewModel> > GetChannels(List <string> channelIds) { PopulatePastChannelSearchesDict(); Dictionary <string, ChannelViewModel> apiChannelsDict = new Dictionary <string, ChannelViewModel>(); foreach (var id in channelIds) { if (!apiChannelsDict.ContainsKey(id)) { if (PastVideoSearchesDict.ContainsKey(id)) { apiChannelsDict.Add(id, PastChannelSearchesDict[id]); } else { ApiChannel apiChannel = await GetChannelDataFromApi(id); if (apiChannel.Items.Length > 0) { ChannelViewModel viewModel = ChannelViewModel.FromApiChannel(apiChannel); await WriteChannelViewModelToFile(viewModel); apiChannelsDict.Add(id, viewModel); PastChannelSearchesDict.Add(id, viewModel); } } } } return(apiChannelsDict); }
public async Task <bool> CreateAsync(ChannelViewModel model, IDataSource dataSource) { if (new string[] { "config", "reload", "monitor", "heartbeat", "default", "dynamic" }.Contains(model.ChannelId)) { return(false); } var channel = new Channel { ChannelId = model.ChannelId, Description = model.Description }; await this.DbContext.Channel.AddAsync(channel); bool result = false; try { await this.DbContext.SaveChangesAsync(); model.Id = channel.Id; result = true; } catch { } return(result); }
public async Task <bool?> UpdateAsync(int key, ChannelViewModel model, IDataSource dataSource) { if (new string[] { "config", "reload", "monitor", "heartbeat", "default", "dynamic" }.Contains(model.ChannelId)) { return(false); } var channel = await this.ReadAsync(key); if (channel == null) { return(null); } channel.ChannelId = model.ChannelId; channel.Description = model.Description; bool result = false; try { await this.DbContext.SaveChangesAsync(); result = true; } catch { } return(result); }
public IHttpActionResult PostCreateNewChannel([FromBody] ChannelBindingModel model) { if (model == null) { return(this.BadRequest()); } if (!this.ModelState.IsValid) { return(this.BadRequest()); } var dbModel = this.Data.Channels.FirstOrDefault(c => c.Name == model.Name); if (dbModel != null) { return(this.Conflict()); } var newChannel = new Channel() { Name = model.Name }; this.Data.Channels.Add(newChannel); this.Data.SaveChanges(); var viewModel = new ChannelViewModel() { Id = newChannel.Id, Name = newChannel.Name }; return(this.Created("http://localhost:7777/api/channels/" + viewModel.Id, viewModel)); }
/// <summary> /// Creates a reference line cursor for a single channel. /// </summary> internal static BoundCursor CreateChannelReferenceCursor(ChannelViewModel channelVM) { var channelCaption = channelVM.Caption; var channelColor = CairoHelpers.ToCairoColor(channelVM.Color); var cursor = new ScopeCursor { Lines = ScopeCursorLines.Y, LineWeight = ScopeCursorLineWeight.Low, SelectableLines = ScopeCursorLines.Y, Markers = ScopeCursorMarkers.YFull, Color = channelColor, Captions = new [] { new ScopePositionCaption(() => channelCaption, ScopeHorizontalAlignment.Left, ScopeVerticalAlignment.Bottom, ScopeAlignmentReference.YPositionAndHorizontalRangeEdge, true, channelColor), new ScopePositionCaption(() => channelCaption, ScopeHorizontalAlignment.Right, ScopeVerticalAlignment.Bottom, ScopeAlignmentReference.YPositionAndHorizontalRangeEdge, true, channelColor), }, }; // === Create bindings. === // Bind the cursor's position. var binding = PB.Binding.Create(() => cursor.Position.Y == channelVM.ReferencePointPosition.Y); return(new BoundCursor(cursor, new [] { binding })); }
/// <summary> /// Creates a trigger criteria cursor for a level-based trigger. /// </summary> internal static BoundCursor CreateTriggerCriteriaCursor( LevelTriggerViewModel triggerVM, ChannelViewModel triggerChannelConfiguration, Func <double> referenceLevelProvider) { var triggerModeSymbol = triggerVM.Mode == LevelTriggerMode.RisingEdge ? _triggerTypeRisingSymbol : triggerVM.Mode == LevelTriggerMode.FallingEdge ? _triggerTypeFallingSymbol : '?'; Func <ScopeCursor, ValueConverter <double, double>, PB.Binding> bindingProvider = (cursor, valueConverter) => PB.Binding.Create(() => cursor.Position.Y == valueConverter.DerivedValue && valueConverter.OriginalValue == triggerVM.Level); var influencingObjects = new INotifyPropertyChanged[] { triggerChannelConfiguration, triggerChannelConfiguration.ReferencePointPosition }; return(CreateTriggerCriteriaCursor( triggerModeSymbol, () => triggerVM.Level, bindingProvider, () => triggerChannelConfiguration.YScaleFactor, () => triggerChannelConfiguration.ReferencePointPosition.Y, referenceLevelProvider, triggerVM.ChannelVM.BaseUnitString, triggerChannelConfiguration.Color, influencingObjects)); }
private async ValueTask RenameChannel(ChannelViewModel existing, FFmpegProfileViewModel ffmpegProfile) { int newFFmpegProfileId = string.IsNullOrWhiteSpace(FFmpegProfileName) ? existing.FfmpegProfileId : ffmpegProfile.Id; if (existing.Name != Name || existing.FfmpegProfileId != newFFmpegProfileId || existing.StreamingMode != StreamingMode) { var updateChannel = new UpdateChannel( existing.Id, Name, existing.Number, newFFmpegProfileId, existing.Logo, StreamingMode); await _channelsApi.ApiChannelsPatchAsync(updateChannel); } _logger.LogInformation( "Successfully synchronized channel {ChannelNumber} - {ChannelName}", Number, Name); }
public void Details() { // Arrange var id = 20; var name = "Kanal"; var scenarios = new List <NcScenario>(); var channel = new NcChannel { Id = id, Name = name }; var mock = new Mock <IChannelManager>(); mock.Setup(x => x.FindById(id)).Returns(channel); mock.Setup(x => x.GetScenariosByChannelId(id)).Returns(scenarios); var expected = new ChannelViewModel { Id = id, Name = name, Scenarios = mapper.MapEnumerable <ScenarioListDTO>(scenarios).ToList(), }.ToExpectedObject(); // Act var controller = new ChannelsController(mock.Object, mapper); var result = controller.Details(id); // Assert var actual = (result as ViewResult)?.Model; expected.ShouldEqual(actual); }
public IHttpActionResult CreateNewChannel(AddChannelBindingModel model) { if (model == null) { return(this.BadRequest("Name is required!Cannot be empty.")); } if (!this.ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } if (this.Data.Channels.Any(ch => ch.Name == model.Name)) { return(this.Conflict()); } var channel = new Channel { Name = model.Name }; this.Data.Channels.Add(channel); this.Data.SaveChanges(); var result = new ChannelViewModel() { Id = channel.Id, Name = channel.Name }; // return status 201, Location and (channel Id and name) return(this.CreatedAtRoute("DefaultApi", new { id = channel.Id }, result)); }
/// <summary> /// Creates a cursor used for level measurements. /// </summary> internal static BoundCursor CreateLevelMeasurementCursor( MeasurementCursorViewModel cursorVM, ChannelViewModel cursorChannelConfiguration, bool isReferenceCursor, Func <double> deltaReferenceLevelProvider, Func <double> referenceLevelProvider) { Func <ScopeCursor, ValueConverter <double, double>, PB.Binding> bindingProvider = (cursor, valueConverter) => PB.Binding.Create(() => cursor.Position.Y == valueConverter.DerivedValue && valueConverter.OriginalValue == cursorVM.Value); var influencingObjects = new INotifyPropertyChanged[] { cursorChannelConfiguration, cursorChannelConfiguration.ReferencePointPosition }; return(CreateMeasurementCursor( MeasurementAxis.Y, isReferenceCursor, () => cursorVM.Value, bindingProvider, deltaReferenceLevelProvider, () => cursorChannelConfiguration.YScaleFactor, () => cursorChannelConfiguration.ReferencePointPosition.Y, referenceLevelProvider, cursorChannelConfiguration.BaseUnitString, cursorChannelConfiguration.Color, influencingObjects)); }
public ActionResult Create(int SiteId) { var viewModel = new ChannelViewModel(); viewModel.MapTo(_service.Create()); viewModel.ParentId = SiteId; return(View(viewModel)); }
public ModifyChannel(Channel channelBeingModified) { model = new ChannelViewModel { ChannelBeingModified = channelBeingModified }; InitializeComponent(); this.DataContext = model; }
public async Task <ActionResult> AddChannel() { ISubscriptionServiceService iss = new SubscriptionServiceService(); var list = await iss.ReturnSubscriptionServices(); ChannelViewModel channelvm = new ChannelViewModel(list); return(View(channelvm)); }
public IActionResult Details(int id) { var channel = channelManager.FindById(id); ChannelViewModel model = mapper.Map <ChannelViewModel>(channel); model.Scenarios = mapper.MapEnumerable <NcScenario, ScenarioListDTO>(channelManager.GetScenariosByChannelId(channel.Id)).ToList(); return(View(model)); }
public JsonResult DestroyChannel([DataSourceRequest] DataSourceRequest request, ChannelViewModel channel) { var deletedChannel = this.channels.DestroyChannel(channel); var loggedUserId = this.User.Identity.GetUserId(); Base.CreateActivity(ActivityType.Delete, deletedChannel.Id.ToString(), ActivityTargetType.Channel, loggedUserId); return Json(new[] { channel }, JsonRequestBehavior.AllowGet); }
public static List<CancellationTokenSource> GetTimers(ChannelViewModel channelModel) { lock (LockObject) { return CancellationTokenSources.ContainsKey(channelModel) ? CancellationTokenSources[channelModel] : new List<CancellationTokenSource>(); } }
public IHttpResponse Index() { if (!this.User.IsLoggedIn) { return(this.View()); } var currentUser = this.ApplicationDbContext.Users.Include(x => x.FollowedChannels).FirstOrDefault(x => x.Username == this.User.Username); var yourChannels = this.ApplicationDbContext .UserChannels.Include(x => x.Channel).Include(x => x.Channel.Tags) .Where(x => x.UserId == currentUser.Id).ToList(); var seeOther = new List <Channel>(); var allChannels = this.ApplicationDbContext.Channels.Include(x => x.Followers).ToList(); foreach (var userChannel in allChannels) { if (!this.ApplicationDbContext.UserChannels.Include(x => x.Channel).ThenInclude(x => x.Followers).Any(x => x.Channel.Id == userChannel.Id)) { seeOther.Add(userChannel); } } //take all my channels, take their tags, check if allTags equals any of my tags var suggested = new List <Channel>(); var myTags = new List <Tag>(); foreach (var yourChannel in yourChannels) { foreach (var tag in yourChannel.Channel.Tags) { myTags.Add(tag); } } var allTags = this.ApplicationDbContext.Tags.ToList(); foreach (var tag in allTags) { if (!myTags.Contains(tag)) { suggested = this.ApplicationDbContext.Channels.Include(x => x.Followers) .Where(x => x.Id == tag.ChannelId).ToList(); } } var viewModel = new ChannelViewModel { YourChannels = yourChannels, SeeOther = seeOther, SuggestedChannels = suggested }; return(this.View("/Home/IndexLoggedIn", viewModel)); }
// GET: Channel/Delete/5 public ActionResult Delete(int id) { var channel = _context.Channels.Where(x => x.Id == id).FirstOrDefault(); channel.AccessRestriction = _context.AccessRestrictions.Where(x => x.Id == channel.AccessRestrictionId).FirstOrDefault(); channel.Group = _context.Groups.Where(x => x.Id == channel.GroupId).FirstOrDefault(); channel.User = _context.Users.Where(x => x.Id == channel.UserId).FirstOrDefault(); ChannelViewModel viewChannel = channel; return(View(viewChannel)); }
public ActionResult Create(ChannelViewModel item) { if (ModelState.IsValid) { Channel channel = item.FromMap(); channel.Site = _site.GetByID(item.ParentId); _service.Insert(channel); _service.Save(); return(RedirectToAction("Index", "Channel", new { id = item.ParentId })); } return(View(item)); }
private void DeclareVars() { serverViewModel = new ServerViewModel(); // Instantiates the ViewModel channelViewModel = new ChannelViewModel(); // Instantiates the ViewModel chatViewModel = new ChatViewModel(); // Instantiates the ViewModel memberViewModel = new MemberViewModel(); // Instantiates the ViewModel ServerListView.ItemsSource = serverViewModel.Servers; // Set the Server List's Source to the ViewModel ChannelListView.ItemsSource = channelViewModel.Channels; // Set the Channel List's Source to the ViewModel ChatListView.ItemsSource = chatViewModel.Messages; // Set the Cannel List's Source to the ViewModel MemberListView.ItemsSource = memberViewModel.Members; // Set the Cannel List's Source to the ViewModel Packet.PacketQueue = new List <Packet>(); }
public IActionResult Details(ChannelViewModel model) { var viewModel = this.channelService.GetChannelById(model.Id); this.Model["Name"] = viewModel.Name; this.Model["Tags"] = viewModel.Tags; this.Model["Followers"] = viewModel.Followers; this.Model["Type"] = viewModel.Type; this.Model["Description"] = viewModel.Description; return(this.View()); }
public ICollection <ChannelViewModel> Read() { ICollection <ChannelViewModel> channels = new List <ChannelViewModel>(); var dataCollection = this.DbContext.Channel.Select(c => c).ToList(); foreach (var data in dataCollection) { channels.Add(ChannelViewModel.NewInstance(data)); } return(channels); }
public ActionResult Uploadvideo(ChannelViewModel chl) { using (var db = new MyUtubeEntities1()) { var channelList = db.Channels.Where(u => u.UserId == CurrentSession.CurrentUser.Id) .Select(x => new ChannelViewModel { Value = x.Id, Text = x.ChannelName }).ToList(); ViewBag.ChannelList = channelList; } return(View()); }
public JsonResult CreateChannel([DataSourceRequest] DataSourceRequest request, ChannelViewModel channel, int currentProviderId) { if (channel == null || !ModelState.IsValid) { return Json(new[] { channel }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet); } var createdChannel = this.channels.CreateChannel(channel, currentProviderId); var loggedUserId = this.User.Identity.GetUserId(); Base.CreateActivity(ActivityType.Create, createdChannel.Id.ToString(), ActivityTargetType.Channel, loggedUserId); return Json(new[] { createdChannel }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet); }
public async Task <ActionResult> Delete(int id, IFormCollection collection) { try { var currentUser = await _userManager.GetUserAsync(HttpContext.User); var adminRole = await _roleManager.FindByNameAsync("Administrator"); var channel = _context.Channels.Where(x => x.Id == id).FirstOrDefault(); if (channel.UserId != null) { if (channel.UserId == currentUser.Id) { _context.Remove(channel); _context.SaveChanges(); _mongoOperations.DeleteCollection(channel.Name); return(RedirectToAction("Index")); } else { return(RedirectToAction("Index")); } } else { var ass = _context.Associations.Where(x => x.UserId == currentUser.Id && x.RoleId == adminRole.Id); if (ass.Any(x => x.GroupId == channel.GroupId)) { _context.Remove(channel); _context.SaveChanges(); _mongoOperations.DeleteCollection(channel.Name); return(RedirectToAction("Index")); } else { return(RedirectToAction("Index")); } } } catch { var channel = _context.Channels.Where(x => x.Id == id).FirstOrDefault(); channel.AccessRestriction = _context.AccessRestrictions.Where(x => x.Id == channel.AccessRestrictionId).FirstOrDefault(); channel.Group = _context.Groups.Where(x => x.Id == channel.GroupId).FirstOrDefault(); channel.User = _context.Users.Where(x => x.Id == channel.UserId).FirstOrDefault(); ChannelViewModel viewChannel = channel; return(View(viewChannel)); } }
private async ValueTask BuildPlayout(CancellationToken cancellationToken, ChannelViewModel channel) { var programScheduleApi = new ProgramScheduleApi(_serverUrl); Option <ProgramScheduleViewModel> maybeSchedule = await programScheduleApi .ApiSchedulesGetAsync(cancellationToken) .Map(list => list.SingleOrDefault(s => s.Name == ScheduleName)); await maybeSchedule.Match( schedule => SynchronizePlayoutAsync(channel.Id, schedule.Id, cancellationToken), () => { _logger.LogError("Unable to locate schedule {Schedule}", ScheduleName); return(ValueTask.CompletedTask); }); }
public ActionResult AddNewChannel(ChannelViewModel model) { using (var db = new MyTubeEntities()) { var channel = new Channel { UserId = CurrentSession.CurrentUser.Id, Name = model.ChannelName, Description = model.ChannelDescription, IsActive = true, }; db.Channels.Add(channel); db.SaveChanges(); return(Json(new { Success = true, NewChannel = new { Id = channel.Id, Name = channel.Name } })); } }
public ChannelViewModel CreateChannel(ChannelViewModel channel, int currentProviderId) { var newChannel = new Channel { Name = channel.Name, ReveivingOptions = channel.ReveivingOptions, SatelliteData = channel.SatelliteData, EpgSource = channel.EpgSource, Website = channel.Website, Presentation = channel.Presentation, ContractTemplate = channel.ContractTemplate, LogoLink = channel.LogoLink, CreatedOn = DateTime.Now, ProviderId = currentProviderId, Comments = channel.Comments, IsVisible = channel.IsVisible }; if (string.IsNullOrEmpty(newChannel.EpgSource) && string.IsNullOrEmpty(channel.EpgSource)) { newChannel.EpgSource = "#"; } if (string.IsNullOrEmpty(newChannel.Website) && string.IsNullOrEmpty(channel.Website)) { newChannel.Website = "#"; } if (string.IsNullOrEmpty(newChannel.Presentation) && string.IsNullOrEmpty(channel.Presentation)) { newChannel.Presentation = "#"; } if (string.IsNullOrEmpty(newChannel.ContractTemplate) && string.IsNullOrEmpty(channel.ContractTemplate)) { newChannel.ContractTemplate = "#"; } if (string.IsNullOrEmpty(newChannel.LogoLink) && string.IsNullOrEmpty(channel.LogoLink)) { newChannel.LogoLink = "#"; } this.Data.Channels.Add(newChannel); this.Data.Channels.SaveChanges(); channel.Id = newChannel.Id; return channel; }
internal void Update(ChannelViewModel channel) { if (channel!=null) { this.RelayTree = channel.CreateHostTree().Nodes .Where(node => node.Host.SessionID==peerCast.SessionID) .Select(node => new RelayTreeNodeViewModel(node)).ToArray(); } else { this.RelayTree = new RelayTreeNodeViewModel[0]; } OnPropertyChanged("RelayTree"); if (this.channel!=channel) { this.channel = channel; this.refresh.OnCanExecuteChanged(); } }
public void UpdateConnections(ChannelViewModel channel) { if (channel==null) { Connections.Clear(); return; } var new_list = channel.Connections.ToArray(); foreach (var item in Connections.Except(new_list).ToArray()) { Connections.Remove(item); } foreach (var item in Connections) { item.Update(); } foreach (var item in new_list.Except(Connections).ToArray()) { Connections.Add(item); } }
public ChannelViewModel DestroyChannel(ChannelViewModel channel) { this.Data.Channels.Delete(channel.Id); this.Data.Channels.SaveChanges(); return channel; }
private void UpdateRelayTree(ChannelViewModel channel) { RelayTree.Update(channel); }
private void UpdateChannel(ChannelViewModel channel) { Connections.UpdateConnections(channel); ChannelInfo.UpdateChannelInfo(channel); }
// Join a new channel private void Join() { if (Channels.All(x => !x.ChannelName.Equals(NewChannelName, StringComparison.InvariantCultureIgnoreCase))) { try { var result = TwitchApiClient.GetUserByName(NewChannelName.ToLower()); var vm = new ChannelViewModel(_irc, result.Name); vm.Parted += OnParted; Channels.Add(vm); CurrentChannel = vm; } catch (ErrorResponseDataException ex) { if (ex.Status == HttpStatusCode.NotFound) MessageBox.Show("Channel not found"); } } NewChannelName = string.Empty; }
public ChatMemberViewModel(string name, ChannelViewModel channel, ChatGroupViewModel group) { Name = name; Channel = channel; Group = group; }
private static void AddToken(ChannelViewModel channelModel, CancellationTokenSource tokenSource) { lock (LockObject) { if (CancellationTokenSources.ContainsKey(channelModel) && !CancellationTokenSources[channelModel].Contains(tokenSource)) CancellationTokenSources[channelModel].Add(tokenSource); else CancellationTokenSources.Add(channelModel, new List<CancellationTokenSource> {tokenSource}); } }
public static void InitTimers(ChannelViewModel channelModel) { var timerCustomCommands = Commands.Where(t => t.Type == CommandType.Timer); foreach (var timerCustomCommand in timerCustomCommands) { var message = CustomCommandHandler.CreateCommand(timerCustomCommand, null, channelModel); Action action = () => { channelModel.Client.Message(channelModel.ChannelName, message.Message); }; Start(channelModel, action, timerCustomCommand.CooldownTime * 1000); } foreach (Timer timer in Enum.GetValues(typeof(Timer))) { var delay = Configs.ContainsKey(timer.ToString()) ? Configs[timer.ToString()] : Configs[Timer.Global.ToString()]; Action action; switch (timer) { case Timer.Global: continue; case Timer.Help: { action = () => { var text = HelpCommand.GetHelpTimerText(); channelModel.Client.Message(channelModel.ChannelName, text); }; break; } case Timer.UpdateChatters: { action = () => { List<ChatterInfo> listForUpdate; var allChatters = channelModel.GetAllChatters().GroupBy(t => t.Name).Select(group => group.First()).ToList(); try { var chatterInfo = TwitchApiClient.GetUsersList(channelModel.ChannelName); var newUsers = chatterInfo.Chatters.GetAll(); listForUpdate = newUsers.Select(t => new ChatterInfo { ChatName = channelModel.ChannelName, Name = t.Key, Seconds = delay }).ToList(); var forDelete = allChatters.Where(user => !newUsers.Any(t => t.Key.Equals(user.Name))).ToList(); Application.Current.Dispatcher.Invoke(() => { foreach (var memberViewModel in forDelete) allChatters.Remove(memberViewModel); foreach (var user in newUsers) { var group = channelModel.GetGroup(user.Value); if (!allChatters.Any(t => t.Name.Equals(user.Key))) group.Add(new ChatMemberViewModel(user.Key, channelModel, group)); } }); } catch { listForUpdate = allChatters.Select(t => new ChatterInfo { ChatName = channelModel.ChannelName, Name = t.Name, Seconds = delay}).ToList(); } if(_updateWasOneTime) ChatterInfoRepository.Instance.UpdateChatterInfo(channelModel.ChannelName, listForUpdate, delay); _updateWasOneTime = true; }; break; } default: throw new ArgumentOutOfRangeException(); } Start(channelModel, action, delay*1000); } }
/// <summary> /// Provides a deterministic way to create the Channel property. /// </summary> public static void CreateChannel() { if (_chvm == null) { _chvm = new ChannelViewModel(); } }
/// <summary> /// Provides a deterministic way to delete the Channel property. /// </summary> public static void ClearChannel() { if (_chvm != null) _chvm.Cleanup(); _chvm = null; }
public JsonResult UpdateChannel([DataSourceRequest] DataSourceRequest request, ChannelViewModel channel) { foreach (var propertyName in ModelState.Select(modelError => modelError.Key)) { if (propertyName.Contains("Client")) { ModelState[propertyName].Errors.Clear(); } else if (propertyName.Contains("Provider")) { ModelState[propertyName].Errors.Clear(); } } if (channel == null || !ModelState.IsValid) { return Json(new[] { channel }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet); } var updatedChannel = this.channels.UpdateChannel(channel); var loggedUserId = this.User.Identity.GetUserId(); Base.CreateActivity(ActivityType.Edit, updatedChannel.Id.ToString(), ActivityTargetType.Channel, loggedUserId); return Json((new[] { channel }.ToDataSourceResult(request, ModelState)), JsonRequestBehavior.AllowGet); }
public static CancellationTokenSource Start(ChannelViewModel channelModel, Action action, int intervalInMilliseconds) { var tokenSource = new CancellationTokenSource(); AddToken(channelModel, tokenSource); PeriodicTaskFactory.Start(action, intervalInMilliseconds, cancelToken: tokenSource.Token); return tokenSource; }
public ChannelViewModel UpdateChannel(ChannelViewModel channel) { var channelFromDb = this.Data.Channels .All() .FirstOrDefault(c => c.Id == channel.Id); channelFromDb.Name = channel.Name; channelFromDb.ReveivingOptions = channel.ReveivingOptions; channelFromDb.SatelliteData = channel.SatelliteData; channelFromDb.Comments = channel.Comments; channelFromDb.IsVisible = channel.IsVisible; if (string.IsNullOrEmpty(channel.EpgSource) && string.IsNullOrEmpty(channelFromDb.EpgSource)) { channelFromDb.EpgSource = "#"; } else { channelFromDb.EpgSource = channel.EpgSource; } if (string.IsNullOrEmpty(channel.Website) && string.IsNullOrEmpty(channelFromDb.Website)) { channelFromDb.Website = "#"; } else { channelFromDb.Website = channel.Website; } if (string.IsNullOrEmpty(channel.Presentation) && string.IsNullOrEmpty(channelFromDb.Presentation)) { channelFromDb.Presentation = "#"; } else { channelFromDb.Presentation = channel.Presentation; } if (string.IsNullOrEmpty(channel.ContractTemplate) && string.IsNullOrEmpty(channelFromDb.ContractTemplate)) { channelFromDb.ContractTemplate = "#"; } else { channelFromDb.ContractTemplate = channel.ContractTemplate; } if (string.IsNullOrEmpty(channel.LogoLink) && string.IsNullOrEmpty(channel.LogoLink)) { channelFromDb.LogoLink = "#"; } else { channelFromDb.LogoLink = channel.LogoLink; } this.Data.Channels.SaveChanges(); return channel; }
public static Task RunOnce(ChannelViewModel channelModel, Action action) { var tokenSource = new CancellationTokenSource(); AddToken(channelModel, tokenSource); return PeriodicTaskFactory.Start(action, cancelToken: tokenSource.Token, maxIterations: 1); }
public static void Stop(ChannelViewModel channelModel, CancellationTokenSource tokenSource) { lock (LockObject) { if (CancellationTokenSources.ContainsKey(channelModel) && CancellationTokenSources[channelModel].Contains(tokenSource)) { if (!tokenSource.IsCancellationRequested) { tokenSource.Cancel(); tokenSource.Dispose(); } CancellationTokenSources[channelModel].Remove(tokenSource); } } }
// Channel was parted private void OnParted(ChannelViewModel model) { model.Parted -= OnParted; Application.Current.Dispatcher.Invoke(() => { Channels.Remove(model); }); }