private bool InsertBookRecord(ImportObject importerObject) { try { ImportObject importerObj = importerObject; bool exists = _bookRepository.CheckIfBookExistsByNameWriterAndByPublisher(importerObj.BookName, importerObj.AuthorName, importerObj.PublisherName); EBook book = new EBook(); if (!exists) { GenerateBookRecord(importerObj, ref book); _bookRepository.CreateEntity(book); } else { book = _bookRepository.GetBookByNameAndByPublisher(importerObj.BookName, importerObj.AuthorName, importerObj.PublisherName); if (!book.Users.Contains(importerObj.User)) { book.Users.Add(importerObj.User); _bookRepository.UpdateEntity(book); } } return(true); } catch (Exception error) { _logger.Error("Integration Error while doing InsertBookRecord", error); return(false); } }
/// <summary> /// Imports the specified input. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> public bool Import(ImportInputDto input) { ImportObjectValidaiton validator = new ImportObjectValidaiton(); DataTable datatable = _parserApplication.ReadExcelFile(input.ImportDto.Input); EUser user = _userRepository.GetOne(input.ImportDto.UserId); bool recordInserted = false; foreach (DataRow row in datatable.Rows) { ImportObject importerObject = _importer.ConvertRowIntoImportObject(row); importerObject.User = user; var result = validator.Validate(importerObject); if (!result.IsValid) { continue; } recordInserted = InsertBookRecord(importerObject); if (!recordInserted) { break; } } return(recordInserted); }
public ImportObject ProcessImport(string xmlString) { ImportObject impObj = null; try { var result = string.Empty; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString))) { var reader = new XmlTextReader(stream); var serializer = new XmlSerializer(typeof(ImportObject)); if (!serializer.CanDeserialize(reader)) { throw new DeveloperException("Can't deserialize file."); } impObj = serializer.Deserialize(reader) as ImportObject; if (impObj == null) { throw new DeveloperException("Can't deserialize file."); } impObj.Type = TelType.ANSWER; switch (impObj.TelCode) { case TelCodeEnum.WMS_API: result = ProcessApi(impObj); break; case TelCodeEnum.WMS_PROCESS: result = ProcessBP(impObj: impObj, xml: xmlString); break; case TelCodeEnum.WMS_INSERT: result = ProcessCrud(impObj); break; } impObj.Content.Items = new XmlNode[1]; var doc = new XmlDocument(); doc.LoadXml(result); impObj.Content.Items[0] = doc.DocumentElement; } } catch (Exception ex) { if (impObj == null) { throw; } var doc = new XmlDocument(); doc.LoadXml("<ERROR></ERROR>"); if (doc.DocumentElement == null) { throw; } doc.DocumentElement.InnerText = ex.To <string>(); var tmp = new List <XmlNode>((XmlNode[])impObj.Content.Items.Clone()); tmp.Add(doc.DocumentElement); impObj.Content.Items = tmp.ToArray(); } return(impObj); }
public static void SaveDelta(Delta delta, string file) { var ns = new XmlSerializerNamespaces(); ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); ns.Add("xsd", "http://www.w3.org/2001/XMLSchema"); var serializer = new XmlSerializer(typeof(Delta)); var list = new List<ImportObject>(); foreach (var obj in delta.Objects.Where(x => x.NeedsInclude())) { var newObj = new ImportObject(); newObj.SourceObjectIdentifier = obj.SourceObjectIdentifier; newObj.TargetObjectIdentifier = obj.TargetObjectIdentifier; newObj.ObjectType = obj.ObjectType; newObj.State = obj.State; newObj.Changes = obj.Changes != null ? obj.Changes.Where(x => x.IsIncluded).ToArray() : null; newObj.AnchorPairs = obj.AnchorPairs; list.Add(newObj); } var newDelta = new Delta(); newDelta.Objects = list.ToArray(); var settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = false; settings.Indent = true; using (var w = XmlWriter.Create(file, settings)) serializer.Serialize(w, newDelta, ns); }
private void treeViewCategories_Selected(object sender, RoutedEventArgs e) { const string iconsCategoryDirectory = @"Icons\IconsCategory"; lastSelectedTreeViewItem = selectedTreeViewItem; lastSelectedItemType = selectedItemType; selectedTreeViewItem = e.OriginalSource as TreeViewItem; if (selectedTreeViewItem.Tag is Category <FurnitureObject> ) { selectedItemType = LastSelectedItemType.Category; Category <FurnitureObject> currentCategory = selectedTreeViewItem.Tag as Category <FurnitureObject>; AddCategory addCategory = new AddCategory(currentCategory.Name, currentCategory, true, false, System.IO.Path.GetFullPath(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\", iconsCategoryDirectory))); Grid grid = new Grid(); grid.Children.Add(addCategory); groupBoxRightSide.Content = grid; } else { if (selectedTreeViewItem.Tag is FurnitureObject) { selectedItemType = LastSelectedItemType.FurnitureObject; FurnitureObject currentObject = selectedTreeViewItem.Tag as FurnitureObject; double tradeAllowance = ((selectedTreeViewItem.Parent as TreeViewItem).Tag as Category <FurnitureObject>).TradeAllowance; ImportObject importObject = new ImportObject("Object", currentObject, configuration.Materials, true, false, tradeAllowance); importObject.StatusUpdated += importObject_StatusUpdated; Grid grid = new Grid(); grid.Children.Add(importObject); groupBoxRightSide.Content = grid; } } }
public override void Submit_OnClick(object sender, EventArgs e) { if (HifMyFile.PostedFile != null && "" != HifMyFile.PostedFile.FileName) { var filePath = HifMyFile.PostedFile.FileName; if (!EFileSystemTypeUtils.IsZip(PathUtils.GetExtension(filePath))) { FailMessage("必须上传Zip压缩文件"); return; } try { var localFilePath = PathUtils.GetTemporaryFilesPath(PathUtils.GetFileName(filePath)); HifMyFile.PostedFile.SaveAs(localFilePath); ImportObject.ImportTableStyleByZipFile(_tableName, _relatedIdentity, localFilePath); AuthRequest.AddSiteLog(SiteId, "导入表单显示样式"); LayerUtils.Close(Page); } catch (Exception ex) { FailMessage(ex, "导入表样式失败!"); } } }
public async Task <ActionResult <List <int> > > Import([FromBody] ImportRequest request) { if (!await _authManager.HasChannelPermissionsAsync(request.SiteId, request.ChannelId, Types.ChannelPermissions.Add)) { return(Unauthorized()); } try { var site = await _siteRepository.GetAsync(request.SiteId); var filePath = _pathManager.GetTemporaryFilesPath(request.FileName); var adminId = _authManager.AdminId; var caching = new CacheUtils(_cacheManager); var importObject = new ImportObject(_pathManager, _databaseManager, caching, site, adminId); await importObject.ImportChannelsAndContentsByZipFileAsync(request.ChannelId, filePath, request.IsOverride, null); await _authManager.AddSiteLogAsync(request.SiteId, "导入栏目"); } catch { return(this.Error("压缩包格式不正确,请上传正确的栏目压缩包")); } return(new List <int> { request.SiteId, request.ChannelId }); }
public override void Submit_OnClick(object sender, EventArgs e) { if (StringUtils.EqualsIgnoreCase(_type, TypeRelatedField)) { if (HifMyFile.PostedFile != null && "" != HifMyFile.PostedFile.FileName) { var filePath = HifMyFile.PostedFile.FileName; if (EFileSystemTypeUtils.GetEnumType(Path.GetExtension(filePath)) != EFileSystemType.Zip) { FailMessage("必须上传ZIP文件"); return; } try { var localFilePath = PathUtils.GetTemporaryFilesPath(Path.GetFileName(filePath)); HifMyFile.PostedFile.SaveAs(localFilePath); var importObject = new ImportObject(SiteId); importObject.ImportRelatedFieldByZipFile(localFilePath, TranslateUtils.ToBool(DdlIsOverride.SelectedValue)); Body.AddSiteLog(SiteId, "导入联动字段"); LayerUtils.Close(Page); } catch (Exception ex) { FailMessage(ex, "导入联动字段失败!"); } } } }
public override void Submit_OnClick(object sender, EventArgs e) { if (myFile.PostedFile != null && "" != myFile.PostedFile.FileName) { var filePath = myFile.PostedFile.FileName; if (!EFileSystemTypeUtils.IsZip(PathUtils.GetExtension(filePath))) { FailMessage("必须上传Zip压缩文件"); return; } try { var localFilePath = PathUtils.GetTemporaryFilesPath(PathUtils.GetFileName(filePath)); myFile.PostedFile.SaveAs(localFilePath); var importObject = new ImportObject(PublishmentSystemId); importObject.ImportChannelsAndContentsByZipFile(TranslateUtils.ToInt(ParentNodeID.SelectedValue), localFilePath, TranslateUtils.ToBool(IsOverride.SelectedValue)); Body.AddSiteLog(PublishmentSystemId, "导入栏目"); PageUtils.CloseModalPage(Page); } catch (Exception ex) { FailMessage(ex, "导入栏目失败!"); } } }
public override void Submit_OnClick(object sender, EventArgs e) { if (HifFile.PostedFile != null && "" != HifFile.PostedFile.FileName) { var filePath = HifFile.PostedFile.FileName; if (!EFileSystemTypeUtils.IsZip(PathUtils.GetExtension(filePath))) { FailMessage("必须上传Zip压缩文件"); return; } try { var localFilePath = PathUtils.GetTemporaryFilesPath(PathUtils.GetFileName(filePath)); HifFile.PostedFile.SaveAs(localFilePath); var importObject = new ImportObject(SiteId, AuthRequest.AdminName); importObject.ImportChannelsAndContentsByZipFile(TranslateUtils.ToInt(DdlParentChannelId.SelectedValue), localFilePath, TranslateUtils.ToBool(DdlIsOverride.SelectedValue)); AuthRequest.AddSiteLog(SiteId, "导入栏目"); LayerUtils.Close(Page); } catch (Exception ex) { FailMessage(ex, "导入栏目失败!"); } } }
public void CommandEdit(object param) { if (!ObjectExists(param)) return; Guid uid = (Guid)param; ObjectPool objPool = Editor.Project.ObjectPoolManager.PoolFromItemKey(uid); ObjectClass objClass = objPool.GetObject(uid); using (ImportObject form = new ImportObject(objClass)) { foreach (ObjectClass obj in objPool.Objects) { if (obj.Name != objClass.Name) form.ReservedNames.Add(obj.Name); } if (form.ShowDialog() == DialogResult.OK) { using (objClass.BeginModify()) { if (form.SourceImage != null) objClass.Image = form.SourceImage; objClass.TrySetName(form.ObjectName); objClass.MaskBounds = new Rectangle(form.MaskLeft ?? 0, form.MaskTop ?? 0, (form.MaskRight ?? 0) - (form.MaskLeft ?? 0), (form.MaskBottom ?? 0) - (form.MaskTop ?? 0)); objClass.Origin = new Point(form.OriginX ?? 0, form.OriginY ?? 0); } } } }
public override void Submit_OnClick(object sender, EventArgs e) { if (myFile.PostedFile != null && "" != myFile.PostedFile.FileName) { var filePath = myFile.PostedFile.FileName; if (!EFileSystemTypeUtils.IsZip(PathUtils.GetExtension(filePath))) { FailMessage("必须上传Zip压缩文件"); return; } try { var localFilePath = PathUtils.GetTemporaryFilesPath(PathUtils.GetFileName(filePath)); myFile.PostedFile.SaveAs(localFilePath); ImportObject.ImportTableStyleByZipFile(_tableStyle, _tableName, _relatedIdentity, localFilePath); Body.AddSiteLog(PublishmentSystemId, "导入表单显示样式", $"类型:{ETableStyleUtils.GetText(_tableStyle)}"); PageUtils.CloseModalPage(Page); } catch (Exception ex) { FailMessage(ex, "导入表样式失败!"); } } }
private void CommandImportObject() { if (CommandCanImportObject()) { using (ImportObject form = new ImportObject()) { foreach (ObjectClass objClass in SelectedObjectPool.Objects) { form.ReservedNames.Add(objClass.Name); } if (form.ShowDialog() == DialogResult.OK) { TextureResource resource = TextureResourceBitmapExt.CreateTextureResource(form.SourceFile); ObjectClass objClass = new ObjectClass(form.ObjectName) { MaskBounds = new Rectangle(form.MaskLeft ?? 0, form.MaskTop ?? 0, (form.MaskRight ?? 0) - (form.MaskLeft ?? 0), (form.MaskBottom ?? 0) - (form.MaskTop ?? 0)), Origin = new Point(form.OriginX ?? 0, form.OriginY ?? 0), }; SelectedObjectPool.AddObject(objClass); objClass.Image = resource; RefreshObjectPoolCollection(); OnSyncObjectPoolManager(EventArgs.Empty); } } } }
private string ProcessApi(ImportObject impObj) { if (string.IsNullOrEmpty(_apiUri)) { throw new OperationException("Не указана точка соединения для сервиса API."); } var objType = GetEntityTypeByTent(GetManagerForObject(), impObj); if (impObj.Content != null) { var items = impObj.Content.Items.FirstOrDefault(i => i.Name.EqIgnoreCase("ITEMS")); if (items != null && !string.IsNullOrEmpty(items.InnerText.Trim())) { var action = impObj.Action; if (string.IsNullOrEmpty(action)) { throw new DeveloperException("Action is not defined."); } var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(items.OuterXml); var helper = new IntegrationServiceImpl(_apiUri); return(helper.ProcessApi(action, objType.Name, xmlDoc) ?? string.Empty); } } return(string.Empty); }
public void CommandEdit(object param) { if (!ObjectExists(param)) { return; } Guid uid = (Guid)param; ObjectPool objPool = Editor.Project.ObjectPoolManager.PoolFromItemKey(uid); ObjectClass objClass = objPool.GetObject(uid); using (ImportObject form = new ImportObject(objClass)) { foreach (ObjectClass obj in objPool.Objects) { if (obj.Name != objClass.Name) { form.ReservedNames.Add(obj.Name); } } if (form.ShowDialog() == DialogResult.OK) { using (objClass.BeginModify()) { if (form.SourceImage != null) { objClass.Image = form.SourceImage; } objClass.TrySetName(form.ObjectName); objClass.MaskBounds = new Rectangle(form.MaskLeft ?? 0, form.MaskTop ?? 0, (form.MaskRight ?? 0) - (form.MaskLeft ?? 0), (form.MaskBottom ?? 0) - (form.MaskTop ?? 0)); objClass.Origin = new Point(form.OriginX ?? 0, form.OriginY ?? 0); } } } }
public override void Submit_OnClick(object sender, EventArgs e) { if (myFile.PostedFile != null && "" != myFile.PostedFile.FileName) { try { var filePath = myFile.PostedFile.FileName; if (!StringUtils.EqualsIgnoreCase(PathUtils.GetExtension(filePath), ".csv")) { FailMessage("必须上传后缀为“.csv”的Excel文件"); return; } var localFilePath = PathUtils.GetTemporaryFilesPath(PathUtils.GetFileName(filePath)); myFile.PostedFile.SaveAs(localFilePath); var importObject = new ImportObject(PublishmentSystemId); importObject.ImportInputContentsByCsvFile(_inputInfo, localFilePath, TranslateUtils.ToInt(ImportStart.Text), TranslateUtils.ToInt(ImportCount.Text), TranslateUtils.ToBool(IsChecked.SelectedValue)); Body.AddSiteLog(PublishmentSystemId, "导入提交表单内容", $"提交表单:{_inputInfo.InputName}"); PageUtils.CloseModalPage(Page); } catch (Exception ex) { FailMessage(ex, "导入提交表单失败!"); } } }
public void ImportSiteTemplateToEmptySite(int siteId, string siteTemplateDir, bool isImportContents, bool isImportTableStyles, string administratorName) { var siteTemplatePath = PathUtility.GetSiteTemplatesPath(siteTemplateDir); if (DirectoryUtils.IsDirectoryExists(siteTemplatePath)) { var templateFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTemplate); var tableDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Table); var configurationFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileConfiguration); var siteContentDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.SiteContent); var importObject = new ImportObject(siteId, administratorName); importObject.ImportFiles(siteTemplatePath, true); importObject.ImportTemplates(templateFilePath, true, administratorName); importObject.ImportConfiguration(configurationFilePath); var filePathList = ImportObject.GetSiteContentFilePathList(siteContentDirectoryPath); foreach (var filePath in filePathList) { importObject.ImportSiteContent(siteContentDirectoryPath, filePath, isImportContents); } if (isImportTableStyles) { importObject.ImportTableStyles(tableDirectoryPath); } importObject.RemoveDbCache(); } }
public static void SaveDelta(Delta delta, string file) { var ns = new XmlSerializerNamespaces(); ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); ns.Add("xsd", "http://www.w3.org/2001/XMLSchema"); var serializer = new XmlSerializer(typeof(Delta)); var list = new List <ImportObject>(); foreach (var obj in delta.Objects.Where(x => x.NeedsInclude())) { var newObj = new ImportObject(); newObj.SourceObjectIdentifier = obj.SourceObjectIdentifier; newObj.TargetObjectIdentifier = obj.TargetObjectIdentifier; newObj.ObjectType = obj.ObjectType; newObj.State = obj.State; newObj.Changes = obj.Changes != null?obj.Changes.Where(x => x.IsIncluded).ToArray() : null; newObj.AnchorPairs = obj.AnchorPairs; list.Add(newObj); } var newDelta = new Delta(); newDelta.Objects = list.ToArray(); var settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = false; settings.Indent = true; using (var w = XmlWriter.Create(file, settings)) serializer.Serialize(w, newDelta, ns); }
private string GetDatabaseFileName(string rootPath) { rootPath += @"\" + ObjectType.General.ToString(); string dbProperties = Path.Combine(rootPath, AccessIO.Properties.Resources.DatabaseProperties + "." + FileExtensions.dbp.ToString() + ".txt"); if (!File.Exists(dbProperties)) { return(Path.GetFileName(dbProperties)); } else { try { StreamReader sr = new StreamReader(dbProperties); ImportObject import = new ImportObject(sr); return(import.ReadObjectName()); } catch (WrongFileFormatException ex) { if (ex.LineNumber <= 1) { return(Path.GetFileName(dbProperties)); } else { throw; } } } }
public AttributeNode(Delta delta, ImportObject obj, ImportChange attr) { this.delta = delta; this.obj = obj; this.attr = attr; this.attr.PropertyChanged += SourcePropertyChanged; }
/// <summary> /// Constructor. /// </summary> /// <param name="delta"></param> /// <param name="obj"></param> /// <param name="attr"></param> public AttributeNode(Delta delta, ImportObject obj, ImportChange attr) { this.delta = delta; this.obj = obj; this.attr = attr; this.attr.PropertyChanged += SourcePropertyChanged; }
public static void LoadExclusions(Delta delta, string file) { var serializer = new XmlSerializer(typeof(List <ExclusionObject>)); List <ExclusionObject> objectList; try { using (var r = XmlReader.Create(file)) objectList = (List <ExclusionObject>)serializer.Deserialize(r); } catch (InvalidOperationException ex) { System.Windows.MessageBox.Show(string.Format("Unable to deserialize XML. Verify that you loaded an exclusion file.")); return; } int foundObjectCount = 0; int notFoundObjectCount = 0; int foundAttributeCount = 0; int notFoundAttributeCount = 0; foreach (ExclusionObject exclusion_object in objectList) { try { ImportObject o = delta.Objects.First(x => x.SourceObjectIdentifier == exclusion_object.SourceObjectIdentifier && x.TargetObjectIdentifier == exclusion_object.TargetObjectIdentifier); foundObjectCount++; try { foreach (var change in exclusion_object.Changes) { ImportChange c = o.Changes.First(x => x.Operation == change.Operation && x.AttributeName == change.AttributeName && x.AttributeValue == change.AttributeValue); c.IsIncluded = false; foundAttributeCount++; } } catch (InvalidOperationException) { notFoundAttributeCount++; } // If there were no sub changes, exclude the parent if (exclusion_object.Changes.Length == 0) { o.IsIncluded = false; } } catch (InvalidOperationException) { notFoundObjectCount++; } } System.Windows.MessageBox.Show(string.Format("Found and excluded {0} object and {1} attributes. {2} objects and {3} attributes were not found", foundObjectCount, foundAttributeCount, notFoundObjectCount, notFoundAttributeCount)); }
/// <summary> /// Sets import session information. /// </summary> /// <param name="parameters">Import parameters.</param> public void SetImportSessionInfo(ImportParameters parameters) { FileName = parameters.FileName; ImportObject = parameters.ImportObject; TotalRowsCount = parameters.TotalRowsCount; ProcessedRowsCount = parameters.ProcessedRowsCount; ImportedRowsCount = parameters.ImportedRowsCount; NotImportedRowsCount = parameters.TotalRowsCount - parameters.ImportedRowsCount; ImportTags = parameters.ImportTags; }
public ObjectNode(Delta delta, ImportObject obj) { this.delta = delta; this.obj = obj; this.obj.PropertyChanged += new PropertyChangedEventHandler(SourcePropertyChanged); this.children = null; if (obj.Changes != null) this.children = obj.Changes.Select(a => new AttributeNode(delta, obj, a) { Parent = this }).ToArray(); }
private string ProcessBP(ImportObject impObj, string xml) { if (string.IsNullOrEmpty(impObj.Action)) { throw new DeveloperException("Action not set."); } var bpMgr = IoC.Instance.Resolve <IBPProcessManager>(); if (bpMgr == null) { throw new DeveloperException("IBPProcessManager not registered."); } var context = new BpContext { Items = impObj.Content.Items }; context.Set("DialogVisible", true); // признак того, что надо показывать диалоги context.Set(RootName, xml); bpMgr.Parameters.Add(BpContext.BpContextArgumentName, context); CompleteContext resCtx = null; bpMgr.Run(code: impObj.Action, completedHandler: ctx => { WaitHandle.Set(); resCtx = ctx; }); WaitHandle.WaitOne(); var result = string.Empty; if (resCtx != null) { if (resCtx.Exception != null) { //Избавляемся от & в сообщении об ошибке var errmessage = resCtx.Exception.Message; if (!string.IsNullOrEmpty(errmessage)) { errmessage = errmessage.Replace("&", "&"); } result = string.Format("<ERROR>{0}</ERROR>", errmessage); } else { // оставил старую логику result = resCtx.Parameters.ContainsKey("RESULT") ? resCtx.Parameters["RESULT"].ToString() : null; } } if (result != null) { return(result); } return("<STATUS>OK</STATUS>"); }
private void extendedMenuItemImport_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { TabItem currentTabItem = (TabItem)mainTabControl.SelectedItem; if (currentTabItem != null) { if (currentTabItem.Header.ToString() == "Categories") { if (selectedItemType == LastSelectedItemType.Category) { if (treeViewMaterials.Items.Count == 0) { MessageBox.Show("Please define material categories!"); mainTabControl.SelectedIndex = 1; return; } double tradeAllowance = (selectedTreeViewItem.Tag as Category <FurnitureObject>).TradeAllowance; ImportObject importObject = new ImportObject("Import Object", null, configuration.Materials, false, false, tradeAllowance); importObject.StatusUpdated += importObject_StatusUpdated; importObject.ImportMaterialStatusUpdated += importObject_ImportMaterialStatusUpdated; Grid grid = new Grid(); grid.Children.Add(importObject); groupBoxRightSide.Content = grid; } else { MessageBox.Show("Select a category!"); return; } } else { if (selectedItemType == LastSelectedItemType.CategoryMaterial) { ImportMaterial importMaterial = new ImportMaterial("Import Material", null, false, false, false); importMaterial.StatusUpdated += importMaterial_StatusUpdated; Grid grid = new Grid(); grid.Children.Add(importMaterial); groupBoxPreviewMaterial.Content = grid; } else { MessageBox.Show("Select a category!"); return; } } } }
public async Task <ActionResult <BoolResult> > Import([FromQuery] ImportRequest request, [FromForm] IFormFile file) { if (!await _authManager.HasSitePermissionsAsync(request.SiteId, Types.SitePermissions.SettingsStyleContent)) { return(Unauthorized()); } var site = await _siteRepository.GetAsync(request.SiteId); if (site == null) { return(NotFound()); } var channel = await _channelRepository.GetAsync(request.ChannelId); if (file == null) { return(this.Error("请选择有效的文件上传")); } var fileName = PathUtils.GetFileName(file.FileName); var sExt = PathUtils.GetExtension(fileName); if (!StringUtils.EqualsIgnoreCase(sExt, ".zip")) { return(this.Error("导入文件为 Zip 格式,请选择有效的文件上传")); } var filePath = _pathManager.GetTemporaryFilesPath(fileName); await _pathManager.UploadAsync(file, filePath); var tableName = _channelRepository.GetTableName(site, channel); var directoryPath = await ImportObject.ImportTableStyleByZipFileAsync(_pathManager, _databaseManager, tableName, _tableStyleRepository.GetRelatedIdentities(channel), filePath); FileUtils.DeleteFileIfExists(filePath); DirectoryUtils.DeleteDirectoryIfExists(directoryPath); await _authManager.AddSiteLogAsync(request.SiteId, "导入站点字段"); return(new BoolResult { Value = true }); }
private void GenerateBookRecord(ImportObject importerObj, ref EBook book) { book.Author = _authorRepository.CreateIfAuthorIsNotExists(importerObj.AuthorName); book.Publisher = _publisherRepository.CreatePublisherIfNotExists(importerObj.PublisherName); book.Genre = _genreRepository.CreateGenreIfNotExists(importerObj.GenreName); book.Serie = _seriesRepository.CreateSeriesIfNotExists(importerObj.SerieName, book.Publisher); book.Rack = _rackRepository.GetRackByRackNumber(int.Parse(importerObj.RackId)); book.Shelf = _shelfRepository.GetShelfById(int.Parse(importerObj.ShelfId)); book.Name = importerObj.BookName; book.PublishDate = int.Parse(importerObj.Publishdate); book.No = ConvertToRomanIntegers(importerObj.No); book.SkinType = importerObj.Skintype.Equals("ciltli", StringComparison.InvariantCulture) ? SkinType.Ciltli : SkinType.Ciltsiz; book.CreatedDateTime = DateTime.Now; book.Users.Add(importerObj.User); }
public ObjectNode(Delta delta, ImportObject obj) { this.delta = delta; this.obj = obj; this.obj.PropertyChanged += new PropertyChangedEventHandler(SourcePropertyChanged); this.children = null; if (obj.Changes != null) { this.children = obj.Changes.Select(a => new AttributeNode(delta, obj, a) { Parent = this }).ToArray(); } }
private Type GetEntityTypeByTent(IManagerForObject mgrForObj, ImportObject impObj) { if (mgrForObj == null) { throw new ArgumentNullException("mgrForObj"); } if (impObj == null) { throw new ArgumentNullException("impObj"); } var objType = mgrForObj.GetTypeByTENTName(impObj.Entity); if (objType == null) { throw new DeveloperException("Can't find type '{0}'.", impObj.Entity); } return(objType); }
public void ImportSiteTemplateToEmptySite(int siteId, string siteTemplateDir, bool isUseTables, bool isImportContents, bool isImportTableStyles, string administratorName) { var siteTemplatePath = PathUtility.GetSiteTemplatesPath(siteTemplateDir); if (DirectoryUtils.IsDirectoryExists(siteTemplatePath)) { var siteInfo = SiteManager.GetSiteInfo(siteId); var templateFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTemplate); var tableDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Table); var configurationFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileConfiguration); var siteContentDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.SiteContent); var importObject = new ImportObject(siteId); importObject.ImportFiles(siteTemplatePath, true); importObject.ImportTemplates(templateFilePath, true, administratorName); importObject.ImportAuxiliaryTables(tableDirectoryPath, isUseTables); importObject.ImportConfiguration(configurationFilePath); var filePathArrayList = ImportObject.GetSiteContentFilePathArrayList(siteContentDirectoryPath); foreach (string filePath in filePathArrayList) { importObject.ImportSiteContent(siteContentDirectoryPath, filePath, isImportContents); } DataProvider.ChannelDao.UpdateContentNum(siteInfo); if (isImportTableStyles) { importObject.ImportTableStyles(tableDirectoryPath); } importObject.RemoveDbCache(); } }
public async Task <ActionResult <BoolResult> > Import([FromQuery] SiteRequest request, [FromForm] IFormFile file) { if (!await _authManager.HasSitePermissionsAsync(request.SiteId, MenuUtils.SitePermissions.SettingsStyleRelatedField)) { return(Unauthorized()); } var site = await _siteRepository.GetAsync(request.SiteId); if (file == null) { return(this.Error(Constants.ErrorUpload)); } var fileName = Path.GetFileName(file.FileName); var sExt = PathUtils.GetExtension(fileName); if (!StringUtils.EqualsIgnoreCase(sExt, ".zip")) { return(this.Error("导入文件为 Zip 格式,请选择有效的文件上传")); } var filePath = _pathManager.GetTemporaryFilesPath(fileName); await _pathManager.UploadAsync(file, filePath); var directoryPath = await ImportObject.ImportRelatedFieldByZipFileAsync(_pathManager, _databaseManager, site, filePath); FileUtils.DeleteFileIfExists(filePath); DirectoryUtils.DeleteDirectoryIfExists(directoryPath); await _authManager.AddSiteLogAsync(request.SiteId, "导入联动字段"); return(new BoolResult { Value = true }); }
public async Task ImportSiteTemplateToEmptySiteAsync(Site site, string siteTemplateDir, bool isImportContents, bool isImportTableStyles, int adminId, string guid) { var siteTemplatePath = _pathManager.GetSiteTemplatesPath(siteTemplateDir); if (!DirectoryUtils.IsDirectoryExists(siteTemplatePath)) { return; } var templateFilePath = _pathManager.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteFiles.SiteTemplates.FileTemplate); var tableDirectoryPath = _pathManager.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteFiles.SiteTemplates.Table); var configurationFilePath = _pathManager.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteFiles.SiteTemplates.FileConfiguration); var siteContentDirectoryPath = _pathManager.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteFiles.SiteTemplates.SiteContent); var importObject = new ImportObject(_pathManager, _databaseManager, _caching, site, adminId); _caching.SetProcess(guid, $"导入站点文件: {siteTemplatePath}"); await importObject.ImportFilesAsync(siteTemplatePath, true, guid); _caching.SetProcess(guid, $"导入模板文件: {templateFilePath}"); await importObject.ImportTemplatesAsync(templateFilePath, true, adminId, guid); _caching.SetProcess(guid, $"导入配置文件: {configurationFilePath}"); await importObject.ImportConfigurationAsync(configurationFilePath, guid); var filePathList = ImportObject.GetSiteContentFilePathList(siteContentDirectoryPath); foreach (var filePath in filePathList) { _caching.SetProcess(guid, $"导入栏目文件: {filePath}"); await importObject.ImportSiteContentAsync(siteContentDirectoryPath, filePath, isImportContents, guid); } if (isImportTableStyles) { _caching.SetProcess(guid, $"导入表字段: {tableDirectoryPath}"); await importObject.ImportTableStylesAsync(tableDirectoryPath, guid); } }
private void importObject_StatusUpdated(object sender, EventArgs e) { ImportObject importObject = sender as ImportObject; FurnitureObject importedObject = importObject.GetImportedObject(); if ((sender as ImportObject).IsEdited) { selectedTreeViewItem.Tag = importedObject; SaveCategories(); InitializeTreeViewCategories(); TreeViewItem parent = selectedTreeViewItem.Parent as TreeViewItem; if (parent != null) { parent.IsExpanded = true; } groupBoxRightSide.Content = null; } else { ExtendedTreeViewItem extendedItem = new ExtendedTreeViewItem(importedObject.DefaultIconPath, importedObject.Name, importedObject.FullPath); TreeViewItem item = new TreeViewItem(); item.Tag = importedObject; item.Header = extendedItem; if (selectedTreeViewItem != null) { selectedTreeViewItem.Items.Add(item); Category <FurnitureObject> currentCategory = selectedTreeViewItem.Tag as Category <FurnitureObject>; currentCategory.StoredObjects.Add(importedObject); SaveCategories(); } if (importObject.ExistingImportedMaterials == true) { configuration.Materials = importObject.GetMaterials(); InitializeTreeViewMaterials(); groupBoxPreviewMaterial.Content = null; } } }
public ReferencedByNode(Delta delta, ImportObject obj) { this.delta = delta; this.obj = obj; }
private Hashtable m_OpenNodes; // hash of nodes currently open on the tree: key="name"(ex:"entry") value="arraylist of ImportObjects" // private bool m_outputHasStarted = false; public ImportObjectManager(string rootName, Converter conv) { m_root = new ImportObject(rootName, null); m_current = m_root; #if TracingOutput System.Diagnostics.Debug.WriteLine(" Mgr::Current = " + m_current.AncestorLongNames()); #endif m_converter = conv; m_OpenNodes = new Hashtable(); ArrayList rootLevel = new ArrayList(); rootLevel.Add(m_root); m_OpenNodes.Add(rootName, rootLevel); }
private void AddNewObject(ImportObject newEntry) // will set current and add to m_opennodes hash { #if TracingOutput System.Diagnostics.Debug.WriteLine("Mgr::AddNewObject: " + newEntry.AncestorLongNames()); #endif // make sure there aren't any children nodes of the new entry at the same level as the newEntry RemoveChildrenForNewImportObject(newEntry.Parent, newEntry.Name, m_converter.m_HierarchyChildren, newEntry); // make sure there aren't any open like nodes at the same level foreach (ImportObject child in newEntry.Parent.Children) { if (child == newEntry) // don't close the one we just added! continue; if (child.Name == newEntry.Name) { if (!child.Closed) CloseImportObject(child); } } m_current = newEntry; #if TracingOutput System.Diagnostics.Debug.WriteLine(" Mgr::Current = " + m_current.AncestorLongNames()); #endif if (m_OpenNodes.ContainsKey(newEntry.Name)) { ArrayList nodes = m_OpenNodes[newEntry.Name] as ArrayList; nodes.Add(newEntry); } else { ArrayList nodes = new ArrayList(); nodes.Add(newEntry); m_OpenNodes.Add(newEntry.Name, nodes); } }
public void RemoveNodeAndChildren(ImportObject node) { // just remove this node from it's parent and it will be gone... if (node.Parent != null) { ImportObject parent = node.Parent; parent.RemoveChild(node); } }
byte[] m_markerData; // marker data for the marker that created this ImportObject public ImportObject(string name, ImportObject parent) : base(name) { m_marker = ""; m_markerData = null; m_markerLine = -1; m_parent = parent; m_children = new List<ImportObject>(); m_childrenCount = 0; m_closed = false; if (parent != null) m_depth = parent.Depth+1; else m_depth = 0; // case where there is no parent : root }
public bool AddNewEntry(ClsHierarchyEntry newHierarchy, out ImportObject addedNode) { // get the ancestors of this hierarchy // get the best ancestor of the currently open ones // if none found, look for the ancestors of the ancestors - repeat until a best ancestor is found // once found, back down the list of ancestors and add them addedNode = null; string name = newHierarchy.Name; TreeNode leaf = new TreeNode(name); ArrayList nodes = new ArrayList(); ArrayList nextLevel = new ArrayList(); nodes.Add(leaf); ImportObject bestParent = null; TreeNode foundNode = null; bool done = false; while (!done) { foreach(TreeNode node in nodes) { ArrayList possibleParents = new ArrayList(); GetAncestorsOf(node.Name, ref possibleParents); bestParent = GetBestOpenParent(possibleParents); if (bestParent != null) { done = true; foundNode = node; break; } foreach (string ancestor in possibleParents) { TreeNode posparent = new TreeNode(ancestor); node.AddAncestor(posparent); nextLevel.Add(posparent); } } nodes = nextLevel; } if (bestParent != null) { // this is a level one node, or requires one to be created so bump the counter if (bestParent.Depth == 0) this.m_converter.m_NumElements++; while (foundNode != null) { ImportObject newEntry = new ImportObject(foundNode.Name, bestParent); addedNode = newEntry; bestParent.AddChild(newEntry); this.AddNewObject(newEntry); // will set current and add to m_opennodes hash // System.Diagnostics.Debug.WriteLine("**** POINT TO LOOK FOR FLUSHING OUT THE ENTRY ***** c"); // set up variables for next level in tree bestParent = newEntry; foundNode = foundNode.Leaf; } return true; } if (bestParent != null) { // the best parent is the starting point to walk to the leaf this.AddNewObject(bestParent); // System.Diagnostics.Debug.WriteLine("**** POINT TO LOOK FOR FLUSHING OUT THE ENTRY ***** b"); } // create the best parent // then walk the 'foundnode.leaf' methods and add until it's null, // then add the pending sfm info return false; #if false // find all the currently open parent objects for this new entry ArrayList possibleParents = new ArrayList(); SearchHierarcyForParentsOf(m_root, newHierarchy.Name, ref possibleParents); ImportObject bestParent = GetBestOpenParent(possibleParents); if (bestParent != null) { // create the new 'entry' AddNewObject(new ImportObject(newHierarchy.Name, bestParent)); return true; } return false; // eded = m_sfmToHierarchy[currentSfm] as ClsHierarchyEntry; // if (mgr.AddNewEntry(needed)) #endif }
// Any class that has children (Entry, Sense, Subentry), when that class is // created/started any open classes at the current level that are also // children of the new class will be closed. // // Deterministic - Describes an algorithm in which the correct next step // depends only on the current state protected void RemoveChildrenForNewImportObject(ImportObject parent, string importClassName, Hashtable childrenTable, ImportObject objNotToRemove) { // Get a list of children names of the new 'importClassName' and then // close any of the children nodes of the 'parent' if they are the same. if (childrenTable.ContainsKey(importClassName)) { ArrayList childNames = childrenTable[importClassName] as ArrayList; // small performance enhancement by getting rid of the foreach and using a for loop int count = parent.ChildrenCount; // .ChildrenList.Count; for (int i = 0; i<count; i++) { ImportObject child = parent.ChildAt(i); if (child == objNotToRemove) continue; if (!child.Closed && childNames.Contains(child.Name)) // found child node that should be closed { CloseImportObject(child); // don't be 'open' for anymore markers } } } // parent.AddChild(importClassName); }
private void SearchChildrenForMatches(ImportObject start, string sfm, ref ArrayList possibleObjects) { // small performance enhancement by getting rid of the foreach and using a for loop int count = start.ChildrenCount; // .ChildrenList.Count; for (int i = 0; i < count; i++) { ImportObject child = start.ChildAt(i); // ChildrenList[i]; if (child.Closed == false && (child.CanAddSFM(sfm, m_converter) || child.CanAddSFMasAutoField(sfm, m_converter))) { possibleObjects.Add(child); // save it as a possible resting place for this sfm and data } SearchChildrenForMatches(child, sfm, ref possibleObjects); } }
private void SearchHierarcyForParentsOf(ImportObject start, string childName, ref ArrayList possibleObjects) { if (m_converter.m_HierarchyChildren.ContainsKey(start.Name)) { ArrayList children = m_converter.m_HierarchyChildren[start.Name] as ArrayList; if (children.Contains(childName)) possibleObjects.Add(start.Name); } foreach (ImportObject child in start.Children) { SearchHierarcyForParentsOf(child, childName, ref possibleObjects); } }
/// ------------------------------------------------------------------ /// Rules for knowing where to add new classes (Entry, Sense, ...) /// This set of rules is for adding a new entry (sfm was begin marker) /// ------------------------------------------------------------------- /// 1 - if the current entry starts with this sfm /// + if it doesn't have one then use it here as this must have been 'guessed' to start. /// else the current entry can't take this sfm, close it and add a new one /// 2 - find all possible parents for this element /// 3 - if one or more of the parents are open in the tree /// + use the parent with the largest depth and add the child there /// else /// + create a parent tree for this entry (root:entry:sense:...) /// + use the current open entries and remove from root as far as possible /// what remains should be added and the child added at the end /// /// Rules for determining where to add a marker when it isn't a begin marker /// ------------------------------------------------------------------ /// 1 - if the current entry can take the marker, add it here /// 2 - starting at the deepest level, look for an entry that can take the marker /// + if an entry is found, add it here /// else /// pretend it starts an entry and process as a begin marker /// /// ------------------------------------------------------------------ public bool CanUseBeginMarkerOnExistingEntry(string entryName, string sfm, byte[] sfmData, int line, bool isUnique) { if (m_OpenNodes.ContainsKey(entryName)) { ImportObject rval = null; ArrayList objs = m_OpenNodes[entryName] as ArrayList; foreach (ImportObject posParent in objs) { if (posParent.Closed) continue; // just to make sure there aren't any closed items in the open list if (rval == null || rval.Depth < posParent.Depth) rval = posParent; } if (rval != null && rval.CanAddBeginSFM(sfm, m_converter)) { rval.AddBeginSFM(sfm,sfmData, line, m_converter); m_current = rval; #if TracingOutput System.Diagnostics.Debug.WriteLine(" Mgr::Current = " + m_current.AncestorLongNames()); #endif return true; } } return false; }
public bool RemoveChild(ImportObject child) { if (m_children.Contains(child)) { m_children.Remove(child); m_childrenCount--; return true; } return false; }
// private void AddChild(string name) // { // m_children.Add(new ImportObject(name, this)); // m_childrenCount++; // } public void AddChild(ImportObject child) { m_children.Add(child); m_childrenCount++; }
private void CloseImportObject(ImportObject obj) { obj.MakeClosed(); // will also close all child obj's RemoveObjFromOpenList(obj); foreach(ImportObject child in obj.Children) { // RemoveObjFromOpenList(child); CloseImportObject(child); } }
private bool RemoveObjFromOpenList(ImportObject obj) { // remove this node from the hash of nodes if (m_OpenNodes.ContainsKey(obj.Name)) { ArrayList objs = m_OpenNodes[obj.Name] as ArrayList; objs.Remove(obj); if (objs.Count == 0) // empty now, remove from hash { m_OpenNodes.Remove(obj.Name); } return true; } return false; }
/// <summary> /// Once we know that we need to create a new entry/import class, we need to know where /// to insert the new entry. We used to be linear (stack based) but are now tree based so /// a more robust routine is now needed. /// This will make the newly added entry the 'current' as well as closing any that need /// to be closed. /// </summary> /// <param name="name"></param> /// <returns></returns> public bool AddNewEntry(string name, string sfm, byte[] sfmData, int line, bool isUnique, out ImportObject addedEntry) { addedEntry = null; // ClsHierarchyEntry entry = m_converter.m_Hierarchy[name] as ClsHierarchyEntry; // find all the currently open parent objects for this new entry ArrayList possibleParents = new ArrayList(); SearchHierarcyForParentsOf(m_root, name, ref possibleParents); ImportObject bestParent = GetBestOpenParent(possibleParents); if (bestParent != null) { ImportObject newEntry = new ImportObject(name, bestParent); addedEntry = newEntry; bestParent.AddChild(newEntry); this.AddNewObject(newEntry); // will set current and add to m_opennodes hash newEntry.AddPendingSfmData(sfm, sfmData, line, isUnique); #if TracingOutput System.Diagnostics.Debug.WriteLine("Adding pending sfm to <" + newEntry.Name + "> : " + sfm); #endif return true; } else // no possible open parent, have to add atleast one entry { } // if (possibleParents.Count == 0) // { // ArrayList neededParents = new ArrayList(); // //neededParents.Add( // // this is a case where one or more parents are needed first // // ex: found the begin marker for a 'picture' but there isn't // // currently a 'sense' open. // } #if false // First lets take the currentPath items and put them into a hash and add the depth // as the value item. Hashtable currentPathDepths = new Hashtable(); int currentPathDepth = 0; // walk the tree building the hashtable, just from current up to root ImportObject node = this.Current; while (node != null) { currentPathDepths.Add(node.Name, currentPathDepth++); node = node.Parent; } // see if the destination is in the currentPath if (currentPathDepths.ContainsKey(name)) { downPath.Push( new ClsPathObject(destination.KEY)); } else { // check each ancestor of the destination item string currentBestAncestor = null; int currentBestDepth = Int32.MaxValue; foreach(string name in destination.Ancestors) { if (currentPathDepths.ContainsKey(name)) { int depth = (int)(currentPathDepths[name]); if (depth < currentBestDepth) { currentBestAncestor = name; currentBestDepth = depth; } } } // see if we've found a common ancestor if (currentBestAncestor != null) { downPath.Push(new ClsPathObject(destination.KEY)); downPath.Push(new ClsPathObject(currentBestAncestor)); } } return downPath; #endif return false; }