/// <summary> /// Method to merge the custon theme <see cref="ResourceDictionary"/> to another <see cref="ResourceDictionary"/>. /// </summary> /// <param name="resources">A <see cref="ResourceDictionary"/>.</param> /// <param name="mergeApp">Should merge application resources.</param> public static void MergeThemeTo(ResourceDictionary resources, bool mergeApp = true) { if (resources == null) { ArgumentNullException e = Exceptions.GetArgumentNull(nameof(resources), typeof(ResourceDictionary)); log.Error(e.Output(), e); throw e; } try { var res = (Application.Current.MainWindow)?.Resources; if (mergeApp == true && res != null && !resources.MergedDictionaries.ToList().Contains(res)) { resources.MergedDictionaries.Add((Application.Current.MainWindow).Resources); } } catch (Exception e) { log.Error(e.Output(), e); throw; } Load(Theme); MergeTo(resources); }
/// <summary> /// Method to convert a <see cref="FrameworkElement"/> Tag to an <see cref="object"/> of <see cref="Type"/> T. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fe">An <see cref="object"/> inherited from <see cref="FrameworkElement"/>.</param> /// <param name="defaut">A value by default.</param> /// <returns>The Tag value of the element or a default value if null.</returns> public static T GetTag <T>(object fe, T defaut = null) where T : class { if (fe is null) { ArgumentNullException e = Exceptions.GetArgumentNull(nameof(fe), typeof(object)); log.Error(e.Output(), e); throw e; } if (!fe.GetType().IsSubclassOf(typeof(FrameworkElement))) { TypeAccessException e = new TypeAccessException ( string.Format( CultureInfo.CurrentCulture, Fotootof.Libraries.Logs.Properties.Translations.TypeAccessExceptionFrameworkElement, nameof(fe), fe.GetType() ) ); log.Error(e.Output(), e); throw e; } if (defaut != null) { return((T)(fe as FrameworkElement).Tag ?? defaut); } else { return((T)(fe as FrameworkElement).Tag); } }
/// <summary> /// Method to add an item into the collection if the item not already exists with the predicate paste in argument. /// </summary> /// <typeparam name="T">The type of items in the collection.</typeparam> /// <param name="collection">The collection to search in and add in.</param> /// <param name="item">The object to add to the collection.</param> /// <param name="predicate">The predicate matching to check.</param> /// <returns>The updated collection.</returns> /// <exception cref="InvalidOperationException">Occurs if the predicate argument is null.</exception> public static ObservableCollection <T> AddIfNotExists <T>(this ObservableCollection <T> collection, T item, Predicate <T> predicate) { try { if (collection.Exists(predicate) == false) { collection.Add(item); } } catch (ArgumentNullException e) { ArgumentNullException ex = new ArgumentNullException($"An Exception occurs while adding object to the collection.", e); log.Error(ex.Output()); log.Error(e.Output(), e); throw ex; } catch (Exception e) { InvalidOperationException ex = new InvalidOperationException($"An Exception occurs while adding object to the collection.", e); log.Error(ex.Output()); log.Error(e.Output(), e); throw ex; } return(collection); }
/// <summary> /// /// </summary> /// <param name="ctrl">The Control to find.</param> /// <param name="propertyName">The property name to store in settings.</param> /// <param name="defaultValue"></param> /// <returns></returns> public static BindingProperty <object> GetBindingProperty(Control ctrl, string propertyName, object defaultValue = null) { if (ctrl == null) { ArgumentNullException ane = new ArgumentNullException(cNE); log.Error(ane.Output()); throw ane; } if (propertyName.IsNullOrWhiteSpace()) { ArgumentNullException ane = new ArgumentNullException(pNNE); log.Error(ane.Output()); throw ane; } var setting = GetUiElement(ctrl); var binding = setting.FindBindingProperty(propertyName); if (binding == null) { binding = new BindingProperty <object>() { Name = propertyName, Value = defaultValue }; setting.Context.Add(binding); } return(binding); }
/// <summary> /// Method to load picture from disk. /// </summary> /// <param name="filename">The full path file name of the picture.</param> /// <param name="width">The width of the image.</param> /// <param name="isHttp">Is Http filename Url ?.</param> /// <returns>A BitmapImage that contain the picture.</returns> public static BitmapImage GetPicture(string filename, int width = 512, bool isHttp = false) { // Initialize bitmap image. BitmapImage src = new BitmapImage(); // Try to create bitmap image from picture. try { log.Debug($"{typeof(PictureMemoryCache).Name}.{MethodBase.GetCurrentMethod().Name} : Creating bitmap image from picture."); if (string.IsNullOrWhiteSpace(filename)) { ArgumentNullException e = new ArgumentNullException(nameof(filename)); log.Error(e.Output(), e); return(src); } if (!Path.IsPathRooted(filename) && !isHttp) { filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename); } if (!File.Exists(filename) && !isHttp) { FileNotFoundException e = new FileNotFoundException("File not found :", filename); log.Error(e.Output(), e); return(src); } log.Debug($"{typeof(PictureMemoryCache).Name}.{MethodBase.GetCurrentMethod().Name} : {filename}"); src.BeginInit(); src.CacheOption = BitmapCacheOption.OnLoad; src.CreateOptions = BitmapCreateOptions.IgnoreImageCache | BitmapCreateOptions.PreservePixelFormat; src.UriSource = new Uri(@filename, UriKind.Absolute); src.DecodePixelWidth = width; src.EndInit(); // Freeze picture if possible. if (!src.IsFrozen && src.CanFreeze) { src.Freeze(); log.Debug($"{typeof(PictureMemoryCache).Name}.{MethodBase.GetCurrentMethod().Name} : Freezing Picture => done."); } } // Catch create bitmap image fail. // Just log error but generate no new exception. catch (Exception e) { log.Error("PictureMemoryCache try to create bitmap image but operation failed !", e); log.Error("filename : " + filename); } return(src); }
/// <summary> /// Method to select a <see cref="VersionEntity"/> or default entity. /// </summary> /// <param name="op">Version select options to perform query.</param> /// <returns>A <see cref="VersionEntity"/> or default if not found.</returns> public VersionEntity SingleOrDefault(VersionOptionsSelect op) { if (op == null) { ArgumentNullException e = new ArgumentNullException(nameof(op)); log.Error(e.Output(), e); throw e; } using (Db.Context) { return(VersionManager.Select(op)); } }
/// <summary> /// Method to check if an item exists with the predicate paste in argument. /// </summary> /// <typeparam name="T">The type of items in the collection.</typeparam> /// <param name="collection">The collection to search in.</param> /// <param name="match">The predicate matching to check.</param> /// <returns>True if an item or more is found otherwise false.</returns> public static bool Exists <T>(this ObservableCollection <T> collection, Func <T, bool> match) { if (match == null) { ArgumentNullException e = new ArgumentNullException($"'{nameof(match)}' type of '{typeof(Predicate<T>).Name}' must not be null."); log.Error(e.Output(), e); throw e; } return(collection.Exists(new Predicate <T>(match))); }
/// <summary> /// Method to check if an item exists with the predicate paste in argument. /// </summary> /// <typeparam name="T">The type of items in the collection.</typeparam> /// <param name="collection">The collection to search in.</param> /// <param name="predicate">The predicate matching to check.</param> /// <returns>True if an item or more is found otherwise false.</returns> public static bool Exists <T>(this ObservableCollection <T> collection, Predicate <T> predicate) { if (predicate == null) { ArgumentNullException e = new ArgumentNullException($"'{nameof(predicate)}' type of '{typeof(Predicate<T>).Name}' must not be null."); log.Error(e.Output(), e); throw e; } return(collection.ToList().Exists(predicate)); }
/// <summary> /// Method to store an UiElement in settings. /// </summary> /// <param name="element">The UiElement to store.</param> public static void SetUiElement(UiElement <object> element) { if (element == null) { ArgumentNullException e = new ArgumentNullException("The argument object UiElement<object> is required not null : " + nameof(element)); log.Error(e.Output()); throw e; } ApplicationBase.UI.Controls.AddKeySingle(element); }
/// <summary> /// Method to store a Control property in settings. /// </summary> /// <param name="ctrl">The Control to add.</param> /// <param name="propertyName">The property name to store in settings.</param> /// <param name="propertyValue">The property value to store in settings.</param> public static void SetUiElement(Control ctrl, string propertyName, object propertyValue = null) { if (ctrl == null) { ArgumentNullException ane = new ArgumentNullException(cNE); log.Error(ane.Output()); throw ane; } ApplicationBase.UI.Controls.AddKeySingle(new UiElement <object>(ctrl, propertyName, propertyValue)); }
public static IEnumerable <IExtension> GetModules(string assemblyName) { // Check if modules are already loaded. if (extensions != null) { return(extensions); } // Initialize assemblies. Initialize(); // Check if the assembly name is a valid string. if (assemblyName.IsNullOrWhiteSpace()) { ArgumentNullException ex = Exceptions.GetArgumentNull(nameof(assemblyName), typeof(string)); log.Error(ex.Output(), ex); return(null); } // Check if an assembly with that name has been loaded. if (!Assemblies.Keys.Contains(assemblyName)) { NullReferenceException ex = new NullReferenceException(nameof(assemblyName)); log.Error(ex.Output(), ex); return(null); } try { InterfaceBuilder builder = new InterfaceBuilder(); CompositionContainer container = new CompositionContainer(Assemblies[assemblyName]); container.ComposeParts(builder); return(extensions = builder.Extensions); } catch (ReflectionTypeLoadException ex) { log.Error(ex.Output(), ex); if (ex.LoaderExceptions != null) { foreach (Exception le in ex.LoaderExceptions) { log.Error(le.Output(), le); } } } catch (Exception ex) { log.Fatal(ex.Output(), ex); } return(null); }
/// <summary> /// Method to get a single <see cref="PictureEntity"/>. /// </summary> /// <param name="op"><see cref="PictureOptionsSelect"/> filters options for the query.</param> /// <returns>An <see cref="PictureEntity"/> or null.</returns> public PictureEntity SingleOrNull(PictureOptionsSelect op) { if (op == null) { ArgumentNullException e = Exceptions.GetArgumentNull(nameof(op), typeof(PictureOptionsSelect)); log.Error(e.Output()); throw e; } using (Db.Context) { return(PictureManager.Select(op)); } }
/// <summary> /// Method to get a single <see cref="AlbumEntity"/>. /// </summary> /// <param name="op"><see cref="AlbumOptionsSelect"/> filters options for the query.</param> /// <returns>An <see cref="AlbumEntity"/> or null.</returns> public AlbumEntity SingleOrNull(AlbumOptionsSelect op) { if (op == null) { ArgumentNullException e = new ArgumentNullException(nameof(op)); log.Error(e.Output(), e); throw e; } using (Db.Context) { return(AlbumManager.Select(op)); } }
/// <summary> /// Method to get a list of <see cref="AlbumEntity"/>. /// </summary> /// <param name="op"><see cref="AlbumOptionsList"/> filters options for the query.</param> /// <returns>An <see cref="ObservableCollection{AlbumEntity}"/>.</returns> public ObservableCollection <AlbumEntity> List(AlbumOptionsList op) { if (op == null) { ArgumentNullException e = Exceptions.GetArgumentNull(nameof(op), typeof(AlbumOptionsList)); log.Error(e.Output()); throw e; } using (Db.Context) { return(new ObservableCollection <AlbumEntity>(AlbumManager.List(op))); } }
/// <summary> /// /// </summary> /// <param name="ctrl"></param> /// <param name="propertyName"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static long GetLong(Control ctrl, string propertyName, long defaultValue = default(long)) { if (ctrl == null) { ArgumentNullException ane = new ArgumentNullException(cNE); log.Error(ane.Output()); throw ane; } if (propertyName.IsNullOrWhiteSpace()) { ArgumentNullException ane = new ArgumentNullException(pNNE); log.Error(ane.Output()); throw ane; } log.Debug($"{MethodBase.GetCurrentMethod().Name} : {ctrl.Uid}.{ctrl.Name}.{propertyName}"); var val = GetBindingProperty(ctrl, propertyName, defaultValue).Value; log.Debug($"{MethodBase.GetCurrentMethod().Name} : {val.GetType()} => {val}"); // Value is long so return it. if (val.GetType() == typeof(long)) { return((long)val); } // Value is int so convert it before return. if (val.GetType() == typeof(int)) { return(Convert.ToInt64(val)); } // Value is int so parse it before return. if (val.GetType() == typeof(string)) { return(long.Parse(val.ToString())); } // Invalid object to convert as long. InvalidCastException e = new InvalidCastException($"Invalid cast conversion type : {val.GetType()} => long"); log.Error(e.Output()); log.Error($"{MethodBase.GetCurrentMethod().Name} : {ctrl.Uid}.{ctrl.Name}.{propertyName} => {val.GetType()}"); MessageBoxs.DebugFatal(e); throw e; }
/// <summary> /// Method to insert a list of Album entities into the database. /// </summary> /// <param name="newItems">The list of items to add.</param> public static IEnumerable <AlbumEntity> DbInsert(IEnumerable <AlbumEntity> newItems) { if (newItems == null) { ArgumentNullException e = Exceptions.GetArgumentNull(nameof(newItems), typeof(IEnumerable <AlbumEntity>)); log.Error(e.Output()); return(null); } // Check if the list to add is not empty. if (newItems.Count() == 0) { log.Debug($"{typeof(AlbumEntityCollection).Name}.{MethodBase.GetCurrentMethod().Name} : the list of {typeof(AlbumEntity).Name} to insert is empty."); return(null); } IList <AlbumEntity> itemsAdded = new List <AlbumEntity>(); log.Info($"Adding {newItems.Count()} album{(newItems.Count() > 1 ? "s" : "")} : Please wait..."); try { foreach (AlbumEntity entity in newItems) { // Get all Album to check some properties before inserting new item. // Format Alias before update. FormatAlias(entity); // Add new item into the database. itemsAdded.Add(Db.Albums.Add(entity)); log.Info($"Album [{entity.PrimaryKey}:{entity.Name}] added."); } // Clear application navigator to refresh it for new data. AppNavigatorBase.Clear(); log.Info($"Adding {itemsAdded.Count()} album{(itemsAdded.Count() > 1 ? "s" : "")} : Done."); } catch (Exception ex) { log.Error(ex.Output(), ex);; MessageBoxs.Fatal(ex, $"Adding {newItems.Count() - itemsAdded.Count()}/{newItems.Count()} album{(newItems.Count() > 1 ? "s" : "")} : Failed."); } return(itemsAdded); }
/// <summary> /// Method to check if a Directory or Folder has Permissions. /// </summary> /// <param name="directoryInfo">The full path or name of the directory.</param> /// <param name="accessType">The file system rights to check.</param> /// <returns>True if the folder contains access type, otherwise False.</returns> /// <see href="http://technico.qnownow.com/how-to-check-read-or-write-permissions-on-a-folder-in-c/"/> public static bool HasDirectoryPermissions(this DirectoryInfo directoryInfo, FileSystemRights accessType) { if (directoryInfo.FullName.IsNullOrWhiteSpace()) { ArgumentNullException e = new ArgumentNullException(nameof(accessType), "FileSystemRights argument must not be null !"); log.Error(e.Output(), e); throw e; } if (directoryInfo.Exists == false) { DirectoryNotFoundException e = new DirectoryNotFoundException($"{directoryInfo.FullName} not found !"); log.Info(e.Output(), e); throw e; } return(SysDirectory.HasDirectoryPermissions(directoryInfo.FullName, accessType)); }
/// <summary> /// /// </summary> /// <typeparam name="V"></typeparam> /// <param name="ctrl"></param> /// <param name="propertyName"></param> /// <param name="defaultValue"></param> /// <returns></returns> /// <exception cref="ArgumentNullException">Occurs if Control or Property Name argument are null.</exception> public static V GetValue <V>(Control ctrl, string propertyName, V defaultValue = default(V)) where V : class { if (ctrl == null) { ArgumentNullException ane = new ArgumentNullException(cNE); log.Error(ane.Output()); throw ane; } if (propertyName.IsNullOrWhiteSpace()) { ArgumentNullException ane = new ArgumentNullException(pNNE); log.Error(ane.Output()); throw ane; } return(GetBindingProperty(ctrl, propertyName, defaultValue).Value as V); }
/// <summary> /// /// </summary> /// <param name="ctrl"></param> /// <param name="propertyName"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static string GetString(Control ctrl, string propertyName, string defaultValue = default(string)) { if (ctrl == null) { ArgumentNullException ane = new ArgumentNullException(cNE); log.Error(ane.Output()); throw ane; } if (propertyName.IsNullOrWhiteSpace()) { ArgumentNullException ane = new ArgumentNullException(pNNE); log.Error(ane.Output()); throw ane; } return((string)GetBindingProperty(ctrl, propertyName, defaultValue).Value); }
/// <summary> /// Method to get an UiElement application setting. /// </summary> /// <param name="ctrl">The Control to find settings.</param> /// <returns>The corresponding UiElement of Control or a new one if not find.</returns> /// <exception cref="ArgumentNullException">Occurs if Control argument is null.</exception> public static UiElement <object> GetUiElement(Control ctrl) { if (ctrl == null) { ArgumentNullException ane = new ArgumentNullException(cNE); log.Error(ane.Output()); throw ane; } var setting = ApplicationBase.UI.Controls.FindControl(ctrl); if (setting == null) { setting = new UiElement <object>(ctrl); ApplicationBase.UI.Controls.Add(setting); } return(setting); }
/// <summary> /// Method to delete a list of Album entities from the database. /// </summary> /// <param name="oldItems">The list of items to remove.</param> public static async Task <IList <AlbumEntity> > DbDeleteAsync(IEnumerable <AlbumEntity> oldItems) { // Log error if the list to update if not null. if (oldItems == null) { ArgumentNullException e = Exceptions.GetArgumentNull(nameof(oldItems), typeof(IEnumerable <AlbumEntity>)); log.Error(e.Output(), e); return(null); } // Check if the list to update is not empty. if (oldItems.Count() == 0) { log.Debug($"{typeof(AlbumEntityCollection).Name}.{MethodBase.GetCurrentMethod().Name} : the list of {typeof(AlbumEntity).Name} to delete is empty."); return(null); } // Create a new list for update return. IList <AlbumEntity> itemsDeleted = new List <AlbumEntity>(); log.Info($"Deleting {oldItems.Count()} album{(oldItems.Count() > 1 ? "s" : "")} : Please wait..."); // Check for Removing items. try { foreach (AlbumEntity entity in oldItems) { itemsDeleted.Add(await Db.Albums.DeleteAsync(entity)); log.Info($"Album [{entity.PrimaryKey}:{entity.Name}] deleted."); } // Clear application navigator to refresh it for new data. AppNavigatorBase.Clear(); log.Info($"Deleting {itemsDeleted.Count()} album{(itemsDeleted.Count() > 1 ? "s" : "")} : Done !"); } catch (Exception ex) { log.Error(ex.Output(), ex); MessageBoxs.Fatal(ex, $"Deleting {oldItems.Count() - itemsDeleted.Count()}/{oldItems.Count()} album{(oldItems.Count() > 1 ? "s" : "")} : Failed."); } return(itemsDeleted); }
/// <summary> /// Method to load the custom theme <see cref="ResourceDictionary"/> from an <see cref="Assembly"/> /// </summary> /// <param name="assemblyComponent">The path of the <see cref="Assembly"/> ; the path of the <see cref="ResourceDictionary"/> </param> /// <param name="uriKind">The kind of uri <see cref="UriKind"/></param> /// <example> /// {Assembly};component/{ResourceDictionary} /// </example> public static void Load(string assemblyComponent, UriKind uriKind = UriKind.Relative) { if (assemblyComponent == null) { ArgumentNullException e = Exceptions.GetArgumentNull(nameof(assemblyComponent), typeof(string)); log.Error(e.Output(), e); throw e; } assemblyComponent = GetAssemblyComponent(assemblyComponent); ResourceDictionary rd = null; try { rd = new ResourceDictionary { Source = new Uri(@assemblyComponent, uriKind) }; } catch (Exception e) { log.Error(e.Output(), e); throw; } if (rd.Count == 0) { log.Debug($"{typeof(ThemeLoader).Name}.{MethodBase.GetCurrentMethod().Name} : Loading empty Assembly Component resources dictionary."); } if (!Resources.MergedDictionaries.ToList().Contains(rd)) { Resources.MergedDictionaries.Add(rd); log.Debug($"{typeof(ThemeLoader).Name}.{MethodBase.GetCurrentMethod().Name} : Resources theme dictionary merged."); } else { log.Debug($"{typeof(ThemeLoader).Name}.{MethodBase.GetCurrentMethod().Name} : Assembly Component resources dictionary already loaded."); } }
/// <summary> /// Method to store a long Control property value. /// </summary> /// <param name="ctrl">The Control.</param> /// <param name="propertyName">The property name to store in settings.</param> /// <param name="propertyValue">The property value to store in settings.</param> /// <returns>The property value stored in settings.</returns> public static long SetLong(Control ctrl, string propertyName, long propertyValue = default(long)) { if (ctrl == null) { ArgumentNullException ane = new ArgumentNullException(cNE); log.Error(ane.Output()); throw ane; } if (propertyName.IsNullOrWhiteSpace()) { ArgumentNullException ane = new ArgumentNullException(pNNE); log.Error(ane.Output()); throw ane; } BindingProperty <object> bp = GetBindingProperty(ctrl, propertyName, propertyValue); bp.Value = propertyValue; return((int)bp.Value); }
/// <summary> /// Method to merge the custon theme <see cref="ResourceDictionary"/> to another <see cref="ResourceDictionary"/>. /// </summary> /// <param name="resources">A <see cref="ResourceDictionary"/>.</param> private static void MergeTo(ResourceDictionary resources) { if (resources == null) { ArgumentNullException e = Exceptions.GetArgumentNull(nameof(resources), typeof(ResourceDictionary)); log.Error(e.Output(), e); throw e; } try { if (!resources.MergedDictionaries.ToList().Contains(Resources)) { resources.MergedDictionaries.Add(Resources); } } catch (Exception e) { log.Error(e.Output(), e); throw; } }
/// <summary> /// Method to list albums entities. /// </summary> /// <param name="op"></param> /// <returns>A list of albums entities.</returns> public IList <AlbumEntity> List(AlbumOptionsList op) { if (op == null) { ArgumentNullException e = new ArgumentNullException(nameof(op)); log.Error(e.Output(), e); throw e; } // Initialize query. IQueryable <AlbumEntity> query = Connector.Albums; Query_Dependencies(ref query, op); // Filter by entity primary keys. query.QueryListInclude(op, "AlbumId"); query.QueryListExclude(op, "AlbumId"); // Check Section filters. query = Query_FilterSections(query, op); query = Query_FilterInfos(query, op); // Set number elements to skip. if (op.Start > 0) { query = query.Skip(op.Start); } // Set the number elements to select. if (op.Limit > 0) { query = query.Take(op.Limit); } return(query.ToList()); }
/// <summary> /// Method to select a <see cref="PictureEntity"/>. /// </summary> /// <param name="op">Picture entities select options to perform query.</param> /// <param name="nullable"></param> /// <returns>An Picture entity or null if not found.</returns> /// <exception cref="ArgumentNullException">Occurs if Picture Select Options are null <see cref="PictureOptionsSelect"/></exception> public PictureEntity Select(PictureOptionsSelect op, bool nullable = false) { log.Debug($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : {op?.GetType()}"); if (op == null) { ArgumentNullException e = Exceptions.GetArgumentNull(nameof(op), typeof(PictureOptionsSelect)); log.Error($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : {e.Output()}"); throw e; } if (!SetSafeUser(op.UserId)) { return(null); } // Initialize query. IQueryable <PictureEntity> query = Connector.Pictures; // Load dependencies if required. QueryDependencies(ref query, op); if (op.PrimaryKey > 0) { query = query.Where(x => x.PrimaryKey == op.PrimaryKey); } if (!op.Alias.IsNullOrWhiteSpace()) { query = query.Where(x => x.Alias == op.Alias); } // Filter by User. //if (entity != null && user != null) //{ // SectionEntity section = null; // foreach (AlbumsInSections sectDep in entity.AlbumsInSections) // { // IQueryable<SectionEntity> sections = Connector.Sections; // sections = sections.Include(x => x.SectionsInAclGroups); // SectionEntity s = sections.SingleOrDefault(x => x.PrimaryKey == sectDep.SectionId); // if (s.PrimaryKey == 0) // { // return null; // } // foreach (SectionsInAclGroups aclgDep in s.SectionsInAclGroups) // { // section = GetUserSection(aclgDep.SectionId, user); // if (section != null && section.PrimaryKey > 0) break; // } // if (section != null && section.PrimaryKey > 0) break; // } // if (section == null) // { // return null; // } //} return(SingleDefaultOrNull(query, nullable)); }
/// <summary> /// Method to update an Entity. /// </summary> /// <param name="tableName"></param> /// <param name="pkName"></param> /// <param name="entityPK"></param> /// <returns>The updated Entity.</returns> public async Task <int> SetDefaultAsync(string tableName, string pkName, int entityPK) { int result = 0; log.Warn($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : Setting Default => {tableName}.{pkName}"); log.Debug($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : Entity Primary Key => {entityPK}"); if (tableName.IsNullOrWhiteSpace()) { ArgumentNullException e = new ArgumentNullException(nameof(tableName)); log.Error(e.Output(), e); return(0); } if (pkName.IsNullOrWhiteSpace()) { ArgumentNullException e = new ArgumentNullException(nameof(pkName)); log.Error(e.Output(), e); return(0); } if (entityPK < 0) { IndexOutOfRangeException e = new IndexOutOfRangeException(nameof(pkName)); log.Error(e.Output(), e); return(0); } string query = ""; // Becareful : SQLiteException maybe occurs whithout ` or/and '. //log.Debug(query = $"UPDATE `{tableName}` SET `IsDefault` = 0"); log.Debug(query = $"UPDATE {QN(tableName)} SET {QN("IsDefault")} = {Q("0")}"); try { #pragma warning disable EF1000 // Query is already generated by Linq. Becareful ! Linq on Linq cause SQLiteException. result = await(Connector as DbContext).Database.ExecuteSqlCommandAsync(query); #pragma warning restore EF1000 // Query is already generated by Linq. Becareful ! Linq on Linq cause SQLiteException. Save(); } catch (SQLiteException se) { log.Error(query); log.Error(se.Output(), se); return(0); } catch (Exception se) { log.Fatal(query); log.Fatal(se.Output(), se); return(0); } log.Info($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : Affected Rows => {result}"); // Becareful : SQLiteException maybe occurs whithout ` or/and '. log.Debug(query = $"UPDATE {QN(tableName)} SET {QN("IsDefault")} = {Q("1")} WHERE _rowid_ = {Q(entityPK.ToString())}"); try { #pragma warning disable EF1000 // Query is already generated by Linq. Becareful ! Linq on Linq cause SQLiteException. result = await(Connector as DbContext).Database.ExecuteSqlCommandAsync(query); #pragma warning restore EF1000 // Query is already generated by Linq. Becareful ! Linq on Linq cause SQLiteException. Save(); } catch (SQLiteException se) { log.Error(query); log.Error(se.Output(), se); return(0); } catch (Exception se) { log.Fatal(query); log.Fatal(se.Output(), se); return(0); } log.Info($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : {result} Affected Rows"); return(result); }
/// <summary> /// Method to initialize Picture Meta Data informations. /// </summary> /// <exception cref="ArgumentNullException">Occurs when invalid argument Picture file name is passed. Filename must be not null or empty or whitespace.</exception> /// <exception cref="FileFormatException">Occurs when loading meta data failed.</exception> private void Initialize() { if (Filename.IsNullOrWhiteSpace()) { ArgumentNullException e = new ArgumentNullException($"Invalid argument Picture file name [{Filename}]. Filename must be not null or empty or whitespace."); log.Error(e.Output(), e); throw e; } Data.Filename = Filename; Data.Comment = ""; Data.Copyright = ""; Data.DateTaken = ""; Data.Rating = 0; Data.Title = ""; Data.Format = new System.Windows.Media.PixelFormat(); Data.Height = 0; Data.Width = 0; Data.PixelHeight = 0; Data.PixelWidth = 0; Data.Length = 0; try { // open a filestream for the file we wish to look at using (Stream fs = File.Open(Filename, FileMode.Open, FileAccess.ReadWrite)) { Data.Length = fs.Length; // create a decoder to parse the file BitmapDecoder decoder = BitmapDecoder.Create(fs, BitmapCreateOptions.None, BitmapCacheOption.Default); if (decoder == null || decoder.Frames.Count == 0) { log.Error("Creating bipmap decoder : failed ! "); return; } // grab the bitmap frame, which contains the metadata BitmapFrame frame = decoder.Frames[0]; if (frame == null) { log.Error("Getting bipmap decoder frame : failed ! "); return; } Data.Format = frame.Format; Data.Height = frame.Height; Data.Width = frame.Width; Data.PixelHeight = frame.PixelHeight; Data.PixelWidth = frame.PixelWidth; // get the metadata as BitmapMetadata BitmapMetadata bmp = frame.Metadata as BitmapMetadata; if (bmp == null) { log.Error("Getting bipmap metadata : failed ! "); Data.DateTaken = new FileInfo(Filename).CreationTime.ToString(); return; } Data.Title = bmp.Title ?? Path.GetFileName(Filename); Data.DateTaken = bmp.DateTaken; Data.Copyright = bmp.Copyright; Data.Comment = bmp.Comment; Data.Rating = bmp.Rating; } } catch (Exception e) { throw new FileFormatException("initializing picture meta data informations : failed !", e); } }
/// <summary> /// Method to select an Album. /// </summary> /// <param name="op"></param> /// <returns>An album entity.</returns> public AlbumEntity Select(AlbumOptionsSelect op) { log.Debug("---------------------------------------------------------------------------------"); log.Debug($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : {op?.GetType()}"); if (op == null) { ArgumentNullException e = Exceptions.GetArgumentNull(nameof(op), typeof(AlbumOptionsSelect)); log.Error($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : {e.Output()}"); throw e; } // Initialize entity result. AlbumEntity entity = null; // Safe User if (!SetSafeUser(op.UserId)) { return(null); } // Initialize query. IQueryable <AlbumEntity> query = Connector.Albums; log.Debug($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : Initializing query => {Connector?.Albums?.Count()} item(s)"); // Load dependencies if required. Query_Dependencies(ref query, op); log.Debug($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : Loading dependencies."); // Filter by Album Primary Key property. if (op.PrimaryKey != 0) { entity = SingleIdOrNull(query, op); log.Debug($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : Filter by Album Primary Key property => {entity?.PrimaryKey}"); if (entity == null) { return(null); } } // Filter by Album Alias property. if (op.Alias.IsNotNullOrWhiteSpace()) { entity = SingleAliasOrNull(query, op); log.Debug($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : Filter by Album Alias property => {entity?.PrimaryKey} | {entity?.Alias}"); if (entity == null) { return(null); } } // Filter by Album BackgroundPictureId property. if (op.BackgroundPictureId > 0) { entity = SingleBackgroundPictureIdOrNull(query, op); log.Debug($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : Filter by Album BackgroundPictureId property => {entity?.PrimaryKey} | {entity?.Alias}"); if (entity == null) { return(null); } } // Filter by Album PreviewPictureId property. if (op.PreviewPictureId > 0) { entity = SinglePreviewPictureIdOrNull(query, op); log.Debug($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : Filter by Album PreviewPictureId property => {entity?.PrimaryKey} | {entity?.Alias}"); if (entity == null) { return(null); } } // Filter by Album ThumbnailPictureId property. if (op.ThumbnailPictureId > 0) { entity = SingleThumbnailPictureIdOrNull(query, op); log.Debug($"{GetType().Name}.{MethodBase.GetCurrentMethod().Name} : Filter by Album ThumbnailPictureId property => {entity?.PrimaryKey} | {entity?.Alias}"); if (entity == null) { return(null); } } // Filter by User. if (entity != null && User != null) { SectionEntity section = null; foreach (AlbumsInSections sectDep in entity.AlbumsInSections) { IQueryable <SectionEntity> sections = Connector.Sections; sections = sections.Include(x => x.SectionsInAclGroups); SectionEntity s = sections.SingleOrDefault(x => x.PrimaryKey == sectDep.SectionId); if (s.PrimaryKey == 0) { return(null); } foreach (SectionsInAclGroups aclgDep in s.SectionsInAclGroups) { section = GetUserSection(aclgDep.SectionId, User); if (section != null && section.PrimaryKey > 0) { break; } } if (section != null && section.PrimaryKey > 0) { break; } } if (section == null) { return(null); } } log.Debug("---------------------------------------------------------------------------------"); return(entity); }