public ActionResult Associations(int id) { CFItem model = ItemService.GetItem(id); if (model == null) { throw new Exception("Item not found"); } EntityContentViewModel childItems = new EntityContentViewModel(); childItems.Id = model.Id; childItems.LoadNextChildrenSet(model.ChildItems); childItems.LoadNextMasterSet(ItemService.GetItems()); ViewBag.ChildItems = childItems; EntityContentViewModel relatedItems = new EntityContentViewModel(); relatedItems.Id = model.Id; relatedItems.LoadNextChildrenSet(model.ChildRelations); relatedItems.LoadNextMasterSet(ItemService.GetItems()); ViewBag.RelatedItems = relatedItems; return(View(model)); }
protected void UpdateFiles(CFItem srcItem, CFItem dstItem) { UpdateFiles(new List <Attachment>() { srcItem.AttachmentField }, dstItem); }
public BulletinBoardItem(CFItem dataModel, RequestContext ctx, string fields) { CFDataFile file = dataModel.Files.FirstOrDefault(); FileViewModel vm = new FileViewModel(file, dataModel.Id, ctx); Id = dataModel.Id; Thumbnail = vm.Thumbnail; Image = vm.Url; List <string> requiredFields = fields != null?fields.ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() : new List <string>(); Metadata = new List <MetadataFieldValue>(); foreach (CFMetadataSet ms in dataModel.MetadataSets) { foreach (FormField field in ms.Fields) { if (requiredFields.Contains(field.GetName().ToLower())) { List <TextValue> vals = field.GetValues().Where(tv => !string.IsNullOrEmpty(tv.Value)).ToList(); if (vals.Count > 0) { Metadata.Add(new MetadataFieldValue() { FieldName = field.GetName(), FieldValues = vals }); } } } } }
public ActionResult Edit(FormViewModel vm) { var model = GetModel(); if (ModelState.IsValid) { FormContainer formContainer = model.Region <FormContainer>("FormContainer"); CFItem submission = SubmissionService.SaveSubmission( vm.Form, vm.FormSubmissionRef, vm.ItemId, formContainer.EntityTypeId, formContainer.FormId, formContainer.CollectionId); CFAuditEntry.eAction action = submission.Id == 0 ? CFAuditEntry.eAction.Create : CFAuditEntry.eAction.Update; string actor = User.Identity.IsAuthenticated ? User.Identity.Name : "Annonymous"; Db.SaveChanges(User.Identity); string confirmLink = "confirmation"; return(Redirect(confirmLink)); } ViewBag.PageModel = model; return(View(model.GetView(), vm)); }
public void TestNoAccessDefinitionWithParents() { SecurityServiceBase srv = new TestSecurityService(Db); string collectionName = "TestUserIsAdminCollection"; string collectionDesciption = "Test collection description"; string itemName = "TestUserIsAdminItem"; string itemDesciption = "Test item description"; AccessMode defaultAccess = GetDefaultPermissions(); AccessMode modes; int entityType = mDh.Ets.GetEntityTypes(CFEntityType.eTarget.Collections).FirstOrDefault().Id; CFCollection c1 = mDh.CreateCollection(mDh.Cs, entityType, collectionName, collectionDesciption, true); entityType = mDh.Ets.GetEntityTypes(CFEntityType.eTarget.Items).FirstOrDefault().Id; CFItem i1 = mDh.CreateItem(mDh.Is, entityType, itemName, itemDesciption, true); c1.ChildMembers.Add(i1); Db.SaveChanges(); foreach (TestUser user in Users) { modes = srv.GetPermissions(user.Guid, i1); Assert.AreEqual(defaultAccess, modes); Assert.AreNotEqual(AccessMode.All, modes); } }
private void AddRelatedMember(string parentGuid, string childGuid, bool overwrite = false) { try { CFAggregation parent = Db.XmlModels.Where(x => x.MappedGuid == parentGuid).FirstOrDefault() as CFAggregation; CFItem child = Db.XmlModels.Where(x => x.MappedGuid == childGuid).FirstOrDefault() as CFItem; if (!overwrite) { parent.AddRelated(child); } else { //remove all child members first before adding new one foreach (var c in parent.RelatedMembers) { CFItem removeRel = Db.XmlModels.Where(x => x.Id == c.Id).FirstOrDefault() as CFItem; parent.RemoveRelated(removeRel); } //add new one parent.AddRelated(child); } Db.Entry(parent).State = System.Data.Entity.EntityState.Modified; } catch (Exception ex) { throw ex; } }
public void CreateItems() { int COUNT = 50; CatfishDbContext db = new CatfishDbContext(); List <CFEntityType> itemTypes = db.EntityTypes.Where(t => t.TargetTypes.Contains(CFEntityType.eTarget.Items.ToString())).ToList(); //db.EntityTypes.Where(t => t.TargetType == EntityType.eTarget.Items).ToList(); if (itemTypes.Count == 0) { throw new Exception("No entity types have been defined for collections."); } var rand = new Random(); ItemService srv = new ItemService(db); for (int i = 0; i < COUNT; ++i) { CFEntityType cType = itemTypes[rand.Next(0, itemTypes.Count)]; CFItem c = srv.CreateEntity <CFItem>(cType.Id); string name = TestData.LoremIpsum(5, 10); c.SetDescription(TestData.LoremIpsum(20, 100, 1, 10)); c.SetName("Item: " + name); c.Serialize(); db.Items.Add(c); } db.SaveChanges(); }
public ActionResult Associations(int id) { SecurityService.CreateAccessContext(); CFItem model = ItemService.GetItem(id); if (model == null) { throw new Exception("Item not found"); } //EntityContentViewModel childItems = new EntityContentViewModel(); //childItems.Id = model.Id; //childItems.LoadNextChildrenSet(model.ChildItems); //childItems.LoadNextMasterSet(ItemService.GetItems()); //ViewBag.ChildItems = childItems; //EntityContentViewModel relatedItems = new EntityContentViewModel(); //relatedItems.Id = model.Id; //relatedItems.LoadNextChildrenSet(model.RelatedMembers); //relatedItems.LoadNextMasterSet(ItemService.GetItems()); //ViewBag.RelatedItems = relatedItems; return(View(model)); }
public void UpdateExistingEntityMetadataTest() { const string metadataName = "UpdateExistingEntityMetadataTest"; const string metadataDescription = "Test for function UpdateExistingEntityMetadata."; const string entityTypeName = "UpdateExistingEntityMetadataTest"; const string entityTypeDescription = "Test for function UpdateExistingEntityMetadata."; // Create an entity CFMetadataSet metadata = CreateBasicMetadataSet(metadataName, metadataDescription); CFEntityType entityType = CreateEntityType(mDh, entityTypeName, entityTypeDescription, "Items", metadata); entityType.AttributeMappings.Add(new CFEntityTypeAttributeMapping() { Name = "Name Mapping", MetadataSet = metadata, FieldName = NAME_NAME }); entityType.AttributeMappings.Add(new CFEntityTypeAttributeMapping() { Name = "DescriptionMapping", MetadataSet = metadata, FieldName = NAME_DESCRIPTION }); mDh.Db.SaveChanges(); CFItem item1 = mDh.CreateItem(mDh.Is, entityType.Id, "Item 1", "Item 1 Description", true); CFItem item2 = mDh.CreateItem(mDh.Is, entityType.Id, "Item 2", "Item 2 Description", true); }
//Writes a unicode text file to storage (ie. renaming a table) void WriteUnicodeTextFile(string S, CFItem Itm) { CFStream Strm = (CFStream)Itm; byte[] Content = Encoding.Unicode.GetBytes(S); Strm.SetData(Content); }
public ActionResult Edit(CFItem model) { var sytemCollections = CollectionService.GetSystemCollections(); var systemCollectionList = new SelectList(sytemCollections.OrderBy(c => c.Name), "Id", "Name"); ViewBag.SystemCollections = systemCollectionList; SecurityService.CreateAccessContext(); if (ModelState.IsValid) { CFItem dbModel = ItemService.UpdateStoredItem(model); Db.SaveChanges(User.Identity); SuccessMessage(Catfish.Resources.Views.Items.Edit.SaveSuccess); if (model.Id == 0) { return(RedirectToAction("Edit", new { id = dbModel.Id })); } else { return(View(dbModel)); } } ErrorMessage(Catfish.Resources.Views.Items.Edit.SaveInvalid); model = ItemService.CreateItem(model.EntityTypeId.Value); model.AttachmentField = new Attachment() { FileGuids = string.Join(Attachment.FileGuidSeparator.ToString(), model.Files.Select(f => f.Guid)) }; return(View(model)); }
public JsonResult MoveItemToSystemCollection(int itemId, int sysCollectionId) { try { CFItem item = ItemService.GetItem(itemId); //remove all parents from this item if (item.ParentMembers.Count > 1) { foreach (CFAggregation p in item.ParentMembers) { p.RemoveChild(item); } } //add item to systemcollection CFCollection systemCollection = CollectionService.GetCollection(sysCollectionId); systemCollection.AddChild(item); Db.Entry(item).State = EntityState.Modified; Db.Entry(systemCollection).State = EntityState.Modified; Db.SaveChanges(User.Identity); //SuccessMessage(Catfish.Resources.Views.Items.Edit.MoveSuccess); return(Json(systemCollection.Name)); } catch (Exception ex) { //ErrorMessage(Catfish.Resources.Views.Items.Edit.MoveFailed); return(Json(Catfish.Resources.Views.Items.Edit.MoveFailed)); } }
public void DeleteItem() { DatabaseHelper Dh = new DatabaseHelper(true); ItemService Is = new ItemService(Dh.Db); Piranha.Entities.User admin = Dh.PDb.Users.First(); IIdentity identity = new GenericIdentity(admin.Login, Dh.PDb.Groups.Find(admin.GroupId).Name); CFItem test = Is.GetItems().FirstOrDefault(); int id = test.Id; IQueryable <CFItem> items = Is.GetItems(); Assert.AreEqual(DatabaseHelper.TOTAL_ITEMS, items.Count()); Is.DeleteItem(id); Dh.Db.SaveChanges(identity); Assert.AreNotEqual(DatabaseHelper.TOTAL_ITEMS, items.Count()); Assert.AreEqual(DatabaseHelper.TOTAL_ITEMS - 1, items.Count()); try { Is.DeleteItem(id); Dh.Db.SaveChanges(identity); Assert.Fail("An Exception should have been thrown on a bad delete."); } catch (ArgumentException ex) { } Assert.AreNotEqual(DatabaseHelper.TOTAL_ITEMS, items.Count()); Assert.AreEqual(DatabaseHelper.TOTAL_ITEMS - 1, items.Count()); }
/// <summary> /// Updates a Item in the database with the the values provided. A new Item is created if one does not already exist. /// </summary> /// <param name="changedItem">The item content to be modified.</param> /// <returns>The modified database item.</returns> public CFItem UpdateStoredItem(CFItem changedItem) { CFItem dbModel = new CFItem(); if (changedItem.Id > 0) { dbModel = Db.XmlModels.Find(changedItem.Id) as CFItem; } else { dbModel = CreateEntity <CFItem>(changedItem.EntityTypeId.Value); } //updating the "value" text elements dbModel.UpdateValues(changedItem); //Processing any file attachments that have been submitted UpdateFiles(changedItem, dbModel); if (changedItem.Id > 0) {//update Item Db.Entry(dbModel).State = EntityState.Modified; } else { dbModel.Serialize(); Db.XmlModels.Add(dbModel); } return(dbModel); }
/// <summary> /// Updates a Item in the database with the the values provided. A new Item is created if one does not already exist. /// </summary> /// <param name="changedItem">The item content to be modified.</param> /// <returns>The modified database item.</returns> public CFItem UpdateStoredItem(CFItem changedItem) { CFItem dbModel = new CFItem(); if (changedItem.Id > 0) { //dbModel = Db.XmlModels.Find(changedItem.Id) as CFItem; dbModel = GetItem(changedItem.Id, AccessMode.Write); if (dbModel == null) { throw new UnauthorizedAccessException("User does not have WRITE access to item " + changedItem.Id); } } else { dbModel = CreateEntity <CFItem>(changedItem.EntityTypeId.Value); } //updating the "value" text elements dbModel.UpdateValues(changedItem); //oct 10 2018 -- attemp to add attchment in the metadtaset to item.Attachment -- this might be wrong approach! foreach (CFMetadataSet ms in changedItem.MetadataSets) { foreach (FormField field in ms.Fields) { if (field.GetType().FullName == "Catfish.Core.Models.Forms.Attachment") { if (!string.IsNullOrEmpty((field as Catfish.Core.Models.Forms.Attachment).FileGuids)) { if (string.IsNullOrEmpty(changedItem.AttachmentField.FileGuids)) { changedItem.AttachmentField.FileGuids = (field as Catfish.Core.Models.Forms.Attachment).FileGuids; } else { changedItem.AttachmentField.FileGuids += "|" + (field as Catfish.Core.Models.Forms.Attachment).FileGuids; } } } } } //Processing any file attachments that have been submitted UpdateFiles(changedItem, dbModel); if (changedItem.Id > 0) {//update Item Db.Entry(dbModel).State = EntityState.Modified; } else { dbModel.Serialize(); Db.XmlModels.Add(dbModel); } return(dbModel); }
//Gets a raw byte-stream from storage public byte[] GetFile(CFItem Itm) { byte[] buf = new byte[Itm.Size]; CFStream Strm = (CFStream)Itm; Strm.Read(buf, 0, (int)Itm.Size); return(buf); }
public JsonResult Submit(FormViewModel vm, FormContainer formContainer) { if (ModelState.IsValid) { SubmissionService subSrv = new SubmissionService(Db); //add AttributeMappings -- Apr 10 2018 IDictionary <string, string> attributeMappings = new Dictionary <string, string>(); foreach (var map in formContainer.FieldMappings) { attributeMappings.Add(map.AttributeName, map.FieldName); } CFItem submission = subSrv.SaveSubmission( vm.Form, vm.FormSubmissionRef, vm.ItemId, formContainer.EntityTypeId, formContainer.FormId, formContainer.CollectionId, attributeMappings); //Sept 16 2019 -- if formContainer.AttachItemToUser = true, throw exception if current user is not authenticate if (formContainer.AttachItemToUser) { if (!User.Identity.IsAuthenticated) { //throw new HttpException("You have to authenticate to save this page."); vm.Errors = new Dictionary <string, string[]>(); vm.Errors.Add("NotAuthorized", (new string[] { "You are not authorized." })); return(Json(vm)); } } // Set's the audit log value when saving. // TODO: this should be more automated. CFAuditEntry.eAction action = submission.Id == 0 ? CFAuditEntry.eAction.Create : CFAuditEntry.eAction.Update; string actor = User.Identity.IsAuthenticated ? User.Identity.Name : "Annonymous"; Db.SaveChanges(User.Identity); } else { vm.Errors = new Dictionary <string, string[]>(); IEnumerable <KeyValuePair <string, System.Web.Mvc.ModelState> > errors = ModelState.Where(m => m.Value.Errors.Count > 0); List <string> errorList = new List <string>(); foreach (var error in errors) { vm.Errors.Add(error.Key, error.Value.Errors.Select(e => e.ErrorMessage).ToArray()); // errorList.AddRange(error.Value.Errors.Select(e => e.ErrorMessage)); } // vm.Errors.Add("Message", errorList.ToArray()); } return(Json(vm)); }
// GET: Manager/Items/Edit/5 public ActionResult Edit(int?id, int?entityTypeId) { SecurityService.CreateAccessContext(); CFItem model; if (id.HasValue && id.Value > 0) { model = ItemService.GetItem(id.Value); if (model == null) { return(HttpNotFound("Item was not found")); } //Sept 27 2019 -- set the READ ONLY if (!Catfish.Core.Contexts.AccessContext.current.IsAdmin)//not admin { string accessMode = ""; foreach (CFAccessGroup ag in model.AccessGroups) { accessMode = ag.AccessDefinition.AccessModes.ToString(); if (accessMode == "Read") { ViewBag.ReadOnly = true; } else if (accessMode == "Write") { ViewBag.ReadOnly = false; break; } } } } else { if (entityTypeId.HasValue) { model = ItemService.CreateItem(entityTypeId.Value); } else { List <CFEntityType> entityTypes = EntityTypeService.GetEntityTypes(CFEntityType.eTarget.Items).ToList(); //srv.GetEntityTypes(EntityType.eTarget.Items).ToList(); ViewBag.SelectEntityViewModel = new SelectEntityTypeViewModel() { EntityTypes = entityTypes }; model = new CFItem(); } } var sytemCollections = CollectionService.GetSystemCollections(); var systemCollectionList = new SelectList(sytemCollections.OrderBy(c => c.Name), "Id", "Name"); ViewBag.SystemCollections = systemCollectionList; model.AttachmentField = new Attachment() { FileGuids = string.Join(Attachment.FileGuidSeparator.ToString(), model.Files.Select(f => f.Guid)) }; return(View(model)); }
public void TestDenyInheritanceFlag() { SecurityServiceBase srv = new TestSecurityService(Db); string itemName = "TestUserIsAdminItem"; string itemDesciption = "Test item description"; AccessMode defaultAccess = GetDefaultPermissions(); CFAccessDefinition ad1 = new CFAccessDefinition() { Name = "Test 1", AccessModes = AccessMode.Read | AccessMode.Write }; CFAccessDefinition ad2 = new CFAccessDefinition() { Name = "Test 2", AccessModes = AccessMode.Control | AccessMode.Append }; int entityType = mDh.Ets.GetEntityTypes(CFEntityType.eTarget.Items).FirstOrDefault().Id; CFItem i1 = mDh.CreateItem(mDh.Is, entityType, itemName, itemDesciption, true); List <CFAccessGroup> groups = new List <CFAccessGroup>() { new CFAccessGroup() { AccessGuids = new List <Guid>() { Guid.Parse(Groups[0]) }, AccessDefinition = ad1 }, new CFAccessGroup() { AccessGuids = new List <Guid>() { Guid.Parse(Users[1].Guid) }, AccessDefinition = ad2 } }; i1.AccessGroups = groups; i1.BlockInheritance = true; i1.Serialize(); Db.SaveChanges(); AccessMode modes1 = srv.GetPermissions(Users[0].Guid, i1); AccessMode modes2 = srv.GetPermissions(Users[1].Guid, i1); AccessMode modes3 = srv.GetPermissions(Users[2].Guid, i1); AccessMode modes4 = srv.GetPermissions(Users[3].Guid, i1); Assert.AreEqual(ad1.AccessModes, modes1); Assert.AreEqual(ad1.AccessModes | ad2.AccessModes, modes2); Assert.AreEqual(AccessMode.None, modes3); Assert.AreEqual(AccessMode.None, modes4); }
//Reads a single binary integer from storage (Version Info) int ReadIntBinary(CFItem Itm) { CFStream Strm = (CFStream)Itm; byte[] buf = new byte[4]; int n = Strm.Read(buf, 0, 4); return(BitConverter.ToInt32(buf, 0)); }
//Gets a BIFF file from storage public BIFFFile GetBIFF(CFItem Itm) { byte[] buf = new byte[Itm.Size]; CFStream Strm = (CFStream)Itm; Strm.Read(buf, 0, (int)Itm.Size); return(new BIFFFile(buf)); }
protected void UpdateFiles(Attachment srcAttachmentField, CFItem dstItem) { List <string> keepFileGuids = srcAttachmentField.FileGuids.Split(new char[] { Attachment.FileGuidSeparator }, StringSplitOptions.RemoveEmptyEntries).ToList(); //Removing attachments that are in the dbModel but not in attachments to be kept foreach (CFDataFile file in dstItem.Files.ToList()) { if (keepFileGuids.IndexOf(file.Guid) < 0) { //Deleting the file node from the XML Model dstItem.RemoveFile(file); } } //Adding new files foreach (string fileGuid in keepFileGuids) { if (dstItem.Files.Where(f => f.Guid == fileGuid).Any() == false) { CFDataFile file = Db.XmlModels.Where(m => m.MappedGuid == fileGuid) .Select(m => m as CFDataFile) .FirstOrDefault(); if (file != null) { dstItem.AddData(file); //since the data object has now been inserted into the submission item, it is no longer needed //to stay as a stanalone object in the XmlModel table. Db.XmlModels.Remove(file); //moving the physical files from the temporary upload folder to a folder identified by the GUID of the //item inside the uploaded data folder string dstDir = Path.Combine(ConfigHelper.DataRoot, dstItem.MappedGuid); if (!Directory.Exists(dstDir)) { Directory.CreateDirectory(dstDir); } string srcFile = Path.Combine(file.Path, file.LocalFileName); string dstFile = Path.Combine(dstDir, file.LocalFileName); File.Move(srcFile, dstFile); //moving the thumbnail, if it's not a shared one if (file.ThumbnailType == CFDataFile.eThumbnailTypes.NonShared) { string srcThumbnail = Path.Combine(file.Path, file.Thumbnail); string dstThumbnail = Path.Combine(dstDir, file.Thumbnail); File.Move(srcThumbnail, dstThumbnail); } //updating the file path file.Path = dstDir; } } } }
public void Test_FIX_BUG_17_CORRUPTED_PPT_FILE() { const string FILE_PATH = @"2_MB-W.ppt"; using (CompoundFile file = new CompoundFile(FILE_PATH)) { //CFStorage dataSpaceInfo = file.RootStorage.GetStorage("\u0006DataSpaces").GetStorage("DataSpaceInfo"); CFItem dsiItem = file.GetAllNamedEntries("DataSpaceInfo").FirstOrDefault(); } }
//Reads a unicode text file from storage (Table Name / Author etc.) string ReadTextFileUnicode(long Sz, CFItem Itm) { string S = ""; CFStream Strm = (CFStream)Itm; byte[] buf = new byte[Sz]; int n = Strm.Read(buf, 0, (int)Sz); S = Encoding.Unicode.GetString(buf, 0, (int)Sz); return(S); }
private void treeView1_MouseUp(object sender, MouseEventArgs e) { // Get the node under the mouse cursor. // We intercept both left and right mouse clicks // and set the selected treenode according. TreeNode n = treeView1.GetNodeAt(e.X, e.Y); if (n != null) { if (this.hexEditor.ByteProvider != null && this.hexEditor.ByteProvider.HasChanges()) { if (MessageBox.Show("Do you want to save pending changes ?", "Save changes", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { this.hexEditor.ByteProvider.ApplyChanges(); } } treeView1.SelectedNode = n; // The tag property contains the underlying CFItem. CFItem target = (CFItem)n.Tag; if (target.IsStream) { addStorageStripMenuItem1.Enabled = false; addStreamToolStripMenuItem.Enabled = false; importDataStripMenuItem1.Enabled = true; exportDataToolStripMenuItem.Enabled = true; } else { addStorageStripMenuItem1.Enabled = true; addStreamToolStripMenuItem.Enabled = true; importDataStripMenuItem1.Enabled = false; exportDataToolStripMenuItem.Enabled = false; } propertyGrid1.SelectedObject = n.Tag; CFStream targetStream = n.Tag as CFStream; if (targetStream != null) { this.hexEditor.ByteProvider = new StreamDataProvider(targetStream); } else { this.hexEditor.ByteProvider = null; } } }
public void TestCreateItem() { DatabaseHelper Dh = new DatabaseHelper(true); ItemService Is = new ItemService(Dh.Db); int entityTypeId = Dh.Db.EntityTypes.Where(e => e.TargetTypes.Contains("Item")).Select(e => e.Id).FirstOrDefault(); string name = "Test 1"; string description = "Description"; CFItem i = CreateItem(Is, entityTypeId, name, description); Assert.AreEqual(name, i.Name); Assert.AreEqual(description, i.Description); }
private Ingestion DeserializeAggregations(XmlReader reader) { while (reader.Read()) { if (reader.IsStartElement()) { string name = reader.LocalName; CFXmlModel model = null; string strGuid = reader.GetAttribute("guid"); switch (name) { case "collection": model = new CFCollection(); break; case "item": model = new CFItem(); break; case "form": model = new Form(); break; case "file": model = new CFDataFile(); break; default: throw new FormatException("Invalid XML element: " + reader.Name); } if (model != null) { model.Guid = strGuid; model.MappedGuid = strGuid; model.Content = reader.ReadOuterXml(); Aggregations.Add(model); } } if (reader.NodeType == System.Xml.XmlNodeType.EndElement) { if (reader.Name == "aggregations") { return(this); } } } return(this); }
public void ItemTest() { string path = GetSampleDataFilePathName("Item.xml"); Assert.IsTrue(File.Exists(path)); CFItem model = CFXmlModel.Load(path) as CFItem; Assert.IsNotNull(model); List <CFMetadataSet> metadatasets = model.MetadataSets.ToList(); Assert.AreEqual(2, metadatasets.Count()); }
public JsonResult UpdateRelatedItems(EntityContentViewModel vm) { try { if (!ModelState.IsValid) { throw new Exception("Model validation failed"); } if (vm.Id == 0) { throw new Exception("Parent model ID mnot specified"); } CFAggregation model = Db.XmlModels.Where(x => x.Id == vm.Id).FirstOrDefault() as CFAggregation; if (model == null) { throw new Exception("Specified parent entity of type Aggregation not found"); } //Associating children foreach (var c in vm.ChildEntityList) { CFItem child = Db.XmlModels.Where(x => x.Id == c.Id).FirstOrDefault() as CFItem; if (child == null) { throw new Exception("Id=" + c.Id + ": Specified related item not found"); } model.ChildRelations.Add(child); } //Removing deleted children foreach (var c in vm.RemovalPendingChildEntities) { CFItem child = Db.XmlModels.Where(x => x.Id == c.Id).FirstOrDefault() as CFItem; model.ChildRelations.Remove(child); } Db.Entry(model).State = System.Data.Entity.EntityState.Modified; Db.SaveChanges(User.Identity); vm.Status = KoBaseViewModel.eStatus.Success; return(Json(vm)); } catch (Exception ex) { return(Json(vm.Error("UpdateRelatedItems Error: " + ex.Message))); } }
private CFItem CreateItem(ItemService itemSrv, int entityTypeId, string name, string description, bool store = false) { CFItem i = itemSrv.CreateItem(entityTypeId); i.SetName(name); i.SetDescription(description); if (store) { i = itemSrv.UpdateStoredItem(i); } return(i); }