/// <summary> /// Turns an entity on or off. /// </summary> /// <param name="id"></param> /// <returns></returns> public EntityActionResult Clone(int id) { var result = Copy(id); if (!result.Success) { return(result); } T test = new T(); if (!(test is IEntityClonable)) { return(new EntityActionResult(false, "This model is not cloneable", isAuthorized: true, isAvailable: true)); } T entity = (T)result.Item; var svc = EntityRegistration.GetService <T>(); svc.Create(entity); // Check again. if (entity.Errors.HasAny) { return(new EntityActionResult(false, "Unable to clone item.", errors: entity.Errors, item: entity)); } return(new EntityActionResult(true, "Item has been cloned.")); }
/// <summary> /// Finds Items by owner if non-admin is logged in otherwise, all items if admin. /// </summary> /// <param name="p"></param> /// <returns></returns> public EntityActionResult Find(int page, int pageSize, IQuery <T> query) { var svc = EntityRegistration.GetService <T>(); var results = svc.Find(query, page, pageSize); return(new EntityActionResult(true, string.Empty, null, results)); }
/// <summary> /// Turns an entity on or off. /// </summary> /// <param name="id"></param> /// <returns></returns> public EntityActionResult OnOff(int id) { var result = Edit(id); if (!result.Success) { return(result); } T test = new T(); if (!(test is IEntityActivatable)) { return(new EntityActionResult(false, "This model is not activatable", isAuthorized: true, isAvailable: true)); } T entity = (T)result.Item; var onoff = entity as IEntityActivatable; onoff.IsActive = !onoff.IsActive; var svc = EntityRegistration.GetService <T>(); svc.Update(entity); // Check again. if (entity.Errors.HasAny) { return(new EntityActionResult(false, "Unable to activate/deactivate item.", errors: entity.Errors, item: entity)); } var message = onoff.IsActive ? "Activated" : "Deactivated"; return(new EntityActionResult(true, "Item has been " + message)); }
/// <summary> /// Get the details using a query based fetcher. /// </summary> /// <param name="queryFetcher"></param> /// <returns></returns> public virtual EntityActionResult Details(Func <IQuery <T> > queryFetcher) { var svc = EntityRegistration.GetService <T>(); var query = queryFetcher(); return(Details(() => svc.Repository.First(query))); }
/// <summary> /// Import items into the entity repository. /// </summary> /// <param name="items"></param> /// <returns></returns> public override BoolErrorsItem <IList <T> > Import(IList <T> items) { // Check for overriden handler. if (_importHandler != null) { return(base.Import(items)); } // Get the service for the enitity of type T. IEntityService <T> service = EntityRegistration.GetService <T>(); service.Create(items); bool success = true; IValidationResults errors = new ValidationResults(); int ndx = 1; foreach (T item in items) { IEntity entity = item as IEntity; if (entity.Errors.HasAny) { success = false; // Now copy over the errors w/ context information( e.g. 1st entity imported ). errors.Add("Item # [" + ndx + "] : "); entity.Errors.EachFull(err => errors.Add(err)); } ndx++; } string fullError = errors.Message(); return(new BoolErrorsItem <IList <T> >(items, success, fullError, errors)); }
/// <summary> /// Delete the item represented by the id. /// </summary> /// <param name="p"></param> /// <returns></returns> public EntityActionResult Delete(int id) { if (!HasAccessTo("Delete")) { return(new EntityActionResult(success: false, message: "Not authorized to perform this action", isAuthorized: false)); } var svc = EntityRegistration.GetService <T>(); var entity = svc.Get(id); // Check item is there. if (entity == null) { return(new EntityActionResult(success: false, message: "Entity has been deleted.")); } // Check security. if (!entity.IsOwnerOrAdmin()) { return(new EntityActionResult(success: false, message: "Not authorized to perform this action", item: entity, isAuthorized: false)); } // Issues deleting? svc.Delete(entity); if (entity.Errors.HasAny) { return(new EntityActionResult(false, "Unable to delete item.", errors: entity.Errors, item: entity)); } return(new EntityActionResult(true, "Item has been deleted.", item: entity)); }
/// <summary> /// Delete the item represented by the id. /// </summary> /// <param name="p"></param> /// <returns></returns> public EntityActionResult Create(T entity, Action <T> onBeforeUpdateCallback = null) { // Check item is there. if (entity == null) { return(new EntityActionResult(success: false, message: "Item not supplied.")); } if (!HasAccessTo("Create")) { return(new EntityActionResult(success: false, message: "Not authorized to perform this action", isAuthorized: false)); } if (onBeforeUpdateCallback != null) { onBeforeUpdateCallback(entity); } if (entity.Errors.HasAny) { return(new EntityActionResult(false, "Unable to create item", errors: entity.Errors, item: entity)); } var svc = EntityRegistration.GetService <T>(); svc.Create(entity); if (entity.Errors.HasAny) { return(new EntityActionResult(false, "Unable to create item", errors: entity.Errors, item: entity)); } return(new EntityActionResult(true, string.Empty, null, entity)); }
/// <summary> /// Delete all entries based on the level. /// </summary> /// <param name="level"></param> public static void Delete(LogLevel level) { var logService = EntityRegistration.GetService <LogEventEntity>(); logService.Repository.Delete(Query <LogEventEntity> .New().Where(l => l.LogLevel).Is((int)level)); //entity => entity.LogLevel == level); }
/// <summary> /// Delete the item represented by the id. /// </summary> /// <param name="p"></param> /// <returns></returns> public EntityActionResult Copy(int id) { if (!HasAccessTo("Create")) { return(new EntityActionResult(success: false, message: "Not authorized to perform this action", isAuthorized: false)); } var svc = EntityRegistration.GetService <T>(); var entity = svc.Get(id); // Check item is there. if (entity == null) { return(new EntityActionResult(success: false, message: "Entity has been deleted.")); } // Check security. if (!entity.IsOwnerOrAdmin()) { return(new EntityActionResult(success: false, message: "Not authorized to perform this action", isAuthorized: false)); } // Reset the id so it's not marked as persistant. entity.ToNewCopy(); return(new EntityActionResult(true, string.Empty, null, entity)); }
/// <summary> /// Gets the by tags. /// </summary> /// <param name="tag">The tag.</param> /// <returns></returns> public static IList <T> GetByTags <T>(string tag, Func <int[], IQuery <T> > queryBuilder) { int groupId = ModuleMap.Instance.GetId(typeof(T)); // This is an NON-Optimized query done in 2 steps. // This is just to have compatibility between both the in-memory repository and real database. // Step 1: Get all the tags to get the refid's IList <Tag> tags = Tag.Find(Query <Tag> .New().Where(t => t.GroupId).Is(groupId).And(t => t.Name).Is(tag)); // Check if tags available. if (tags == null || tags.Count == 0) { return(new List <T>()); } var ids = from t in tags select t.RefId; int[] idsarray = ids.ToArray(); // Check for empty ids. if (idsarray == null || idsarray.Length == 0) { return(new List <T>()); } // Step 2: Now get blogposts. var service = EntityRegistration.GetService <T>(); var query = queryBuilder(idsarray); IList <T> items = service.Find(query); return(items); }
/// <summary> /// Delete the item represented by the id. /// </summary> /// <param name="p"></param> /// <returns></returns> public EntityActionResult Edit(int id) { return(Edit(() => { var svc = EntityRegistration.GetService <T>(); var entity = svc.Get(id); return entity; })); }
/// <summary> /// Find paged items by using the query, current page, and items per page. /// </summary> /// <param name="query">The query used to get recent items.</param> /// <param name="page">The page of data to get.</param> /// <param name="pageSize">The number of items per page to get.</param> /// <returns></returns> public virtual T FindByUrl(string url) { string strId = url.Substring(url.LastIndexOf("-") + 1); int id = Convert.ToInt32(strId); var service = EntityRegistration.GetService <T>(); T entity = service.Get(id); return(entity); }
/// <summary> /// Delete the photo. /// </summary> /// <param name="profile"></param> public static void DeletePhoto(this Profile profile) { var svc = EntityRegistration.GetService <Profile>(); var mservice = EntityRegistration.GetService <ComLib.Web.Modules.Media.MediaFile>(); mservice.Delete(profile.ImageRefId); profile.ImageRefId = 0; profile.ImageUrl = string.Empty; profile.Save(); }
/// <summary> /// Exports items in a batch/page. /// </summary> /// <returns></returns> public override BoolMessageItem <IList <T> > Export(int page, int pageSize) { // Check for overriden handler. if (_exportPageHandler != null) { return(base.Export(page, pageSize)); } IEntityService <T> service = EntityRegistration.GetService <T>(); IList <T> items = service.Get(1, pageSize); return(new BoolMessageItem <IList <T> >(items, true, string.Empty)); }
/// <summary> /// Delete the item represented by the id. /// </summary> /// <param name="entity">The entity to update.</param> /// <param name="onBeforeUpdateCallback">Callback with the updated and original entity respectively.</param> /// <returns></returns> public EntityActionResult Edit(T entity, Action <T> onBeforeUpdateCallback = null) { // Check item is there. if (entity == null) { return(new EntityActionResult(success: false, message: "Item not supplied.", item: entity)); } if (!HasAccessTo("Edit")) { return(new EntityActionResult(success: false, message: "Not authorized to perform this action", isAuthorized: false)); } // Prevent override of audit fields. var svc = EntityRegistration.GetService <T>(); var orig = svc.Get(entity.Id); // apply back any audit fields from original. entity.DoUpdateModel <T>(orig); // Check security. if (!entity.IsOwnerOrAdmin()) { return(new EntityActionResult(success: false, message: "Not authorized to perform this action", item: entity, isAuthorized: false)); } if (onBeforeUpdateCallback != null) { onBeforeUpdateCallback(orig); if (entity.Errors.HasAny) { return(new EntityActionResult(false, "Unable to edit item.", errors: entity.Errors, item: entity)); } } // Callback may have done some actions. if (entity.Errors.HasAny) { return(new EntityActionResult(false, "Unable to edit item.", errors: entity.Errors, item: entity)); } svc.Update(entity); // Check again. if (entity.Errors.HasAny) { return(new EntityActionResult(false, "Unable to edit item.", errors: entity.Errors, item: entity)); } return(new EntityActionResult(true, string.Empty, null, entity)); }
/// <summary> /// Save the orderings. /// </summary> /// <param name="orderings"></param> /// <returns></returns> public virtual BoolMessage SaveOrdering(string orderings) { if (!HasAccessTo("Edit")) { return(new BoolMessage(false, "Not authorized to perform this action")); } T test = new T(); if (!(test is IEntitySortable)) { return(new BoolMessage(false, "This model is not sortable")); } List <int> ids = new List <int>(); List <int> sorts = new List <int>(); string[] entries = orderings.Split(','); // Each ordering id, sortindex foreach (string ordering in entries) { string[] props = ordering.Split(':'); // Get id and sortindex. if (props != null && props.Length > 0 && !string.IsNullOrEmpty(props[0])) { // Get the id, zone and sort index. int id = System.Convert.ToInt32(props[0]); int sortIndex = System.Convert.ToInt32(props[1]); ids.Add(id); sorts.Add(sortIndex); } } var idArr = ids.ToArray(); var svc = EntityRegistration.GetService <T>(); // Get only the items w/ matching ids. var items = svc.Repository.ToLookUp(Query <T> .New().Where(i => i.Id).In <int>(idArr)); // Now save the new sortindex. for (int ndx = 0; ndx < ids.Count; ndx++) { T item = items[ids[ndx]]; ((IEntitySortable)item).SortIndex = sorts[ndx]; svc.Update(item); } return(new BoolMessage(true, "Order of items has been saved.")); }
public void CanGet() { var helper = new EntityHelper <Link>(); var link = EntityRegistration.GetService <Link>().GetAll()[0]; var id = link.Id; var result = helper.Details(id); Assert.AreEqual(result.Success, true); Assert.IsNotNull(result.Item); Assert.AreEqual(result.ItemAs <Link>().Id, id); Assert.AreEqual(result.ItemAs <Link>().Name, link.Name); Assert.AreEqual(result.IsAvailable, true); Assert.AreEqual(result.IsAuthorized, true); }
/// <summary> /// Find recent items in Json based format. /// </summary> /// <param name="page"></param> /// <param name="pagesize"></param> /// <returns></returns> public EntityActionResult FindByAsJson(int page, int pagesize, IList <PropertyInfo> columnProps, Func <IEntityService <T>, int, int, PagedList <T> > pagedListFetcher = null, Func <int, int, EntityActionResult> actionResultFetcher = null) { PagedList <T> result = null; string message = string.Empty; string resultText = string.Empty; bool success = false; int totalPages = 0; try { EntityActionResult entityresult = null; if (actionResultFetcher != null) { entityresult = actionResultFetcher(page, pagesize); } else if (pagedListFetcher != null) { var svc = EntityRegistration.GetService <T>(); var results = pagedListFetcher(svc, page, pagesize); entityresult = new EntityActionResult(results != null, string.Empty, null, results); } else { entityresult = FindByRecent(page, pagesize); } result = entityresult.ItemAs <PagedList <T> >(); totalPages = result.TotalPages; try { resultText = ComLib.Web.Helpers.JsonHelper.ConvertToJsonString <T>(result, columnProps); success = true; } catch (Exception ex) { message = "Unable to convert items of : " + typeof(T).Name + " to JSON format."; ComLib.Logging.Logger.Error(message, ex); } } catch (Exception ex) { message = "Unable to get items for : " + typeof(T).Name; ComLib.Logging.Logger.Error(message, ex); success = false; } string jsontext = EntityJsonHelper.BuildManageJsonResult <T>(success, message, result, resultText, null); return(new EntityActionResult(success, message, null, jsontext)); }
private BoolMessageItem <IList <T> > InternalImport(ImportExportActionContext <T> ctx) { IEntityService <T> service = EntityRegistration.GetService <T>(); IActionContext actionContext = EntityRegistration.GetContext(typeof(T).FullName); actionContext.Errors = ctx.Errors; actionContext.Messages = ctx.Messages; actionContext.CombineMessageErrors = false; actionContext.Items = ctx.ItemList; actionContext.Args["isImporting"] = true; BoolMessage createResult = service.Create(actionContext); return(new BoolMessageItem <IList <T> >(ctx.ItemList, createResult.Success, createResult.Message)); }
public void CanNotCloneOtherUsersItem() { var helper = new EntityHelper <Link>(); Auth.Init(new AuthWin("Admin", new UserPrincipal(1, "johndoe", "User", "Custom", true))); var entity = EntityRegistration.GetService <Link>().First(null); var result = helper.Clone(entity.Id); Assert.AreEqual(result.Success, false); Assert.IsNotNull(result.Item); Assert.AreEqual(result.IsAvailable, true); Assert.AreEqual(result.IsAuthorized, false); }
public void CanCopy() { var helper = CreateHelper <Link>(); var firstItem = EntityRegistration.GetService <Link>().GetAll()[0]; var result = helper.Copy(firstItem.Id); // This is a viewmodel Assert.AreEqual(result.Success, true); Assert.AreEqual(result.Message, string.Empty); Assert.IsNotNull(result.Item); Assert.AreEqual(result.ItemAs <Link>().Id, 0); Assert.AreEqual(result.ItemAs <Link>().Name, firstItem.Name); Assert.IsTrue(result.IsAuthorized); Assert.IsTrue(result.IsAvailable); }
public override ActionResult Edit(WidgetInstance instance) { DashboardLayout(true); // 1. Get the entity. // 2. Load its state back into it's properties. // 3. Clearn any errors ( used to compatibility between In-Memory repo and real ) // 4. Update it's data using the form var service = EntityRegistration.GetService <WidgetInstance>(); var entity = service.Get(instance.Id); // NOTE: Since widgets extend from WidgetInstance, so there can be any properties. // not just the ones from WidgetInstance. // Custom UpdateModel support since the MVC base controller's UpdateModel doesn't handle interfaces/derived classes. MapperSupport.MapperWebForms.UpdateModel(entity, this.Request.Form, null, _excludeMappingProps); return(base.Edit(entity)); }
/// <summary> /// Delete files associated w/ the specified entity. /// </summary> /// <param name="refId"></param> /// <param name="entityGroup"></param> public static bool DeleteFilesForEntity(int refId, string entityGroup) { int entityGroupid = ModuleMap.Instance.GetId(entityGroup); var service = EntityRegistration.GetService <MediaFile>(); bool result = true; try { service.Repository.Delete(Query <MediaFile> .New().Where(m => m.RefGroupId).Is(entityGroupid).And(m => m.RefId).Is(refId)); } catch (Exception ex) { result = false; } return(result); }
/// <summary> /// Delete the item represented by the id. /// </summary> /// <param name="p"></param> /// <returns></returns> public EntityActionResult FindByRecent(int page, int pageSize, IQuery <T> query = null) { if (query == null) { query = Query <T> .New().Where(t => t.Id).MoreThan(1).OrderByDescending(t => t.Id).Limit(pageSize); } var svc = EntityRegistration.GetService <T>(); var recents = svc.Find(query, page, pageSize); if (recents == null) { recents = new PagedList <T>(page, pageSize, 0, new List <T>()); } return(new EntityActionResult(true, string.Empty, null, recents)); }
/// <summary> /// Delete the item represented by the id. /// </summary> /// <param name="p"></param> /// <returns></returns> public EntityActionResult First() { if (!HasAccessTo("Read")) { return(new EntityActionResult(success: false, message: "Not authorized to perform this action", isAuthorized: false)); } var svc = EntityRegistration.GetService <T>(); var entity = svc.First(null); if (entity.IsOkToServe()) { return(new EntityActionResult(true, string.Empty, null, entity)); } return(new EntityActionResult(true, "Item not found", null, entity, true, false)); }
public void CanSetAuditData() { Auth.Init(new AuthWin("admin", new UserPrincipal(1, "kishore", "admin", "windows", true))); var blog = new Blog(); blog.Title = "1234567890123"; blog.Description = "123456789012345678901"; blog.Content = "title and description exceed max lengths"; var service = EntityRegistration.GetService <Blog>(); service.Create(blog); Assert.AreEqual(blog.CreateUser, "kishore"); Assert.AreEqual(blog.UpdateUser, "kishore"); Assert.AreEqual(blog.CreateDate.Date, DateTime.Today); }
public void CanCreate() { Auth.Init(new AuthWin("admin", new UserPrincipal(1, "kishore", "admin", "windows", true))); var blog = new Blog(); blog.Title = "1234567890"; blog.Description = "12345678901234567890"; blog.Content = "title and description"; var service = EntityRegistration.GetService <Blog>(); service.Create(blog); var blog2 = service.Get(blog.Id); Assert.AreEqual(blog2, blog); }
/// <summary> /// Find items by category /// </summary> /// <param name="year"></param> /// <param name="month"></param> /// <returns></returns> public static Tuple2 <PagedList <T>, Category> FindCategoryAndItems <T>(int id, int page, int pageSize, string categoryIdFieldName) { IList <T> posts = null; Node <Category> nodes = Categorys.Category.ToNodes(typeof(T).Name, true); if (nodes.Root[id] == null) { return(new Tuple2 <PagedList <T>, Category>(new PagedList <T>(1, 1, 0, posts), null)); } Node <Category> category = nodes.Root[id]; IQuery <T> query = !category.Item.IsRoot ? Query <T> .New().Where(categoryIdFieldName).Is(id) : Query <T> .New().Where(categoryIdFieldName).Is(id).Or(categoryIdFieldName).In <int>(CategoryHelper.GetChildIdsFor(nodes, id)); var service = EntityRegistration.GetService <T>(); PagedList <T> items = service.Find(query, page, pageSize); return(new Tuple2 <PagedList <T>, Category>(items, category.Item)); }
public void CanEdit() { var helper = new EntityHelper <Link>(); var link = EntityRegistration.GetService <Link>().GetAll()[0]; link.Name = link.Name + " updated"; string updatedName = link.Name; var result = helper.Edit(link); link = helper.Details(link.Id).ItemAs <Link>(); // This is a viewmodel Assert.AreEqual(result.Success, true); Assert.AreEqual(result.Message, string.Empty); Assert.IsNotNull(result.Item); Assert.AreEqual(result.ItemAs <Link>().Id, link.Id); Assert.AreEqual(result.ItemAs <Link>().Name, updatedName); Assert.IsTrue(result.IsAuthorized); Assert.IsTrue(result.IsAvailable); }
/// <summary> /// Create media files in the underlying datastore using the files supplied in the httprequest. /// </summary> /// <param name="request"></param> /// <param name="modelState"></param> /// <param name="id"></param> /// <param name="isParentDirectoryId"></param> /// <returns></returns> public static BoolMessageItem <IList <MediaFile> > CreateMediaFiles(HttpRequestBase request, ModelStateDictionary modelState, int id, int entityTypeId = 1, bool isParentDirectoryId = true) { IList <MediaFile> files = MediaFileMapper.MapFiles(request, id, entityTypeId, isParentDirectoryId); if (files.IsNullOrEmpty()) { modelState.AddModelError("Files", "No media files uploaded."); return(new BoolMessageItem <IList <MediaFile> >(null, false, "No files were uploaded")); } else { var service = EntityRegistration.GetService <MediaFile>(); int errorcount = 0; CreateMediaFiles(files, service, modelState, ref errorcount); if (errorcount == 0) { return(new BoolMessageItem <IList <MediaFile> >(files, true, string.Empty)); } return(new BoolMessageItem <IList <MediaFile> >(null, false, "Errors upload files")); } }