void LoadFromMap() { string tmpfolder = CDHelper.Config.DefaultTemplateGroupFileName; tmpfolder = tmpfolder.Remove(tmpfolder.IndexOf(".")); tmpfolder = Path.Combine(HttpContext.Current.Server.MapPath("~/" + CDHelper.Config.SiteSkinsBasePath), tmpfolder + ".map"); if (File.Exists(tmpfolder)) { TemplateMap tm = new TemplateMap(tmpfolder); Channel ch = ChannelHelper.GetChannel(ChannelID, null); ChannelTemplateGroup cg = tm.GetChannelTemplate(ch.FullUrl); if (cg != null) { TemplateIDTextBox.Text = cg.IndexTemplate; DetailTemplateIDTextBox.Text = cg.DetailTemplate; ListTemplateIDTextBox.Text = cg.ListTemplate; SearchTemplateIDTextBox.Text = cg.SearchTemplate; indexCheckbox.Checked = cg.IndexInherit; listCheckbox.Checked = cg.ListInherit; detailCheckbox.Checked = cg.DetailInherit; searchCheckbox.Checked = cg.SearchInherit; } } else { ShowInfomation(); } }
public void Clear() { TemplateFileInfoList.Clear(); TemplateDataMap.Clear(); TemplateMap.Clear(); _Instance = null; }
private static async Task <int> WriteFileAsync(Project project, string file, string inputCamel, TemplateType templateType) { try { string template = await TemplateMap.GetTemplateFilePathAsync(project, file, templateType, inputCamel); if (!string.IsNullOrEmpty(template)) { int index = template.IndexOf('$'); if (index > -1) { template = template.Remove(index, 1); } await WriteToDiskAsync(file, template); return(index); } await WriteToDiskAsync(file, string.Empty); return(0); } catch (Exception e) { return(0); } }
/// <summary> /// Gets the templates. /// </summary> /// <returns>A dictionary containing the Field - Template map</returns> public Dictionary <string, string> GetTemplates() { var templateDictionary = new Dictionary <string, string>(); try { string[] valueTemplateArray = TemplateMap.Split(';'); foreach (string valueTemplate in valueTemplateArray) { if (!string.IsNullOrEmpty(valueTemplate)) { string value = valueTemplate.Substring(0, valueTemplate.IndexOf(':')); string template = valueTemplate.Substring(valueTemplate.IndexOf(':') + 1); templateDictionary.Add(value, template); } } } catch (Exception) { throw new InvalidOperationException(ERR_INVALID_TEMPLATE_MAP); } if (templateDictionary.Count == 0) { throw new ArgumentOutOfRangeException(ERR_EMPTY_TEMPLATE_MAP); } return(templateDictionary); }
string DelChannel() { if (!CheckChannelPermission()) { return("无法删除此栏目,没有权限!"); } if (!We7Helper.IsEmptyID(ChannelID)) { List <Channel> listSon = ChannelHelper.GetChannels(ChannelID); if (listSon != null) { if (listSon.Count > 0) { return("栏目下有子栏目不能删除,请您先删除子栏目后再试。"); } } //删除节点 Channel ch = ChannelHelper.GetChannel(ChannelID, new string[] { "Name", "FullUrl" }); ChannelHelper.DeleteChannel(ChannelID); TemplateMap.DeleteChannelUrls(ch.FullUrl); TemplateMap.ResetInstance(); //记录日志 string content = string.Format("删除栏目:“{0}”", ch.Name); AddLog("栏目管理", content); } return("0"); }
private void ProcessOutboundClass(int dataObjectIndex, string startClassName, string startClassIdentifier, bool isRootClass, List <string> classIdentifiers, bool hasRelatedProperty, ClassMap classMap, List <TemplateMap> templateMaps) { string className = Utility.TitleCase(classMap.name); string baseUri = _graphBaseUri + className + "/"; string classId = classMap.id.Substring(classMap.id.IndexOf(":") + 1); for (int classIdentifierIndex = 0; classIdentifierIndex < classIdentifiers.Count; classIdentifierIndex++) { string classIdentifier = classIdentifiers[classIdentifierIndex]; if (String.IsNullOrEmpty(startClassIdentifier) || className != startClassName || classIdentifier == startClassIdentifier) { XElement individualElement = CreateIndividualElement(baseUri, classId, classIdentifier); if (individualElement != null) { _rdfXml.Add(individualElement); // add primary classification template if (isRootClass && _primaryClassificationStyle == ClassificationStyle.Both) { TemplateMap classificationTemplate = _classificationConfig.TemplateMap; CreateTemplateElement(dataObjectIndex, startClassName, startClassIdentifier, baseUri, classIdentifier, classIdentifierIndex, classificationTemplate, hasRelatedProperty); } ProcessOutboundTemplates(startClassName, startClassIdentifier, dataObjectIndex, individualElement, templateMaps, baseUri, classIdentifier, classIdentifierIndex, hasRelatedProperty); } } } }
private static TemplateMap ReadTemplates(string mapFileLocation) { var parser = new TemplateFileParser(); var map = new TemplateMap(File.Exists(mapFileLocation) ? parser.Parse(mapFileLocation).ToArray() : new MapObjectTemplate[0]); foreach (var format in new[] { MapFormat.RoE, MapFormat.AB, MapFormat.SoD, MapFormat.HotA, MapFormat.WoG }) { var file = Path.ChangeExtension(mapFileLocation, $"{format}.txt"); if (File.Exists(file)) { var values = parser.Parse(file).ToArray(); map.AddFormatMapping(format, values); } else { Log.Debug("ID mapping file {file} doesn't exist. Skipping.", file); } } return(map); }
private void replaceTemplateValues(IXLWorksheet ws, TemplateMap templateMap, Car car, Driver driver, string number) { string numberAndDate = number + " от " + DateTime.Now.ToString("dd.MM.yy."); string rawSecondShortDate = Common.getCellString(ws, templateMap.cellDateShortSecond); string rawFullDate = Common.getCellString(ws, templateMap.cellDateFull); string rawFirstNumber = Common.getCellString(ws, templateMap.cellNumberFirst); string fullDate = DateTime.Now.ToString("dd MMMM yyyy г.", CultureInfo.CreateSpecificCulture("ru-RU")); Common.setCellString(ws, templateMap.cellDateFull, rawFullDate.Replace("{fullDate}", fullDate)); Common.setCellString(ws, templateMap.cellNumberFirst, rawFirstNumber.Replace("{numberAndDate}", numberAndDate)); string rawSecondNumber = Common.getCellString(ws, templateMap.cellNumberFirst); Common.setCellString(ws, templateMap.cellNumberSecond, rawSecondNumber.Replace("{numberAndDate}", numberAndDate)); Common.setCellString(ws, templateMap.cellCar, car.name + ": " + car.number); Common.setCellString(ws, templateMap.cellVin, car.vin); Common.setCellString(ws, templateMap.cellDocs, car.docs); Common.setCellString(ws, templateMap.cellDriver, driver.name); Common.setCellString(ws, templateMap.cellDriverPassport, driver.passport); }
private void WriteToFile(TemplateMap map, string path) { try { using (var stream = new MemoryStream()) { var serizlier = new DataContractJsonSerializer( typeof(TemplateMap), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true, }); serizlier.WriteObject(stream, map); stream.Position = 0; Directory.CreateDirectory(Path.GetDirectoryName(path)); File.WriteAllBytes(path, stream.ToArray()); } } catch (System.Exception e) { _packageService.LogToOutputPane(string.Concat( "Could not save the mapping file to: ", path, "\r\n", e.Message)); } }
public Type GetImplementation <T>() where T : IItemWrapper { var typeOfT = typeof(T); if (!typeOfT.IsInterface) { throw new Exception("Fortis: An interface implementing IITemWrapper must be passed as the generic argument to get the corresponding implementation. " + typeOfT.Name + " is not an interface."); } if (!InterfaceTemplateMap.ContainsKey(typeOfT)) { throw new Exception("Fortis: Type " + typeOfT.Name + " does not exist in interface template map"); } var templateId = InterfaceTemplateMap[typeOfT]; if (!TemplateMap.ContainsKey(templateId)) { throw new Exception("Fortis: Template ID " + templateId + " does not exist in template map"); } foreach (var type in TemplateMap[templateId]) { if (typeOfT.IsAssignableFrom(type)) { return(type); } } return(null); }
public void Build() { var item = _packageService.GetSelectedItem(); if (item == null) { return; } var project = _packageService.GetActiveProject(); if (project == null) { return; } var projectService = new ProjectService(project, _packageService, _templateSerivice); string folder = projectService.GetParentFolder(item); if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { return; } string defaultExt = projectService.GetProjectDefaultExtension(); string input = PromptForFileName( folder, defaultExt ).TrimStart('/', '\\').Replace("/", "\\"); if (string.IsNullOrEmpty(input)) { return; } else if (input.EndsWith("\\")) { input = input + DummyFileName; } TemplateMap templates = _templateSerivice.GetTemplates(); if (projectService.TryGetRelativePath(folder, out string relativePath)) { relativePath = CombinePaths(relativePath, input); // I'm intentionally avoiding the use of Path.Combine because input may contain pattern characters // such as ':' which will cause Path.Combine to handle differently. We simply need a string concat here } else { relativePath = input; } projectService.AddItem(relativePath); }
void InitControls() { string mapString = @" 栏目主页:<a href='{0}?template={8}{1}' target='_blank'>{1}</a> <br /> <span style='display:none' > 栏目列表页:<a href='{5}?template={8}{2}' target='_blank'>{2}</a> <br /> </span> 栏目详细页:<a href='{6}?template={8}{3}' target='_blank'>{3}</a> <br /> 栏目搜索页:<a href='{7}?template={8}{4}' target='_blank'>{4}</a> <br /> "; Channel ch = ChannelHelper.GetChannel(ChannelID, null); if (ch != null) { string url1 = TemplateMap.GetTemplateFromMap("", ch.FullUrl); string url2 = TemplateMap.GetTemplateFromMap("list", ch.FullUrl); string url3 = TemplateMap.GetTemplateFromMap("detail", ch.FullUrl); string url4 = TemplateMap.GetTemplateFromMap("search", ch.FullUrl); string[] fields = new string[] { "ID", "SN", "Updated", "ChannelFullUrl", "State" }; List <Article> al = ArticleHelper.GetArticlesByUrl(ch.FullUrl.Replace('*', '%'), 0, 1, fields, true); string url6 = ""; if (al != null && al.Count > 0) { url6 = ch.FullUrl + al[0].FullUrl; } else { url6 = "#"; } GeneralConfigInfo gi = GeneralConfigs.GetConfig(); string skinPath = gi.DefaultTemplateGroupFileName; if (!string.IsNullOrEmpty(skinPath)) { skinPath = skinPath.Remove(skinPath.ToLower().IndexOf(".xml")); skinPath = string.Format("/{0}/{1}/", gi.SiteSkinsBasePath, skinPath); mapString = string.Format(mapString, ch.FullUrl, url1, url2, url3, url4, ch.ListUrl, url6, ch.SearchUrl, skinPath); MapListLiteral.Text = mapString; } } }
string SaveChannel(string id, string parentId, int index) { if (!CheckChannelPermission()) { return("您没有操作权限。"); } try { //更新子节点的父节点属性 Channel c = new Channel(); c = ChannelHelper.GetChannel(id, null); if (c.ParentID != parentId) { if (CanMove(c, parentId)) { string oldUrl = c.FullUrl; string oldPath = c.FullPath; c.ParentID = parentId; ChannelHelper.UpdateChannel(c); //ChannelHelper.UpdateChannelUrlBatch(oldUrl, newUrl); ChannelHelper.UpdateChannelUrlBatch2(oldUrl, c.FullUrl); ChannelHelper.UpdateChannelPathBatch(c, oldPath); TemplateMap.ReplaceChannelUrls(oldUrl, c.FullUrl); TemplateMap.ResetInstance(); } else { return("无法移动栏目,目标栏目下有标识为 " + c.ChannelName + " 的子栏目!"); } } if (c.Index != index) { ResortChannelList(id, c.ParentID, index); } return("0"); } catch (Exception ex) { return("无法保存数据!" + ex.Message); } }
void SaveToMapFile() { ChannelTemplateGroup cg = new ChannelTemplateGroup(); cg.IndexTemplate = TemplateIDTextBox.Text; cg.DetailTemplate = DetailTemplateIDTextBox.Text; cg.ListTemplate = ListTemplateIDTextBox.Text; cg.SearchTemplate = SearchTemplateIDTextBox.Text; cg.IndexInherit = indexCheckbox.Checked; cg.ListInherit = listCheckbox.Checked; cg.DetailInherit = detailCheckbox.Checked; cg.SearchInherit = searchCheckbox.Checked; string tmpfolder = CDHelper.Config.DefaultTemplateGroupFileName; tmpfolder = tmpfolder.Remove(tmpfolder.IndexOf(".")); tmpfolder = Path.Combine(HttpContext.Current.Server.MapPath("~/" + CDHelper.Config.SiteSkinsBasePath), tmpfolder + ".map"); Channel ch = ChannelHelper.GetChannel(ChannelID, null); TemplateMap.SaveToTemplateMapFile(cg, ch.FullUrl, tmpfolder); TemplateMap.ResetInstance(); }
public TemplateObject GetTemplateObject(TemplateMap templateMap) { TemplateObject theTemplateObject = null; if (templateObjects != null) { foreach (TemplateObject templateObject in templateObjects) { if (templateObject.templateId == templateMap.id) { int roleIdsMatchedCount = 0; foreach (RoleMap roleMap in templateMap.roleMaps) { foreach (RoleObject roleObject in templateObject.roleObjects) { if (roleObject.roleId == roleMap.id) { if (roleMap.type == RoleType.Reference && roleMap.classMap == null && roleMap.value == roleObject.value) { return(templateObject); } roleIdsMatchedCount++; break; } } } if (roleIdsMatchedCount == templateMap.roleMaps.Count) { theTemplateObject = templateObject; } } } } return(theTemplateObject); }
public TemplateMap GetTemplates() { TemplateMap templates = null; if (_templates == null) { lock (_templateLock) if (_templates == null) { string path = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "VisualStudio.FastNewFile", "Patterns.json"); if ((templates = this.LoadFromFile(path)) == null) { templates = new TemplateMap(); templates.LoadDefaultMappings(); this.WriteToFile(templates, path); } _templates = templates; } } return(_templates); }
public bool IsCompatibleTemplate(Guid templateId, Type template) { // template Type must at least implement IItemWrapper if (!template.ImplementsInterface(typeof(IItemWrapper)) || !TemplateMap.ContainsKey(templateId)) { return(false); } if (template.IsInterface) { return(TemplateMap[templateId].Any(type => type.ImplementsInterface(template))); } else { // Get interface of template to check var templateType = TemplateMap.FirstOrDefault(p => p.Value.Contains(template)).Key; var interfaceType = InterfaceTemplateMap.FirstOrDefault(i => i.Value == templateType).Key; // Get interface of item to chack var interfaceToCheck = InterfaceTemplateMap.FirstOrDefault(i => i.Value == templateId).Key; return(interfaceToCheck == interfaceType || interfaceToCheck.ImplementsInterface(interfaceType)); } }
private static TemplateMap GetTemplateMap() { TemplateMap templates = null; if (_templates == null) lock (_templateLock) if (_templates == null) { string path = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "VisualStudio.AddAnyFile", "Patterns.json"); if ((templates = TemplateMap.LoadFromFile(path)) == null) { templates = new TemplateMap(); templates.LoadDefaultMappings(); TemplateMap.WriteToFile(templates, path); } _templates = templates; } return _templates; }
public string ProjectProperty(string[] propertyNameParts, ref Values values) { string dataPropertyName = String.Empty; string className = propertyNameParts[0]; string templateName = propertyNameParts[1]; string roleName = propertyNameParts[2]; string classPath = String.Empty; if (className.Contains("$")) { string[] temp = className.Split('$'); className = temp[0]; classPath = temp[1]; } ClassTemplateMap classTemplateMap = _graphMap.classTemplateMaps.Find( cm => cm.classMap.name.Replace(" ", "").ToLower() == className.Replace(" ", "").ToLower()); if (classTemplateMap == null) { throw new Exception("Classmap [" + className + "] not found."); } List <TemplateMap> templateMaps = classTemplateMap.templateMaps; TemplateMap templateMap = templateMaps.Find(tm => tm.name.ToLower() == templateName.ToLower()); RoleMap roleMap = templateMap.roleMaps.Find(rm => rm.name.ToLower() == roleName.ToLower()); switch (roleMap.type) { case RoleType.DataProperty: dataPropertyName = roleMap.propertyName; _valueListName = null; break; case RoleType.ObjectProperty: dataPropertyName = roleMap.propertyName; _valueListName = roleMap.valueListName; break; case RoleType.Property: //if last part... dataPropertyName = roleMap.propertyName; if (String.IsNullOrEmpty(roleMap.valueListName)) { _valueListName = null; } else { _valueListName = roleMap.valueListName; for (int i = 0; i < values.Count; i++) { string value = values[i]; ValueListMap valueListMap = _mapping.valueListMaps.Find(x => x.name.ToLower() == roleMap.valueListName.ToLower()); if (valueListMap != null && valueListMap.valueMaps != null) { /// ValueMap valueMap = valueListMap.valueMaps.Find(x => x.uri == value); ValueMap valueMap = valueListMap.valueMaps.Find(x => x.label == value); if (valueMap != null) { value = valueMap.internalValue; } else { value = valueListMap.valueMaps[0].internalValue; } } values[i] = value; } } break; case RoleType.FixedValue: case RoleType.Possessor: case RoleType.Reference: throw new Exception("Role " + roleName + " can not be projected to property."); } return(dataPropertyName); }
private void CreateTemplateElement(int dataObjectIndex, string startClassName, string startClassIdentifier, string baseUri, string classIdentifier, int classIdentifierIndex, TemplateMap templateMap, bool classIdentifierHasRelatedProperty) { string classInstance = baseUri + classIdentifier; IDataObject dataObject = _dataObjects[dataObjectIndex]; string templateId = templateMap.id.Replace(TPL_PREFIX, TPL_NS.NamespaceName); List <RoleMap> propertyRoles = new List <RoleMap>(); XElement baseTemplateElement = new XElement(OWL_THING); StringBuilder baseValues = new StringBuilder(templateMap.id); List <RoleMap> classRoles = new List <RoleMap>(); baseTemplateElement.Add(new XElement(RDF_TYPE, new XAttribute(RDF_RESOURCE, templateId))); foreach (RoleMap roleMap in templateMap.roleMaps) { string roleId = roleMap.id.Substring(roleMap.id.IndexOf(":") + 1); XElement roleElement = new XElement(TPL_NS + roleId); switch (roleMap.type) { case RoleType.Possessor: roleElement.Add(new XAttribute(RDF_RESOURCE, classInstance)); baseTemplateElement.Add(roleElement); baseValues.Append(classIdentifier); break; case RoleType.FixedValue: string dataType = roleMap.dataType.Replace(XSD_PREFIX, XSD_NS.NamespaceName); roleElement.Add(new XAttribute(RDF_DATATYPE, dataType)); roleElement.Add(new XText(roleMap.value)); baseTemplateElement.Add(roleElement); baseValues.Append(roleMap.value); break; case RoleType.Reference: if (roleMap.classMap != null) { classRoles.Add(roleMap); } else { string value = GetReferenceRoleValue(roleMap); roleElement.Add(new XAttribute(RDF_RESOURCE, value)); baseTemplateElement.Add(roleElement); baseValues.Append(roleMap.value); } break; case RoleType.Property: case RoleType.DataProperty: case RoleType.ObjectProperty: if (String.IsNullOrEmpty(roleMap.propertyName)) { throw new Exception("No data property mapped to role [" + startClassName + "." + templateMap.name + "." + roleMap.name + "]"); } propertyRoles.Add(roleMap); break; } } if (propertyRoles.Count > 0) // property template { bool isTemplateValid = true; // template is not valid when value list uri is empty List <List <XElement> > multiPropertyElements = new List <List <XElement> >(); // create property elements foreach (RoleMap propertyRole in propertyRoles) { List <XElement> propertyElements = new List <XElement>(); multiPropertyElements.Add(propertyElements); string[] propertyParts = propertyRole.propertyName.Split('.'); string propertyName = propertyParts[propertyParts.Length - 1]; int lastDotPos = propertyRole.propertyName.LastIndexOf('.'); string objectPath = propertyRole.propertyName.Substring(0, lastDotPos); if (propertyParts.Length == 2) // direct property { string propertyValue = Convert.ToString(dataObject.GetPropertyValue(propertyName)); XElement propertyElement = CreatePropertyElement(propertyRole, propertyValue); if (propertyElement == null) { isTemplateValid = false; break; } propertyElements.Add(propertyElement); } else // related property { string key = objectPath + "." + dataObjectIndex; List <IDataObject> relatedObjects = null; if (!_relatedObjectsCache.TryGetValue(key, out relatedObjects)) { relatedObjects = GetRelatedObjects(propertyRole.propertyName, dataObject); _relatedObjectsCache.Add(key, relatedObjects); } if (classIdentifierHasRelatedProperty) // reference class identifier has related property { IDataObject relatedObject = relatedObjects[classIdentifierIndex]; string propertyValue = Convert.ToString(relatedObject.GetPropertyValue(propertyName)); XElement propertyElement = CreatePropertyElement(propertyRole, propertyValue); if (propertyElement == null) { isTemplateValid = false; break; } propertyElements.Add(propertyElement); } else // related property is property map { foreach (IDataObject relatedObject in relatedObjects) { string propertyValue = Convert.ToString(relatedObject.GetPropertyValue(propertyName)); XElement propertyElement = CreatePropertyElement(propertyRole, propertyValue); if (propertyElement == null) { isTemplateValid = false; break; } propertyElements.Add(propertyElement); } if (!isTemplateValid) { break; } } } } if (isTemplateValid) { // add property elements to template element(s) if (multiPropertyElements.Count > 0 && multiPropertyElements[0].Count > 0) { // enforce dotNetRDF to store/retrieve templates in order as expressed in RDF string hashPrefixFormat = Regex.Replace(multiPropertyElements[0].Count.ToString(), "\\d", "0") + "0"; for (int i = 0; i < multiPropertyElements[0].Count; i++) { XElement templateElement = new XElement(baseTemplateElement); _rdfXml.Add(templateElement); StringBuilder templateValue = new StringBuilder(baseValues.ToString()); for (int j = 0; j < multiPropertyElements.Count; j++) { XElement propertyElement = multiPropertyElements[j][i]; templateElement.Add(propertyElement); if (!String.IsNullOrEmpty(propertyElement.Value)) { templateValue.Append(propertyElement.Value); } else { templateValue.Append(propertyElement.Attribute(RDF_RESOURCE).Value); } } string hashCode = Utility.MD5Hash(templateValue.ToString()); hashCode = i.ToString(hashPrefixFormat) + hashCode.Substring(hashPrefixFormat.Length); templateElement.Add(new XAttribute(RDF_ABOUT, hashCode)); } } } } else if (classRoles.Count > 0) // relationship template with known class role { bool isTemplateValid = false; // template is valid when there is at least one class referernce identifier that is not null Dictionary <RoleMap, List <string> > relatedClassRoles = new Dictionary <RoleMap, List <string> >(); foreach (RoleMap classRole in classRoles) { bool refClassHasRelatedProperty; List <string> refClassIdentifiers = GetClassIdentifiers(classRole.classMap, dataObjectIndex, out refClassHasRelatedProperty); if (refClassHasRelatedProperty) { relatedClassRoles[classRole] = refClassIdentifiers; } else { string refClassIdentifier = refClassIdentifiers.First(); if (!String.IsNullOrEmpty(refClassIdentifier)) { isTemplateValid = true; baseValues.Append(refClassIdentifier); string roleId = classRole.id.Substring(classRole.id.IndexOf(":") + 1); XElement roleElement = new XElement(TPL_NS + roleId); roleElement.Add(new XAttribute(RDF_RESOURCE, _graphBaseUri + Utility.TitleCase(classRole.classMap.name) + "/" + refClassIdentifier)); baseTemplateElement.Add(roleElement); } ClassTemplateMap relatedClassTemplateMap = _graphMap.GetClassTemplateMap(classRole.classMap.id, classRole.classMap.index); if (relatedClassTemplateMap != null && relatedClassTemplateMap.classMap != null) { ProcessOutboundClass(dataObjectIndex, startClassName, startClassIdentifier, false, refClassIdentifiers, refClassHasRelatedProperty, relatedClassTemplateMap.classMap, relatedClassTemplateMap.templateMaps); } } } if (relatedClassRoles.Count > 0) { string refClassBaseValues = baseValues.ToString(); // enforce dotNetRDF to store/retrieve templates in order as expressed in RDF string hashPrefixFormat = Regex.Replace(relatedClassRoles.Count.ToString(), "\\d", "0") + "0"; foreach (var pair in relatedClassRoles) { RoleMap classRole = pair.Key; List <string> refClassIdentifiers = pair.Value; string roleId = classRole.id.Substring(classRole.id.IndexOf(":") + 1); string baseRelatedClassUri = _graphBaseUri + Utility.TitleCase(classRole.classMap.name) + "/"; for (int i = 0; i < refClassIdentifiers.Count; i++) { string refClassIdentifier = refClassIdentifiers[i]; if (!String.IsNullOrEmpty(refClassIdentifier)) { XElement refBaseTemplateElement = new XElement(baseTemplateElement); string hashCode = Utility.MD5Hash(refClassBaseValues + refClassIdentifier); hashCode = i.ToString(hashPrefixFormat) + hashCode.Substring(hashPrefixFormat.Length); refBaseTemplateElement.Add(new XAttribute(RDF_ABOUT, hashCode)); XElement roleElement = new XElement(TPL_NS + roleId); roleElement.Add(new XAttribute(RDF_RESOURCE, baseRelatedClassUri + refClassIdentifier)); refBaseTemplateElement.Add(roleElement); _rdfXml.Add(refBaseTemplateElement); } } ClassTemplateMap relatedClassTemplateMap = _graphMap.GetClassTemplateMap(classRole.classMap.id, classRole.classMap.index); if (relatedClassTemplateMap != null && relatedClassTemplateMap.classMap != null) { ProcessOutboundClass(dataObjectIndex, startClassName, startClassIdentifier, false, refClassIdentifiers, true, relatedClassTemplateMap.classMap, relatedClassTemplateMap.templateMaps); } } } else if (isTemplateValid) { string hashCode = Utility.MD5Hash(baseValues.ToString()); baseTemplateElement.Add(new XAttribute(RDF_ABOUT, hashCode)); _rdfXml.Add(baseTemplateElement); } } else // relationship template with no class role (e.g. primary classification template) { string hashCode = Utility.MD5Hash(baseValues.ToString()); baseTemplateElement.Add(new XAttribute(RDF_ABOUT, hashCode)); _rdfXml.Add(baseTemplateElement); } }
public ProjectItemManager(DTE2 dte, TemplateMap templateMap) { _templateMap = templateMap; _dte = dte; }
public override List <IDataObject> ToDataObjects(string graphName, ref XDocument xDocument) { _dataObjects = null; try { if (xDocument != null) { _graphMap = _mapping.FindGraphMap(graphName); if (_graphMap != null && _graphMap.classTemplateMaps.Count > 0) { XmlDocument xmlDocument = new XmlDocument(); using (XmlReader xmlReader = xDocument.CreateReader()) { xmlDocument.Load(xmlReader); } xDocument.Root.RemoveAll(); RdfXmlParser parser = new RdfXmlParser(); Graph graph = new Graph(); parser.Load(graph, xmlDocument); xmlDocument.RemoveAll(); // load graph to memory store to allow querying locally _memoryStore = new TripleStore(); _memoryStore.Add(graph); graph.Dispose(); if (_memoryStore != null) { ClassMap rootClassMap = _graphMap.classTemplateMaps.First().classMap; string rootClassId = rootClassMap.id; List <string> rootClassInstances = GetClassInstances(rootClassId); if (rootClassInstances.Count > 0) { _dataObjects = new List <IDataObject>(); _dataRecords = new Dictionary <string, string> [rootClassInstances.Count]; _relatedRecordsMaps = new Dictionary <string, List <Dictionary <string, string> > > [rootClassInstances.Count]; _relatedObjectPaths = new List <string>(); for (int i = 0; i < rootClassInstances.Count; i++) { List <string> rootClassInstance = new List <string> { rootClassInstances[i] }; _dataRecords[i] = new Dictionary <string, string>(); _relatedRecordsMaps[i] = new Dictionary <string, List <Dictionary <string, string> > >(); ProcessInboundClass(i, rootClassMap, rootClassInstance); if (_primaryClassificationStyle == ClassificationStyle.Both) { TemplateMap classificationTemplate = _classificationConfig.TemplateMap; ProcessInboundTemplates(i, rootClassInstance, new List <TemplateMap> { classificationTemplate }); } try { IDataObject dataObject = CreateDataObject(_graphMap.dataObjectName, i); _dataObjects.Add(dataObject); } catch (Exception e) { StringBuilder builder = new StringBuilder(); Dictionary <string, string> dataRecord = _dataRecords[i]; builder.AppendLine("Error creating data object. " + e); builder.AppendLine("Data Record: "); foreach (var pair in dataRecord) { builder.AppendLine("\t" + pair.Key + ": " + pair.Value); } _logger.Error(builder.ToString()); } } // fill related data objects and append them to top level data objects if (_relatedObjectPaths != null && _relatedObjectPaths.Count > 0) { ProcessRelatedItems(); CreateRelatedObjects(); } } } } } } catch (Exception ex) { _logger.Error("Error in ToDataObjects: " + ex); throw ex; } return(_dataObjects); }
private void CreateTemplateElement(int dataObjectIndex, string startClassName, string startClassIdentifier, int classIdentifierIndex, XElement individualElement, TemplateMap templateMap, bool classIdentifierHasRelatedProperty) { IDataObject dataObject = _dataObjects[dataObjectIndex]; List <RoleMap> classRoles = new List <RoleMap>(); List <RoleMap> propertyRoles = new List <RoleMap>(); XElement baseTemplateElement = new XElement(_appNamespace + templateMap.name); baseTemplateElement.Add(new XAttribute(RDL_URI_ATTR, templateMap.id)); foreach (RoleMap roleMap in templateMap.roleMaps) { XElement roleElement = new XElement(_appNamespace + roleMap.name); switch (roleMap.type) { case RoleType.Possessor: baseTemplateElement.Add(new XAttribute(POSSESSOR_ATTR, roleMap.id)); break; case RoleType.Reference: if (roleMap.classMap != null) { classRoles.Add(roleMap); } else { roleElement.Add(new XAttribute(RDL_URI_ATTR, roleMap.id)); roleElement.Add(new XAttribute(REF_ATTR, roleMap.value)); baseTemplateElement.Add(roleElement); } break; case RoleType.FixedValue: roleElement.Add(new XAttribute(RDL_URI_ATTR, roleMap.id)); roleElement.Add(new XText(roleMap.value)); baseTemplateElement.Add(roleElement); break; case RoleType.Property: case RoleType.DataProperty: case RoleType.ObjectProperty: if (String.IsNullOrEmpty(roleMap.propertyName)) { throw new Exception("No data property mapped to role [" + startClassName + "." + templateMap.name + "." + roleMap.name + "]"); } propertyRoles.Add(roleMap); break; } } if (propertyRoles.Count > 0) // property template { bool isTemplateValid = true; // template is not valid when value list uri is empty List <List <XElement> > multiPropertyElements = new List <List <XElement> >(); // create property elements foreach (RoleMap propertyRole in propertyRoles) { List <XElement> propertyElements = new List <XElement>(); multiPropertyElements.Add(propertyElements); string[] propertyParts = propertyRole.propertyName.Split('.'); string propertyName = propertyParts[propertyParts.Length - 1]; int lastDotPos = propertyRole.propertyName.LastIndexOf('.'); string objectPath = propertyRole.propertyName.Substring(0, lastDotPos); if (propertyParts.Length == 2) // direct property { string propertyValue = Convert.ToString(dataObject.GetPropertyValue(propertyName)); XElement propertyElement = CreatePropertyElement(propertyRole, propertyValue); if (propertyElement == null) { isTemplateValid = false; break; } propertyElements.Add(propertyElement); } else // related property { string key = objectPath + "." + dataObjectIndex; List <IDataObject> relatedObjects = null; if (!_relatedObjectsCache.TryGetValue(key, out relatedObjects)) { relatedObjects = GetRelatedObjects(propertyRole.propertyName, dataObject); _relatedObjectsCache.Add(key, relatedObjects); } if (classIdentifierHasRelatedProperty) // reference class identifier has related property { IDataObject relatedObject = relatedObjects[classIdentifierIndex]; string propertyValue = Convert.ToString(relatedObject.GetPropertyValue(propertyName)); XElement propertyElement = CreatePropertyElement(propertyRole, propertyValue); if (propertyElement == null) { isTemplateValid = false; break; } propertyElements.Add(propertyElement); } else // related property is property map { foreach (IDataObject relatedObject in relatedObjects) { string propertyValue = Convert.ToString(relatedObject.GetPropertyValue(propertyName)); XElement propertyElement = CreatePropertyElement(propertyRole, propertyValue); if (propertyElement == null) { isTemplateValid = false; break; } propertyElements.Add(propertyElement); } if (!isTemplateValid) { break; } } } } if (isTemplateValid) { // add property elements to template element(s) if (multiPropertyElements.Count > 0 && multiPropertyElements[0].Count > 0) { for (int i = 0; i < multiPropertyElements[0].Count; i++) { XElement templateElement = new XElement(baseTemplateElement); individualElement.Add(templateElement); for (int j = 0; j < multiPropertyElements.Count; j++) { XElement propertyElement = multiPropertyElements[j][i]; templateElement.Add(propertyElement); } } } } } else if (classRoles.Count > 0) // reference template with known class role { bool isTemplateValid = false; // at least one class role identifier is not null or empty foreach (RoleMap classRole in classRoles) { XElement roleElement = new XElement(_appNamespace + classRole.name); ClassTemplateMap relatedClassTemplateMap = _graphMap.GetClassTemplateMap(classRole.classMap.id, classRole.classMap.index); bool refClassHasRelatedProperty; List <string> refClassIdentifiers = GetClassIdentifiers(classRole.classMap, dataObjectIndex, out refClassHasRelatedProperty); if (refClassIdentifiers.Count > 0 && !String.IsNullOrEmpty(refClassIdentifiers.First())) { isTemplateValid = true; roleElement.Add(new XAttribute(RDL_URI_ATTR, classRole.id)); baseTemplateElement.Add(roleElement); if (relatedClassTemplateMap != null && relatedClassTemplateMap.classMap != null) { ProcessOutboundClass(dataObjectIndex, startClassName, startClassIdentifier, false, refClassIdentifiers, refClassHasRelatedProperty, roleElement, relatedClassTemplateMap.classMap, relatedClassTemplateMap.templateMaps); } else { roleElement.Add(new XAttribute(REF_ATTR, "#" + refClassIdentifiers.First())); } } } if (isTemplateValid) { individualElement.Add(baseTemplateElement); } } else // reference template with no class role (e.g. primary classification template) { individualElement.Add(baseTemplateElement); } }