public bool IsMetadataSaverEnabled(string name) { return(!ListHelper.ContainsIgnoreCase(DisabledMetadataSavers, name)); }
private PlayMethod?GetVideoDirectPlayProfile(VideoOptions options, DeviceProfile profile, MediaSourceInfo mediaSource, MediaStream videoStream, MediaStream audioStream) { // See if it can be direct played DirectPlayProfile directPlay = null; foreach (DirectPlayProfile i in profile.DirectPlayProfiles) { if (i.Type == DlnaProfileType.Video && IsVideoDirectPlaySupported(i, mediaSource, videoStream, audioStream)) { directPlay = i; break; } } if (directPlay == null) { return(null); } string container = mediaSource.Container; List <ProfileCondition> conditions = new List <ProfileCondition>(); foreach (ContainerProfile i in profile.ContainerProfiles) { if (i.Type == DlnaProfileType.Video && ListHelper.ContainsIgnoreCase(i.GetContainers(), container)) { foreach (ProfileCondition c in i.Conditions) { conditions.Add(c); } } } ConditionProcessor conditionProcessor = new ConditionProcessor(); int? width = videoStream == null ? null : videoStream.Width; int? height = videoStream == null ? null : videoStream.Height; int? bitDepth = videoStream == null ? null : videoStream.BitDepth; int? videoBitrate = videoStream == null ? null : videoStream.BitRate; double?videoLevel = videoStream == null ? null : videoStream.Level; string videoProfile = videoStream == null ? null : videoStream.Profile; float? videoFramerate = videoStream == null ? null : videoStream.AverageFrameRate ?? videoStream.AverageFrameRate; bool? isAnamorphic = videoStream == null ? null : videoStream.IsAnamorphic; bool? isCabac = videoStream == null ? null : videoStream.IsCabac; int? audioBitrate = audioStream == null ? null : audioStream.BitRate; int? audioChannels = audioStream == null ? null : audioStream.Channels; string audioProfile = audioStream == null ? null : audioStream.Profile; TransportStreamTimestamp?timestamp = videoStream == null ? TransportStreamTimestamp.None : mediaSource.Timestamp; int?packetLength = videoStream == null ? null : videoStream.PacketLength; int?refFrames = videoStream == null ? null : videoStream.RefFrames; // Check container conditions foreach (ProfileCondition i in conditions) { if (!conditionProcessor.IsVideoConditionSatisfied(i, audioBitrate, audioChannels, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isCabac, refFrames)) { return(null); } } string videoCodec = videoStream == null ? null : videoStream.Codec; if (string.IsNullOrEmpty(videoCodec)) { return(null); } conditions = new List <ProfileCondition>(); foreach (CodecProfile i in profile.CodecProfiles) { if (i.Type == CodecType.Video && i.ContainsCodec(videoCodec)) { foreach (ProfileCondition c in i.Conditions) { conditions.Add(c); } } } foreach (ProfileCondition i in conditions) { if (!conditionProcessor.IsVideoConditionSatisfied(i, audioBitrate, audioChannels, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isCabac, refFrames)) { return(null); } } if (audioStream != null) { string audioCodec = audioStream.Codec; if (string.IsNullOrEmpty(audioCodec)) { return(null); } conditions = new List <ProfileCondition>(); foreach (CodecProfile i in profile.CodecProfiles) { if (i.Type == CodecType.VideoAudio && i.ContainsCodec(audioCodec)) { foreach (ProfileCondition c in i.Conditions) { conditions.Add(c); } } } foreach (ProfileCondition i in conditions) { if (!conditionProcessor.IsVideoAudioConditionSatisfied(i, audioChannels, audioBitrate, audioProfile)) { return(null); } } } if (mediaSource.Protocol == MediaProtocol.Http) { if (_localPlayer.CanAccessUrl(mediaSource.Path, mediaSource.RequiredHttpHeaders.Count > 0)) { return(PlayMethod.DirectPlay); } } else if (mediaSource.Protocol == MediaProtocol.File) { if (_localPlayer.CanAccessFile(mediaSource.Path)) { return(PlayMethod.DirectPlay); } } if (!mediaSource.SupportsDirectStream) { return(null); } return(PlayMethod.DirectStream); }
public static bool IsActivated(string name) { List <string> list = ListHelper.LoadList(PluginPaths.LoadOrderListFile).ToList(); return(list.Contains(name)); }
/// <summary> /// Returns a List of Plugin Pointer based on a List path and a Host. /// </summary> /// <param name="path">The Path of the List File</param> /// <param name="host">Host Instance</param> /// <returns></returns> private static List <PluginAssemblyPointer> LoadFromList(string path, IPluginHost host) { return(ListHelper.LoadList(path).Where(x => !string.IsNullOrEmpty(x)) .Select(x => new PluginAssemblyPointer(x, host)).ToList()); }
public ActionResult Create(GarageViewModel model) { model.Country = "US"; model.CreatedDt = DateTime.Now.Date; model.CreatedBy = "ADmin"; IGeocoder geocoder = new GoogleGeocoder() { ApiKey = "AIzaSyA3CNMI-_JAV9-dWIctroZQTuUwjZygT3A" }; IEnumerable <Address> addresses = geocoder.Geocode(model.Garage_Address); model.Latitute = addresses.First().Coordinates.Latitude; model.Longitude = addresses.First().Coordinates.Longitude; ModelState.Remove("State"); ModelState.Remove("City"); ModelState.Remove("Country"); if (ModelState.IsValid) { Garage entity = new Garage(); entity.Garage_Name = model.Garage_Name; entity.Contact_Person = model.Contact_Person; entity.Garage_Address = model.Garage_Address; entity.Phone_Number = model.Phone_Number; entity.Email = model.Email; entity.IsActive = model.IsActive.HasValue ? model.IsActive.Value : false; entity.Garage_Address = model.Garage_Address; entity.City = model.City; entity.State = model.State; entity.Pincode = model.Pincode; entity.OpenTime = model.OpenTime; entity.CloseTime = model.CloseTime; //entity.ServiceDays = model.ServiceDays; entity.ServiceDays = string.Join(",", model.ServiceDays); entity.Country = "US"; entity.CreatedDt = DateTime.Now.Date; entity.CreatedBy = "Admin"; entity.Latitute = model.Latitute; entity.Longitude = model.Longitude; try { db.Garages.Add(entity); db.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } throw raise; } AddNotification(Models.NotifyType.Success, "Records Successfully Saved.", true); return(RedirectToAction("Index")); } ViewBag.StateId = new SelectList(db.States, "Id", "StateName", model.State); ViewBag.CityId = new SelectList(db.Cities.Where(b => b.StateID == model.State), "Id", "CityName", model.City); model.AvailableServiceDays = ListHelper.GetDayNameList(); model.AvailableSubscriptionTypes = ListHelper.GetSubscriptionTypeList(); return(View(model)); }
/// <summary> /// This method returns the Links With Href /// </summary> public string ReplaceLinksWithHref(string text) { // initial value string formattedText = text; // delimiters char[] delimiters = { ' ', '\n', }; // If the text string exists if (ContainsLink(text)) { // if the NewLine is not found if (!text.Contains(Environment.NewLine)) { // The parsing on lines isn't working, this is a good hack till // I rewrite the parser to be more robust someday text = text.Replace("\n", Environment.NewLine); } // just in case, fix for the hack text = text.Replace("\r\r", "\r"); // Get the text lines List <TextLine> lines = WordParser.GetTextLines(text); // If the lines collection exists and has one or more items if (ListHelper.HasOneOrMoreItems(lines)) { // iterate the textLines foreach (TextLine line in lines) { // Get the words - parse only on space List <Word> words = WordParser.GetWords(line.Text, delimiters); // If the words collection exists and has one or more items if (ListHelper.HasOneOrMoreItems(words)) { // iterate each word foreach (Word word in words) { // if this is a link if (StartsWithLink(word.Text, true)) { // set the word as a href string temp = "<a href=" + word.Text + " target=_blank>" + word.Text + "</a>"; // if the word.Text ends with a known extension, but does not start with http or https if ((TextEndsWithKnownExtension(word.Text)) && (!StartsWithLink(word.Text, false))) { // send the user to https. Its 2020, and if the user is send someone to an insecure site, // they must specify http:// in the link, otherwise don't post a link to an insecure site. temp = "<a href=https://" + word.Text + " target=_blank>" + word.Text + "</a>"; } // Replace out the word with the link formattedText = formattedText.Replace(word.Text, temp); } } } } } } // return value return(formattedText); }
protected override void AssignDataSourceToControl(object dataSource) { if (_table != null) { ClearAllCollectionsOfControls(); _table.Rows.Clear(); var tr = new TableRow(); _table.Rows.Add(tr); var tc = new TableCell(); tr.Cells.Add(tc); if (AllowEdit && ShowButtons) { _btnAddFirst = new ASPxButton { AutoPostBack = false, EnableClientSideAPI = true }; _btnAddFirst.SetClientSideEventHandler("Click", "function(s, e) { " + "CallbackPanel" + Model.Id + ".PerformCallback(\"add\"); }"); _btnAddFirst.Text = AddButtonCaption; _btnAddFirst.ID = "btnAddFirst"; _btnAddFirst.Visible = true; tc.Controls.Add(_btnAddFirst); } _dataSourceList = ListHelper.GetList(dataSource); if (_dataSourceList == null) { return; } if (HeadersOnTopOnly) { CreateHeaderRows(null).ForEach(hr => _table.Rows.Add(hr)); } if (_dataSourceList.Count > 0) { int rowindex = 0; foreach (XPBaseObject item in _dataSourceList) { CreateRowForObject(item, false, rowindex); rowindex++; } } CreateFooterRow(); ToggleHeadersVisibility(); foreach (IModelColumn column in Model.Columns) { if (column.Index >= 0) { if ( _controlsPerObjectInList.Values.ToList() .TrueForAll( d => d.ContainsKey(column.PropertyName) && !d[column.PropertyName].Visible)) { if (_headerCellsPerColumn.ContainsKey(column.PropertyName)) { _headerCellsPerColumn[column.PropertyName].Visible = false; } if (_footerCellsPerColumn.ContainsKey(column.PropertyName)) { _footerCellsPerColumn[column.PropertyName].Visible = false; } } } } } }
public MountedCamera GetRandomRearFacingCamera() { return(ListHelper.GetRandomValue(rearFacingCameras)); }
/// <summary> /// This method returns the Project Files /// </summary> public int ReadProjectFiles() { // initial value int count = 0; // clear the list box ProjectFilesListBox.Items.Clear(); // if the value for HasProject is true if ((HasProject) && (Project.HasSolutions)) { // iterate the solutions foreach (Solution solution in Project.Solutions) { // If the value for the property solution.HasProjects is true if (solution.HasProjects) { // iterate the solutions foreach (VSProject project in solution.Projects) { // Create a new instance of a 'DirectoryInfo' object. DirectoryInfo directory = new DirectoryInfo(project.Path); // Create a new collection of 'ProjectFile' objects. project.Files = new List <ProjectFile>(); // if the project has a path and the path exists on the disk if ((project.HasPath) && (File.Exists(project.Path))) { // read the text of the file string fileText = File.ReadAllText(project.Path); // parse the textLines List <TextLine> lines = WordParser.GetTextLines(fileText); // If the lines collection exists and has one or more items if (ListHelper.HasOneOrMoreItems(lines)) { // get the lines that contain include and either .jpg or .png lines = lines.Where(x => x.Text.Contains("Include=") && (x.Text.Contains(".jpg")) || (x.Text.Contains(".png"))).ToList(); // iterate the collection of lines if (ListHelper.HasOneOrMoreItems(lines)) { // Iterate the collection of string objects foreach (TextLine line in lines) { // create a projectFile ProjectFile projectFile = new ProjectFile(); // if this line is considered content projectFile.IsContent = line.Text.Contains("Content"); // get the index of Include= int index = line.Text.IndexOf("Include="); // if the index exists if (index >= 0) { // get the tempPath string tempPath = line.Text.Substring(index + 9, line.Text.Length - index - 8 - 4 - 1); // now build the FullPath projectFile.FullPath = Path.Combine(directory.Parent.FullName, tempPath); // if the file exists if (File.Exists(projectFile.FullPath)) { // Create a new instance of a 'FileInfo' object. FileInfo fileInfo = new FileInfo(projectFile.FullPath); // set the name projectFile.Name = fileInfo.Name; // set the size projectFile.Size = fileInfo.Length; // add this file project.Files.Add(projectFile); // Add this item ProjectFilesListBox.Items.Add(projectFile.Name); // increment count count++; } } } } } } } } } } // display the count ProjectImagesCountControl.Text = count.ToString(); // display the count this.Refresh(); // return value return(count); }
/// <summary> /// This method creates the ButtonDescriptors for each ResposneType that could end up as a button click. /// This separates the presentation layer from the implementation of the response request in case it chances. /// </summary> internal static List <ButtonDescriptor> CreateButtonDescriptors(List <ResponseTypeEnum> allowResponseTypes) { // initial value List <ButtonDescriptor> buttonDescriptors = null; // If the allowResponseTypes collection exists and has one or more items if (ListHelper.HasOneOrMoreItems(allowResponseTypes)) { // Create the return collection buttonDescriptors = new List <ButtonDescriptor>(); // Iterate the collection of ResponseTypeEnum objects foreach (ResponseTypeEnum allowedResponseType in allowResponseTypes) { switch (allowedResponseType) { case ResponseTypeEnum.PlaceBet: // Create the buttonDescriptor ButtonDescriptor placeBetButtonDescriptor = new ButtonDescriptor("Place Bet", DefaultButtonWidth); // Add this item buttonDescriptors.Add(placeBetButtonDescriptor); // required break; case ResponseTypeEnum.SitOut: // Create the buttonDescriptor ButtonDescriptor sitOutButtonDescriptor = new ButtonDescriptor("Sit Out", DefaultButtonWidth); // Add this item buttonDescriptors.Add(sitOutButtonDescriptor); // required break; case ResponseTypeEnum.Hit: // Create the buttonDescriptor ButtonDescriptor hitButtonDescriptor = new ButtonDescriptor("Hit", DefaultButtonWidth); // Add this item buttonDescriptors.Add(hitButtonDescriptor); // required break; case ResponseTypeEnum.Stand: // Create the buttonDescriptor ButtonDescriptor standButtonDescriptor = new ButtonDescriptor("Stand", DefaultButtonWidth); // Add this item buttonDescriptors.Add(standButtonDescriptor); // required break; case ResponseTypeEnum.Insurance: // Create the buttonDescriptor ButtonDescriptor insuranceButtonDescriptor = new ButtonDescriptor("Insurance?", ExtraWideButtonWidth); // Add this item buttonDescriptors.Add(insuranceButtonDescriptor); // required break; case ResponseTypeEnum.No: // Create the buttonDescriptor ButtonDescriptor noButtonDescriptor = new ButtonDescriptor("No", SlimButtonWidth); // Add this item buttonDescriptors.Add(noButtonDescriptor); // required break; } } } // return value return(buttonDescriptors); }
/// <summary> /// This method Parse Projects /// </summary> public List <VSProject> ParseProjects(Solution solution) { // initial value List <VSProject> projects = new List <VSProject>(); // typical delimiter characters char[] commaDelimiter = { ',' }; // If the solutionFilePath string exists if ((NullHelper.Exists(solution)) && (File.Exists(solution.Path))) { // read the text of the file string fileText = File.ReadAllText(solution.Path); // parse the textLines List <TextLine> lines = WordParser.GetTextLines(fileText); // If the lines collection exists and has one or more items if (ListHelper.HasOneOrMoreItems(lines)) { // get the projectLines List <TextLine> projectLines = lines.Where(x => x.Text.StartsWith("Project")).Where(x => x.Text.Contains(".csproj")).ToList(); // if there are one or more projectLines if (ListHelper.HasOneOrMoreItems(projectLines)) { // Iterate the collection of TextLine objects foreach (TextLine line in projectLines) { // if the line.Text exists if (TextHelper.Exists(line.Text)) { // get the equalSignIndex int equalSignIndex = line.Text.IndexOf("="); // if the EqualSignIndex exists if (equalSignIndex >= 0) { // get the text of the word on the right side of the equal sign string wordsOnRightSideOfEqualSign = line.Text.Substring(equalSignIndex + 1).Trim(); // If the wordsOnRightSideOfEqualSign string exists if (TextHelper.Exists(wordsOnRightSideOfEqualSign)) { // get the words List <Word> words = WordParser.GetWords(wordsOnRightSideOfEqualSign, commaDelimiter); // if there are at least two words if ((words != null) && (words.Count >= 3)) { // create a project VSProject project = new VSProject(); // get the text string projectPath = words[1].Text.Substring(2, words[1].Text.Length - 3); // Create a directory DirectoryInfo directory = new DirectoryInfo(solution.Path); // combine the solutoin and the path string path = Path.Combine(directory.Parent.FullName, projectPath); // set the path project.Path = path; // Get the projectName project.Name = words[0].Text.Replace("\"", ""); // set the solution project.Solution = solution; string temp = words[2].Text.Substring(2, words[2].Text.Length - 3).Replace(@"\", "").Replace("{", "").Replace("}", "").Trim(); // get the tempId Guid tempId = Guid.Empty; // parse the Guid Guid.TryParse(temp, out tempId); // set the projectId project.Id = tempId; // now find the index of this project so the same project is not added twice int index = GetProjectIndex(project.Id); // if the index was found if (index < 0) { // Add this project projects.Add(project); } } } } } } } } } // return value return(projects); }
/// <summary> /// This method Add All Files /// </summary> public void AddAllFiles() { // Get the list of files List <string> files = new List <string>(); // get the root path string path = ProjectRootControl.Text; // create an object to hold the types of objects to find List <string> extensions = new List <string>(); // add extensions to find extensions.Add(".jpg"); extensions.Add(".png"); // load the files FileHelper.GetFilesRecursively(path, ref files, extensions); // If the files collection exists and has one or more items if (ListHelper.HasOneOrMoreItems(files)) { // Iterate the collection of string objects foreach (string file in files) { // create a fileInfo FileInfo fileInfo = new FileInfo(file); // Add this file FilesListBox.Items.Add(fileInfo.Name); // Create a new instance of a 'ProjectFile' object. ProjectFile projectFile = new ProjectFile(); // Set the FullPath projectFile.FullPath = fileInfo.FullName; // Set the name projectFile.Name = fileInfo.Name; // if the extension is png if (fileInfo.Extension == ".png") { // set the ImageType projectFile.ImageType = ImageTypeEnum.Png; } else if (fileInfo.Extension == ".jpg") { // set the ImageType projectFile.ImageType = ImageTypeEnum.Jpeg; } // Set the Length projectFile.Size = fileInfo.Length; // Add this file Project.AllFiles.Add(projectFile); } // Set the count this.ItemsFoundControl.Text = files.Count.ToString(); this.ItemsFoundControl.Visible = true; this.ItemsFoundControl.LabelColor = Color.LemonChiffon; } else { // hide the control this.ItemsFoundControl.Visible = false; } }
/// <summary> /// Resolve dependencies for Dynamite Helpers /// </summary> private void ResolveDependencies() { this.contentTypeHelper = AppContainer.Current.Resolve<ContentTypeHelper>(); this.taxonomyHelper = AppContainer.Current.Resolve<TaxonomyHelper>(); this.listHelper = AppContainer.Current.Resolve<ListHelper>(); this.contentOrganizerHelper = AppContainer.Current.Resolve<ContentOrganizerHelper>(); this.myCustomRule = AppContainer.Current.Resolve<MyCustomRule>(); }
/// <summary> /// This method converts a Data Table to a DTNTable for storing some of the scheme info in SQL. /// </summary> public static DTNTable ConvertDataTable(DataTable sourceTable, Project project, DTNDatabase dtnDatabase) { // initial value DTNTable table = null; // if the sourceTable exists and there are one or more Databases for this project if ((NullHelper.Exists(sourceTable, project, dtnDatabase)) && (project.HasDatabases) && (ListHelper.HasOneOrMoreItems(project.Databases))) { // Create a new instance of a 'DTNTable' object. table = new DTNTable(); // Set any properties to store table.ClassFileName = sourceTable.ClassFileName; table.ClassName = sourceTable.ClassName; table.Exclude = sourceTable.Exclude; table.CreateBindingCallback = sourceTable.CreateBindingCallback; // Only 1 Database is officially supported now table.DatabaseId = project.Databases[0].DatabaseId; // Convert the Fields table.Fields = ConvertDataFields(sourceTable.Fields, table.DatabaseId, project.ProjectId, sourceTable.TableId); table.IsView = sourceTable.IsView; table.ProjectId = project.ProjectId; table.Serializable = sourceTable.Serializable; table.TableName = sourceTable.Name; // Update 3.26.2019: The TableId does not actually exist on the DataTable. // This will only be set when a project is reopened so that duplicate tables // are not attempted to be inserted. table.UpdateIdentity(sourceTable.TableId); } // return value return(table); }
public GoalsController(IGoalManager goalManager, ListHelper listHelper) { _goalManager = goalManager; ListHelper = listHelper; }
private void ResolveDependencies() { this._fieldHelper = AppContainer.Current.Resolve<FieldHelper>(); this._listHelper = AppContainer.Current.Resolve<ListHelper>(); this._contentTypeHelper = AppContainer.Current.Resolve<ContentTypeHelper>(); }
/// <summary> /// This method returns the Auto Comment Text for the SourceCode given. /// </summary> public string GetAutoCommentText(CM.CommentDictionary commentDictionary, string sourceCode, DictionaryInfo dictionaryInfo) { // initial value string commentText = ""; // the * is replaced with TargetPattern string target = ""; // the % is replaced with TargetPattern2 string target2 = ""; // locals List <CodeComment> comments = null; List <CodeComment> comments2 = null; bool matchFound = false; string sourceCodeCopy = ""; // if the dictionaryInfo object exists if (dictionaryInfo != null) { // if the sourceCode exists if (TextHelper.Exists(sourceCode)) { // remove the semicolon sourceCode = sourceCode.Replace(";", ""); // trim the sourceCode sourceCode = sourceCode.Trim(); // if the commentDictionary exists if (commentDictionary != null) { // if UseCustomDictionary if (dictionaryInfo.UseCustomDictionary) { // if we need to try custom dictionary first if (dictionaryInfo.TryCustomDictionaryFirst) { // set the comment collection to try first comments = commentDictionary.CustomComments; // set the comment collection to try next comments2 = commentDictionary.Comments; } else { // set the comment collection to try first comments = commentDictionary.Comments; // set the comment collection to try next comments2 = commentDictionary.CustomComments; } } else { // set the comments comments = commentDictionary.Comments; // comments2 is not used } // if there are one or more comments in the comments collection if (ListHelper.HasOneOrMoreItems(comments)) { // iterate the comments foreach (CM.CodeComment comment in comments) { // local sourceCodeCopy = sourceCode; // reply any replacements to the source sourceCodeCopy = ApplyReplacements(sourceCodeCopy, comment.Replacements, ReplacementTargetEnum.ApplyToSource); // if this is a match if (IsMatch(comment, sourceCodeCopy, ref target, ref target2)) { // a match was found matchFound = true; // replace target and target2 if any replacements exist target = ApplyReplacements(target, comment.Replacements, ReplacementTargetEnum.ApplyToTarget1); // apply any replacements to target2 target2 = ApplyReplacements(target2, comment.Replacements, ReplacementTargetEnum.ApplyToTarget2); // replace out the * with the target commentText = comment.Comment.Replace("*", target); // replace out the % with the target2 commentText = commentText.Replace("%", target2); // break out of the loop break; } } } // if the commentText has not been set and comments2 collection has one or more items if ((!matchFound) && (ListHelper.HasOneOrMoreItems(comments2))) { // iterate the comments foreach (CM.CodeComment comment in comments2) { // local sourceCodeCopy = sourceCode; // for debugging only string name = comment.Name; // set the CommentID int id = comment.ID; // if this is a match if (IsMatch(comment, sourceCode, ref target, ref target2)) { // replace target and target2 if any replacements exist target = ApplyReplacements(target, comment.Replacements, ReplacementTargetEnum.ApplyToTarget1); // apply any replacements to target2 target2 = ApplyReplacements(target2, comment.Replacements, ReplacementTargetEnum.ApplyToTarget2); // replace out the * with the target commentText = comment.Comment.Replace("*", target); // replace out the % with the target2 commentText = commentText.Replace("%", target2); // break out of the loop break; } } } } // if the commentText exists if (TextHelper.Exists(commentText)) { // if a(n) is present, we need to determine if the target starts with a vowel or not if (commentText.Contains("a(n)")) { // does the target start with a vowel? bool startsWithVowel = DoesTargetStartWithAVowel(target); // if the target starts with a vowel if (startsWithVowel) { // replace out a(n) with an commentText = commentText.Replace("a(n)", "an"); } else { // replace out a(n) with a commentText = commentText.Replace("a(n)", "a"); } } } } } // return value return(commentText); }
public async Task <IActionResult> EditAsync(string id, PermissionEditModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } var role = await _context .Roles .Include(r => r.RoleClaims) .FirstOrDefaultAsync(r => r.Name == id); if (role == null) { return(BadRequest()); } role.RoleClaims = new List <ApplicationRoleClaim>(); var allPermissions = new List <Checkbox>(); var selectedDepartmentPermissions = viewModel.Department.ReturnSelectedActions(); ListHelper <Checkbox> .AddRange(allPermissions, selectedDepartmentPermissions); var selectedNoticePermissions = viewModel.Notice.ReturnSelectedActions(); ListHelper <Checkbox> .AddRange(allPermissions, selectedNoticePermissions); var selectedLeavePermissions = viewModel.Leave.ReturnSelectedActions(); ListHelper <Checkbox> .AddRange(allPermissions, selectedLeavePermissions); var selectedRolePermissions = viewModel.Role.ReturnSelectedActions(); ListHelper <Checkbox> .AddRange(allPermissions, selectedRolePermissions); var selectedUserPermissions = viewModel.User.ReturnSelectedActions(); ListHelper <Checkbox> .AddRange(allPermissions, selectedUserPermissions); var selectedPermissionForPermissions = viewModel.Permission.ReturnSelectedActions(); ListHelper <Checkbox> .AddRange(allPermissions, selectedPermissionForPermissions); if (viewModel.Mail.IsSelected) { allPermissions.Add(viewModel.Mail); } foreach (var permission in allPermissions) { role.RoleClaims.Add(new ApplicationRoleClaim { ClaimType = CustomClaimType.Permission, ClaimValue = permission.Value }); } await _context.SaveChangesAsync(); return(RedirectToAction("Edit", new { id = id }).WithSuccess(string.Empty, $"permissions for {id} updated")); }
public HelpViewModel() { AllInputs = ListHelper.GetEnumDescItems <HelpInputTypes>(); }
/// <summary> /// This method returns the Next Card from the top of the 'Deck'. /// </summary> public Card PullNextCard(bool remove = true, bool ignoreShuffle = false, bool ignoreException = false) { // initial value Card nextCard = null; // If the RandomIntStorage object exists if (ListHelper.HasOneOrMoreItems(this.RandomCardStorage)) { // if ignreShuffle is false and the ShuffleOptions exist and have one or more shuffles required if ((!ignoreShuffle) && (this.HasShuffleOptions) && (this.ShuffleOptions.HasBeforeItemIsPulledShuffles)) { // Shuffle the deck this.Shuffle(this.ShuffleOptions.BeforeItemIsPulledShuffles); } // pull out the next Card off the top of the deck nextCard = this.RandomCardStorage[0]; // if the value for remove is true if (remove) { // Remove the Card that was just pulled this.RandomCardStorage.RemoveAt(0); } } else if (!this.HasRandomCardStorage) { // if the value for ignoreException is false if (!ignoreException) { // raise an exception throw new Exception("The 'RandomCardStorage' property is not set in the 'PullNextCard' method."); } } else { // if the value for ignoreException is false if (!ignoreException) { // raise an exception throw new Exception("The 'RandomCardStorage' property is empty in the 'PullNextItem' method."); } } // If the nextCard object exists if (NullHelper.Exists(nextCard)) { // Uncomment this to send a report to the console // LogReport(nextCard); // if ignreShuffle is false and the ShuffleOptions exist and have one or more shuffles required if ((!ignoreShuffle) && (this.HasShuffleOptions) && (this.ShuffleOptions.HasAfterItemIsPulledShuffles)) { // Shuffle the deck this.Shuffle(this.ShuffleOptions.AfterItemIsPulledShuffles); } } // return value return(nextCard); }
/// <summary> /// Actualiza los datos del fichero origen generando /// un nuevo archivo. /// </summary> /// <param name="conexion">Conexión a utilizar para realizar las consultas.</param> /// <param name="sobreescribir"><c>true</c> para sobreescribir el archivo destino /// si existe (valor por defecto). <c>false</c> en caso contrario.</param> /// <exception cref="ArgumentNullException">Si no se especifica el archivo origen o el destino.</exception> /// <exception cref="FileNotFoundException">Si no existe el archivo origen.</exception> /// <exception cref="ArgumentException">Si el archivo destino existe y /// <paramref name="sobreescribir"/> es <c>false</c>.</exception> public void ActualizarDatos(Conexion conexion, bool sobreescribir = true) { if (String.IsNullOrWhiteSpace(this.Origen)) { log.Error("No se ha especificado el archivo origen"); throw new ArgumentNullException("Origen", "No se ha especificado el archivo Origen"); } if (!File.Exists(this.Origen)) { log.ErrorFormat("No existe el archivo origen: {0}", this.Origen); throw new FileNotFoundException("El archivo origen especificado no existe.", this.Origen); } if (String.IsNullOrWhiteSpace(this.Destino)) { log.Error("No se ha especificado el archivo destino"); throw new ArgumentNullException("Destino", "No se ha especificado el archivo Destino"); } if (!sobreescribir && File.Exists(this.Destino)) { log.ErrorFormat("El archivo destino existe y no se sobreescribirá: {0}", this.Destino); throw new ArgumentException("El archivo destino existe y no se sobreescribirá"); } Excel.Application excelApp = null; Excel.Workbook libro = null; try { excelApp = new Excel.Application(); excelApp.Visible = false; excelApp.DisplayAlerts = false; libro = excelApp.Workbooks.Open(this.Origen); int cont = 0; foreach (Actualizacion item in this.Actualizaciones) { cont++; log.InfoFormat("Aplicando actualización {0}...", cont); Excel.Worksheet hoja = libro.Sheets[item.Hoja]; hoja.Select(); List <object[]> datos = conexion.Ejecutar(item.SQL, false); Excel.Range rango = hoja.get_Range(item.CeldaInicio); if (item.Trasponer) { rango = rango.get_Resize(datos[0].Length, datos.Count); } else { rango = rango.get_Resize(datos.Count, datos[0].Length); } // Convertimos la lista de vectores en una matriz object[,] datos2 = ListHelper.CreateRectangularArray(datos, item.Trasponer); rango.Value = datos2; } libro.SaveAs(this.Destino, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing, Type.Missing, Type.Missing); libro.Close(); excelApp.Quit(); } catch (Exception ex) { log.Error("Error al actualizar el archivo excel", ex); if (libro != null) { libro.Close(); } } finally { // Según las buenas prácticas de Microsoft, nos aseguramos de liberar los recursos GC.Collect(); GC.WaitForPendingFinalizers(); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(libro); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelApp); } }
public static bool IsPackageActivated(string name) { List <string> list = ListHelper.LoadList(PluginPaths.PluginListFile).ToList(); return(list.Select(x => new BasePluginPointer(x)).Any(x => x.PluginName == name)); }
public static int CompareDBTable(DBTable x, DBTable y) { if (x == y) { return(0); } if (x.Type != y.Type) { if (x.Type == DBTableType.Table) { return(-1); } else { return(1); } } var xpars = new List <DBTable>(); x.GetAllParentTables(xpars); var ypars = new List <DBTable>(); y.GetAllParentTables(ypars); var xchil = new List <DBTable>(); x.GetAllChildTables(xchil); var ychil = new List <DBTable>(); y.GetAllChildTables(ychil); if (xpars.Contains(y)) { return(1); } else if (ypars.Contains(x)) { return(-1); } else { var merge = (List <DBTable>)ListHelper.AND(xpars, ypars, null); if (merge.Count > 0) { int r = xpars.Count.CompareTo(ypars.Count); if (r != 0) { return(r); } } // foreach(DBTable xp in xpars) // if(xp.GetChildTables()) } if (xchil.Contains(y)) { return(-1); } else if (ychil.Contains(x)) { return(1); } else { List <DBTable> merge = (List <DBTable>)ListHelper.AND(xchil, ychil, null); if (merge.Count > 0) { int r = xchil.Count.CompareTo(ychil.Count); if (r != 0) { return(r); } } // foreach(DBTable xp in xpars) // if(xp.GetChildTables()) } return(string.Compare(x.Name, y.Name, StringComparison.Ordinal)); }
/// <summary> /// Adds a Package to the Plugin System /// </summary> /// <param name="file">Package Input Path</param> /// <param name="name">When Loaded successfully contains the Name of the Loaded plugin</param> /// <returns>True if the Adding was Successful</returns> internal static bool AddPackage(string file, out string name) { if (!IsInitialized) { throw new Exception("Can not use the plugin System when its not initialized."); } name = null; SendLogDivider(); SendLog("Adding File: " + file); if (PluginPacker.CanLoad(file)) { AddPackageEventArgs <string> args = new AddPackageEventArgs <string>(file, true); OnAddPackage?.Invoke(args); if (args.Cancel) { return(false); } string tempDir = Path.Combine( PluginPaths.GetSystemProcessTempDirectory("Install"), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) ); //TODO: Get temp dir for unpacking Directory.CreateDirectory(tempDir); //TODO: If the package is already installed Write Backup to PluginDir/backup before loading the new package SendLog("Trying to Load File Format: " + Path.GetFileName(file)); PluginPacker.Unpack(file, tempDir); //TODO: Try load Package Data/Plugin Data if (PackageDataManager.CanLoad(tempDir)) { SendLog("Trying to Load Data Format: " + Path.GetFileName(tempDir)); BasePluginPointer ptr = PackageDataManager.LoadData(tempDir); if (ptr != null) { name = ptr.PluginName; ptr.EnsureDirectoriesExist(); AddPackageEventArgs <BasePluginPointer> ptrArgs = new AddPackageEventArgs <BasePluginPointer>(ptr, true); OnAddPackagePointerLoaded?.Invoke(ptrArgs); if (ptrArgs.Cancel) { return(false); } List <string> installedPackages = ListHelper.LoadList(PluginPaths.GlobalPluginListFile).ToList(); List <string> activePackages = ListHelper.LoadList(PluginPaths.PluginListFile).ToList(); string newPackage = ptr.ToKeyPair(); bool isNew = installedPackages.All(x => !x.StartsWith(ptr.PluginName)); if (isNew) { installedPackages.Add(newPackage); } else { if (activePackages.RemoveAll(x => x.StartsWith(ptr.PluginName)) != 0) { activePackages.Add(newPackage); ListHelper.SaveList(PluginPaths.PluginListFile, activePackages.ToArray()); } installedPackages.RemoveAll(x => x.StartsWith(ptr.PluginName)); installedPackages.Add(newPackage); } ListHelper.SaveList(PluginPaths.GlobalPluginListFile, installedPackages.ToArray()); //TODO: Check if the Install would overwrite things. //TODO: Check if the files that are overwritten are in use. //TODO: Make a system that takes instructions from a file at start up to "complete" installations InstallPackageEventArgs iargs = new InstallPackageEventArgs(isNew, ptr, tempDir, true); OnInstallPackage?.Invoke(iargs); if (iargs.Cancel) { return(false); } PackageDataManager.Install(ptr, tempDir); Directory.Delete(tempDir, true); AfterInstallPackage?.Invoke(new InstallPackageEventArgs(isNew, ptr, tempDir, false)); AfterAddPackage?.Invoke(new AfterAddPackageEventArgs(ptr)); return(true); } SendError(new PackageDataException("File Corrupt", file)); } else { SendError(new PackageDataException("Unable to find a Data Serializer", file, null)); } } else { SendError(new PackerException("Unable to find a Packer", file, null)); } return(false); }
/// <summary> /// event is fired when the 'GetDataButton' is clicked. /// </summary> private void GetDataButton_Click(object sender, EventArgs e) { // Erase this.ResultsTextBox.Text = "Generating random data, please wait..."; // Refresh everything this.Refresh(); Application.DoEvents(); // Create a new Gateway instance Gateway gateway = new Gateway(MainForm.ConnectionName); // if the FirstNames do not exist if (!this.HasFirstNames) { // Load the FirstNames this.FirstNames = gateway.LoadFirstNames(); } // if the LastNames do not exist if (!this.HasLastNames) { // Load the LastNames this.LastNames = gateway.LoadLastNames(); } // if the Verbs do not exist if (!this.HasVerbs) { // Load the Verbs this.Verbs = gateway.LoadVerbs(); } // if the Adjectives do not exist if (!this.HasAdjectives) { // Load the Adjectives this.Adjectives = gateway.LoadAdjectives(); } // if the Nouns do not exist if (!this.HasNouns) { // Load the Nouns this.Nouns = gateway.LoadNouns(); } // if all the lists exist if ((ListHelper.HasOneOrMoreItems(FirstNames, LastNames, Adjectives)) && (ListHelper.HasOneOrMoreItems(Verbs, Nouns))) { // Create the shufflers if they don't exist if (!HasShuffler) { // Create a new instance of a 'RandomShuffler' object. Shuffler = new RandomShuffler(0, firstNames.Count, 5); } // if the Shffler2 doesn't exist if (!HasShuffler2) { // Create a new instance of a 'RandomShuffler' object. Shuffler2 = new RandomShuffler(0, lastNames.Count, 5); } // if the Shffler3 doesn't exist if (!HasShuffler3) { // Create a new instance of a 'RandomShuffler' object. Shuffler3 = new RandomShuffler(0, Verbs.Count, 5); } // if the Shffler4 doesn't exist if (!HasShuffler4) { // Create a new instance of a 'RandomShuffler' object. Shuffler4 = new RandomShuffler(0, Adjectives.Count, 5); } // if the Shffler5 doesn't exist if (!HasShuffler5) { // Create a new instance of a 'RandomShuffler' object. Shuffler5 = new RandomShuffler(0, Nouns.Count, 5); } // Display the character name this.ResultsTextBox.Text = "Random Characters/Plot: " + Environment.NewLine; // iterate up to 10 names for (int x = 0; x < 10; x++) { // Pull the next items int firstNameIndex = shuffler.PullNextItem(); int lastNameIndex = shuffler2.PullNextItem(); int verbIndex = shuffler3.PullNextItem(); int adjectiveIndex = shuffler4.PullNextItem(); int nounIndex = shuffler5.PullNextItem(); // Set the first and last name string firstName = firstNames[firstNameIndex].Name; string lastName = lastNames[lastNameIndex].Name; string verb = Verbs[verbIndex].WordText; string adjective = Adjectives[adjectiveIndex].WordText; string noun = Nouns[nounIndex].WordText; // Add to the text this.ResultsTextBox.Text += firstName + " " + lastName + " " + verb + " " + adjective + " " + noun; // if not the last item if (x < 9) { // Display the character name this.ResultsTextBox.Text += Environment.NewLine; } } } }
static void Main(string[] args) { var listHelper = new ListHelper(); var timeHelper = new TimeHelper(); var primeHelper = new PrimeHelper(); bool exit = false; while (!exit) { Console.Write("Menu: "); string input = Console.ReadLine().ToLower(); DateTime start = DateTime.Now; List <long> problemsDone = new List <long> () { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; bool isNumeric = int.TryParse(input, out int problemNumber); if (isNumeric && problemsDone.Contains(problemNumber)) { InvokeProblemSolveMethod(problemNumber); timeHelper.TimeToSolve(start); } else { switch (input) { case "pf": primeHelper.WritePrimeFactorisation(); break; case "pal": var p4 = new Problem4(); Console.Write("Type any number to see if its a palindrom: "); int i = Int32.Parse(Console.ReadLine()); Console.WriteLine(p4.NumberIsPalindrom(i)); break; case "po": Console.Write("Type any number to see the primes up to this ordinal: "); long j = Int64.Parse(Console.ReadLine()); Console.WriteLine(listHelper.ListItems(primeHelper.PrimesUpToOrdinal(j))); break; case "e": exit = true; Console.WriteLine("Exitting"); break; case "help": Console.WriteLine("Options: Problem <n> = <n>, Prime Factorisation = pf, Is number palindrom = pal, Exit = e"); Console.WriteLine($"Problems Completed: {listHelper.ListItems (problemsDone)}"); break; default: Console.WriteLine("Not a valid option, write 'help' to see available options"); break; } } Console.WriteLine("---------------"); } }
private PlayMethod?GetVideoDirectPlayProfile(DeviceProfile profile, MediaSourceInfo mediaSource, MediaStream videoStream, MediaStream audioStream, bool isEligibleForDirectPlay, bool isEligibleForDirectStream) { // See if it can be direct played DirectPlayProfile directPlay = null; foreach (DirectPlayProfile i in profile.DirectPlayProfiles) { if (i.Type == DlnaProfileType.Video && IsVideoDirectPlaySupported(i, mediaSource, videoStream, audioStream)) { directPlay = i; break; } } if (directPlay == null) { _logger.Debug("Profile: {0}, No direct play profiles found for Path: {1}", profile.Name ?? "Unknown Profile", mediaSource.Path ?? "Unknown path"); return(null); } string container = mediaSource.Container; List <ProfileCondition> conditions = new List <ProfileCondition>(); foreach (ContainerProfile i in profile.ContainerProfiles) { if (i.Type == DlnaProfileType.Video && ListHelper.ContainsIgnoreCase(i.GetContainers(), container)) { foreach (ProfileCondition c in i.Conditions) { conditions.Add(c); } } } ConditionProcessor conditionProcessor = new ConditionProcessor(); int? width = videoStream == null ? null : videoStream.Width; int? height = videoStream == null ? null : videoStream.Height; int? bitDepth = videoStream == null ? null : videoStream.BitDepth; int? videoBitrate = videoStream == null ? null : videoStream.BitRate; double?videoLevel = videoStream == null ? null : videoStream.Level; string videoProfile = videoStream == null ? null : videoStream.Profile; float? videoFramerate = videoStream == null ? null : videoStream.AverageFrameRate ?? videoStream.AverageFrameRate; bool? isAnamorphic = videoStream == null ? null : videoStream.IsAnamorphic; bool? isCabac = videoStream == null ? null : videoStream.IsCabac; int? audioBitrate = audioStream == null ? null : audioStream.BitRate; int? audioChannels = audioStream == null ? null : audioStream.Channels; string audioProfile = audioStream == null ? null : audioStream.Profile; TransportStreamTimestamp?timestamp = videoStream == null ? TransportStreamTimestamp.None : mediaSource.Timestamp; int?packetLength = videoStream == null ? null : videoStream.PacketLength; int?refFrames = videoStream == null ? null : videoStream.RefFrames; int?numAudioStreams = mediaSource.GetStreamCount(MediaStreamType.Audio); int?numVideoStreams = mediaSource.GetStreamCount(MediaStreamType.Video); // Check container conditions foreach (ProfileCondition i in conditions) { if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isCabac, refFrames, numVideoStreams, numAudioStreams)) { LogConditionFailure(profile, "VideoContainerProfile", i, mediaSource); return(null); } } string videoCodec = videoStream == null ? null : videoStream.Codec; if (string.IsNullOrEmpty(videoCodec)) { _logger.Debug("Profile: {0}, DirectPlay=false. Reason=Unknown video codec. Path: {1}", profile.Name ?? "Unknown Profile", mediaSource.Path ?? "Unknown path"); return(null); } conditions = new List <ProfileCondition>(); foreach (CodecProfile i in profile.CodecProfiles) { if (i.Type == CodecType.Video && i.ContainsCodec(videoCodec, container)) { foreach (ProfileCondition c in i.Conditions) { conditions.Add(c); } } } foreach (ProfileCondition i in conditions) { if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isCabac, refFrames, numVideoStreams, numAudioStreams)) { LogConditionFailure(profile, "VideoCodecProfile", i, mediaSource); return(null); } } if (audioStream != null) { string audioCodec = audioStream.Codec; if (string.IsNullOrEmpty(audioCodec)) { _logger.Debug("Profile: {0}, DirectPlay=false. Reason=Unknown audio codec. Path: {1}", profile.Name ?? "Unknown Profile", mediaSource.Path ?? "Unknown path"); return(null); } conditions = new List <ProfileCondition>(); foreach (CodecProfile i in profile.CodecProfiles) { if (i.Type == CodecType.VideoAudio && i.ContainsCodec(audioCodec, container)) { foreach (ProfileCondition c in i.Conditions) { conditions.Add(c); } } } foreach (ProfileCondition i in conditions) { bool?isSecondaryAudio = audioStream == null ? null : mediaSource.IsSecondaryAudio(audioStream); if (!conditionProcessor.IsVideoAudioConditionSatisfied(i, audioChannels, audioBitrate, audioProfile, isSecondaryAudio)) { LogConditionFailure(profile, "VideoAudioCodecProfile", i, mediaSource); return(null); } } } if (isEligibleForDirectPlay && mediaSource.SupportsDirectPlay) { if (mediaSource.Protocol == MediaProtocol.Http) { if (_localPlayer.CanAccessUrl(mediaSource.Path, mediaSource.RequiredHttpHeaders.Count > 0)) { return(PlayMethod.DirectPlay); } } else if (mediaSource.Protocol == MediaProtocol.File) { if (_localPlayer.CanAccessFile(mediaSource.Path)) { return(PlayMethod.DirectPlay); } } } if (isEligibleForDirectStream && mediaSource.SupportsDirectStream) { return(PlayMethod.DirectStream); } return(null); }
public ResponseProfile GetVideoMediaProfile(string container, string audioCodec, string videoCodec, int?width, int?height, int?bitDepth, int?videoBitrate, string videoProfile, double?videoLevel, float?videoFramerate, int?packetLength, TransportStreamTimestamp timestamp, bool?isAnamorphic, bool?isInterlaced, int?refFrames, int?numVideoStreams, int?numAudioStreams, string videoCodecTag, bool?isAvc) { foreach (var i in ResponseProfiles) { if (i.Type != DlnaProfileType.Video) { continue; } if (!ContainerProfile.ContainsContainer(i.GetContainers(), container)) { continue; } var audioCodecs = i.GetAudioCodecs(); if (audioCodecs.Length > 0 && !ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec ?? string.Empty)) { continue; } var videoCodecs = i.GetVideoCodecs(); if (videoCodecs.Length > 0 && !ListHelper.ContainsIgnoreCase(videoCodecs, videoCodec ?? string.Empty)) { continue; } var conditionProcessor = new ConditionProcessor(); var anyOff = false; foreach (ProfileCondition c in i.Conditions) { if (!conditionProcessor.IsVideoConditionSatisfied(GetModelProfileCondition(c), width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc)) { anyOff = true; break; } } if (anyOff) { continue; } return(i); } return(null); }
public ResponseProfile GetVideoMediaProfile(string container, string audioCodec, string videoCodec, int?width, int?height, int?bitDepth, int?videoBitrate, string videoProfile, double?videoLevel, float?videoFramerate, int?packetLength, TransportStreamTimestamp timestamp, bool?isAnamorphic, bool?isCabac, int?refFrames, int?numVideoStreams, int?numAudioStreams) { container = StringHelper.TrimStart((container ?? string.Empty), '.'); foreach (var i in ResponseProfiles) { if (i.Type != DlnaProfileType.Video) { continue; } List <string> containers = i.GetContainers(); if (containers.Count > 0 && !ListHelper.ContainsIgnoreCase(containers, container ?? string.Empty)) { continue; } List <string> audioCodecs = i.GetAudioCodecs(); if (audioCodecs.Count > 0 && !ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec ?? string.Empty)) { continue; } List <string> videoCodecs = i.GetVideoCodecs(); if (videoCodecs.Count > 0 && !ListHelper.ContainsIgnoreCase(videoCodecs, videoCodec ?? string.Empty)) { continue; } ConditionProcessor conditionProcessor = new ConditionProcessor(); var anyOff = false; foreach (ProfileCondition c in i.Conditions) { if (!conditionProcessor.IsVideoConditionSatisfied(c, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isCabac, refFrames, numVideoStreams, numAudioStreams)) { anyOff = true; break; } } if (anyOff) { continue; } return(i); } return(null); }
//public override bool CanConvert(Type objectType) //{ // return TypeHelper.IsBaseType(objectType, typeof(T)); //} public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { var settings = Factory.HttpJsonSettings; var valueType = value.GetType(); var isRef = false; var invokers = value.Table.GetInvokers(valueType); if (settings.Referenced && settings.Reference) { if (writer.CurrentDepth > 0 && Factory.referenceSet.Contains(value)) { isRef = true; invokers = value.Table.GetRefInvokers(); } else { Factory.referenceSet.Add(value); } } writer.WriteStartObject(); foreach (IInvokerJson invoker in invokers) { var propertyType = invoker.DataType; if (TypeHelper.IsBaseType(propertyType, typeof(DBItem))) { if (!settings.Referenced || writer.CurrentDepth > settings.MaxDepth) { continue; } var item = (DBItem)invoker.GetValue(value); if (!(item?.Access.GetFlag(AccessType.Read, Factory.CurrentUser) ?? true)) { continue; } writer.WritePropertyName(invoker.JsonName); JsonSerializer.Serialize(writer, item, propertyType, options); } else if (propertyType == typeof(AccessValue)) { var propertyValue = (AccessValue)invoker.GetValue(value); var accessValue = propertyValue.GetFlags(Factory.CurrentUser); writer.WritePropertyName(invoker.JsonName); JsonSerializer.Serialize <AccessType>(writer, accessValue, options); } else { writer.WritePropertyName(invoker.JsonName); invoker.WriteValue(writer, value, options); } } if (settings.Referencing && writer.CurrentDepth <= settings.MaxDepth && !isRef) { foreach (IInvokerJson invoker in value.Table.GetRefingInvokers(valueType)) { writer.WritePropertyName(invoker.JsonName); var typedEnumerable = invoker.GetValue(value)?.ToEnumerable <DBItem>(); if (typedEnumerable != null) { if (typedEnumerable.FirstOrDefault() is DBGroupItem) { var buffer = typedEnumerable.ToList(); ListHelper.QuickSort(buffer, TreeComparer <IGroup> .Default); typedEnumerable = buffer; } writer.WriteStartArray(); foreach (var item in typedEnumerable) { if (!item.Access.GetFlag(AccessType.Read, Factory.CurrentUser)) { continue; } JsonSerializer.Serialize(writer, item, item.GetType(), options); } writer.WriteEndArray(); } else { writer.WriteNullValue(); } } } writer.WriteEndObject(); }
//////////////////////////////////////////////// ////////// CAMERA ANGLE DETERMINATION ////////// //////////////////////////////////////////////// public MountedCamera GetRandomFrontFacingCamera() { return(ListHelper.GetRandomValue(frontFacingCameras)); }
private object ReadDictionary(Type listType, object existingContainer) { var valueType = ListHelper.GetDictionarValueType(listType); var isObject = typeof(object) == valueType; var container = existingContainer == null?ListHelper.CreateDictionary(listType, ListHelper.GetDictionarKeyType(listType), valueType) : (IDictionary)existingContainer; while (!IsDone()) { var storageType = ReadType(); var key = ReadName(); if (storageType == Types.Object) { NewDocument(_reader.ReadInt32()); } var specificItemType = isObject ? _typeMap[storageType] : valueType; var value = DeserializeValue(specificItemType, storageType); container.Add(key, value); } return(container); }
/// <summary> /// Resolve dependencies for Dynamite Helpers /// </summary> protected void ResolveDependencies() { this._listHelper = AppContainer.Current.Resolve<ListHelper>(); this._dateHelper = AppContainer.Current.Resolve<DateHelper>(); }