/// <summary> /// 获取表中的字段信息(没有做版本判断) /// </summary> /// <param name="pFieldAtrrCollection"></param> /// <returns></returns> private MetaDataField GetMetaTableFieldByXMLAtr(XmlAttributeCollection pFieldAtrrCollection) { if (pFieldAtrrCollection == null || pFieldAtrrCollection.Count <= 0) { return(null); } MetaDataField pMetaDataField = new MetaDataField(); ///获取表名称 XmlAttribute pAttribute = pFieldAtrrCollection["Name"]; if (pAttribute != null) { pMetaDataField.Name = pAttribute.Value; } ///获取要素代码 pAttribute = pFieldAtrrCollection["Code"]; if (pAttribute != null) { pMetaDataField.Code = pAttribute.Value; } ///获取字段类型 pAttribute = pFieldAtrrCollection["Type"]; if (pAttribute != null) { pMetaDataField.Type = pAttribute.Value; } ///获取字段长度 pAttribute = pFieldAtrrCollection["Length"]; if (pAttribute != null) { if (pAttribute.Value != "" && pAttribute.Value != null) { int nLength = -1; if (VCTFile.ConvertToInt32(pAttribute.Value, out nLength)) { pMetaDataField.Length = nLength; } } } ///获取字段精度 pAttribute = pFieldAtrrCollection["Precision"]; if (pAttribute != null) { int nPresion = -1; if (pAttribute.Value != "" && pAttribute.Value != null) { if (VCTFile.ConvertToInt32(pAttribute.Value, out nPresion)) { pMetaDataField.Presion = nPresion; } } } ///获取要素代码字段 pAttribute = pFieldAtrrCollection["FieldType"]; if (pAttribute != null) { EnumFieldType pEnumType = EnumFieldType.Other; switch (pAttribute.Value) { case "bsm": pEnumType = EnumFieldType.EntityID; break; case "ysdm": pEnumType = EnumFieldType.YSDM; break; case "other": pEnumType = EnumFieldType.Other; break; default: break; } pMetaDataField.FiledType = pEnumType; } ///获取约束条件 与值域 对照表 暂时不需要 return(pMetaDataField); }
private static void ImportEntry(XmlNode xmlNode, PwDatabase pwStorage) { PwEntry pe = new PwEntry(true, true); pwStorage.RootGroup.AddEntry(pe, true); XmlAttributeCollection col = xmlNode.Attributes; if (col == null) { return; } XmlNode xmlAttrib; xmlAttrib = col.GetNamedItem(AttrUser); if (xmlAttrib != null) { pe.Strings.Set(PwDefs.UserNameField, new ProtectedString( pwStorage.MemoryProtection.ProtectUserName, xmlAttrib.Value)); } else { Debug.Assert(false); } xmlAttrib = col.GetNamedItem(AttrPassword); if (xmlAttrib != null) { pe.Strings.Set(PwDefs.PasswordField, new ProtectedString( pwStorage.MemoryProtection.ProtectPassword, xmlAttrib.Value)); } else { Debug.Assert(false); } xmlAttrib = col.GetNamedItem(AttrURL); if (xmlAttrib != null) { pe.Strings.Set(PwDefs.UrlField, new ProtectedString( pwStorage.MemoryProtection.ProtectUrl, xmlAttrib.Value)); } else { Debug.Assert(false); } xmlAttrib = col.GetNamedItem(AttrUserFieldName); if (xmlAttrib != null) { pe.Strings.Set(DbUserFieldName, new ProtectedString( false, xmlAttrib.Value)); } else { Debug.Assert(false); } xmlAttrib = col.GetNamedItem(AttrPasswordFieldName); if (xmlAttrib != null) { pe.Strings.Set(DbPasswordFieldName, new ProtectedString( false, xmlAttrib.Value)); } else { Debug.Assert(false); } }
/// <summary> /// Load this Layout from its File /// </summary> /// <param name="scheduleItem"></param> public void loadFromFile(ScheduleItem scheduleItem) { // Store the Schedule and LayoutIds this.ScheduleItem = scheduleItem; this.ScheduleId = scheduleItem.scheduleid; this._layoutId = scheduleItem.id; this.isOverlay = scheduleItem.IsOverlay; this.isInterrupt = scheduleItem.IsInterrupt(); // Get this layouts XML XmlDocument layoutXml = new XmlDocument(); // try to open the layout file try { using (FileStream fs = File.Open(scheduleItem.layoutFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (XmlReader reader = XmlReader.Create(fs)) { layoutXml.Load(reader); reader.Close(); } fs.Close(); } } catch (IOException ioEx) { Trace.WriteLine(new LogMessage("MainForm - PrepareLayout", "IOException: " + ioEx.ToString()), LogType.Error.ToString()); throw; } layoutModifiedTime = File.GetLastWriteTime(scheduleItem.layoutFile); // Attributes of the main layout node XmlNode layoutNode = layoutXml.SelectSingleNode("/layout"); XmlAttributeCollection layoutAttributes = layoutNode.Attributes; // Set the background and size of the form _layoutWidth = int.Parse(layoutAttributes["width"].Value, CultureInfo.InvariantCulture); _layoutHeight = int.Parse(layoutAttributes["height"].Value, CultureInfo.InvariantCulture); // Are stats enabled for this Layout? isStatEnabled = (layoutAttributes["enableStat"] == null) ? true : (int.Parse(layoutAttributes["enableStat"].Value) == 1); // Scaling factor, will be applied to all regions _scaleFactor = Math.Min(Width / _layoutWidth, Height / _layoutHeight); // Want to be able to center this shiv - therefore work out which one of these is going to have left overs int backgroundWidth = (int)(_layoutWidth * _scaleFactor); int backgroundHeight = (int)(_layoutHeight * _scaleFactor); double leftOverX; double leftOverY; try { leftOverX = Math.Abs(Width - backgroundWidth); leftOverY = Math.Abs(Height - backgroundHeight); if (leftOverX != 0) { leftOverX = leftOverX / 2; } if (leftOverY != 0) { leftOverY = leftOverY / 2; } } catch { leftOverX = 0; leftOverY = 0; } // We know know what our Layout controls dimensions should be SetDimensions((int)leftOverX, (int)leftOverY, backgroundWidth, backgroundHeight); // New region and region options objects RegionOptions options = new RegionOptions(); options.PlayerWidth = (int)Width; options.PlayerHeight = (int)Height; options.LayoutModifiedDate = layoutModifiedTime; // Deal with the color // unless we are an overlay, in which case don't put up a background at all if (!isOverlay) { this.BackgroundColor = Brushes.Black; try { if (layoutAttributes["bgcolor"] != null && layoutAttributes["bgcolor"].Value != "") { var bc = new BrushConverter(); this.BackgroundColor = (Brush)bc.ConvertFrom(layoutAttributes["bgcolor"].Value); options.backgroundColor = layoutAttributes["bgcolor"].Value; } } catch { // Default black options.backgroundColor = "#000000"; } // Get the background try { if (layoutAttributes["background"] != null && !string.IsNullOrEmpty(layoutAttributes["background"].Value)) { string bgFilePath = ApplicationSettings.Default.LibraryPath + @"\backgrounds\" + backgroundWidth + "x" + backgroundHeight + "_" + layoutAttributes["background"].Value; // Create a correctly sized background image in the temp folder if (!File.Exists(bgFilePath)) { GenerateBackgroundImage(layoutAttributes["background"].Value, backgroundWidth, backgroundHeight, bgFilePath); } Background = new ImageBrush(new BitmapImage(new Uri(bgFilePath))); options.backgroundImage = @"/backgrounds/" + backgroundWidth + "x" + backgroundHeight + "_" + layoutAttributes["background"].Value; } else { // Assume there is no background image options.backgroundImage = ""; Background = this.BackgroundColor; } } catch (Exception ex) { Trace.WriteLine(new LogMessage("MainForm - PrepareLayout", "Unable to set background: " + ex.Message), LogType.Error.ToString()); // Assume there is no background image Background = this.BackgroundColor; options.backgroundImage = ""; } } // Get the regions XmlNodeList listRegions = layoutXml.SelectNodes("/layout/region"); XmlNodeList listMedia = layoutXml.SelectNodes("/layout/region/media"); // Check to see if there are any regions on this layout. if (listRegions.Count == 0 || listMedia.Count == 0) { Trace.WriteLine(new LogMessage("PrepareLayout", string.Format("A layout with {0} regions and {1} media has been detected.", listRegions.Count.ToString(), listMedia.Count.ToString())), LogType.Info.ToString()); // Add this to our unsafe list. CacheManager.Instance.AddUnsafeItem(UnsafeItemType.Layout, _layoutId, "" + _layoutId, "No Regions or Widgets"); throw new LayoutInvalidException("Layout without any Regions or Widgets"); } // Parse the regions foreach (XmlNode region in listRegions) { // Is there any media if (region.ChildNodes.Count == 0) { Debug.WriteLine("A region with no media detected"); continue; } // Region loop setting options.RegionLoop = false; XmlNode regionOptionsNode = region.SelectSingleNode("options"); if (regionOptionsNode != null) { foreach (XmlNode option in regionOptionsNode.ChildNodes) { if (option.Name == "loop" && option.InnerText == "1") { options.RegionLoop = true; } } } //each region XmlAttributeCollection nodeAttibutes = region.Attributes; options.scheduleId = ScheduleId; options.layoutId = _layoutId; options.regionId = nodeAttibutes["id"].Value.ToString(); options.width = (int)(Convert.ToDouble(nodeAttibutes["width"].Value, CultureInfo.InvariantCulture) * _scaleFactor); options.height = (int)(Convert.ToDouble(nodeAttibutes["height"].Value, CultureInfo.InvariantCulture) * _scaleFactor); options.left = (int)(Convert.ToDouble(nodeAttibutes["left"].Value, CultureInfo.InvariantCulture) * _scaleFactor); options.top = (int)(Convert.ToDouble(nodeAttibutes["top"].Value, CultureInfo.InvariantCulture) * _scaleFactor); options.scaleFactor = _scaleFactor; // Store the original width and original height for scaling options.originalWidth = (int)Convert.ToDouble(nodeAttibutes["width"].Value, CultureInfo.InvariantCulture); options.originalHeight = (int)Convert.ToDouble(nodeAttibutes["height"].Value, CultureInfo.InvariantCulture); // Set the backgrounds (used for Web content offsets) options.backgroundLeft = options.left * -1; options.backgroundTop = options.top * -1; // All the media nodes for this region / layout combination options.mediaNodes = region.SelectNodes("media"); Region temp = new Region(); temp.DurationElapsedEvent += new Region.DurationElapsedDelegate(Region_DurationElapsedEvent); temp.MediaExpiredEvent += Region_MediaExpiredEvent; // ZIndex if (nodeAttibutes["zindex"] != null) { temp.ZIndex = int.Parse(nodeAttibutes["zindex"].Value); } Debug.WriteLine("loadFromFile: Created new region", "Layout"); // Dont be fooled, this innocent little statement kicks everything off temp.loadFromOptions(options); // Add to our list of Regions _regions.Add(temp); Debug.WriteLine("loadFromFile: Adding region", "Layout"); } // Order all Regions by their ZIndex _regions.Sort((l, r) => l.ZIndex < r.ZIndex ? -1 : 1); // Add all Regions to the Scene foreach (Region temp in _regions) { // Add this Region to our Scene LayoutScene.Children.Add(temp); } // Null stuff listRegions = null; listMedia = null; }
void ReadXML() { //xmlDocument = new XmlDocument(); //xmlDocument.Load(filePath); //xPathNavigator = xmlDocument.CreateNavigator(); XmlNode customDataNode = xmlDocument.SelectSingleNode("StcxProject/CustomData"); XmlAttributeCollection customDataAttributes = customDataNode.LastChild.Attributes; operation.DetailName = customDataAttributes[1].Value; XPathNodeIterator xPathTechnologyIterator = CreateSectionIterator("Technology"); XPathNodeIterator xPathOpXmlParamsIterator = CreateSectionIterator("OpXmlParams"); while (xPathOpXmlParamsIterator.MoveNext() && xPathTechnologyIterator.MoveNext()) { Tool currentOperationTool = new Tool(); XPathNavigator currentOpXmlParamsNode = xPathOpXmlParamsIterator.Current; XPathNavigator currentTechnologyNode = xPathTechnologyIterator.Current; if (currentOpXmlParamsNode.Name.Equals("TSTRootGroup")) { currentOpXmlParamsNode.MoveToChild("Name", ""); operation.MachinetoolName = currentOpXmlParamsNode.Value; currentOpXmlParamsNode.MoveToParent(); /*currentOpXmlParamsNode.MoveToChild("RTKParameters", ""); * currentOpXmlParamsNode.MoveToChild("DetailName", ""); * operation.DetailName = currentOpXmlParamsNode.Value; * currentOpXmlParamsNode.MoveToParent(); * currentOpXmlParamsNode.MoveToParent();*/ xPathOpXmlParamsIterator.MoveNext(); // Rewind to same operation position as xPathTechnologyIterator } if (currentTechnologyNode.Name.Equals("TSTTechMillOpGroupFin")) { } else if (currentOpXmlParamsNode.Name.Equals("TSTTechMillOpGroupFin")) { if (IsNodeSetup(currentOpXmlParamsNode)) { if (setup != null) { setup.AddShift(shift); operation.AddSetup(setup); } this.setup = new Setup(); currentOpXmlParamsNode.MoveToChild("Comment", ""); setup.SetupName = currentOpXmlParamsNode.Value; currentOpXmlParamsNode.MoveToParent(); } else { techFolderText = ReadTechDescriptionFromOpXmlSection(currentOpXmlParamsNode) + "Обрабатываемые элементы:" + "\n"; } } else { GetToolInfoFromTechnologySection(currentOperationTool, currentTechnologyNode); GetToolInfoFromOpXmlParamsSection(currentOperationTool, currentOpXmlParamsNode); GetHolderInfoFromOpXmlParamsSection(currentOperationTool, currentOpXmlParamsNode); GetTechnologyInfo(currentOperationTool, currentOpXmlParamsNode, currentTechnologyNode, setup); projectTools.Add(currentOperationTool); } } setup.AddShift(shift); operation.AddSetup(setup); }
private void SetupSearchDefinition(XmlNode node) { if (node != null) { XmlAttributeCollection attrCollection = node.Attributes; if (attrCollection["fieldDefinitionGuid"] != null) { fieldDefinitionGuid = Guid.Parse(attrCollection["fieldDefinitionGuid"].Value); } if (fieldDefinitionGuid == Guid.Empty) { return; } SearchDef searchDef = SearchDef.GetByFieldDefinition(fieldDefinitionGuid); if (searchDef == null) { searchDef = new SearchDef(); searchDef.FieldDefinitionGuid = fieldDefinitionGuid; searchDef.SiteGuid = CacheHelper.GetCurrentSiteSettings().SiteGuid; searchDef.FeatureGuid = FeatureGuid; } bool emptySearchDef = true; foreach (XmlNode childNode in node) { //if (!String.IsNullOrWhiteSpace(childNode.InnerText) || !String.IsNullOrWhiteSpace(childNode.InnerXml)) //{ //need to find a way to clear out the searchdef if needed switch (childNode.Name) { case "Title": searchDef.Title = childNode.InnerText.Trim(); emptySearchDef = false; break; case "Keywords": searchDef.Keywords = childNode.InnerText.Trim(); emptySearchDef = false; break; case "Description": searchDef.Description = childNode.InnerText.Trim(); emptySearchDef = false; break; case "Link": searchDef.Link = childNode.InnerText.Trim(); emptySearchDef = false; break; case "LinkQueryAddendum": searchDef.LinkQueryAddendum = childNode.InnerText.Trim(); emptySearchDef = false; break; } //} } if (!emptySearchDef) { searchDef.Save(); } } }
public DynamicXMLAttributesCollection(XmlAttributeCollection attributes) { Attributes = attributes; }
public FundamentalTypeNode(XmlAttributeCollection collection) : base(collection) { name = GetAttribute("kind"); }
private int getDificulty(XmlAttributeCollection col) { string dif = findAtrib (col, "dif"); if (dif == "") { return 0; } else { return int.Parse (dif); } }
public XmlDocument AssinaXML(string xml, string strUri, X509Certificate2 _X509Cert) { try { string x = _X509Cert.GetKeyAlgorithm().ToString(); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = false; doc.LoadXml(xml); //Verifica se a tag a ser assinada existe e é única int qtdeRefUri = doc.GetElementsByTagName(strUri).Count; if (qtdeRefUri == 0) { //' a URI indicada não existe //Console.WriteLine("A tag de assinatura " + strUri + " não existe no XML. (Código do Erro: 4)"); //Throw New Exception("A tag de assinatura " & strUri.Trim() & " não existe no XML. (Código do Erro: 4)") //intResultado = 4; } else { if (doc.GetElementsByTagName("Signature").Count == 0) { SignedXml signedXml = new SignedXml(doc); signedXml.SigningKey = _X509Cert.PrivateKey; Reference reference = new Reference(); //pega o uri que deve ser assinada XmlAttributeCollection _Uri = doc.GetElementsByTagName(strUri).Item(0).Attributes; foreach (XmlAttribute _atributo in _Uri) { if (_atributo.Name == "Id") { reference.Uri = "#" + _atributo.InnerText; } } XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); XmlDsigC14NTransform c14 = new XmlDsigC14NTransform(); reference.AddTransform(c14); signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(_X509Cert)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); if (strUri == "infNFe" || strUri == "infInut") { doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); } else if (strUri == "infEvento") { doc.GetElementsByTagName("evento").Item(0).AppendChild(doc.ImportNode(xmlDigitalSignature, true)); } /* * string caminho = strUri != "infEvento" ? @"C:\Documents and Settings\Renan\Desktop\gerarxmlASSINADO.xml" : @"C:\Documents and Settings\Renan\Desktop\new20Assinada - CCe.xml"; * using (XmlTextWriter xmlWriter = new XmlTextWriter(caminho, null)) * { * xmlWriter.Formatting = Formatting.None; * doc.Save(xmlWriter); * } */ } } return(doc); } catch (Exception) { throw; } }
public void CreateITextReader(string xmlPath) { Debug.LogError(xmlPath); string class_define = Path.GetFileName(xmlPath); class_define = class_define.Substring(0, class_define.LastIndexOf(".")); class_define = class_define.Substring(0, 1).ToUpper() + class_define.Substring(1); string class_reader_define = class_define + "Reader"; string class_instance_define = class_define.ToLower() + "Instance"; string class_asset_bundle_reader_define = class_define + "AssetBundleReader"; string int_field_define = "\tpublic int {0} = 0;\n"; string float_field_define = "\tpublic float {0} = 0.0f;\n"; string string_field_define = "\tpublic string {0} = \"\";\n"; string field_define = ""; string int_method_define = "\t\t{0}.{1} = TextUtils.XmlReadInt(xmlNode, \"{2}\", 0);\n"; string float_method_define = "\t\t{0}.{1} = TextUtils.XmlReadFloat(xmlNode, \"{2}\", 0.0f);\n"; string string_method_define = "\t\t{0}.{1} = TextUtils.XmlReadString(xmlNode, \"{2}\", \"\");\n"; string method_define = "\t\t{0} {1} = new {0}();\n\n"; string method_return_define = "\t\treturn {0};\n"; string file_name = xmlPath.Substring(xmlPath.IndexOf("Assets/") + "Assets/".Length); string asset_bundle_name = xmlPath.Substring(xmlPath.IndexOf("LocalConfig/") + "LocalConfig/".Length); string class_define_token = "<CLASS_DEFINE>"; string class_reader_define_token = "<CLASS_READER_DEFINE>"; string class_instance_define_token = "<CLASS_INSTANCE_DEFINE>"; string class_asset_bundle_reader_define_token = "<CLASS_ASSET_BUNDLE_READER_DEFINE>"; string field_define_token = "<FIELD_DEFINE>"; string method_define_token = "<METHOD_DEFINE>"; string file_name_token = "<FILE_NAME>"; string asset_bundle_name_token = "<ASSET_BUNDLE_NAME>"; Debug.LogError("class_define " + class_define); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(xmlPath); XmlNodeList nodeList = xmlDocument.ChildNodes[0].ChildNodes; if (nodeList.Count > 0) { method_define = string.Format(method_define, class_define, class_instance_define); XmlNode node = nodeList[0]; XmlAttributeCollection attrs = node.Attributes; for (int j = 0; j < attrs.Count; j++) { XmlAttribute attr = attrs[j]; string key = attr.Name; string field = key.Substring(0, 1).ToLower() + key.Substring(1); string value = attr.Value; int intValue = 0; float floatValue = 0.0f; int valueType = 0; try { if (int.TryParse(value, out intValue)) { valueType = 1; } else if (float.TryParse(value, out floatValue)) { valueType = 2; } else { valueType = 3; } }catch (Exception e) { valueType = 3; Debug.LogError(e.Data + "\n" + e.Message); } switch (valueType) { case 1: field_define += string.Format(int_field_define, field); method_define += string.Format(int_method_define, class_instance_define, field, key); break; case 2: field_define += string.Format(float_field_define, field); method_define += string.Format(float_method_define, class_instance_define, field, key); break; case 3: field_define += string.Format(string_field_define, field); method_define += string.Format(string_method_define, class_instance_define, field, key); break; default: field_define += string.Format(string_field_define, field); method_define += string.Format(string_method_define, class_instance_define, field, key); break; } } method_define += string.Format(method_return_define, class_instance_define); string code = File.ReadAllText(Application.dataPath + "/Editor/WLPlugIns/class.txt"); code = code.Replace(class_define_token, class_define); code = code.Replace(class_reader_define_token, class_reader_define); code = code.Replace(class_instance_define_token, class_instance_define); code = code.Replace(class_asset_bundle_reader_define_token, class_asset_bundle_reader_define); code = code.Replace(field_define_token, field_define); code = code.Replace(method_define_token, method_define); code = code.Replace(file_name_token, file_name); code = code.Replace(asset_bundle_name_token, asset_bundle_name); string outputPath = Application.dataPath + "/Scripts/Auto/"; if (Directory.Exists(outputPath) == false) { Directory.CreateDirectory(outputPath); } File.WriteAllText(outputPath + class_define + ".cs", code); AssetDatabase.Refresh(); } }
public static void LoadRoutes( RoutingConfiguration config, XmlNode documentElement) { if (HttpContext.Current == null) { return; } if (documentElement.Name != "Routes") { return; } foreach (XmlNode node in documentElement.ChildNodes) { if (node.Name == "Route") { RouteDefinition routeDef = new RouteDefinition(); XmlAttributeCollection attributeCollection = node.Attributes; if (attributeCollection["name"] != null) { routeDef.name = attributeCollection["name"].Value; } if (attributeCollection["routeUrl"] != null) { routeDef.routeUrl = attributeCollection["routeUrl"].Value; } if (attributeCollection["virtualPath"] != null) { routeDef.virtualPath = attributeCollection["virtualPath"].Value; } if (attributeCollection["routeHandler"] != null && typeof(IRouteHandler).IsAssignableFrom(Type.GetType(attributeCollection["routeHandler"].Value))) { routeDef.routeHandler = Activator.CreateInstance(Type.GetType(attributeCollection["routeHandler"].Value)) as IRouteHandler; } foreach (XmlNode child in node.ChildNodes) { if (child.Name == "Defaults") { RouteDefault.Load( routeDef, child); } if (child.Name == "Restrictions") { RouteRestriction.Load( routeDef, child); } } config.RouteDefinitions.Add(routeDef); } } }
public static void LoadFeatureSetting( ContentFeature feature, XmlNode featureSettingNode) { if (feature == null) { return; } if (featureSettingNode == null) { return; } if (featureSettingNode.Name == "featureSetting") { ContentFeatureSetting featureSetting = new ContentFeatureSetting(); XmlAttributeCollection attributeCollection = featureSettingNode.Attributes; if (attributeCollection["resourceFile"] != null) { featureSetting.resourceFile = attributeCollection["resourceFile"].Value; } if (attributeCollection["resourceKey"] != null) { featureSetting.resourceKey = attributeCollection["resourceKey"].Value; } if (attributeCollection["grouNameKey"] != null) { featureSetting.groupNameKey = attributeCollection["grouNameKey"].Value; } if (attributeCollection["groupNameKey"] != null) { featureSetting.groupNameKey = attributeCollection["groupNameKey"].Value; } if (attributeCollection["defaultValue"] != null) { featureSetting.defaultValue = attributeCollection["defaultValue"].Value; } if (attributeCollection["controlType"] != null) { featureSetting.controlType = attributeCollection["controlType"].Value; } if (attributeCollection["controlSrc"] != null) { featureSetting.controlSrc = attributeCollection["controlSrc"].Value; } if (attributeCollection["helpKey"] != null) { featureSetting.helpKey = attributeCollection["helpKey"].Value; } if (attributeCollection["sortOrder"] != null) { try { featureSetting.sortOrder = Convert.ToInt32(attributeCollection["sortOrder"].Value); } catch (System.FormatException) { } catch (System.OverflowException) { } } if (attributeCollection["regexValidationExpression"] != null) { featureSetting.regexValidationExpression = attributeCollection["regexValidationExpression"].Value; } StringBuilder attributes = new StringBuilder(); StringBuilder options = new StringBuilder(); foreach (XmlNode subNode in featureSettingNode) { StringBuilder sb = XmlHelper.GetKeyValuePairsAsStringBuilder(subNode.ChildNodes); switch (subNode.Name) { case "Options": featureSetting.options = sb.ToString(); break; case "Attributes": featureSetting.attributes = sb.ToString(); break; //case "PreTokenString": // field.PreTokenString = subNode.InnerText.Trim(); // break; //case "PostTokenString": // field.PostTokenString = subNode.InnerText.Trim(); // break; } } feature.Settings.Add(featureSetting); } }
private void MapDefinedMarkup(XmlNode node, bool isMobile = false) { if (node != null) { //bool desktopOnly = false; XmlAttributeCollection attrCollection = node.Attributes; if (attrCollection["name"] != null) { markupDefinitionName = attrCollection["name"].Value; } if (attrCollection["moduleClass"] != null) { if (isMobile) { mobileInstanceCssClass += " " + attrCollection["moduleClass"].Value; } else { instanceCssClass += " " + attrCollection["moduleClass"].Value; } } useStandardMarkupOnDesktopOnly = XmlUtils.ParseBoolFromAttribute(attrCollection, "desktopOnly", useStandardMarkupOnDesktopOnly); useHeader = XmlUtils.ParseBoolFromAttribute(attrCollection, "useHeader", useHeader); useFooter = XmlUtils.ParseBoolFromAttribute(attrCollection, "useFooter", useFooter); allowImport = XmlUtils.ParseBoolFromAttribute(attrCollection, "allowImport", allowImport); allowExport = XmlUtils.ParseBoolFromAttribute(attrCollection, "allowExport", allowExport); if (attrCollection["itemViewRolesFieldName"] != null) { ItemViewRolesFieldName = attrCollection["itemViewRolesFieldName"].Value; } if (attrCollection["itemEditRolesFieldName"] != null) { ItemEditRolesFieldName = attrCollection["itemEditRolesFieldName"].Value; } //renderModuleLinksWithModuleTitle = XmlUtils.ParseBoolFromAttribute(attrCollection, "renderModuleLinksWithModuleTitle", renderModuleLinksWithModuleTitle); if (attrCollection["editPageClass"] != null) { editPageCssClass += " " + attrCollection["editPageClass"].Value; } if (attrCollection["editPageTitle"] != null) { editPageTitle = attrCollection["editPageTitle"].Value; } if (attrCollection["editPageUpdateButtonText"] != null) { editPageUpdateButtonText = attrCollection["editPageUpdateButtonText"].Value; } if (attrCollection["editPageSaveButtonText"] != null) { editPageSaveButtonText = attrCollection["editPageSaveButtonText"].Value; } if (attrCollection["editPageDeleteButtonText"] != null) { editPageDeleteButtonText = attrCollection["editPageDeleteButtonText"].Value; } if (attrCollection["editPageCancelLinkText"] != null) { editPageCancelLinkText = attrCollection["editPageCancelLinkText"].Value; } if (attrCollection["editPageDeleteWarning"] != null) { editPageDeleteWarning = attrCollection["editPageDeleteWarning"].Value; } if (attrCollection["importPageTitle"] != null) { importPageTitle = attrCollection["importPageTitle"].Value; } if (attrCollection["exportPageTitle"] != null) { exportPageTitle = attrCollection["exportPageTitle"].Value; } if (attrCollection["importPageCancelLinkText"] != null) { importPageCancelLinkText = attrCollection["importPageCancelLinkText"].Value; } log.Debug($"current siteid={siteId}. invariant siteid={siteId.ToInvariantString()}"); if (attrCollection["fieldDefinitionSrc"] != null) { fieldDefinitionSrc = attrCollection["fieldDefinitionSrc"].Value.Replace("$_SitePath_$", "/Data/Sites/" + siteId.ToInvariantString()); } if (attrCollection["fieldDefinitionGuid"] != null) { fieldDefinitionGuid = Guid.Parse(attrCollection["fieldDefinitionGuid"].Value); } if (attrCollection["jsonRenderLocation"] != null) { jsonRenderLocation = attrCollection["jsonRenderLocation"].Value; } if (attrCollection["jsonLabelObjects"] != null) { jsonLabelObjects = Convert.ToBoolean(attrCollection["jsonLabelObjects"].Value); } if (attrCollection["headerLocation"] != null) { headerLocation = attrCollection["headerLocation"].Value; } if (attrCollection["footerLocation"] != null) { footerLocation = attrCollection["footerLocation"].Value; } if (attrCollection["hideOuterWrapperPanel"] != null) { hideOuterWrapperPanel = Convert.ToBoolean(attrCollection["hideOuterWrapperPanel"].Value); } if (attrCollection["hideInnerWrapperPanel"] != null) { hideInnerWrapperPanel = Convert.ToBoolean(attrCollection["hideInnerWrapperPanel"].Value); } if (attrCollection["hideOuterBodyPanel"] != null) { hideOuterBodyPanel = Convert.ToBoolean(attrCollection["hideOuterBodyPanel"].Value); } if (attrCollection["hideInnerBodyPanel"] != null) { hideInnerBodyPanel = Convert.ToBoolean(attrCollection["hideInnerBodyPanel"].Value); } if (attrCollection["showSaveAsNewButton"] != null) { showSaveAsNew = Convert.ToBoolean(attrCollection["showSaveAsNewButton"].Value); } if (attrCollection["maxItems"] != null) { maxItems = Convert.ToInt32(attrCollection["maxItems"].Value); } if (attrCollection["processItems"] != null) { processItems = Convert.ToBoolean(attrCollection["processItems"].Value); } if (attrCollection["viewName"] != null && !string.IsNullOrWhiteSpace(attrCollection["viewName"].Value)) { useRazor = true; ViewName = attrCollection["viewName"].Value; } MarkupDefinition workingMarkupDefinition = new MarkupDefinition(); if (isMobile && !useStandardMarkupOnDesktopOnly) { // do this so mobile settings are added to desktop workingMarkupDefinition = (MarkupDefinition)markupDefinition.Clone(); } foreach (XmlNode childNode in node) { if (!String.IsNullOrWhiteSpace(childNode.InnerText) || !String.IsNullOrWhiteSpace(childNode.InnerXml)) { switch (childNode.Name) { case "ModuleTitleMarkup": workingMarkupDefinition.ModuleTitleMarkup = childNode.InnerText.Trim(); break; case "ModuleTitleFormat": workingMarkupDefinition.ModuleTitleFormat = childNode.InnerText.Trim(); break; case "ModuleLinksFormat": workingMarkupDefinition.ModuleLinksFormat = childNode.InnerText.Trim(); break; case "ModuleInstanceMarkupTop": workingMarkupDefinition.ModuleInstanceMarkupTop = childNode.InnerText.Trim(); break; case "ModuleInstanceMarkupBottom": workingMarkupDefinition.ModuleInstanceMarkupBottom = childNode.InnerText.Trim(); break; case "InstanceFeaturedImageFormat": workingMarkupDefinition.InstanceFeaturedImageFormat = childNode.InnerText.Trim(); break; case "HeaderContentFormat": workingMarkupDefinition.HeaderContentFormat = childNode.InnerText.Trim(); break; case "FooterContentFormat": workingMarkupDefinition.FooterContentFormat = childNode.InnerText.Trim(); break; case "ItemMarkup": workingMarkupDefinition.ItemMarkup = childNode.InnerText.Trim(); break; case "ItemsRepeaterMarkup": workingMarkupDefinition.ItemsRepeaterMarkup = childNode.InnerText.Trim(); XmlAttributeCollection repeaterAttribs = childNode.Attributes; if (repeaterAttribs["itemsPerGroup"] != null) { workingMarkupDefinition.ItemsPerGroup = XmlUtils.ParseInt32FromAttribute(repeaterAttribs, "itemsPerGroup", workingMarkupDefinition.ItemsPerGroup); } break; case "ItemsWrapperFormat": workingMarkupDefinition.ItemsWrapperFormat = childNode.InnerText.Trim(); break; case "ModuleSettingsLinkFormat": workingMarkupDefinition.ModuleSettingsLinkFormat = childNode.InnerText.Trim(); break; case "AddItemLinkFormat": workingMarkupDefinition.AddItemLinkFormat = childNode.InnerText.Trim(); break; case "EditHeaderLinkFormat": workingMarkupDefinition.EditHeaderLinkFormat = childNode.InnerText.Trim(); break; case "EditFooterLinkFormat": workingMarkupDefinition.EditFooterLinkFormat = childNode.InnerText.Trim(); break; case "ItemEditLinkFormat": workingMarkupDefinition.ItemEditLinkFormat = childNode.InnerText.Trim(); break; case "ImportInstructions": importInstructions = childNode.InnerText.Trim(); break; case "ExportInstructions": exportInstructions = childNode.InnerText.Trim(); break; case "ImportLinkFormat": workingMarkupDefinition.ImportLinkFormat = childNode.InnerText.Trim(); break; case "ExportLinkFormat": workingMarkupDefinition.ExportLinkFormat = childNode.InnerText.Trim(); break; case "GlobalViewMarkup": workingMarkupDefinition.GlobalViewMarkup = childNode.InnerText.Trim(); break; case "GlobalViewItemMarkup": workingMarkupDefinition.GlobalViewItemMarkup = childNode.InnerText.Trim(); break; case "CheckBoxListMarkup": case "RadioButtonListMarkup": CheckBoxListMarkup cblm = new CheckBoxListMarkup(); XmlAttributeCollection cblmAttribs = childNode.Attributes; if (cblmAttribs["field"] != null) { cblm.Field = cblmAttribs["field"].Value; } if (cblmAttribs["token"] != null) { cblm.Token = cblmAttribs["token"].Value; } foreach (XmlNode cblmNode in childNode) { switch (cblmNode.Name) { case "Separator": cblm.Separator = cblmNode.InnerText.Trim(); break; case "Content": cblm.Markup = cblmNode.InnerText.Trim(); break; } } checkBoxListMarkups.Add(cblm); break; case "Scripts": if (isMobile) { mobileMarkupScripts = SuperFlexiHelpers.ParseScriptsFromXmlNode(childNode); } else { markupScripts = SuperFlexiHelpers.ParseScriptsFromXmlNode(childNode); } //SetupDefinedScripts(childNode, isMobile); //rawScript = childNode.InnerText; break; case "Styles": markupCSS = SuperFlexiHelpers.ParseCssFromXmlNode(childNode); break; } } } if (isMobile) { mobileMarkupDefinition = workingMarkupDefinition; } else { markupDefinition = workingMarkupDefinition; } } }
private GameObject createCheckpoint(XmlAttributeCollection xml) { GameObject toReturn = new GameObject(); //xml["positionX"]; //xml["positionY"]; //xml["positionZ"]; //xml["scaleX"]; //xml["scaleY"]; //xml["scaleZ"]; //xml["orderInRace"]; //xml["maxPoints"]; //xml["scoreReward"]; //xml["type"]; return toReturn; }
public static void LoadPageItem( ContentPage contentPage, XmlNode pageItemNode) { if (contentPage == null) { return; } if (pageItemNode == null) { return; } if (pageItemNode.Name == "contentFeature") { ContentPageItem pageItem = new ContentPageItem(); XmlAttributeCollection attributeCollection = pageItemNode.Attributes; if (attributeCollection["featureGuid"] != null) { pageItem.featureGuid = new Guid(attributeCollection["featureGuid"].Value); } if (attributeCollection["contentTitle"] != null) { pageItem.contentTitle = attributeCollection["contentTitle"].Value; } if (attributeCollection["contentTemplate"] != null) { pageItem.contentTemplate = attributeCollection["contentTemplate"].Value; } if (attributeCollection["location"] != null) { string location = attributeCollection["location"].Value; switch (location) { case "right": pageItem.location = "rightpane"; break; case "left": pageItem.location = "leftpane"; break; case "center": default: pageItem.location = "contentpane"; break; } } if (attributeCollection["sortOrder"] != null) { int sort = 1; if (int.TryParse(attributeCollection["sortOrder"].Value, out sort)) { pageItem.sortOrder = sort; } } if (attributeCollection["cacheTimeInSeconds"] != null) { int cacheTimeInSeconds = 1; if (int.TryParse(attributeCollection["cacheTimeInSeconds"].Value, out cacheTimeInSeconds)) { pageItem.cacheTimeInSeconds = cacheTimeInSeconds; } } contentPage.PageItems.Add(pageItem); } }
private GameObject createTerrain(XmlAttributeCollection xml) { GameObject toReturn = new GameObject(); //xml["positionX"]; //xml["positionY"]; //xml["positionZ"]; //xml["scaleX"]; //xml["scaleY"]; //xml["scaleZ"]; //xml["influenceX"]; //xml["influenceY"]; //xml["influenceZ"]; return toReturn; }
public ConstIdentBehavior(XmlAttributeCollection collection) : base(collection) { }
private string GetAttributeValue(XmlAttributeCollection attributes, string name) { if (attributes[name] != null) return attributes[name].Value; else return ""; }
// This method gets the attributes that should be propagated internal static CanonicalXmlNodeList GetPropagatedAttributes(XmlElement elem) { if (elem == null) { return(null); } CanonicalXmlNodeList namespaces = new CanonicalXmlNodeList(); XmlNode ancestorNode = elem; if (ancestorNode == null) { return(null); } bool bDefNamespaceToAdd = true; while (ancestorNode != null) { XmlElement ancestorElement = ancestorNode as XmlElement; if (ancestorElement == null) { ancestorNode = ancestorNode.ParentNode; continue; } if (!Utils.IsCommittedNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI)) { // Add the namespace attribute to the collection if needed if (!Utils.IsRedundantNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI)) { string name = ((ancestorElement.Prefix.Length > 0) ? "xmlns:" + ancestorElement.Prefix : "xmlns"); XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = ancestorElement.NamespaceURI; namespaces.Add(nsattrib); } } if (ancestorElement.HasAttributes) { XmlAttributeCollection attribs = ancestorElement.Attributes; foreach (XmlAttribute attrib in attribs) { // Add a default namespace if necessary if (bDefNamespaceToAdd && attrib.LocalName == "xmlns") { XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute("xmlns"); nsattrib.Value = attrib.Value; namespaces.Add(nsattrib); bDefNamespaceToAdd = false; continue; } // retain the declarations of type 'xml:*' as well if (attrib.Prefix == "xmlns" || attrib.Prefix == "xml") { namespaces.Add(attrib); continue; } if (attrib.NamespaceURI.Length > 0) { if (!Utils.IsCommittedNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI)) { // Add the namespace attribute to the collection if needed if (!Utils.IsRedundantNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI)) { string name = ((attrib.Prefix.Length > 0) ? "xmlns:" + attrib.Prefix : "xmlns"); XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name); nsattrib.Value = attrib.NamespaceURI; namespaces.Add(nsattrib); } } } } } ancestorNode = ancestorNode.ParentNode; } return(namespaces); }
private void PopulateConfiugrationObject(Object config, XmlNode node) { if (node == null || config == null) { return; } XmlAttributeCollection attribColl = node.Attributes; foreach (XmlAttribute xmlAttrib in attribColl) { FillConfigWithAttribValue(config, xmlAttrib); } XmlNodeList nodeList = node.ChildNodes; Hashtable sameSections = new Hashtable(); for (int i = 0; i < nodeList.Count; i++) { XmlNode sectionNode = nodeList[i]; Type sectionType = null; if (sectionNode.Name.ToLower() == DYNAMIC_CONFIG_SECTION && sectionNode.HasChildNodes) { ExtractDyanamicConfigSectionObjectType(sectionNode); } } for (int i = 0; i < nodeList.Count; i++) { XmlNode sectionNode = nodeList[i]; Type sectionType = null; if (sectionNode.Name.ToLower() == DYNAMIC_CONFIG_SECTION) { continue; } sectionType = GetConfigSectionObjectType(config, sectionNode.Name); if (sectionType != null) { if (sectionType.IsArray) { string nonArrayType = sectionType.FullName.Replace("[]", ""); ArrayList sameSessionList = null; Hashtable tmp = null; if (!sameSections.Contains(sectionType)) { tmp = new Hashtable(); tmp.Add("section-name", sectionNode.Name); sameSessionList = new ArrayList(); tmp.Add("section-list", sameSessionList); sameSections.Add(sectionType, tmp); } else { tmp = sameSections[sectionType] as Hashtable; sameSessionList = tmp["section-list"] as ArrayList; } ObjectHandle objHandle = Activator.CreateInstance(sectionType.Assembly.FullName, nonArrayType); object singleSessionObject = objHandle.Unwrap(); PopulateConfiugrationObject(singleSessionObject, sectionNode); sameSessionList.Add(singleSessionObject); } else { ObjectHandle objHandle = Activator.CreateInstance(sectionType.Assembly.FullName, sectionType.FullName); object sectionConfig = objHandle.Unwrap(); PopulateConfiugrationObject(sectionConfig, sectionNode); SetConfigSectionObject(config, sectionConfig, sectionNode.Name); } } } if (sameSections.Count > 0) { Hashtable tmp; IDictionaryEnumerator ide = sameSections.GetEnumerator(); while (ide.MoveNext()) { Type arrType = ide.Key as Type; tmp = ide.Value as Hashtable; ArrayList sameSessionList = tmp["section-list"] as ArrayList; string sectionName = tmp["section-name"] as string; object[] sessionArrayObj = Activator.CreateInstance(arrType, new object[] { sameSessionList.Count }) as object[]; if (sessionArrayObj != null) { for (int i = 0; i < sameSessionList.Count; i++) { sessionArrayObj[i] = sameSessionList[i]; } SetConfigSectionObject(config, sessionArrayObj, sectionName); } } } }
private void LoadLevel(XmlNode levelInfo, int levelNr) { // Read the attributes from the level element XmlAttributeCollection xac = levelInfo.Attributes; string levelName = xac["Id"].Value; int levelWidth = int.Parse(xac["Width"].Value); int levelHeight = int.Parse(xac["Height"].Value); int nrOfGoals = 0; // Read the layout of the level XmlNodeList levelLayout = levelInfo.SelectNodes("L"); // Declare the level map ItemType[,] levelMap = new ItemType[levelWidth, levelHeight]; // Read the level line by line for (int i = 0; i < levelHeight; i++) { string line = levelLayout[i].InnerText; bool wallEncountered = false; // Read the line character by character for (int j = 0; j < levelWidth; j++) { // If the end of the line is shorter than the width of the // level, then the rest of the line is filled with spaces. if (j >= line.Length) { levelMap[j, i] = ItemType.Space; } else { switch (line[j].ToString()) { case " ": if (wallEncountered) { levelMap[j, i] = ItemType.Floor; } else { levelMap[j, i] = ItemType.Space; } break; case "#": levelMap[j, i] = ItemType.Wall; wallEncountered = true; break; case "$": levelMap[j, i] = ItemType.Package; break; case ".": levelMap[j, i] = ItemType.Goal; nrOfGoals++; break; case "@": levelMap[j, i] = ItemType.Dragger; break; case "*": levelMap[j, i] = ItemType.PackageOnGoal; nrOfGoals++; break; case "+": levelMap[j, i] = ItemType.DraggerOnGoal; nrOfGoals++; break; case "=": levelMap[j, i] = ItemType.Space; break; } } } } // Add a new level to the collection of levels in the level set. _levels.Add(new Level(levelName, levelMap, levelWidth, levelHeight, nrOfGoals, levelNr, _title)); }
/// <summary> /// Builds the ExceptionManagementSettings and PublisherSettings structures based on the configuration file. /// </summary> /// <param name="parent">Composed from the configuration settings in a corresponding parent configuration section.</param> /// <param name="configContext">Provides access to the virtual path for which the configuration section handler computes configuration values. Normally this parameter is reserved and is null.</param> /// <param name="section">The XML node that contains the configuration information to be handled. section provides direct access to the XML contents of the configuration section.</param> /// <returns>The ExceptionManagementSettings struct built from the configuration settings.</returns> public object Create(object parent, object configContext, XmlNode section) { try { ExceptionManagementSettings settings = new ExceptionManagementSettings(); // Exit if there are no configuration settings. if (section == null) { return(settings); } XmlNode currentAttribute; XmlAttributeCollection nodeAttributes = section.Attributes; // Get the mode attribute. currentAttribute = nodeAttributes.RemoveNamedItem(EXCEPTIONMANAGEMENT_MODE); if (currentAttribute != null && currentAttribute.Value.ToUpper(CultureInfo.InvariantCulture) == "OFF") { settings.Mode = ExceptionManagementMode.Off; } #region Loop through the publisher components and load them into the ExceptionManagementSettings // Loop through the publisher components and load them into the ExceptionManagementSettings. PublisherSettings publisherSettings; foreach (XmlNode node in section.ChildNodes) { if (node.Name == PUBLISHER_NODENAME) { // Initialize a new PublisherSettings. publisherSettings = new PublisherSettings(); // Get a collection of all the attributes. nodeAttributes = node.Attributes; #region Remove the known attributes and load the struct values // Remove the mode attribute from the node and set its value in PublisherSettings. currentAttribute = nodeAttributes.RemoveNamedItem(PUBLISHER_MODE); if (currentAttribute != null && currentAttribute.Value.ToUpper(CultureInfo.InvariantCulture) == "OFF") { publisherSettings.Mode = PublisherMode.Off; } // Remove the assembly attribute from the node and set its value in PublisherSettings. currentAttribute = nodeAttributes.RemoveNamedItem(PUBLISHER_ASSEMBLY); if (currentAttribute != null) { publisherSettings.AssemblyName = currentAttribute.Value; } // Remove the type attribute from the node and set its value in PublisherSettings. currentAttribute = nodeAttributes.RemoveNamedItem(PUBLISHER_TYPE); if (currentAttribute != null) { publisherSettings.TypeName = currentAttribute.Value; } // Remove the exceptionFormat attribute from the node and set its value in PublisherSettings. currentAttribute = nodeAttributes.RemoveNamedItem(PUBLISHER_EXCEPTIONFORMAT); if (currentAttribute != null && currentAttribute.Value.ToUpper(CultureInfo.InvariantCulture) == "XML") { publisherSettings.ExceptionFormat = PublisherFormat.Xml; } // Remove the include attribute from the node and set its value in PublisherSettings. currentAttribute = nodeAttributes.RemoveNamedItem(PUBLISHER_INCLUDETYPES); if (currentAttribute != null) { publisherSettings.IncludeTypes = LoadTypeFilter(currentAttribute.Value.Split(EXCEPTION_TYPE_DELIMITER)); } // Remove the exclude attribute from the node and set its value in PublisherSettings. currentAttribute = nodeAttributes.RemoveNamedItem(PUBLISHER_EXCLUDETYPES); if (currentAttribute != null) { publisherSettings.ExcludeTypes = LoadTypeFilter(currentAttribute.Value.Split(EXCEPTION_TYPE_DELIMITER)); } #endregion #region Loop through any other attributes and load them into OtherAttributes // Loop through any other attributes and load them into OtherAttributes. for (int i = 0; i < nodeAttributes.Count; i++) { publisherSettings.AddOtherAttributes(nodeAttributes.Item(i).Name, nodeAttributes.Item(i).Value); } #endregion // Add the PublisherSettings to the publishers collection. settings.Publishers.Add(publisherSettings); } } // Remove extra allocated space of the ArrayList of Publishers. settings.Publishers.TrimToSize(); #endregion // Return the ExceptionManagementSettings loaded with the values from the config file. return(settings); } catch (Exception exc) { throw new ConfigurationException(resourceManager.GetString("RES_EXCEPTION_LOADING_CONFIGURATION"), exc, section); } }
private static void ProcessTableImage(XmlNodeList nodes, StringBuilder sb) { foreach (XmlNode node in nodes) { switch (node.Name.ToLowerInvariant( )) { case "tbody": ProcessTableImage(node.ChildNodes, sb); break; case "tr": ProcessTableImage(node.ChildNodes, sb); break; case "td": string image = ""; string aref = ""; string p = ""; bool hasLink = false; if (node.FirstChild.Name.ToLowerInvariant( ) == "img") { StringBuilder tempSb = new StringBuilder( ); ProcessTableImage(node.ChildNodes, tempSb); image += tempSb.ToString( ); } if (node.FirstChild.Name.ToLowerInvariant( ) == "a") { hasLink = true; StringBuilder tempSb = new StringBuilder( ); ProcessTableImage(node.ChildNodes, tempSb); aref += tempSb.ToString( ); } if (node.LastChild.Name.ToLowerInvariant( ) == "p") { p += node.LastChild.InnerText; } if (!hasLink) { sb.Append(p + image); } else { sb.Append(p + aref); } break; case "img": sb.Append("|" + ProcessImage(node)); break; case "a": string link = ""; string target = ""; string title = ""; if (node.Attributes.Count != 0) { XmlAttributeCollection attribute = node.Attributes; foreach (XmlAttribute attName in attribute) { if (attName.Name != "id".ToLowerInvariant( )) { if (attName.Value == "_blank") { target += "^"; } if (attName.Name == "href") { link += attName.Value; } if (attName.Name == "title") { title += attName.Value; } } link = ProcessLink(link); } ProcessTableImage(node.ChildNodes, sb); sb.Append("|" + target + link); } break; } } }
private void EnsureItems() { FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { log.Error("File System Provider Could Not Be Loaded."); return; } IFileSystem fileSystem = p.GetFileSystem(); if (fileSystem == null) { log.Error("File System Could Not Be Loaded."); return; } //string virtualPath = fileSystem.VirtualRoot; if (ddDefinitions == null) { ddDefinitions = new DropDownList(); if (this.Controls.Count == 0) { this.Controls.Add(ddDefinitions); } } if (ddDefinitions.Items.Count > 0) { return; } string siteSuperFlexiPath = "~/Data/Sites/" + siteSettings.SiteId.ToInvariantString() + "/SuperFlexi/"; string globalSuperFlexiPath = "~/Data/SuperFlexi/"; Dictionary <string, string> solutions = new Dictionary <string, string>(); List <string> names = new List <string>(); List <SolutionFileLocation> solutionLocations = new List <SolutionFileLocation>() { new SolutionFileLocation { Path = siteSuperFlexiPath + "Solutions/", Extension = ".sfmarkup", RecurseLevel = RecurseLevel.OneLevel, Global = false }, new SolutionFileLocation { Path = siteSuperFlexiPath + "MarkupDefinitions/", Extension = ".config", RecurseLevel = RecurseLevel.TopDirectoryOnly, Global = false }, new SolutionFileLocation { Path = globalSuperFlexiPath + "Solutions/", Extension = ".sfmarkup", RecurseLevel = RecurseLevel.OneLevel, Global = true }, new SolutionFileLocation { Path = globalSuperFlexiPath + "MarkupDefinitions/", Extension = ".config", RecurseLevel = RecurseLevel.TopDirectoryOnly, Global = true } }; foreach (var location in solutionLocations) { //WebFolder folder = new WebFolder(); //DirectoryInfo dir = new DirectoryInfo(HttpContext.Current.Server.MapPath(location.Path)); //if (dir.Exists) if (fileSystem.FolderExists(location.Path)) { List <WebFile> files = new List <WebFile>(); switch (location.RecurseLevel) { case RecurseLevel.OneLevel: var folders = fileSystem.GetFolderList(location.Path); foreach (var folder in folders) { files.AddRange(fileSystem.GetFileList(folder.VirtualPath).Where(f => f.Extension.ToLower() == location.Extension)); } break; case RecurseLevel.TopDirectoryOnly: files.AddRange(fileSystem.GetFileList(location.Path).Where(f => f.Extension.ToLower() == location.Extension)); break; } //foreach (FileInfo file in dir.GetFiles(location.Pattern, location.SearchOption)) foreach (var file in files) { //if (File.Exists(file.FullName)) //{ string nameAppendage = string.Empty; if (location.Global) { nameAppendage = " (global)"; } XmlDocument doc = new XmlDocument(); doc.Load(file.Path); XmlNode node = doc.DocumentElement.SelectSingleNode("/Definitions/MarkupDefinition"); if (node != null) { XmlAttributeCollection attrCollection = node.Attributes; string solutionName = string.Empty; if (attrCollection["name"] != null) { solutionName = attrCollection["name"].Value + nameAppendage;; } else { solutionName = file.Name.ToString().ToLower().Replace(location.Extension, "") + nameAppendage;; } names.Add(solutionName); if (solutions.ContainsKey(solutionName)) { solutionName += string.Format(" [{0}]", names.Where(n => n.Equals(solutionName)).Count()); } //todo: add capability to nest folders in a solution folder? solutions.Add( solutionName, //location.Path + (location.RecurseLevel == RecurseLevel.ImmediateSubDirectory ? file.Directory.Name + "/" : "") + file.Name); file.VirtualPath.Replace("\\", "/").TrimStart('~')); } //} } } } ddDefinitions.DataSource = solutions.OrderBy(i => i.Key); ddDefinitions.DataTextField = "Key"; ddDefinitions.DataValueField = "Value"; ddDefinitions.DataBind(); ddDefinitions.Items.Insert(0, new ListItem(SuperFlexiResources.SolutionDropDownPleaseSelect, string.Empty)); }
private static void ProcessChild(XmlNodeList nodes, StringBuilder sb) { foreach (XmlNode node in nodes) { bool anchor = false; if (node.NodeType == XmlNodeType.Text) { sb.Append(node.Value.TrimStart('\n')); } else if (node.NodeType != XmlNodeType.Whitespace) { switch (node.Name.ToLowerInvariant( )) { case "html": ProcessChild(node.ChildNodes, sb); break; case "b": case "strong": if (node.HasChildNodes) { sb.Append("'''"); ProcessChild(node.ChildNodes, sb); sb.Append("'''"); } break; case "strike": case "s": if (node.HasChildNodes) { sb.Append("--"); ProcessChild(node.ChildNodes, sb); sb.Append("--"); } break; case "em": case "i": if (node.HasChildNodes) { sb.Append("''"); ProcessChild(node.ChildNodes, sb); sb.Append("''"); } break; case "u": if (node.HasChildNodes) { sb.Append("__"); ProcessChild(node.ChildNodes, sb); sb.Append("__"); } break; case "h1": if (node.HasChildNodes) { if (node.FirstChild.NodeType == XmlNodeType.Whitespace) { sb.Append("----\n"); ProcessChild(node.ChildNodes, sb); } else { if (!(sb.Length == 0 || sb.ToString( ).EndsWith("\n"))) { sb.Append("\n"); } sb.Append("=="); ProcessChild(node.ChildNodes, sb); sb.Append("==\n"); } } else { sb.Append("----\n"); } break; case "h2": if (!(sb.Length == 0 || sb.ToString( ).EndsWith("\n"))) { sb.Append("\n"); } sb.Append("==="); ProcessChild(node.ChildNodes, sb); sb.Append("===\n"); break; case "h3": if (!(sb.Length == 0 || sb.ToString( ).EndsWith("\n"))) { sb.Append("\n"); } sb.Append("===="); ProcessChild(node.ChildNodes, sb); sb.Append("====\n"); break; case "h4": if (!(sb.Length == 0 || sb.ToString( ).EndsWith("\n"))) { sb.Append("\n"); } sb.Append("====="); ProcessChild(node.ChildNodes, sb); sb.Append("=====\n"); break; case "pre": if (node.HasChildNodes) { sb.Append("@@" + node.InnerText + "@@"); } break; case "code": if (node.HasChildNodes) { sb.Append("{{"); ProcessChild(node.ChildNodes, sb); sb.Append("}}"); } break; case "hr": case "hr /": sb.Append("\n== ==\n"); ProcessChild(node.ChildNodes, sb); break; case "span": if (node.Attributes["style"] != null && node.Attributes["style"].Value.Replace(" ", "").ToLowerInvariant( ).Contains("font-weight:normal")) { ProcessChild(node.ChildNodes, sb); } else if (node.Attributes["style"] != null && node.Attributes["style"].Value.Replace(" ", "").ToLowerInvariant( ).Contains("white-space:pre")) { sb.Append(": "); } else { sb.Append(node.OuterXml); } break; case "br": if (node.PreviousSibling != null && node.PreviousSibling.Name == "br") { sb.Append("\n"); } else { if (Settings.ProcessSingleLineBreaks) { sb.Append("\n"); } else { sb.Append("\n\n"); } } break; case "table": string tableStyle = ""; if (node.Attributes["class"] != null && node.Attributes["class"].Value.Contains("imageauto")) { sb.Append("[imageauto|"); ProcessTableImage(node.ChildNodes, sb); sb.Append("]"); } else { foreach (XmlAttribute attName in node.Attributes) { tableStyle += attName.Name + "=\"" + attName.Value + "\" "; } sb.Append("{| " + tableStyle + "\n"); ProcessTable(node.ChildNodes, sb); sb.Append("|}\n"); } break; case "ol": if (node.PreviousSibling != null && node.PreviousSibling.Name != "br") { sb.Append("\n"); } if (node.ParentNode != null) { if (node.ParentNode.Name != "td") { ProcessList(node.ChildNodes, "#", sb); } else { sb.Append(node.OuterXml); } } else { ProcessList(node.ChildNodes, "#", sb); } break; case "ul": if (node.PreviousSibling != null && node.PreviousSibling.Name != "br") { sb.Append("\n"); } if (node.ParentNode != null) { if (node.ParentNode.Name != "td") { ProcessList(node.ChildNodes, "*", sb); } else { sb.Append(node.OuterXml); } } else { ProcessList(node.ChildNodes, "*", sb); } break; case "sup": sb.Append("<sup>"); ProcessChild(node.ChildNodes, sb); sb.Append("</sup>"); break; case "sub": sb.Append("<sub>"); ProcessChild(node.ChildNodes, sb); sb.Append("</sub>"); break; case "p": if (node.Attributes["class"] != null && node.Attributes["class"].Value.Contains("imagedescription")) { continue; } ProcessChild(node.ChildNodes, sb); sb.Append("\n"); if (!Settings.ProcessSingleLineBreaks) { sb.Append("\n"); } break; case "div": if (node.Attributes["class"] != null && node.Attributes["class"].Value.Contains("box")) { if (node.HasChildNodes) { sb.Append("((("); ProcessChild(node.ChildNodes, sb); sb.Append(")))"); } } else if (node.Attributes["class"] != null && node.Attributes["class"].Value.Contains("imageleft")) { sb.Append("[imageleft"); ProcessChildImage(node.ChildNodes, sb); sb.Append("]"); } else if (node.Attributes["class"] != null && node.Attributes["class"].Value.Contains("imageright")) { sb.Append("[imageright"); ProcessChildImage(node.ChildNodes, sb); sb.Append("]"); } else if (node.Attributes["class"] != null && node.Attributes["class"].Value.Contains("image")) { sb.Append("[image"); ProcessChildImage(node.ChildNodes, sb); sb.Append("]"); } else if (node.Attributes["class"] != null && node.Attributes["class"].Value.Contains("indent")) { sb.Append(": "); ProcessChild(node.ChildNodes, sb); sb.Append("\n"); } else if (node.Attributes.Count > 0) { sb.Append(node.OuterXml); } else { sb.Append("\n"); if (node.PreviousSibling != null && node.PreviousSibling.Name != "div") { if (!Settings.ProcessSingleLineBreaks) { sb.Append("\n"); } } if (node.FirstChild != null && node.FirstChild.Name == "br") { node.RemoveChild(node.FirstChild); } if (node.HasChildNodes) { ProcessChild(node.ChildNodes, sb); if (Settings.ProcessSingleLineBreaks) { sb.Append("\n"); } else { sb.Append("\n\n"); } } } break; case "img": string description = ""; bool hasClass = false; bool isLink = false; if (node.ParentNode != null && node.ParentNode.Name.ToLowerInvariant( ) == "a") { isLink = true; } if (node.Attributes.Count != 0) { foreach (XmlAttribute attName in node.Attributes) { if (attName.Name == "alt") { description = attName.Value; } if (attName.Name == "class") { hasClass = true; } } } if (!hasClass && !isLink) { sb.Append("[image|" + description + "|" + ProcessImage(node) + "]\n"); } else if (!hasClass && isLink) { sb.Append("[image|" + description + "|" + ProcessImage(node)); } else { sb.Append(description + "|" + ProcessImage(node)); } break; case "a": bool isTable = false; string link = ""; string target = ""; string title = ""; string formattedLink = ""; bool isSystemLink = false; bool childImg = false; bool pageLink = false; if (node.FirstChild != null && node.FirstChild.Name == "img") { childImg = true; } if (node.ParentNode.Name == "td") { isTable = true; } if (node.Attributes.Count != 0) { XmlAttributeCollection attribute = node.Attributes; foreach (XmlAttribute attName in attribute) { if (attName.Name != "id".ToLowerInvariant( )) { if (attName.Value.ToLowerInvariant( ) == "_blank") { target += "^"; } if (attName.Name.ToLowerInvariant( ) == "href") { link += attName.Value.Replace("%20", " "); } if (attName.Name.ToLowerInvariant( ) == "title") { title += attName.Value; } if (attName.Name.ToLowerInvariant( ) == "class" && attName.Value.ToLowerInvariant( ) == "systemlink") { isSystemLink = true; } if (attName.Name.ToLowerInvariant( ) == "class" && (attName.Value.ToLowerInvariant( ) == "unknownlink" || attName.Value.ToLowerInvariant( ) == "pagelink")) { pageLink = true; } } else { anchor = true; sb.Append("[anchor|#" + attName.Value + "]"); ProcessChild(node.ChildNodes, sb); break; } } if (isSystemLink) { string[] splittedLink = link.Split('='); if (splittedLink.Length == 2) { formattedLink = "c:" + splittedLink[1]; } else { formattedLink = link.LastIndexOf('/') > 0 ? link.Substring(link.LastIndexOf('/') + 1) : link; } } else if (pageLink) { formattedLink = link.LastIndexOf('/') > 0 ? link.Substring(link.LastIndexOf('/') + 1) : link; formattedLink = formattedLink.Remove(formattedLink.IndexOf(Settings.PageExtension)); formattedLink = Uri.UnescapeDataString(formattedLink); } else { formattedLink = ProcessLink(link); } if (!anchor && !isTable && !childImg) { if (HttpUtility.HtmlDecode(title) != HttpUtility.HtmlDecode(link)) { sb.Append("[" + target + formattedLink + "|"); ProcessChild(node.ChildNodes, sb); sb.Append("]"); } else { sb.Append("[" + target + formattedLink + "]"); } } if (!anchor && !childImg && isTable) { sb.Append("[" + target + formattedLink + "|"); ProcessChild(node.ChildNodes, sb); sb.Append("]"); } if (!anchor && childImg && !isTable) { ProcessChild(node.ChildNodes, sb); sb.Append("|" + target + formattedLink + "]"); } } break; default: sb.Append(node.OuterXml); break; } } } }
public bool StructMetaTableByXML(XmlNode pTable, EnumDBStandard pDBStandard, List <string> pList) { string sDBStandard = ""; switch (pDBStandard) { case EnumDBStandard.XJBZ: sDBStandard = "XJBZ"; break; case EnumDBStandard.SJBZ: sDBStandard = "SJBZ"; break; case EnumDBStandard.XZJBZ: sDBStandard = "XZJBZ"; break; case EnumDBStandard.ALL: default: break; } XmlAttributeCollection pAttributeCollection = pTable.Attributes; m_pMetaDataFilds = new List <MetaDataField>(); ///如果没有属性集合则返回 if (pAttributeCollection == null || pAttributeCollection.Count <= 0) { return(false); } ///获取表名称 XmlAttribute pTableAttribute = pAttributeCollection["Name"]; if (pTableAttribute != null) { this.m_strTableName = pTableAttribute.Value; } ///获取要素代码 pTableAttribute = pAttributeCollection["Code"]; if (pTableAttribute != null) { this.m_strFeatureCode = pTableAttribute.Value; } ///获取要素类型 pTableAttribute = pAttributeCollection["GeometryType"]; if (pTableAttribute != null) { this.m_strType = pTableAttribute.Value; } ///获取属性表名称 pTableAttribute = pAttributeCollection["AtrTBName"]; if (pTableAttribute != null) { this.m_strAtrTableName = pTableAttribute.Value; } ///获取约束条件 与分类 暂时不需要 ///2011-9-11添加过滤条件 if (pList != null && !pList.Contains(m_strAtrTableName)) { return(false); } ///获取图形表现编码 pTableAttribute = pAttributeCollection["GraphPerformance"]; if (pTableAttribute != null) { this.m_strGraPerformance = pTableAttribute.Value; } for (int i = 0; i < pTable.ChildNodes.Count; i++) { XmlNode pTableSubNode = pTable.ChildNodes[i]; //处理字段信息 if (pTableSubNode.Name == "FIELDS") { ///读表格属性信息构造配置表对象 foreach (XmlNode pFiled in pTableSubNode.ChildNodes) { XmlAttribute pVersion = pFiled.Attributes["Versions"]; if (pVersion != null && !pVersion.Value.ToString().Contains(sDBStandard)) { ////如果该表不属于当前级别的数据库标准 continue; } else { ///获取字段信息 MetaDataField pMetaDataField = GetMetaTableFieldByXMLAtr(pFiled.Attributes); if (pMetaDataField != null) { this.m_pMetaDataFilds.Add(pMetaDataField); if (pMetaDataField.FiledType == EnumFieldType.EntityID) { m_strEntityIDFiledName = pMetaDataField.Code; } else if (pMetaDataField.FiledType == EnumFieldType.YSDM) { m_strYSDMFiledName = pMetaDataField.Code; } } } } } //处理关联要素信息 else if (pTableSubNode.Name == "TABLELINKS") { foreach (XmlNode pTableLinkItem in pTableSubNode.ChildNodes) { XmlAttribute pTableLinkNameAttr = pTableLinkItem.Attributes["TableName"]; XmlAttribute pTableLinkCodeAttr = pTableLinkItem.Attributes["Code"]; if (pTableLinkNameAttr != null && pTableLinkCodeAttr != null) { m_LinkFeatureCode.Add(pTableLinkCodeAttr.Value); } } } } return(true); }
public static MeasureData fromXML(string XML, List <Mask> masks, List <Sensor> sensors) { XmlDocument xdoc = new XmlDocument(); try { xdoc.LoadXml(XML); string name = xdoc.GetElementsByTagName("name")[0].InnerText; string desc = xdoc.GetElementsByTagName("description")[0].InnerText; int gid = Convert.ToInt32(xdoc.GetElementsByTagName("group")[0].InnerText); int mask = Convert.ToInt32(xdoc.GetElementsByTagName("mask")[0].InnerText); DateTime start = DateTime.Parse(xdoc.GetElementsByTagName("start")[0].InnerText); double length = double.Parse(xdoc.GetElementsByTagName("length")[0].InnerText); bool isMeasured = bool.Parse(xdoc.GetElementsByTagName("ismeasured")[0].InnerText); Dictionary <Sensor, Dictionary <double, double> > dispdata = null; if (!isMeasured) { dispdata = new Dictionary <Sensor, Dictionary <double, double> >(); } XmlNodeList list = xdoc.GetElementsByTagName("sensor"); Dictionary <Sensor, List <PointD> > data = new Dictionary <Sensor, List <PointD> >(); Mask m = null; foreach (Mask mm in masks) { if (mm.ID == mask) { m = mm; } } foreach (XmlNode node in list) { string sid = node.Attributes["sid"].Value; Sensor s = null; foreach (Sensor se in sensors) { if (se.SID == sid) { s = se; } } if (s != null) { data.Add(s, new List <PointD>()); if (!isMeasured) { dispdata.Add(s, new Dictionary <double, double>()); } foreach (XmlNode dnode in node.ChildNodes) { PointD point = new PointD(); XmlAttributeCollection collect = dnode.Attributes; point.X = double.Parse(collect["time"].Value); point.Y = double.Parse(collect["value"].Value); if (point.X >= 0d) { if (!isMeasured) { try { dispdata[s].Add(point.X, Double.Parse(collect["disp"].Value)); } catch {} } } data[s].Add(point); } } } MeasureData dat = new MeasureData(data, -1, name, start, desc, gid, length, 1, isMeasured, m, 0, 0); dat.DispData = dispdata; return(dat); } catch (Exception ex) { message = ex.Message; return(null); } }
private void LoadInstanceElement(NFIClass xLogicClass) { string strLogicPath = mstrRootPath; strLogicPath += xLogicClass.GetInstance(); strLogicPath = strLogicPath.Replace(".xml", ""); TextAsset textAsset = (TextAsset)Resources.Load(strLogicPath); XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(textAsset.text); XmlNode xRoot = xmldoc.SelectSingleNode("XML"); XmlNodeList xNodeList = xRoot.SelectNodes("Object"); for (int i = 0; i < xNodeList.Count; ++i) { //NFCLog.Instance.Log("Class:" + xLogicClass.GetName()); XmlNode xNodeClass = xNodeList.Item(i); XmlAttribute strID = xNodeClass.Attributes["Id"]; //NFCLog.Instance.Log("ClassID:" + strID.Value); NFIElement xElement = GetElement(strID.Value); if (null == xElement) { xElement = new NFElement(); AddElement(strID.Value, xElement); xLogicClass.AddConfigName(strID.Value); XmlAttributeCollection xCollection = xNodeClass.Attributes; for (int j = 0; j < xCollection.Count; ++j) { XmlAttribute xAttribute = xCollection[j]; NFIProperty xProperty = xLogicClass.GetPropertyManager().GetProperty(xAttribute.Name); if (null != xProperty) { NFDataList.VARIANT_TYPE eType = xProperty.GetType(); switch (eType) { case NFDataList.VARIANT_TYPE.VTYPE_INT: { try { NFDataList.TData xValue = new NFDataList.TData(NFDataList.VARIANT_TYPE.VTYPE_INT); xValue.Set(int.Parse(xAttribute.Value)); NFIProperty property = xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue); property.SetUpload(xProperty.GetUpload()); } catch { Debug.LogError("ID:" + strID.Value + " Property Name:" + xAttribute.Name + " Value:" + xAttribute.Value); } } break; case NFDataList.VARIANT_TYPE.VTYPE_FLOAT: { try { NFDataList.TData xValue = new NFDataList.TData(NFDataList.VARIANT_TYPE.VTYPE_FLOAT); xValue.Set(float.Parse(xAttribute.Value, CultureInfo.InvariantCulture.NumberFormat)); NFIProperty property = xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue); property.SetUpload(xProperty.GetUpload()); } catch { Debug.LogError("ID:" + strID.Value + " Property Name:" + xAttribute.Name + " Value:" + xAttribute.Value); } } break; case NFDataList.VARIANT_TYPE.VTYPE_STRING: { NFDataList.TData xValue = new NFDataList.TData(NFDataList.VARIANT_TYPE.VTYPE_STRING); xValue.Set(xAttribute.Value); NFIProperty property = xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue); property.SetUpload(xProperty.GetUpload()); } break; case NFDataList.VARIANT_TYPE.VTYPE_OBJECT: { try { NFDataList.TData xValue = new NFDataList.TData(NFDataList.VARIANT_TYPE.VTYPE_OBJECT); xValue.Set(new NFGUID(0, int.Parse(xAttribute.Value))); NFIProperty property = xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue); property.SetUpload(xProperty.GetUpload()); } catch { Debug.LogError("ID:" + strID.Value + " Property Name:" + xAttribute.Name + " Value:" + xAttribute.Value); } } break; case NFDataList.VARIANT_TYPE.VTYPE_VECTOR2: { try { NFDataList.TData xValue = new NFDataList.TData(NFDataList.VARIANT_TYPE.VTYPE_VECTOR2); //xValue.Set(new NFGUID(0, int.Parse(xAttribute.Value))); NFIProperty property = xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue); property.SetUpload(xProperty.GetUpload()); } catch { Debug.LogError("ID:" + strID.Value + " Property Name:" + xAttribute.Name + " Value:" + xAttribute.Value); } } break; case NFDataList.VARIANT_TYPE.VTYPE_VECTOR3: { try { NFDataList.TData xValue = new NFDataList.TData(NFDataList.VARIANT_TYPE.VTYPE_VECTOR3); //xValue.Set(new NFGUID(0, int.Parse(xAttribute.Value))); NFIProperty property = xElement.GetPropertyManager().AddProperty(xAttribute.Name, xValue); property.SetUpload(xProperty.GetUpload()); } catch { Debug.LogError("ID:" + strID.Value + " Property Name:" + xAttribute.Name + " Value:" + xAttribute.Value); } } break; default: break; } } } } } }
/// <summary> /// Pareses a strategy from a xml document. /// </summary> public Strategy ParseXmlStrategy(XmlDocument xmlDocStrategy) { // Read the number of slots int openFilters = int.Parse(xmlDocStrategy.GetElementsByTagName("openFilters")[0].InnerText); int closeFilters = int.Parse(xmlDocStrategy.GetElementsByTagName("closeFilters")[0].InnerText); // Create the strategy. Strategy tempStrategy = new Strategy(openFilters, closeFilters); // Same and Opposite direction Actions tempStrategy.SameSignalAction = (SameDirSignalAction )Enum.Parse(typeof(SameDirSignalAction), xmlDocStrategy.GetElementsByTagName("sameDirSignalAction")[0].InnerText); tempStrategy.OppSignalAction = (OppositeDirSignalAction)Enum.Parse(typeof(OppositeDirSignalAction), xmlDocStrategy.GetElementsByTagName("oppDirSignalAction")[0].InnerText); // Market tempStrategy.Symbol = xmlDocStrategy.GetElementsByTagName("instrumentSymbol")[0].InnerText; tempStrategy.DataPeriod = (DataPeriods)Enum.Parse(typeof(DataPeriods), xmlDocStrategy.GetElementsByTagName("instrumentPeriod")[0].InnerText); // Permanent Stop Loss tempStrategy.PermanentSL = Math.Abs(int.Parse(xmlDocStrategy.GetElementsByTagName("permanentStopLoss")[0].InnerText)); // Math.Abs() removes the negative sign from previous versions. tempStrategy.UsePermanentSL = bool.Parse(xmlDocStrategy.GetElementsByTagName("permanentStopLoss")[0].Attributes["usePermanentSL"].InnerText); try { tempStrategy.PermanentSLType = (PermanentProtectionType)Enum.Parse(typeof(PermanentProtectionType), xmlDocStrategy.GetElementsByTagName("permanentStopLoss")[0].Attributes["permanentSLType"].InnerText); } catch { tempStrategy.PermanentSLType = PermanentProtectionType.Relative; } // Permanent Take Profit tempStrategy.PermanentTP = int.Parse(xmlDocStrategy.GetElementsByTagName("permanentTakeProfit")[0].InnerText); tempStrategy.UsePermanentTP = bool.Parse(xmlDocStrategy.GetElementsByTagName("permanentTakeProfit")[0].Attributes["usePermanentTP"].InnerText); try { tempStrategy.PermanentTPType = (PermanentProtectionType)Enum.Parse(typeof(PermanentProtectionType), xmlDocStrategy.GetElementsByTagName("permanentTakeProfit")[0].Attributes["permanentTPType"].InnerText); } catch { tempStrategy.PermanentTPType = PermanentProtectionType.Relative; } // Break Even try { tempStrategy.BreakEven = int.Parse(xmlDocStrategy.GetElementsByTagName("breakEven")[0].InnerText); tempStrategy.UseBreakEven = bool.Parse(xmlDocStrategy.GetElementsByTagName("breakEven")[0].Attributes["useBreakEven"].InnerText); } catch { } // Money Management try { tempStrategy.UseAccountPercentEntry = bool.Parse(xmlDocStrategy.GetElementsByTagName("useAccountPercentEntry")[0].InnerText); } catch { tempStrategy.UseAccountPercentEntry = bool.Parse(xmlDocStrategy.GetElementsByTagName("useAcountPercentEntry")[0].InnerText); } tempStrategy.MaxOpenLots = StringToDouble(xmlDocStrategy.GetElementsByTagName("maxOpenLots")[0].InnerText); tempStrategy.EntryLots = StringToDouble(xmlDocStrategy.GetElementsByTagName("entryLots")[0].InnerText); tempStrategy.AddingLots = StringToDouble(xmlDocStrategy.GetElementsByTagName("addingLots")[0].InnerText); tempStrategy.ReducingLots = StringToDouble(xmlDocStrategy.GetElementsByTagName("reducingLots")[0].InnerText); // Description tempStrategy.Description = xmlDocStrategy.GetElementsByTagName("description")[0].InnerText; // Strategy name. tempStrategy.StrategyName = xmlDocStrategy.GetElementsByTagName("strategyName")[0].InnerText; // Reading the slots XmlNodeList xmlSlotList = xmlDocStrategy.GetElementsByTagName("slot"); for (int slot = 0; slot < xmlSlotList.Count; slot++) { XmlNodeList xmlSlotTagList = xmlSlotList[slot].ChildNodes; SlotTypes slotType = (SlotTypes)Enum.Parse(typeof(SlotTypes), xmlSlotList[slot].Attributes["slotType"].InnerText); // Logical group if (slotType == SlotTypes.OpenFilter || slotType == SlotTypes.CloseFilter) { XmlAttributeCollection attributes = xmlSlotList[slot].Attributes; XmlNode nodeGroup = attributes.GetNamedItem("logicalGroup"); string defGroup = GetDefaultGroup(slotType, slot, tempStrategy.CloseSlot); if (nodeGroup != null) { string group = nodeGroup.InnerText; tempStrategy.Slot[slot].LogicalGroup = group; if (group != defGroup && group.ToLower() != "all" && !Configs.UseLogicalGroups) { System.Windows.Forms.MessageBox.Show( Language.T("The strategy requires logical groups.") + Environment.NewLine + Language.T("\"Use Logical Groups\" option was temporarily switched on."), Language.T("Logical Groups"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); Configs.UseLogicalGroups = true; } } else { tempStrategy.Slot[slot].LogicalGroup = defGroup; } } // Indicator name. string indicatorName = xmlSlotTagList[0].InnerText; Indicator indicator = Indicator_Store.ConstructIndicator(indicatorName, slotType); for (int tag = 1; tag < xmlSlotTagList.Count; tag++) { // List parameters if (xmlSlotTagList[tag].Name == "listParam") { int listParam = int.Parse(xmlSlotTagList[tag].Attributes["paramNumber"].InnerText); XmlNode xmlListParamNode = xmlSlotTagList[tag].FirstChild; indicator.IndParam.ListParam[listParam].Caption = xmlListParamNode.InnerText; xmlListParamNode = xmlListParamNode.NextSibling; int index = int.Parse(xmlListParamNode.InnerText); indicator.IndParam.ListParam[listParam].Index = index; indicator.IndParam.ListParam[listParam].Text = indicator.IndParam.ListParam[listParam].ItemList[index]; } // Numeric parameters if (xmlSlotTagList[tag].Name == "numParam") { XmlNode xmlNumParamNode = xmlSlotTagList[tag].FirstChild; int numParam = int.Parse(xmlSlotTagList[tag].Attributes["paramNumber"].InnerText); indicator.IndParam.NumParam[numParam].Caption = xmlNumParamNode.InnerText; xmlNumParamNode = xmlNumParamNode.NextSibling; string sNumParamValue = xmlNumParamNode.InnerText; sNumParamValue = sNumParamValue.Replace(',', Data.PointChar); sNumParamValue = sNumParamValue.Replace('.', Data.PointChar); float fValue = float.Parse(sNumParamValue); // Removing of the Stop Loss negative sign used in previous versions. string sParCaption = indicator.IndParam.NumParam[numParam].Caption; if (sParCaption == "Trailing Stop" || sParCaption == "Initial Stop Loss" || sParCaption == "Stop Loss") { fValue = Math.Abs(fValue); } indicator.IndParam.NumParam[numParam].Value = fValue; } // Check parameters if (xmlSlotTagList[tag].Name == "checkParam") { XmlNode xmlCheckParamNode = xmlSlotTagList[tag].FirstChild; int checkParam = int.Parse(xmlSlotTagList[tag].Attributes["paramNumber"].InnerText); indicator.IndParam.CheckParam[checkParam].Caption = xmlCheckParamNode.InnerText; xmlCheckParamNode = xmlCheckParamNode.NextSibling; indicator.IndParam.CheckParam[checkParam].Checked = bool.Parse(xmlCheckParamNode.InnerText); } } // Calculate the indicator. indicator.Calculate(slotType); tempStrategy.Slot[slot].IndicatorName = indicator.IndicatorName; tempStrategy.Slot[slot].IndParam = indicator.IndParam; tempStrategy.Slot[slot].Component = indicator.Component; tempStrategy.Slot[slot].SeparatedChart = indicator.SeparatedChart; tempStrategy.Slot[slot].SpecValue = indicator.SpecialValues; tempStrategy.Slot[slot].MinValue = indicator.SeparatedChartMinValue; tempStrategy.Slot[slot].MaxValue = indicator.SeparatedChartMaxValue; tempStrategy.Slot[slot].IsDefined = true; } return(tempStrategy); }
public static string GetAttributeByString(XmlAttributeCollection attributes, string identifier) { XmlAttribute attribute = attributes[identifier]; if (attribute != null) return attribute.Value; return ""; }
private void _btnLoad_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.Filter = "Annotations Roles File (.xml)|*.xml"; if (openFileDialog.ShowDialog(this) == DialogResult.OK) { XmlDocument document = new XmlDocument(); document.Load(openFileDialog.FileName); XmlNodeList groups = document.GetElementsByTagName("Group"); if (groups != null && groups.Count > 0) { _lstUsers.Items.Clear(); _lstGroups.Items.Clear(); _chkLstGroups.Items.Clear(); AnnGroupsRoles groupRoles = new AnnGroupsRoles(); _automationManager.GroupsRoles = _groupsRoles; foreach (XmlNode group in groups) { XmlAttributeCollection attribs = group.Attributes; if (attribs != null) { string groupName = attribs["Name"].Value; if (!string.IsNullOrEmpty(groupName)) { string rolesValue = attribs["Roles"].Value; string usersValue = attribs["Users"].Value; List <string> users = new List <string>(usersValue.Split(';')); AnnRoles roles = new AnnRoles(); roles.AddRange(rolesValue.Split(';')); AddGroup(groupRoles, groupName, roles); // Fill Users foreach (string user in users) { AddUser(groupRoles, groupName, user); } } } if (_groupsRoles.GroupRoles != null) { _groupsRoles.GroupRoles.Clear(); } if (groupRoles.GroupRoles != null) { foreach (var item in groupRoles.GroupRoles) { _groupsRoles.GroupRoles.Add(item.Key, item.Value); } } if (_groupsRoles.GroupUsers != null) { _groupsRoles.GroupUsers.Clear(); } if (groupRoles.GroupUsers != null) { foreach (var item in groupRoles.GroupUsers) { _groupsRoles.GroupUsers.Add(item.Key, item.Value); } } } } else { Messager.ShowError(this, "Invalid Roles File"); } } UpdateUI(); } }
private GameObject createLight(XmlAttributeCollection xml) { GameObject toReturn = new GameObject(); //xml["positionX"]; //xml["positionY"]; //xml["positionZ"]; //xml["type"]; //xml["color"]; //xml["type"]; //xml["intensity"]; //xml["spotangle"]; //xml["range"]; return toReturn; }
protected void ParseFromXmlNode(XmlNode mediaNode) { XmlAttributeCollection attributes = mediaNode.Attributes; foreach (XmlAttribute attribute in attributes) { if (attribute.Name == _nameXml) { _name = attribute.Value; } else if (attribute.Name == _description_id) { _descriptionId = attribute.Value; } else if (attribute.Name == _public) { if (attribute.Value == "0") { _isPublic = false; } } else if (attribute.Name == _typeXml) { if (attribute.Value == _video) { _mediaType = MediaType.Video; } else if (attribute.Value == _image) { _mediaType = MediaType.Image; } } else if (attribute.Name == _uploaddate) { if (attribute.Value == string.Empty) { break; } double totalSeconds = Convert.ToDouble(attribute.Value); int hours = Convert.ToInt32(totalSeconds / 3600); int mins = Convert.ToInt32((totalSeconds % 3600) / 60); int secs = Convert.ToInt32((totalSeconds % 3600) % 60); TimeSpan ts = new TimeSpan(hours, mins, secs); _uploadDate = new DateTime(1970, 1, 1, 0, 0, 0, 0).Add(ts); } else if (attribute.Name == _usernameXml) { _username = attribute.Value; } } XmlNode browserUrlNode = mediaNode.SelectSingleNode("descendant::browseurl"); _browserUrl = browserUrlNode.InnerText; XmlNode urlNode = mediaNode.SelectSingleNode("descendant::url"); _url = urlNode.InnerText; XmlNode thumbNode = mediaNode.SelectSingleNode("descendant::thumb"); _thumbUrl = thumbNode.InnerText; XmlNode titleNode = mediaNode.SelectSingleNode("descendant::title"); _title = titleNode.InnerText; XmlNode descriptionNode = mediaNode.SelectSingleNode("descendant::description"); _description = descriptionNode.InnerText; }
private string findAtrib(XmlAttributeCollection col, string name) { foreach (XmlAttribute atrib in col) { if (atrib.Name == name) { return atrib.Value; } } return ""; }
//quick and dirty public List <ApiXmlObject> ReadConfigFile() { try { xmlDoc.Load(xmlFileName); //First grab all the types of contexts child nodes XmlNodeList contextNodeList = xmlDoc.GetElementsByTagName("context"); XmlNodeList contextChildNodesList = null; XmlNodeList itemsNodeList = null; XmlNodeList innerItemsNodeList = null; XmlAttributeCollection innerItemsAttributes = null; ApiXmlObject tempHolder = null; //there should only be one foreach (XmlNode node in contextNodeList) { contextChildNodesList = node.ChildNodes; } //now go through all of the children string urlBase; //this is part of the url foreach (XmlNode node in contextChildNodesList) { urlBase = "/" + node.Name; itemsNodeList = node.ChildNodes; //go through all the item nodes //each item node is an object in our list foreach (XmlNode itemNode in itemsNodeList) { //inner items are <name> and <url> innerItemsNodeList = itemNode.ChildNodes; tempHolder = new ApiXmlObject(); foreach (XmlNode innerItemNode in innerItemsNodeList) { if (innerItemNode.Name == "name") { tempHolder.Category = innerItemNode.InnerText; } //url has attributes as well as inner text else if (innerItemNode.Name == "URL") { //set the url tempHolder.urlClass.URLS.Add(urlBase + innerItemNode.InnerText); //methods and parameters are attributes innerItemsAttributes = innerItemNode.Attributes; if (innerItemsAttributes.Count > 0) { foreach (XmlAttribute att in innerItemsAttributes) { //add even if blank so the size of the collections are always the same if (att.Name == "Methods") { tempHolder.urlClass.HttpMethods.Add(att.Value); } else if (att.Name == "Parameters") { tempHolder.urlClass.Parameters.Add(att.Value); } } } } } //add the item to the full list resultList.Add(tempHolder); } } } catch (Exception e) { MessageBox.Show(e.Message); } return(resultList); }
private bool getDustType(XmlAttributeCollection col) { string dif = findAtrib (col, "type"); if (dif == "") { return false; } else if(dif == "key") { return true; } return false; }
public static Action EnterTag(Request request, XmlNode templateNode, SubQuery query) { if (templateNode.NodeType != XmlNodeType.Element) { return(DoNothing); throw new NotImplementedException("EnterTag: " + templateNode.NodeType); } bool needsUnwind = false; UndoStackHolder thiz = (UndoStackHolder)query ?? request; ISettingsDictionary dict = query; if (dict == null && request != null) { dict = request.TargetSettings; } XmlAttributeCollection collection = templateNode.Attributes; EnterContext(request, query); if (collection == null || collection.Count <= 0) { return(() => { ExitContext(request, query); }); } else { var used = new List <XmlAttribute>(); string defaultElement = ""; Action gmrerstore; gmrerstore = request.WithAttributesForUnwind(templateNode, ref defaultElement, used); int uc = used.Count; UndoStack savedValues = null; foreach (XmlAttribute node in collection) { if (used.Contains(node)) { continue; } bool found; string n = node.Name.ToLower(); switch (n) { case "state": case "flag": case "graph": case "topic": case "that": break; default: { lock (ReservedAttributes) { if (ReservedAttributes.Contains(n)) { continue; } bool prev = NamedValuesFromSettings.UseLuceneForGet; try { NamedValuesFromSettings.UseLuceneForGet = false; if (!dict.containsSettingCalled(n)) { ReservedAttributes.Add(n); request.writeToLog("ReservedAttributes: {0}", n); } else { if (!PushableAttributes.Contains(n)) { PushableAttributes.Add(n); request.writeToLog("PushableAttributes: {0}", n); } } } finally { NamedValuesFromSettings.UseLuceneForGet = prev; } } // now require temp vars to s ay with_id="tempId" // to set the id="tempid" teporarily while evalig tags if (!n.StartsWith("with_")) { continue; } else { n = n.Substring(5); } Unifiable v = ReduceStar <Unifiable>(node.Value, query, dict, out found); UndoStack.FindUndoAll(thiz, true); savedValues = savedValues ?? UndoStack.GetStackFor(thiz); //savedValues = savedValues ?? query.GetFreshUndoStack(); savedValues.pushValues(dict, n, v); needsUnwind = true; } break; } } // unwind return(() => { if (needsUnwind) { try { EnterContext(request, query); if (savedValues != null) { savedValues.UndoAll(); } } catch (Exception ex) { request.writeToLog("ERROR " + ex); } finally { ExitContext(request, query); } } ExitContext(request, query); if (uc > 0) { gmrerstore(); } }); } }
protected virtual void LoadSpellValuesFromXML(XmlAttributeCollection attributes) { manaCost = int.Parse(attributes["manaCost"].Value); castTime = float.Parse(attributes["castTime"].Value); _affectType = (SpellAffectType)Enum.Parse(typeof(SpellAffectType), attributes["affectType"].Value); _name = attributes["name"].Value; if (attributes["cooldown"] == null) cooldown = 0f; else cooldown = float.Parse(attributes["cooldown"].Value); }
private string GetValeurAttribut(XmlAttributeCollection xmlAttrCollection, string attrName) { XmlAttribute xmlAttr = xmlAttrCollection[attrName]; return((xmlAttr == null) ? "" : xmlAttr.Value); }