public async Task Load(string fileName, ProgressUtility progress) { flights.Clear(); // CSV doesn't have realtime clock, so go with the file date instead. this.startTime = File.GetLastWriteTime(fileName); // time (ms) long min = long.MaxValue; long max = long.MinValue; await Task.Run(() => { timeElementName = null; using (Stream s = File.OpenRead(fileName)) { Dictionary <string, LogItemSchema> map = new Dictionary <string, LogItemSchema>(); XmlNameTable nametable = new NameTable(); using (XmlCsvReader reader = new XmlCsvReader(s, System.Text.Encoding.UTF8, new Uri(fileName), nametable)) { reader.FirstRowHasColumnNames = true; reader.ColumnsAsAttributes = true; while (reader.Read()) { progress.ShowProgress(0, s.Length, s.Position); if (this.schema == null) { // create the schema this.schema = new LogItemSchema() { Name = "CsvLog", Type = "Root" }; LogItemSchema row = null; foreach (String name in reader.ColumnNames) { if (timeElementName == null && (name.ToLower().Contains("time") || name.ToLower().Contains("ticks"))) { timeElementName = name; } if (name.Contains(":")) { // then we have sub-parts. int pos = name.IndexOf(":"); string key = name.Substring(0, pos); string field = name.Substring(pos + 1); LogItemSchema group = null; if (!map.ContainsKey(key)) { group = new LogItemSchema() { Name = key, Type = key }; this.schema.AddChild(group); map[key] = group; } else { group = map[key]; } var leaf = new LogItemSchema() { Name = field, Type = "Double" }; group.AddChild(leaf); map[name] = leaf; } else { if (row == null) { row = new LogItemSchema() { Name = "Other", Type = "Other" }; this.schema.AddChild(row); } var leaf = new LogItemSchema() { Name = name, Type = "Double" }; row.AddChild(leaf); map[name] = leaf; } } } if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "row") { // read a row long time = GetTicks(reader); min = Math.Min(min, time); max = Math.Max(max, time); LogEntry row = new Model.LogEntry() { Name = "Other", Timestamp = (ulong)time }; log.Add(row); Dictionary <string, LogEntry> groups = new Dictionary <string, LogEntry>(); if (reader.MoveToFirstAttribute()) { do { string name = XmlConvert.DecodeName(reader.LocalName); LogItemSchema itemSchema = map[name]; LogEntry e = row; if (name.Contains(":")) { // then we have sub-parts. int pos = name.IndexOf(":"); string key = name.Substring(0, pos); string field = name.Substring(pos + 1); if (!groups.ContainsKey(key)) { e = new LogEntry() { Name = key, Timestamp = (ulong)time }; groups[key] = e; log.Add(e); } else { e = groups[key]; } name = field; } string value = reader.Value; double d = 0; if (double.TryParse(value, out d)) { e.SetField(name, d); } else { if (!string.IsNullOrEmpty(value)) { // not a number. itemSchema.Type = "String"; e.SetField(name, value); } } }while (reader.MoveToNextAttribute()); reader.MoveToElement(); } } } } } }); // this log has no absolute UTC time, only ticks since board was booted, so we make up a start time. DateTime end = this.startTime.AddMilliseconds((max - min) / 1000); var flight = new Flight() { Log = this, StartTime = this.startTime, Duration = end - this.startTime }; this.duration = end - this.startTime; this.flights.Add(flight); }
private void SerializeNode( JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) { switch (node.NodeType) { case XmlNodeType.Element: if (this.IsArray(node) && XmlNodeConverter.AllSameName(node) && node.ChildNodes.Count > 0) { this.SerializeGroupedNodes(writer, node, manager, false); break; } manager.PushScope(); foreach (IXmlNode attribute in node.Attributes) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/") { string prefix = attribute.LocalName != "xmlns" ? XmlConvert.DecodeName(attribute.LocalName) : string.Empty; string uri = attribute.Value; manager.AddNamespace(prefix, uri); } } if (writePropertyName) { writer.WritePropertyName(this.GetPropertyName(node, manager)); } if (!this.ValueAttributes(node.Attributes) && node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType == XmlNodeType.Text) { writer.WriteValue(node.ChildNodes[0].Value); } else if (node.ChildNodes.Count == 0 && node.Attributes.Count == 0) { if (((IXmlElement)node).IsEmpty) { writer.WriteNull(); } else { writer.WriteValue(string.Empty); } } else { writer.WriteStartObject(); for (int index = 0; index < node.Attributes.Count; ++index) { this.SerializeNode(writer, node.Attributes[index], manager, true); } this.SerializeGroupedNodes(writer, node, manager, true); writer.WriteEndObject(); } manager.PopScope(); break; case XmlNodeType.Attribute: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.ProcessingInstruction: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == "http://james.newtonking.com/projects/json" || node.NamespaceUri == "http://james.newtonking.com/projects/json" && node.LocalName == "Array") { break; } if (writePropertyName) { writer.WritePropertyName(this.GetPropertyName(node, manager)); } writer.WriteValue(node.Value); break; case XmlNodeType.Comment: if (!writePropertyName) { break; } writer.WriteComment(node.Value); break; case XmlNodeType.Document: case XmlNodeType.DocumentFragment: this.SerializeGroupedNodes(writer, node, manager, writePropertyName); break; case XmlNodeType.DocumentType: IXmlDocumentType xmlDocumentType = (IXmlDocumentType)node; writer.WritePropertyName(this.GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(xmlDocumentType.Name)) { writer.WritePropertyName("@name"); writer.WriteValue(xmlDocumentType.Name); } if (!string.IsNullOrEmpty(xmlDocumentType.Public)) { writer.WritePropertyName("@public"); writer.WriteValue(xmlDocumentType.Public); } if (!string.IsNullOrEmpty(xmlDocumentType.System)) { writer.WritePropertyName("@system"); writer.WriteValue(xmlDocumentType.System); } if (!string.IsNullOrEmpty(xmlDocumentType.InternalSubset)) { writer.WritePropertyName("@internalSubset"); writer.WriteValue(xmlDocumentType.InternalSubset); } writer.WriteEndObject(); break; case XmlNodeType.XmlDeclaration: IXmlDeclaration xmlDeclaration = (IXmlDeclaration)node; writer.WritePropertyName(this.GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(xmlDeclaration.Version)) { writer.WritePropertyName("@version"); writer.WriteValue(xmlDeclaration.Version); } if (!string.IsNullOrEmpty(xmlDeclaration.Encoding)) { writer.WritePropertyName("@encoding"); writer.WriteValue(xmlDeclaration.Encoding); } if (!string.IsNullOrEmpty(xmlDeclaration.Standalone)) { writer.WritePropertyName("@standalone"); writer.WriteValue(xmlDeclaration.Standalone); } writer.WriteEndObject(); break; default: throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + (object)node.NodeType); } }
internal static string UnescapeName(string name) { return(XmlConvert.DecodeName(name)); }
internal DataTable InstantiateTable(DataSet dataSet, XmlElement node, XmlElement typeNode) { string typeName = string.Empty; XmlAttributeCollection attrs = node.Attributes; DataTable table; int minOccurs = 1; int maxOccurs = 1; string keys = null; ArrayList tableChildren = new ArrayList(); if (attrs.Count > 0) { typeName = GetInstanceName(node); table = dataSet.Tables.GetTable(typeName, _schemaUri); if (table != null) { return(table); } } table = new DataTable(XmlConvert.DecodeName(typeName)); // fxcop: new DataTable should inherit the CaseSensitive, Locale from DataSet and possibly updating during SetProperties table.Namespace = _schemaUri; GetMinMax(node, ref minOccurs, ref maxOccurs); table.MinOccurs = minOccurs; table.MaxOccurs = maxOccurs; _ds.Tables.Add(table); HandleTypeNode(typeNode, table, tableChildren); SetProperties(table, attrs); // check to see if we fave unique constraint if (keys != null) { string[] list = keys.TrimEnd(null).Split(null); int keyLength = list.Length; var cols = new DataColumn[keyLength]; for (int i = 0; i < keyLength; i++) { DataColumn col = table.Columns[list[i], _schemaUri]; if (col == null) { throw ExceptionBuilder.ElementTypeNotFound(list[i]); } cols[i] = col; } table.PrimaryKey = cols; } foreach (DataTable _tableChild in tableChildren) { DataRelation relation = null; DataRelationCollection childRelations = table.ChildRelations; for (int j = 0; j < childRelations.Count; j++) { if (!childRelations[j].Nested) { continue; } if (_tableChild == childRelations[j].ChildTable) { relation = childRelations[j]; } } if (relation != null) { continue; } DataColumn parentKey = table.AddUniqueKey(); // foreign key in the child table DataColumn childKey = _tableChild.AddForeignKey(parentKey); // create relationship // setup relationship between parent and this table relation = new DataRelation(table.TableName + "_" + _tableChild.TableName, parentKey, childKey, true); relation.CheckMultipleNested = false; // disable the check for multiple nested parent relation.Nested = true; _tableChild.DataSet.Relations.Add(relation); relation.CheckMultipleNested = true; // enable the check for multiple nested parent } return(table); }
internal static string ToXmlNmTokens(string value) { return(XmlConvert.DecodeName(CollapseWhitespace(value))); }
internal static string?ToXmlNCName(string?value) { return(XmlConvert.DecodeName(CollapseWhitespace(value))); }
internal static string ConvertXmlNameToJsonName(string xmlName) { return(XmlConvert.DecodeName(xmlName)); }
// Insert or Update imported data into the content manager. // Call content item handlers. public void Import(XElement element, ImportContentSession importContentSession) { var elementId = element.Attribute("Id"); if (elementId == null) { return; } var identity = elementId.Value; if (String.IsNullOrWhiteSpace(identity)) { return; } var status = element.Attribute("Status"); var item = importContentSession.Get(identity, VersionOptions.Latest, XmlConvert.DecodeName(element.Name.LocalName)); if (item == null) { item = New(XmlConvert.DecodeName(element.Name.LocalName)); if (status != null && status.Value == "Draft") { Create(item, VersionOptions.Draft); } else { Create(item); } } else { // If the existing item is published, create a new draft for that item. if (item.IsPublished()) { item = Get(item.Id, VersionOptions.DraftRequired); } } // Create a version record if import handlers need it. if (item.VersionRecord == null) { item.VersionRecord = new ContentItemVersionRecord { ContentItemRecord = new ContentItemRecord { ContentType = AcquireContentTypeRecord(item.ContentType) }, Number = 1, Latest = true, Published = true }; } var context = new ImportContentContext(item, element, importContentSession); Handlers.Invoke(contentHandler => contentHandler.Importing(context), Logger); Handlers.Invoke(contentHandler => contentHandler.Imported(context), Logger); var savedItem = Get(item.Id, VersionOptions.Latest); // The item has been pre-created in the first pass of the import, create it in db. if (savedItem == null) { if (status != null && status.Value == "Draft") { Create(item, VersionOptions.Draft); } else { Create(item); } } if (status == null || status.Value == Published) { Publish(item); } }
/// <summary> /// Receives client's call and adds a node in the workflow /// </summary> /// <param name="eventArgument">WorkflowId & Node id</param> public void RaiseCallbackEvent(string eventArgument) { try { fieldTypes = new XmlSchema(); //Creating the schema that will contain the field types string[] args = eventArgument.Split('&'); string nodeID = args[0]; string nodeName = args[1]; //Initializing the string to return serialized_field_types += args[0] + '&'; // idnodo & nodeName & basetype | id | label | position x | position y | width | height | rendered_label | constraints & ... /** * EXAMPLE: * workflow_1_node_1&nodeName&StringBox|1|pippo|120|208|100|30|pippo|AddMaxLengthConstraint#30@AddMinLengthConstraint#3@AddRangeLengthConstraint#3$30 **/ for (int i = 2; i < args.Length; i++) { string[] property = args[i].Split('|'); IBaseType f = getField(property[0]); if (f != null) { f.TypeName = property[0] + property[1]; f.Name = XmlConvert.DecodeName(property[2]); //Applying costraints if (!property[8].Equals("")) //apply only if some costraints are defined { //--------------------------- // COSTRAINTS STRING FORMAT: // & CostraintName # CostraintParameter1 | .. | CostraintParameterNN //--------------------------- string[] constraints = property[8].Split('@'); for (int k = 0; k < constraints.Length; k++) { string[] constraintRapresentation = constraints[k].Split('#'); //divide costraint name from parameters string[] tmpParams; if (constraintRapresentation[1].Equals("")) { tmpParams = null; } else { tmpParams = constraintRapresentation[1].Split('$'); //divide each param } List <MethodInfo> constraintList = FieldsManager.GetConstraints(f.GetType()); bool constraint_loaded = false; foreach (MethodInfo c in constraintList) { if (constraintRapresentation[0].Equals(c.Name)) { constraint_loaded = (bool)c.Invoke(f, tmpParams); //apply costraint to field break; } } if (!constraint_loaded) { throw new Exception("No constraint with name \"" + constraintRapresentation[0] + "\" could be applied."); } } } //for the client fieldTypes.Items.Add(f.TypeSchema); } } } catch (Exception e) { Console.Write(e.Message); error = e.Message; } }
/// <summary> /// Loads a NuGet.config file at the given filepath. /// </summary> /// <param name="filePath">The full filepath to the NuGet.config file to load.</param> /// <returns>The newly loaded <see cref="NugetConfigFile"/>.</returns> public static NugetConfigFile Load(string filePath) { NugetConfigFile configFile = new NugetConfigFile(); configFile.PackageSources = new List <NugetPackageSource>(); configFile.InstallFromCache = true; configFile.ReadOnlyPackageFiles = false; XDocument file = XDocument.Load(filePath); // Force disable NugetHelper.DisableWSAPExportSetting(filePath, false); // read the full list of package sources (some may be disabled below) XElement packageSources = file.Root.Element("packageSources"); if (packageSources != null) { var adds = packageSources.Elements("add"); foreach (var add in adds) { configFile.PackageSources.Add(new NugetPackageSource(add.Attribute("key").Value, add.Attribute("value").Value)); } } // read the active package source (may be an aggregate of all enabled sources!) XElement activePackageSource = file.Root.Element("activePackageSource"); if (activePackageSource != null) { var add = activePackageSource.Element("add"); configFile.ActivePackageSource = new NugetPackageSource(add.Attribute("key").Value, add.Attribute("value").Value); } // disable all listed disabled package sources XElement disabledPackageSources = file.Root.Element("disabledPackageSources"); if (disabledPackageSources != null) { var adds = disabledPackageSources.Elements("add"); foreach (var add in adds) { string name = add.Attribute("key").Value; string disabled = add.Attribute("value").Value; if (String.Equals(disabled, "true", StringComparison.OrdinalIgnoreCase)) { var source = configFile.PackageSources.FirstOrDefault(p => p.Name == name); if (source != null) { source.IsEnabled = false; } } } } // set all listed passwords for package source credentials XElement packageSourceCredentials = file.Root.Element("packageSourceCredentials"); if (packageSourceCredentials != null) { foreach (var sourceElement in packageSourceCredentials.Elements()) { string name = XmlConvert.DecodeName(sourceElement.Name.LocalName); var source = configFile.PackageSources.FirstOrDefault(p => p.Name == name); if (source != null) { var adds = sourceElement.Elements("add"); foreach (var add in adds) { if (string.Equals(add.Attribute("key").Value, "userName", StringComparison.OrdinalIgnoreCase)) { string userName = add.Attribute("value").Value; source.UserName = userName; } if (string.Equals(add.Attribute("key").Value, "clearTextPassword", StringComparison.OrdinalIgnoreCase)) { string password = add.Attribute("value").Value; source.SavedPassword = password; } } } } } // read the configuration data XElement config = file.Root.Element("config"); if (config != null) { var adds = config.Elements("add"); foreach (var add in adds) { string key = add.Attribute("key").Value; string value = add.Attribute("value").Value; if (String.Equals(key, "repositoryPath", StringComparison.OrdinalIgnoreCase)) { configFile.savedRepositoryPath = value; configFile.RepositoryPath = Environment.ExpandEnvironmentVariables(value); if (!Path.IsPathRooted(configFile.RepositoryPath)) { string repositoryPath = Path.Combine(UnityEngine.Application.dataPath, configFile.RepositoryPath); repositoryPath = Path.GetFullPath(repositoryPath); configFile.RepositoryPath = repositoryPath; } } else if (String.Equals(key, "DefaultPushSource", StringComparison.OrdinalIgnoreCase)) { configFile.DefaultPushSource = value; } else if (String.Equals(key, "verbose", StringComparison.OrdinalIgnoreCase)) { configFile.Verbose = bool.Parse(value); } else if (String.Equals(key, "InstallFromCache", StringComparison.OrdinalIgnoreCase)) { configFile.InstallFromCache = bool.Parse(value); } else if (String.Equals(key, "ReadOnlyPackageFiles", StringComparison.OrdinalIgnoreCase)) { configFile.ReadOnlyPackageFiles = bool.Parse(value); } } } return(configFile); }
private string DecodeNodeName(string nodeName) { return(XmlConvert.DecodeName(nodeName)); }
protected void Page_Load(object sender, EventArgs e) { // Init the Session element that bring the logo to null if (Page != null) { Page.Session["TE_currentLogo"] = null; } // Taking the CurrentWorkflow from the session elemnt. ComputableWorkflowReference wfr = null; IComputableWorkflow wf = null; try { wfr = (ComputableWorkflowReference)Page.Session["WFE_CurrentWorkflow"]; wf = wfr.GetWorkflow(); } catch (Exception) { Response.Write("No workflow in session!"); Response.End(); return; } bool useStaticLabel = false; try { useStaticLabel = (bool)Page.Session["UsingStaticFields"]; } catch (Exception) { Response.Write("No UsingStaticFields in session!"); Response.End(); return; } if (useStaticLabel) { editStaticLabel.InnerHtml = "<label for=\"color_staticLabel\">Static Label Color:</label><input rel=\"staticLabel\" class=\"gccolor\" onblur=\"toolbox.applyChanges('staticLabel','color', this.value, 'color' );\" title=\"Color of the Static Label. Example: #ff00ff\" id=\"color_staticLabel\" type=\"text\"/><div style=\"display:none;\"><input id=\"staticLabelApplyToID\" type=\"checkbox\" /></div>"; } else { editStaticLabel.InnerHtml = ""; } // bla bla bla int tabCounter = 1; List <Panel> divPanel = new List <Panel>(); presenPanel.Controls.Add(new LiteralControl("<ul class=\"tabs\">")); // Iterating each workflow node to render the form elemnt list foreach (WFnode nd in wf.getNodeList()) { Panel p = new Panel(); //p.Enabled = false; XmlDocument renderDoc = nd.GetRenderingDocument(); string nodeName = XmlConvert.DecodeName(renderDoc.DocumentElement.Attributes["name"].InnerText); presenPanel.Controls.Add(new LiteralControl("<li><a href=\"#tabs" + tabCounter + "\" >" + nodeName + "</a></li>")); //p.Controls.Add(new LiteralControl("<div id=\"tabs" + tabCounter + "\" style=\"position: relative; height: 500px;\" >")); // Hangling the webcontrol XmlNode cmplexRenering = renderDoc.DocumentElement.FirstChild; Control wc = nd.GetWebControl(Page.Server, cmplexRenering); //Disabling all BaseValidator to remove useless text <.< DisableControl(wc); p.Controls.Add(new LiteralControl("<div>")); p.Controls.Add(wc); p.Controls.Add(new LiteralControl("</div>")); divPanel.Add(p); tabCounter++; } presenPanel.Controls.Add(new LiteralControl("</ul>")); presenPanel.Controls.Add(new LiteralControl("<div class=\"panes\"> ")); // Add each panel to presenPanel foreach (var p in divPanel) { presenPanel.Controls.Add(p); } presenPanel.Controls.Add(new LiteralControl("</div>")); // Retriving the current Theme informations IWorkflowThemeReference iwfr = (IWorkflowThemeReference)Page.Session["WFE_CurrentWorkflow"]; if (Page.Session["CurrentTheme"] == null) { Page.Session["CurrentTheme"] = (Theme)iwfr.GetTheme(); } Theme theme = (Theme)Page.Session["CurrentTheme"]; //Theme theme = (Theme)iwfr.GetTheme(); string propertyListJson = "<script language='javascript'> initTE('" + theme.Title + "');"; propertyListJson += " var PropertyList=function(){"; IBaseType field; foreach (Type t in FieldsManager.FieldTypes) { field = (IBaseType)FieldsManager.GetInstance(t); if (!String.IsNullOrEmpty(field.JSON_StyleProperties)) { propertyListJson += "var " + field.GetType().Name + "PropertyList = " + field.JSON_StyleProperties + ";"; } } propertyListJson += @" return{ getList:function( type ){ if( eval( ""typeof "" + type + ""PropertyList == 'undefined'"" ) ) { type = ""StringBox""; } return eval( type + ""PropertyList""); }, validate:function( type, value ){ if( type == ""color"" ) return (value.match( /#[a-fA-F0-9]{6}/ ) || value.match(/rgb\([ ]*[0-9]{1,3}[ ]*,[ ]*[0-9]{1,3}[ ]*,[ ]*[0-9]{1,3}[ ]*\)/i)); if( type == ""size"" ) return ( value.match( /\d+px/ ) || value.match( /\d+\%/ ) || value.match( /\d+em/ )); if( type == ""none"" ) return true; if( type == ""font"" ) return true; return false; } }; }(); "; CssParser cssParser = new CssParser(); cssParser.AddStyleSheet(theme.CSS); foreach (var styles in cssParser.Styles) { foreach (KeyValuePair <string, string> pv in styles.Value.Attributes) { propertyListJson += string.Format(CssAddJS, styles.Key.Substring(0, 1), styles.Key.Substring(1), pv.Key, pv.Value); } } if (theme.Image != null) { Page.Session["TE_currentLogo"] = theme.Image; propertyListJson += "stopUpload('drawLogo.aspx', true);"; } propertyListJson += "</script>"; Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", propertyListJson); //Adding the CSS to the Page Header. Page.Header.Controls.Add( new LiteralControl( @"<style type='text/css'>" + theme.CSS + "</style" + ">" ) ); //for manage contacts back button (GUI modify) Session["contactReturn"] = "/ThemeEditor/ThemeEditor.aspx"; }
public Int32 CreateNewBug(string psFieldDefXml) { bool hasInvalidField = false; // Create a new datastore instance DatastoreItemList psDataList = new DatastoreItemList(); psDataList.Datastore = this.psDataStore; // Craete a blank bug psDataList.CreateBlank(PsDatastoreItemTypeEnum.psDatastoreItemTypeBugs); DatastoreItem psDataItem = psDataList.DatastoreItems.Add(null, PsApplyRulesMask.psApplyRulesAll); // Set fields for the new bug Fields psFields = psDataItem.Fields; // New PS Bug Field Description XML file will look like // ======================================================= // <psfieldDef> // <Title> // Title (Ex. RFH: Hotfix for ...) // </Title> // <Tree Path> // Path (Ex. SCCM 2007 SP2) // </Tree Path> // <Issue type> // Issue Type (Ex. RFH / CDCR) // </Issue type> // <Get Help> // Get Help (Ex. Yes / No) // </Get Help> // <Priority> // Priority (Ex. 1, 2, 3, 4) // </Priority> // <Severity> // Severity (Ex. 1, 2, 3, 4) // </Severity> // <SMS Product> // SMS Product (Ex. x86 / x64) // </SMS Product> // <Component> // Component (Ex. component name) // </Component> // <FeatureArea> // Feature Area (Ex. feature area name) // </FeatureArea> // <Open Build> // Open Build (Ex. build version 6487.2000) // </Open Build> // <Language> // Language (Ex. ENU) // </Language> // <How found> // How Found (Ex. Internal) // </How found> // <Source> // Source (Ex. Ad Hoc) // </Source> // <Source ID> // Source ID (ex. Airforce) // </Source ID> // <PSS> // SR Number (ex. SR Number) // </PSS> // <KB Article> // KB Number (ex. KB Number 98765432) // </KB Article> // <Repro Steps> // Repro Steps (ex. Repro Steps) // </Repro Steps> // <Description> // Description (ex. Description) // </Description> // <Related Bugs> // SMS Sustained Engineering:5991 // </Related Bugs> // <QFE Status> // Core Review // </QFE Status> // </psfieldDef> XmlReader xmlReader = XmlReader.Create(new StringReader(psFieldDefXml)); while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element) { if (string.Compare(XmlConvert.DecodeName(xmlReader.Name), "psfieldDef", StringComparison.OrdinalIgnoreCase) == 0) { xmlReader.Read(); // Read psfieldDef } else if (string.Compare(XmlConvert.DecodeName(xmlReader.Name), "Tree Path", StringComparison.OrdinalIgnoreCase) == 0) { xmlReader.ReadStartElement(xmlReader.Name); // Read <Tree Path> psFields["TreeID"].Value = this.GetTreeIDFromTreePath(this.psDataStore.RootNode, xmlReader.Value); xmlReader.Read(); xmlReader.ReadEndElement(); } else if (string.Compare(XmlConvert.DecodeName(xmlReader.Name), "Related Bugs", StringComparison.OrdinalIgnoreCase) == 0) { xmlReader.ReadStartElement(xmlReader.Name); // Read <RelatedBugs> string product = xmlReader.Value.Substring(0, xmlReader.Value.IndexOf(':')); Int32 bugId = 0; Int32.TryParse(xmlReader.Value.Substring(xmlReader.Value.IndexOf(':') + 1), out bugId); ((Bug)psDataItem).AddRelatedLink(bugId, product); xmlReader.Read(); xmlReader.ReadEndElement(); } else if (string.Compare(XmlConvert.DecodeName(xmlReader.Name), "File", StringComparison.OrdinalIgnoreCase) == 0) { xmlReader.ReadStartElement(xmlReader.Name); // Read <File> ((Bug)psDataItem).Files.Add(xmlReader.Value); xmlReader.Read(); xmlReader.ReadEndElement(); } else { string fieldName = XmlConvert.DecodeName(xmlReader.Name); xmlReader.ReadStartElement(xmlReader.Name); // Read Start Element Ex. <Title> psFields[fieldName].Value = xmlReader.Value; xmlReader.Read(); xmlReader.ReadEndElement(); // Read End Element Ex. </Title> } } } // Let's make sure all fields are valid before saving foreach (Field psField in psDataItem.Fields) { if (psField.Validity != PsFieldStatusEnum.psFieldStatusValid) { hasInvalidField = true; throw new Exception("Invalid Field (" + psField.Name + ") with Value (" + psField.Value + "). Counld not new bug!"); } } if (hasInvalidField) { throw (new ApplicationException("Invalid Field(s) were found. Could not create new bug.")); } else { psDataItem.Save(true); return(Convert.ToInt32(psFields["ID"].Value)); } }
public static void AddCountToStatistic(string Statistic, string PluginName) { try { SimpleAES StringEncrypter = new SimpleAES(); Directory.CreateDirectory(Directory.GetParent(StatisticsFilePath).FullName); if (!File.Exists(StatisticsFilePath)) { new XDocument( new XElement("LSPDFRPlus") ) .Save(StatisticsFilePath); } string pswd = Environment.UserName; string EncryptedStatistic = XmlConvert.EncodeName(StringEncrypter.EncryptToString(Statistic + PluginName + pswd)); string EncryptedPlugin = XmlConvert.EncodeName(StringEncrypter.EncryptToString(PluginName + pswd)); XDocument xdoc = XDocument.Load(StatisticsFilePath); char[] trim = new char[] { '\'', '\"', ' ' }; XElement LSPDFRPlusElement; if (xdoc.Element("LSPDFRPlus") == null) { LSPDFRPlusElement = new XElement("LSPDFRPlus"); xdoc.Add(LSPDFRPlusElement); } LSPDFRPlusElement = xdoc.Element("LSPDFRPlus"); XElement StatisticElement; if (LSPDFRPlusElement.Elements(EncryptedStatistic).Where(x => (string)x.Attribute("Plugin") == EncryptedPlugin).ToList().Count == 0) { //Game.LogTrivial("Creating new statistic entry."); StatisticElement = new XElement(EncryptedStatistic); StatisticElement.Add(new XAttribute("Plugin", EncryptedPlugin)); LSPDFRPlusElement.Add(StatisticElement); } StatisticElement = LSPDFRPlusElement.Elements(EncryptedStatistic).Where(x => (string)x.Attribute("Plugin") == EncryptedPlugin).FirstOrDefault(); int StatisticCount; if (StatisticElement.IsEmpty) { StatisticCount = 0; } else { string DecryptedStatistic = StringEncrypter.DecryptString(XmlConvert.DecodeName(StatisticElement.Value)); //Game.LogTrivial("Decryptedstatistic: " + DecryptedStatistic); int index = DecryptedStatistic.IndexOf(EncryptedStatistic); string cleanPath = (index < 0) ? "0" : DecryptedStatistic.Remove(index, EncryptedStatistic.Length); //if (cleanPath == "0") { Game.LogTrivial("Cleanpath debug 2"); } index = cleanPath.IndexOf(pswd); cleanPath = (index < 0) ? "0" : cleanPath.Remove(index, pswd.Length); //if (cleanPath == "0") { Game.LogTrivial("Cleanpath debug 1"); } StatisticCount = int.Parse(cleanPath); } //Game.LogTrivial("Statisticscount: " + StatisticCount.ToString()); StatisticCount++; string ValueToWrite = StatisticCount.ToString() + pswd; int indextoinsertat = LSPDFRPlusHandler.rnd.Next(ValueToWrite.Length); ValueToWrite = ValueToWrite.Substring(0, indextoinsertat) + EncryptedStatistic + ValueToWrite.Substring(indextoinsertat); //Game.LogTrivial("Valueotwrite: " + ValueToWrite); StatisticElement.Value = XmlConvert.EncodeName(StringEncrypter.EncryptToString(ValueToWrite)); xdoc.Save(StatisticsFilePath); } catch (System.Threading.ThreadAbortException e) { } catch (Exception e) { Game.LogTrivial("LSPDFR+ encountered a statistics exception. It was: " + e.ToString()); Game.DisplayNotification("~r~LSPDFR+: Statistics error."); } }
private void BeginProperty(XmlReader reader) { StackFrame topFrame = stack.Peek(); EntityPropertyInfo entityPropertyInfo = topFrame.entity.Properties[reader.LocalName]; if (!topFrame.dynamic) { // Assumptions: // - expecting property to match exactly XML element name // - only public members looked for // Improvement: // - Process this validation when the metadata has been processed. PropertyInfo property = topFrame.instanceType.GetProperty(reader.LocalName); if (property == null) { throw new InvalidOperationException(string.Format("Property {0} does not exist on typeName {1}", reader.LocalName, topFrame.instanceType.Name)); } // Assumptions: // - No type conversion is performed to assign the variable // Improvements: // - Process this validation when the metadata has been processed. if (!property.PropertyType.IsAssignableFrom(entityPropertyInfo.Type)) { throw new InvalidOperationException(string.Format("Property {0} cannot be assigned from type {1}", reader.LocalName, entityInfo.Properties[reader.LocalName].TypeName)); } StackFrame frame = topFrame.Clone(); frame.elementName = XmlConvert.DecodeName(reader.LocalName); frame.property = property; frame.entityPropertyInfo = entityPropertyInfo; frame.state = state; stack.Push(frame); } else { StackFrame frame = topFrame.Clone(); frame.elementName = XmlConvert.DecodeName(reader.LocalName); frame.entityPropertyInfo = entityPropertyInfo; frame.state = state; if (hasAddMethod) { frame.iAddInstance = (IEntityPropertySetter)frame.instance; } else { MethodInfo addMethod = topFrame.instanceType.GetMethod("Add"); frame.addMethod = addMethod; } stack.Push(frame); } if (entityPropertyInfo.IsArray) { state = ParserState.ArrayProperty; if (reader.IsEmptyElement) { EndArrayProperty(reader); } } else { state = ParserState.Property; if (reader.IsEmptyElement) { ProcessPropertyValue(reader); EndProperty(reader); } } }
//used for WCF known types internal static WebServiceTypeData GetWebServiceTypeData(Type type) { WebServiceTypeData typeData = null; XsdDataContractExporter exporter = new XsdDataContractExporter(); XmlQualifiedName qname = exporter.GetSchemaTypeName(type); if (!qname.IsEmpty) { if (type.IsEnum) { bool isUlong = (Enum.GetUnderlyingType(type) == typeof(ulong)); typeData = new WebServiceEnumData(XmlConvert.DecodeName(qname.Name), XmlConvert.DecodeName(qname.Namespace), Enum.GetNames(type), Enum.GetValues(type), isUlong); } else { typeData = new WebServiceTypeData(XmlConvert.DecodeName(qname.Name), XmlConvert.DecodeName(qname.Namespace)); } } return(typeData); }
private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager) { string str = node.NamespaceUri == null || node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/" ? (string)null : manager.LookupPrefix(node.NamespaceUri); return(!string.IsNullOrEmpty(str) ? str + ":" + XmlConvert.DecodeName(node.LocalName) : XmlConvert.DecodeName(node.LocalName)); }
/// <summary> /// Sets all properties in the object <code>o</code> to the xml element <code>el</code> defined properties. /// </summary> void SetAttributes(object o, XmlElement el) { if (el.Name == "AcceptButton") { mainForm = (Form)o; acceptButtonName = el.Attributes["value"].InnerText.Split(' ')[0]; return; } if (el.Name == "CancelButton") { mainForm = (Form)o; cancelButtonName = el.Attributes["value"].InnerText.Split(' ')[0]; return; } if (el.Name == "ToolTip") { string val = el.Attributes["value"].InnerText; tooltips[o] = stringValueFilter != null?stringValueFilter.GetFilteredValue(val) : val; return; } if (el.Attributes["value"] != null) { string val = el.Attributes["value"].InnerText; try { SetValue(o, el.Name, stringValueFilter != null ? stringValueFilter.GetFilteredValue(val) : val); } catch (Exception) { } } else if (el.Attributes["event"] != null) { try { EventInfo eventInfo = o.GetType().GetEvent(el.Name); eventInfo.AddEventHandler(o, Delegate.CreateDelegate(eventInfo.EventHandlerType, customizationObject, el.Attributes["event"].InnerText)); } catch (Exception) { } } else { PropertyInfo propertyInfo = o.GetType().GetProperty(el.Name); object pv = propertyInfo.GetValue(o, null); if (pv is IList) { foreach (XmlNode subNode in el.ChildNodes) { if (subNode is XmlElement) { XmlElement subElement = (XmlElement)subNode; object collectionObject = objectCreator.CreateObject(XmlConvert.DecodeName(subElement.Name), subElement); if (collectionObject == null) { continue; } if (collectionObject is IComponent) { string name = null; if (subElement["Name"] != null && subElement["Name"].Attributes["value"] != null) { name = subElement["Name"].Attributes["value"].InnerText; } if (name == null || name.Length == 0) { name = "CreatedObject" + num++; } // collectionObject = host.CreateComponent(collectionObject.GetType(), name); } SetUpObject(collectionObject, subElement); if (collectionObject is Control) { string name = ((Control)collectionObject).Name; if (name != null && name.Length > 0) { ControlDictionary[name] = (Control)collectionObject; } } if (collectionObject != null) { ((IList)pv).Add(collectionObject); } } } } else { object propertyObject = objectCreator.CreateObject(o.GetType().GetProperty(el.Name).PropertyType.Name, el); if (propertyObject is IComponent) { PropertyInfo pInfo = propertyObject.GetType().GetProperty("Name"); string name = null; if (el["Name"] != null && el["Name"].Attributes["value"] != null) { name = el["Name"].Attributes["value"].InnerText; } if (name == null || name.Length == 0) { name = "CreatedObject" + num++; } propertyObject = objectCreator.CreateObject(name, el); } SetUpObject(propertyObject, el); propertyInfo.SetValue(o, propertyObject, null); } } }
private void Read(ConfigurationNode node, StringCollection fileNames) { var name = node.Name; var endOfNode = _xmlReader.IsEmptyElement; if (name != null) { var hasNext = _xmlReader.MoveToFirstAttribute(); while (hasNext) { var attributeName = _xmlReader.Name; var attributeValue = _xmlReader.Value; if (attributeName == "name") { } else if (attributeName == "description") { node.Description = attributeValue; } else { var attribute = new ConfigurationAttribute(attributeName, attributeValue, null); node.Attributes.Add(attribute); } hasNext = _xmlReader.MoveToNextAttribute(); } } while (!endOfNode && _xmlReader.Read()) { switch (_xmlReader.NodeType) { case XmlNodeType.Element: { var elementName = _xmlReader.Name; switch (elementName) { case ConfigurationElementName.Attribute: ReadAttribute(node); break; case ConfigurationElementName.Node: { var nodeName = _xmlReader.GetAttribute("name"); var childNode = new ConfigurationNode(nodeName); node.AddChildNode(childNode); Read(childNode, fileNames); } break; case "include": { var fileName = _xmlReader.GetAttribute("fileName"); fileName = Environment.ExpandEnvironmentVariables(fileName); var reader2 = new ConfigurationReader(); var includeNode = reader2.Read(fileName, _sectionName, fileNames); node.Attributes.Add(includeNode.Attributes); foreach (var childNode in includeNode.ChildNodes) { node.AddChildNode(childNode); } if (_enableFileSystemWatcher && !fileNames.Contains(fileName)) { fileNames.Add(fileName); } } break; default: { var nodeName = XmlConvert.DecodeName(elementName); var childNode = new ConfigurationNode(nodeName); node.AddChildNode(childNode); Read(childNode, fileNames); } break; } } break; case XmlNodeType.EndElement: endOfNode = true; break; } } }
internal static string ToXmlName(string value) { return(XmlConvert.DecodeName(value)); }
internal void HandleColumn(XmlElement node, DataTable table) { Debug.Assert(FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS) || FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS), "Illegal node type"); string instanceName; string strName; Type type; string strType; string strValues; int minOccurs = 0; int maxOccurs = 1; string strDefault; DataColumn column; // Get the name if (node.Attributes.Count > 0) { string strRef = node.GetAttribute(Keywords.REF); if (strRef != null && strRef.Length > 0) { return; //skip ref nodes. B2 item } strName = instanceName = GetInstanceName(node); column = table.Columns[instanceName, _schemaUri]; if (column != null) { if (column.ColumnMapping == MappingType.Attribute) { if (FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS)) { throw ExceptionBuilder.DuplicateDeclaration(strName); } } else { if (FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS)) { throw ExceptionBuilder.DuplicateDeclaration(strName); } } instanceName = GenUniqueColumnName(strName, table); } } else { strName = instanceName = string.Empty; } // Now get the type XmlElement typeNode = FindTypeNode(node); SimpleType xsdType = null; if (typeNode == null) { strType = node.GetAttribute(Keywords.TYPE); throw ExceptionBuilder.UndefinedDatatype(strType); } strType = typeNode.GetAttribute(Keywords.DT_TYPE, Keywords.DTNS); strValues = typeNode.GetAttribute(Keywords.DT_VALUES, Keywords.DTNS); if (strType == null || strType.Length == 0) { strType = string.Empty; type = typeof(string); } else { type = ParseDataType(strType, strValues); // HACK: temp work around special types if (strType == "float") { strType = string.Empty; } if (strType == "char") { strType = string.Empty; xsdType = SimpleType.CreateSimpleType(StorageType.Char, type); } if (strType == "enumeration") { strType = string.Empty; xsdType = SimpleType.CreateEnumeratedType(strValues); } if (strType == "bin.base64") { strType = string.Empty; xsdType = SimpleType.CreateByteArrayType("base64"); } if (strType == "bin.hex") { strType = string.Empty; xsdType = SimpleType.CreateByteArrayType("hex"); } } bool isAttribute = FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS); GetMinMax(node, isAttribute, ref minOccurs, ref maxOccurs); strDefault = null; // Does XDR has default? strDefault = node.GetAttribute(Keywords.DEFAULT); bool bNullable = false; column = new DataColumn(XmlConvert.DecodeName(instanceName), type, null, isAttribute ? MappingType.Attribute : MappingType.Element); SetProperties(column, node.Attributes); // xmlschema.SetProperties will skipp setting expressions column.XmlDataType = strType; column.SimpleType = xsdType; column.AllowDBNull = (minOccurs == 0) || bNullable; column.Namespace = (isAttribute) ? string.Empty : _schemaUri; // We will skip handling expression columns in SetProperties, so we need set the expressions here if (node.Attributes != null) { for (int i = 0; i < node.Attributes.Count; i++) { if (node.Attributes[i].NamespaceURI == Keywords.MSDNS) { if (node.Attributes[i].LocalName == "Expression") { column.Expression = node.Attributes[i].Value; break; } } } } string targetNamespace = node.GetAttribute(Keywords.TARGETNAMESPACE); if (targetNamespace != null && targetNamespace.Length > 0) { column.Namespace = targetNamespace; } table.Columns.Add(column); if (strDefault != null && strDefault.Length != 0) { try { column.DefaultValue = SqlConvert.ChangeTypeForXML(strDefault, type); } catch (System.FormatException) { throw ExceptionBuilder.CannotConvert(strDefault, type.FullName); } } }
private static string GetCodeElementName(string xmlName) { // Legacy support. Remove later. (Written 2014-01-10) xmlName = xmlName.Replace("__sbo__", "<").Replace("__sbc__", ">"); return(XmlConvert.DecodeName(xmlName)); }
private XmlElement ExportGenericInfo(Type clrType, string elementName, string elementNs) { Type?itemType; int nestedCollectionLevel = 0; while (CollectionDataContract.IsCollection(clrType, out itemType)) { if (DataContract.GetBuiltInDataContract(clrType) != null || CollectionDataContract.IsCollectionDataContract(clrType)) { break; } clrType = itemType; nestedCollectionLevel++; } Type[]? genericArguments = null; IList <int>?genericArgumentCounts = null; if (clrType.IsGenericType) { genericArguments = clrType.GetGenericArguments(); string typeName; if (clrType.DeclaringType == null) { typeName = clrType.Name; } else { int nsLen = (clrType.Namespace == null) ? 0 : clrType.Namespace.Length; if (nsLen > 0) { nsLen++; //include the . following namespace } typeName = DataContract.GetClrTypeFullName(clrType).Substring(nsLen).Replace('+', '.'); } int iParam = typeName.IndexOf('['); if (iParam >= 0) { typeName = typeName.Substring(0, iParam); } genericArgumentCounts = DataContract.GetDataContractNameForGenericName(typeName, null); clrType = clrType.GetGenericTypeDefinition(); } XmlQualifiedName dcqname = DataContract.GetStableName(clrType); if (nestedCollectionLevel > 0) { string collectionName = dcqname.Name; for (int n = 0; n < nestedCollectionLevel; n++) { collectionName = Globals.ArrayPrefix + collectionName; } dcqname = new XmlQualifiedName(collectionName, DataContract.GetCollectionNamespace(dcqname.Namespace)); } XmlElement typeElement = XmlDoc.CreateElement(elementName, elementNs); XmlAttribute nameAttribute = XmlDoc.CreateAttribute(Globals.GenericNameAttribute); nameAttribute.Value = genericArguments != null?XmlConvert.DecodeName(dcqname.Name) : dcqname.Name; //nameAttribute.Value = dcqname.Name; typeElement.Attributes.Append(nameAttribute); XmlAttribute nsAttribute = XmlDoc.CreateAttribute(Globals.GenericNamespaceAttribute); nsAttribute.Value = dcqname.Namespace; typeElement.Attributes.Append(nsAttribute); if (genericArguments != null) { int argIndex = 0; int nestedLevel = 0; Debug.Assert(genericArgumentCounts != null); foreach (int genericArgumentCount in genericArgumentCounts) { for (int i = 0; i < genericArgumentCount; i++, argIndex++) { XmlElement argumentElement = ExportGenericInfo(genericArguments[argIndex], Globals.GenericParameterLocalName, Globals.SerializationNamespace); if (nestedLevel > 0) { XmlAttribute nestedLevelAttribute = XmlDoc.CreateAttribute(Globals.GenericParameterNestedLevelAttribute); nestedLevelAttribute.Value = nestedLevel.ToString(CultureInfo.InvariantCulture); argumentElement.Attributes.Append(nestedLevelAttribute); } typeElement.AppendChild(argumentElement); } nestedLevel++; } if (genericArgumentCounts[nestedLevel - 1] == 0) { XmlAttribute typeNestedLevelsAttribute = XmlDoc.CreateAttribute(Globals.GenericParameterNestedLevelAttribute); typeNestedLevelsAttribute.Value = genericArgumentCounts.Count.ToString(CultureInfo.InvariantCulture); typeElement.Attributes.Append(typeNestedLevelsAttribute); } } return(typeElement); }
private int ReadOldRowData(DataSet ds, ref DataTable table, ref int pos, XmlReader row) { // read table information if (ds != null) { table = ds.Tables.GetTable(XmlConvert.DecodeName(row.LocalName), row.NamespaceURI); } else { table = GetTable(XmlConvert.DecodeName(row.LocalName), row.NamespaceURI); } if (table == null) { row.Skip(); // need to skip this element if we dont know about it, before returning -1 return(-1); } int iRowDepth = row.Depth; string value = null; if (table == null) { throw ExceptionBuilder.DiffgramMissingTable(XmlConvert.DecodeName(row.LocalName)); } value = row.GetAttribute(Keywords.ROWORDER, Keywords.MSDNS); if (!string.IsNullOrEmpty(value)) { pos = (int)Convert.ChangeType(value, typeof(int), null); } int record = table.NewRecord(); foreach (DataColumn col in table.Columns) { col[record] = DBNull.Value; } foreach (DataColumn col in table.Columns) { if ((col.ColumnMapping == MappingType.Element) || (col.ColumnMapping == MappingType.SimpleContent)) { continue; } if (col.ColumnMapping == MappingType.Hidden) { value = row.GetAttribute("hidden" + col.EncodedColumnName, Keywords.MSDNS); } else { value = row.GetAttribute(col.EncodedColumnName, col.Namespace); } if (value == null) { continue; } col[record] = col.ConvertXmlToObject(value); } row.Read(); SkipWhitespaces(row); int currentDepth = row.Depth; if (currentDepth <= iRowDepth) { // the node is empty if (currentDepth == iRowDepth && row.NodeType == XmlNodeType.EndElement) { // read past the EndElement of the current row // note: (currentDepth == iRowDepth) check is needed so we do not skip elements on parent rows. row.Read(); SkipWhitespaces(row); } return(record); } if (table.XmlText != null) { DataColumn col = table.XmlText; col[record] = col.ConvertXmlToObject(row.ReadString()); } else { while (row.Depth > iRowDepth) { string ln = XmlConvert.DecodeName(row.LocalName); string ns = row.NamespaceURI; DataColumn column = table.Columns[ln, ns]; if (column == null) { while ((row.NodeType != XmlNodeType.EndElement) && (row.LocalName != ln) && (row.NamespaceURI != ns)) { row.Read(); // consume the current node } row.Read(); // now points to the next column //SkipWhitespaces(row); seems no need, just in case if we see other issue , this will be here as hint continue; // add a read here! } if (column.IsCustomType) { // if column's type is object or column type does not implement IXmlSerializable bool isPolymorphism = (column.DataType == typeof(object) || (row.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS) != null) || (row.GetAttribute(Keywords.TYPE, Keywords.XSINS) != null)); bool skipped = false; if (column.Table.DataSet != null && column.Table.DataSet._udtIsWrapped) { row.Read(); // if UDT is wrapped, skip the wrapper skipped = true; } XmlRootAttribute xmlAttrib = null; if (!isPolymorphism && !column.ImplementsIXMLSerializable) { // THIS CHECK MAY BE IS WRONG think more // if does not implement IXLSerializable, need to go with XmlSerializer: pass XmlRootAttribute if (skipped) { xmlAttrib = new XmlRootAttribute(row.LocalName); xmlAttrib.Namespace = row.NamespaceURI; } else { xmlAttrib = new XmlRootAttribute(column.EncodedColumnName); xmlAttrib.Namespace = column.Namespace; } } // for else case xmlAttrib MUST be null column[record] = column.ConvertXmlToObject(row, xmlAttrib); // you need to pass null XmlAttib here if (skipped) { row.Read(); // if Wrapper is skipped, skip its end tag } } else { int iColumnDepth = row.Depth; row.Read(); // SkipWhitespaces(row);seems no need, just in case if we see other issue , this will be here as hint if (row.Depth > iColumnDepth) { //we are inside the column if (row.NodeType == XmlNodeType.Text || row.NodeType == XmlNodeType.Whitespace || row.NodeType == XmlNodeType.SignificantWhitespace) { string text = row.ReadString(); column[record] = column.ConvertXmlToObject(text); row.Read(); // now points to the next column } } else { // <element></element> case if (column.DataType == typeof(string)) { column[record] = string.Empty; } } } } } row.Read(); //now it should point to next row SkipWhitespaces(row); return(record); }
protected override void MeteringServiceRequestCompleted(PlayReadyMeteringReportServiceRequest meteringRequest, Exception hrCompletionStatus) { TestLogger.LogMessage("Enter MeteringAndReportResult.MeteringServiceRequestCompleted()"); if (hrCompletionStatus == null) { string strMeteringReportXml = XmlConvert.DecodeName(meteringRequest.ResponseCustomData); TestLogger.LogMessage("Metering report Xml = " + strMeteringReportXml); uint actualPlayCount = 0; bool bFound = false; if (strMeteringReportXml.Contains("meteringRecord")) { //ResponseCustomData format on server http://playready.directtaps.net string [] dataList = strMeteringReportXml.Split(' '); foreach (var data in dataList) { if (data.Contains("Play:")) { bFound = true; string strplayCount = data.Trim().Substring(5); actualPlayCount = Convert.ToUInt32(Regex.Match(strplayCount, @"\d+").Value); } } } else { //otherwise, ResponseCustomData format on server http://capprsvr05/I90playreadymain/rightsmanager.asmx XElement xElement = XElement.Parse(strMeteringReportXml); actualPlayCount = (from item in xElement.Descendants("Action") where (string)item.Attribute("Name") == "Play" select(uint) item.Attribute("Value") ).First(); bFound = true; } if (!bFound) { throw new Exception("unrecoganized meteringRequest.ResponseCustomData"); } PlayCount = actualPlayCount; if (actualPlayCount == _expectedPlayCount) { TestLogger.LogMessage("Actual PlayCount = " + actualPlayCount + " from metering processed report."); TestLogger.LogMessage("************************************ MeteringReport succeeded ****************************************"); _reportResult(true, null); } else { TestLogger.LogMessage("!!!!!!Actual PlayCount = " + actualPlayCount + "but expected = " + _expectedPlayCount); _reportResult(false, null); } } else { if (PerformEnablingActionIfRequested(hrCompletionStatus) || HandleExpectedError(hrCompletionStatus)) { TestLogger.LogMessage("Exception handled."); } else { TestLogger.LogError("MeteringServiceRequestCompleted ERROR: " + hrCompletionStatus.ToString()); _reportResult(false, null); } } TestLogger.LogMessage("Leave MeteringAndReportResult.MeteringServiceRequestCompleted()"); }
/// <summary> /// Creates collections of (groups) of items to be processed /// </summary> /// <param name="groups"></param> private void createCollections(List <IGrouping <string, XElement> > groups) { // get collection from grouped items and create Blueprint foreach (var g in groups) { blueprintDocument += $@"# Group {g.Key}\n\n"; blueprintDocument += $@"## Collection [{g.Key}]\n\n"; // iterate individual items foreach (var i in g) { var _parent = i.Parent; // method var _method = _parent.Name.ToString().ToUpper(); var _path = XmlConvert.DecodeName(i.Parent.Parent.Name.ToString()); var _summary = ((XElement)i.NextNode).Value; var _description = _parent.Element("description")?.Value.ToString(); var _parameters = _parent.Descendants("parameters").ToList(); // getting response obj reference and code // loading all definitions so that i don't have to re convert them to json since i have them already var _responseContentType = _parent.Descendants("produces").First().Value; var _responseNameSpace = XName.Get("ref", "http://james.newtonking.com/projects/json"); var _responseCode = XmlConvert.DecodeName(((XElement)_parent.Descendants("responses").First().FirstNode).Name.ToString()); string[] _responseNodeNameArray = getResponseTypeName(_parent, _responseNameSpace); var _response = i.Document.Root.Descendants(_responseNodeNameArray[0]).Descendants(_responseNodeNameArray[1]); // creating json object for either response or request use var jsonResult = createJsonFromXElement(_response); blueprintDocument += $@"### {_summary} [{_method} {_path}]\n\n"; // adding optional description if (!string.IsNullOrEmpty(_description)) { blueprintDocument += $@">{_description}\n\n"; } // building parameter list if (_parameters.Any()) { blueprintDocument += $@"+ Parameters\n"; var paramType = _parameters.First().Element("in")?.Value; foreach (var p in _parameters) { if (paramType != "body") { var _type = p.Descendants("type").First().Value; var _value = p.Descendants("name").First().Value; string _example; if (_type == "integer") { _example = "123"; } else if (_type == "bool") { _example = "false"; } else { _example = "abc"; } blueprintDocument += $@" + {_value}: {_example} ({_type})\n"; } else { blueprintDocument += $@"+ Request {_responseCode} ({_responseContentType})\n\n{jsonResult}\n\n"; } } } blueprintDocument += $@"+ Response {_responseCode} ({_responseContentType})\n\n{jsonResult}\n\n"; } } }
public static string DecodeString(string decodeStr) { return(XmlConvert.DecodeName(decodeStr)); }
public T ReadNextEntity(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: switch (this.state) { case ParserState.Start: // Assumption: // - skip the soap response tags if ((reader.LocalName == "QueryXmlResponse") || (reader.LocalName == "QueryXmlResult")) { continue; } if (string.CompareOrdinal(reader.LocalName, "queryResult") == 0) { this.state = ParserState.Root; } else { throw new InvalidOperationException("Expecting <queryResult> element but found " + reader.LocalName); } break; case ParserState.Root: if (string.CompareOrdinal(reader.LocalName, "template") == 0) { state = ParserState.Template; } else if (string.CompareOrdinal(reader.LocalName, "data") == 0) { if (entityInfo == null) { throw new InvalidOperationException("No root entity was defined in the template section"); } state = ParserState.Data; } else { throw new InvalidOperationException("Unexepected element " + reader.LocalName); } break; case ParserState.Template: if (string.CompareOrdinal(reader.LocalName, "entity") == 0) { if (entityInfo != null) { throw new InvalidOperationException("Only one root entity is supported at this time"); } StackFrame state = new StackFrame(); state.entity = new EntityInfo(reader["name"], reader["type"], bool.Parse(reader["dynamic"])); stack.Push(state); entityInfo = state.entity; this.state = ParserState.EntityTemplate; } break; case ParserState.EntityTemplate: if (string.CompareOrdinal(reader.LocalName, "property") == 0) { var name = reader["name"]; var entity = stack.Peek().entity; entity.Properties.Add(XmlConvert.DecodeName(name), new EntityPropertyInfo(name, reader["type"])); // Sometime empty elements come with an end element, adjust the statemachine state accordingly if (!reader.IsEmptyElement) { state = ParserState.PropertyTemplate; } } else if (string.CompareOrdinal(reader.LocalName, "entity") == 0) { StackFrame state = new StackFrame(); state.entity = new EntityInfo(reader["name"], reader["type"], bool.Parse(reader["dynamic"])); stack.Peek().entitySet.Entities.Add(state.entity.EntityName, state.entity); stack.Push(state); } else if (string.CompareOrdinal(reader.LocalName, "entitySet") == 0) { StackFrame state = new StackFrame(); state.entitySet = new EntitySetInfo(reader["name"]); stack.Peek().entity.EntitySets.Add(state.entitySet.Name, state.entitySet); stack.Push(state); } break; case ParserState.Data: BeginRootEntity(reader); break; case ParserState.Entity: if (stack.Peek().entity.Properties.ContainsKey(XmlConvert.DecodeName(reader.LocalName))) { BeginProperty(reader); } else if (stack.Peek().entity.EntitySets.ContainsKey(XmlConvert.DecodeName(reader.LocalName))) { BeginEntitySet(reader); } else { throw new InvalidOperationException("Don't know how to handle element " + reader.LocalName); } break; case ParserState.EntitySet: if (stack.Peek().entitySet.Entities.ContainsKey(reader.LocalName)) { BeginNestedEntity(reader); } else { throw new InvalidOperationException("Don't know how to handle element " + reader.LocalName); } break; case ParserState.ArrayProperty: if (string.CompareOrdinal(reader.LocalName, "item") == 0) { this.state = ParserState.ArrayItem; } else { throw new InvalidOperationException("Expecting <item> but encountered " + reader.LocalName); } break; case ParserState.Errors: if (string.CompareOrdinal(reader.LocalName, "errors") == 0) { state = ParserState.Error; break; } return(default(T)); case ParserState.Error: if (string.CompareOrdinal(reader.LocalName, "error") == 0) { ReadErrorMessages(reader); } break; default: break; } break; case XmlNodeType.EndElement: switch (this.state) { case ParserState.Root: ValidateEndElement(reader.LocalName, "queryResult", ParserState.Errors); break; case ParserState.Errors: if (string.CompareOrdinal(reader.LocalName, "errors") == 0) { ValidateEndElement(reader.LocalName, "errors", ParserState.Root); } return(default(T)); case ParserState.Error: if (string.CompareOrdinal(reader.LocalName, "error") == 0) { break; } ValidateEndElement(reader.LocalName, "errors", ParserState.Root); return(default(T)); case ParserState.Data: ValidateEndElement(reader.LocalName, "data", ParserState.Root); break; case ParserState.Template: ValidateEndElement(reader.LocalName, "template", ParserState.Root); break; case ParserState.EntityTemplate: if ((string.CompareOrdinal(reader.LocalName, "entity") != 0) && (string.CompareOrdinal(reader.LocalName, "entitySet") != 0)) { throw new InvalidOperationException("Expecting </entity> or </entitySet> but encountered " + reader.LocalName); } stack.Pop(); if (stack.Count == 0) { this.state = ParserState.Template; } break; case ParserState.PropertyTemplate: ValidateEndElement(reader.LocalName, "property", ParserState.EntityTemplate); break; case ParserState.Property: EndProperty(reader); break; case ParserState.ArrayProperty: EndArrayProperty(reader); break; case ParserState.ArrayItem: ValidateEndElement(reader.LocalName, "item", ParserState.ArrayProperty); break; case ParserState.Entity: if (string.CompareOrdinal(reader.LocalName, stack.Peek().elementName) != 0) { throw new InvalidOperationException(string.Format("Expecting </{0}> but encountered {1}", stack.Peek().elementName, reader.LocalName)); } if (stack.Count == 1) { return(EndRootEntity()); } else { EndNestedEntity(); } break; case ParserState.EntitySet: EndEntiySet(reader); break; default: throw new InvalidOperationException(string.Format("Not expecting element {0} while in state {1}", reader.LocalName, this.state)); } break; case XmlNodeType.Text: switch (this.state) { case ParserState.Property: ProcessPropertyValue(reader); break; case ParserState.ArrayItem: ProcessArrayPropertyItem(reader); break; } break; } } return(default(T)); }
private static string UnfixNodeName(string name) { return(name == null ? null : XmlConvert.DecodeName(name)); }
public override int GetHashCode() { return((String.Format("{0} {1}", XmlConvert.DecodeName(_localName), XmlConvert.DecodeName(_namespaceURI))).GetHashCode()); }