protected virtual void ApplyConfiguration(string endpointConfig) { if (endpointConfig == null) { return; } #if NET_2_1 try { // It should automatically use XmlXapResolver var cfg = new SilverlightClientConfigLoader().Load(XmlReader.Create("ServiceReferences.ClientConfig")); SilverlightClientConfigLoader.ServiceEndpointConfiguration se = null; if (endpointConfig == "*") { se = cfg.GetServiceEndpointConfiguration(Endpoint.Contract.Name); } if (se == null) { se = cfg.GetServiceEndpointConfiguration(endpointConfig); } if (se.Binding != null && Endpoint.Binding == null) { Endpoint.Binding = se.Binding; } else // ignore it { Console.WriteLine("WARNING: Configured binding not found in configuration {0}", endpointConfig); } if (se.Address != null && Endpoint.Address == null) { Endpoint.Address = se.Address; } else // ignore it { Console.WriteLine("WARNING: Configured endpoint address not found in configuration {0}", endpointConfig); } } catch (Exception) { // ignore it. Console.WriteLine("WARNING: failed to load endpoint configuration for {0}", endpointConfig); } #else string contractName = Endpoint.Contract.ConfigurationName; ClientSection client = ConfigUtil.ClientSection; ChannelEndpointElement endpoint = null; foreach (ChannelEndpointElement el in client.Endpoints) { if (el.Contract == contractName && (endpointConfig == el.Name || endpointConfig == "*")) { if (endpoint != null) { throw new InvalidOperationException(String.Format("More then one endpoint matching contract {0} was found.", contractName)); } endpoint = el; } } if (endpoint == null) { throw new InvalidOperationException(String.Format("Client endpoint configuration '{0}' was not found in {1} endpoints.", endpointConfig, client.Endpoints.Count)); } #if NET_4_0 var binding = String.IsNullOrEmpty(endpoint.Binding) ? null : ConfigUtil.CreateBinding(endpoint.Binding, endpoint.BindingConfiguration); var contractType = ConfigUtil.GetTypeFromConfigString(endpoint.Contract, NamedConfigCategory.Contract); if (contractType == null) { throw new ArgumentException(String.Format("Contract '{0}' was not found", endpoint.Contract)); } var contract = String.IsNullOrEmpty(endpoint.Contract) ? Endpoint.Contract : ContractDescription.GetContract(contractType); if (!String.IsNullOrEmpty(endpoint.Kind)) { var se = ConfigUtil.ConfigureStandardEndpoint(contract, endpoint); if (se.Binding == null) { se.Binding = binding; } if (se.Address == null && se.Binding != null) // standard endpoint might have empty address { se.Address = new EndpointAddress(endpoint.Address); } if (se.Binding == null && se.Address != null) // look for protocol mapping { se.Binding = ConfigUtil.GetBindingByProtocolMapping(se.Address.Uri); } service_endpoint = se; } else { if (binding == null && endpoint.Address != null) // look for protocol mapping { Endpoint.Binding = ConfigUtil.GetBindingByProtocolMapping(endpoint.Address); } } #endif if (Endpoint.Binding == null) { Endpoint.Binding = ConfigUtil.CreateBinding(endpoint.Binding, endpoint.BindingConfiguration); } if (Endpoint.Address == null) { Endpoint.Address = new EndpointAddress(endpoint.Address); } if (endpoint.BehaviorConfiguration != "") { ApplyBehavior(endpoint.BehaviorConfiguration); } #endif }
/// <summary> /// Parses the DAV result. /// Note that it will only parse if the server status was 207. /// There maybe error outputs on 4xx and 5xx but this will not parsed /// by this class. /// </summary> /// <param name="request"></param> /// <param name="response"></param> /// <param name="uri"></param> public DAVRequestResult(WebDAV request, HttpWebResponse response, Uri uri) { Request = request; Items = new List <Item>(); Status = (ServerStatus)Enum.Parse(typeof(ServerStatus), response.StatusCode.ToString(), false); StatusText = response.StatusDescription; IsMultiState = Status == ServerStatus.MultiStatus; _stream = new MemoryStream(); response.GetResponseStream().CopyTo(_stream); // dispose response.Dispose(); _stream.Seek(0, SeekOrigin.Begin); if (_stream.Length == 0) { return; } // A kingdom for normal DOMDocument support. // Why not XDocument? XmlReader is faster and less resource hungry. // A huge multitstatus would be first loaded to memory completely. // // This reader can only go forward. Read-* methods will cause // to jump over elements. Hence we stop at the element and // store the element name. Then wait for Text-Elements value // to capture. using (XmlReader reader = XmlReader.Create(_stream, null)) { Item item = new Item(); var waitForResourceType = false; var lastElementName = ""; var waitForLockScope = false; var waitForLockType = false; List <DAVLocking> lockingList = null; List <PropertyState> propertyStateList = null; PropertyState pItem = null; DAVLocking litem = null; while (reader.Read()) { switch (reader.NodeType) { // look for special elements case XmlNodeType.Element: if (reader.NamespaceURI == XmlNamespaces.NsDav) { switch (reader.LocalName) { // DAV Elements // Response case Elements.Response: // start a new item // pItem must be set before d:prop in order to // catch non-real properties such "href" item = new Item(); propertyStateList = new List <PropertyState>(); pItem = new PropertyState(); break; // Resource type case Elements.Collection: if (waitForResourceType) { item.ResourceType = ResourceType.Collection; } break; // Lock case Elements.LockEntry: litem = new DAVLocking(); lockingList.Add(litem); break; case Elements.LockScope: waitForLockScope = true; break; case Elements.LockType: waitForLockType = true; break; case Elements.ExclusiveLocking: if (waitForLockScope) { litem.Scope = DAVLocking.LockScope.Exclusive; } break; case Elements.SharedLocking: if (waitForLockScope) { litem.Scope = DAVLocking.LockScope.Shared; } break; case Elements.WriteLocking: if (waitForLockType) { litem.Type = DAVLocking.LockType.Write; } break; case Elements.LockDiscovery: ///TODO break; // DAV Properties case Elements.Properties: // a pItem was already created before break; case Properties.ResourceType: waitForResourceType = true; break; case Properties.SupportedLock: lockingList = new List <DAVLocking>(); break; default: lastElementName = reader.LocalName; break; } } break; // clean up case XmlNodeType.EndElement: if (reader.NamespaceURI == XmlNamespaces.NsDav) { switch (reader.LocalName) { // DAV Elements case Elements.PropertyState: // save to list and create a new one (which stays maybe temporary) propertyStateList.Add(pItem); pItem = new PropertyState(); break; case Elements.Response: // clean the list // the HTTP Status is important foreach (PropertyState state in propertyStateList) { if (state.Status == ServerStatus.OK) { item.Properties = state.Properties; } else { item.FailedProperties.Add(state); } } // Close the item Items.Add(item); item = null; // Reset the property state list propertyStateList = null; pItem = null; break; // Locking case Elements.LockType: waitForLockType = false; break; case Elements.LockScope: waitForLockScope = false; break; // DAV Properties case Properties.ResourceType: waitForResourceType = false; break; case Properties.SupportedLock: item.Locking = lockingList; break; } } break; // Grap the text values case XmlNodeType.Text: // no whitespace please if (reader.Value == null) { continue; } // can't set in empty element if (item == null) { continue; } switch (lastElementName) { // DAV Elements case Elements.Reference: string _ref = Uri.UnescapeDataString(reader.Value); pItem.Properties.Add(lastElementName, _ref); pItem.Properties.Add(lastElementName + ".local", _ref.Trim('/').Split('/').Last()); break; // Status element case Elements.Status: List <string> s = new List <string>(reader.Value.Split(' ')); s.RemoveAt(0); pItem.Status = (ServerStatus)Enum.Parse(typeof(ServerStatus), s[0], false); s.RemoveAt(0); pItem.ServerStatusText = String.Join(" ", s.ToArray()); break; // DAV Properties case Properties.QuotaUsedBytes: case Properties.QuotaAvailableBytes: case Properties.GetContentLength: pItem.Properties.Add(lastElementName, long.Parse(reader.Value)); break; case Properties.DisplayName: case Properties.GetContentLanguage: case Properties.GetContentType: case Properties.GetETag: pItem.Properties.Add(lastElementName, reader.Value); break; case Properties.GetLastModified: case Properties.CreationDate: pItem.Properties.Add(lastElementName, DateTime.Parse(reader.Value)); break; } lastElementName = ""; break; } } } }
public override void Init(XElement xconfig) { this.xconfig = xconfig; // Множество кассет cassettesToLoad = xconfig.Elements("LoadCassette") .Select(lc => { string path = lc.Value; XAttribute wr_att = lc.Attribute("write"); return(new CassInfo() { name = path.Split('/', '\\').Last(), path = path, writable = (wr_att != null && wr_att.Value == "yes") }); }) .ToArray(); XmlReaderSettings settings = new XmlReaderSettings(); // Множество фог-документов, находящихся в кассетах fogs = cassettesToLoad .SelectMany(cass => { var fogs_inoriginals = Directory.GetDirectories(cass.path + "/originals") .SelectMany(d => Directory.GetFiles(d, "*.fog")).ToArray(); return(Enumerable.Repeat(cass.path + "/meta/" + cass.name + "_current.fog", 1) .Concat(fogs_inoriginals) .Select(pth => { string owner = null; string prefix = null; string counter = null; using (XmlReader reader = XmlReader.Create(pth, settings)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name != "rdf:RDF") { throw new Exception($"Err: Name={reader.Name}"); } owner = reader.GetAttribute("owner"); prefix = reader.GetAttribute("prefix"); counter = reader.GetAttribute("counter"); break; } } } return new FogInfo() { cassette = cass, pth = pth, owner = owner, prefix = prefix, counter = counter, editable = cass.writable && prefix != null && counter == null }; }) ); }) .ToArray(); }
/// <summary> /// Item1 = name. Item2 = directory. /// </summary> /// <param name="templateID"></param> /// <returns></returns> public static Tuple <string, string> GetTemplateById(string templateID) { string strFileName = string.Empty; string strFolderName = string.Empty; List <Template> retList = new List <Template>(); DirectoryInfo directoryInfo = new DirectoryInfo( Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Program.Model.Settings.TemplateDirectory)); if (directoryInfo.Exists) { try { var serializer = new XmlSerializer(typeof(Template)); var files = directoryInfo.GetFiles("*.xml"); foreach (FileInfo file in files) { try { var doc = new XmlDocument(); doc.Load(file.FullName); if (AppVersionHelper.IsNotDebug()) { var cryptoProcessor = new CryptoProcessor( Program.Model.Settings.SystemSettings.PublicKeyXmlSign, Program.Model.Settings.SystemSettings.PrivateKeyXmlDecrypt); cryptoProcessor.DecryptXmlDocument(doc); } // // #248 - fix memory leaks during XML files processing // // var nodeReader = new XmlNodeReader(doc); using (var nodeReader = new XmlNodeReader(doc)) { using (var xmlReader = XmlReader.Create(nodeReader, XmlUtils.GetXmlReaderSettings())) { var template = (Template)serializer.Deserialize(xmlReader); if (templateID == template.Id) { strFileName = file.Name; strFolderName = file.DirectoryName; } } } } catch (Exception ex) { log.Error(ex); if (file != null) { log.ErrorFormat("File:'{0}'", file); } log.ErrorFormat("Folder:'{0}'", directoryInfo); } } } catch (Exception ex) { log.Error(ex); log.ErrorFormat("Folder:'{0}'", directoryInfo); } } else { log.Error("Folder with models is not exists"); log.ErrorFormat("Folder:'{0}'", directoryInfo); } return(new Tuple <string, string>(strFileName, strFolderName)); }
static EditorSettings Load() { var settings = new EditorSettings(); if (File.Exists(SettingsPath)) { try { using (var reader = XmlReader.Create(SettingsPath)) { reader.MoveToContent(); while (reader.Read()) { if (reader.NodeType != XmlNodeType.Element) { continue; } if (reader.Name == WindowStateElement) { FormWindowState windowState; Enum.TryParse <FormWindowState>(reader.ReadElementContentAsString(), out windowState); settings.WindowState = windowState; } else if (reader.Name == EditorThemeElement) { ColorTheme editorTheme; Enum.TryParse <ColorTheme>(reader.ReadElementContentAsString(), out editorTheme); settings.EditorTheme = editorTheme; } else if (reader.Name == DesktopBoundsElement) { int x, y, width, height; reader.ReadToFollowing(RectangleXElement); int.TryParse(reader.ReadElementContentAsString(), out x); reader.ReadToFollowing(RectangleYElement); int.TryParse(reader.ReadElementContentAsString(), out y); reader.ReadToFollowing(RectangleWidthElement); int.TryParse(reader.ReadElementContentAsString(), out width); reader.ReadToFollowing(RectangleHeightElement); int.TryParse(reader.ReadElementContentAsString(), out height); settings.DesktopBounds = new Rectangle(x, y, width, height); } else if (reader.Name == RecentlyUsedFilesElement) { var fileReader = reader.ReadSubtree(); while (fileReader.ReadToFollowing(RecentlyUsedFileElement)) { if (fileReader.Name == RecentlyUsedFileElement) { string fileName; DateTimeOffset timestamp; fileReader.ReadToFollowing(FileTimestampElement); DateTimeOffset.TryParse(fileReader.ReadElementContentAsString(), out timestamp); fileReader.ReadToFollowing(FileNameElement); fileName = fileReader.ReadElementContentAsString(); settings.recentlyUsedFiles.Add(timestamp, fileName); } } } } } } catch (XmlException) { } } return(settings); }
static void Main(string[] args) { Console.WriteLine("Loading XML input file: " + XML_INPUT_FILE_PATH); // create a list which will hold our command classes' name/value enumeration pairs SortedDictionary <string, byte> commandClassEnumDictionary = new SortedDictionary <string, byte>(); // create a dictionary which will keep track of the latest version number of each command class enum (with the enum value as the key...to eliminate class "renaming" issues) Dictionary <byte, byte> commandClassNewestVersionLookup = new Dictionary <byte, byte>(); // // create a sorted dictionary of commands for each command class (storing only the entries for the latest command class version--which should be a superset of earlier versions) SortedDictionary <string, List <KeyValuePair <string, byte> > > commandClassEnumerations = new SortedDictionary <string, List <KeyValuePair <string, byte> > >(); /*** STEP 1 (FRONT END): READ COMMAND CLASSES AND THEIR COMMANDS FROM XML FILE ***/ FileStream fileStream = null; try { fileStream = new FileStream(XML_INPUT_FILE_PATH, FileMode.Open); } catch (Exception ex) { Console.WriteLine("Could not open file: " + XML_INPUT_FILE_PATH); Console.WriteLine("exception: " + ex.Message); return; } try { XmlReader reader = XmlReader.Create(fileStream); try { while (reader.ReadToFollowing("cmd_class")) { // make sure we are at depth (level) 1 (i.e. reading the correct "cmd_class" entries) if (reader.Depth != 1) { // invalid depth; skip this entry continue; } // retrieve command class name, key (command class #) and version string commandClassName = reader.GetAttribute("name"); string commandClassEnumValueAsString = reader.GetAttribute("key"); string commandClassVersionAsString = reader.GetAttribute("version"); // validate entries if (commandClassName == null) { // command class name missing; skip this entry continue; } if (commandClassEnumValueAsString == null || commandClassEnumValueAsString.Length < 3 || commandClassEnumValueAsString.Substring(0, 2).ToLowerInvariant() != "0x") { // enum value (command class number) missing; skip this entry continue; } if (commandClassVersionAsString == null) { // command class version missing; skip this entry continue; } // try to parse the command class's enumeration value and version byte commandClassEnumValue; byte commandClassVersion; if (!byte.TryParse(commandClassEnumValueAsString.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out commandClassEnumValue)) { // enum value (command class number) invalid; skip this entry continue; } if (!byte.TryParse(commandClassVersionAsString, NumberStyles.Number, CultureInfo.InvariantCulture, out commandClassVersion)) { // command class version invalid; skip this entry continue; } // shorten the command class name string commandClassShortName = ExtractShortCommandClassNameFromLongCommandClassName(commandClassName); if (commandClassShortName == null) { // command class name invalid; skip this entry continue; } // determine the command class name formatting: either as-is (in languages like Java with UPPER_CASE_CONSTANTS) or in special casing (for languages like JavaScript) string commandClassEnumName = null; switch (OUTPUT_LANGUAGE) { case OutputLanguage.Java: { // create a non-ambiguous reference variable for the shortened command class name commandClassEnumName = commandClassShortName; // verify that the shortened command name can be converted to UpperCamelCase (since this will be required during the source file writing phase) if (ConvertUpperCaseUnderscoreSeparatedToUpperCamelCase(commandClassShortName) == null) { // command class name invalid; skip this entry continue; } } break; case OutputLanguage.JavaScript: { // conver the shortened command class name to UpperCamelCase and store it in the "enum name" reference commandClassEnumName = ConvertUpperCaseUnderscoreSeparatedToUpperCamelCase(commandClassShortName); } break; default: throw new Exception("Output language not supported."); } // if (commandClassEnumName == null) { // command class name invalid; skip this entry continue; } // get the newest already-stored version of the command class, if it was already added to our enumeration // NOTE: we do this immediately before adding the command class and initial version to the list, so that we don't capture the just-added version // NOTE: we look up version #s based on the class's enum value--instead of the class's name--because command class names can change over time byte?newestVersion = null; if (commandClassNewestVersionLookup.ContainsKey(commandClassEnumValue)) { newestVersion = commandClassNewestVersionLookup[commandClassEnumValue]; } // // if an earlier version of the command class already exists, remove it now if (newestVersion != null && newestVersion < commandClassVersion) { // find the class name of the previously-stored command class string oldCommandClassKey = null; // int commandClassKeysCount = commandClassEnumDictionary.Count; string[] commandClassKeys = new string[commandClassKeysCount]; commandClassEnumDictionary.Keys.CopyTo(commandClassKeys, 0); // for (int iCommandClass = 0; iCommandClass < commandClassKeysCount; iCommandClass++) { if (commandClassEnumDictionary[commandClassKeys[iCommandClass]] == commandClassEnumValue) { oldCommandClassKey = commandClassKeys[iCommandClass]; } } // remove the version of the previously-stored command class from our version lookup dictionary commandClassNewestVersionLookup.Remove(commandClassEnumValue); // // remove the older command class from the "command class enum" dictionary if (commandClassEnumDictionary.ContainsKey(oldCommandClassKey)) { commandClassEnumDictionary.Remove(oldCommandClassKey); } // // remove the older command class from the "command enums for each command class" dictionary if (commandClassEnumerations.ContainsKey(oldCommandClassKey)) { commandClassEnumerations.Remove(oldCommandClassKey); } } // if our current data is either a new command class or a newer version of an already-stored command class, add it now if (newestVersion == null || newestVersion < commandClassVersion) { // add the command class to our "command class enum" commandClassEnumDictionary.Add(commandClassEnumName, commandClassEnumValue); // // and also add the corresponding version lookup entry commandClassNewestVersionLookup.Add(commandClassEnumValue, commandClassVersion); // now, create an enumeration for the command class's commands (derived from the command class xml node's inner xml) string commandClassCommandsEnumName = commandClassEnumName + "Command"; List <KeyValuePair <string, byte> > commandEnumPairs = ParseXmlForCommandClassCommands(commandClassShortName, reader.ReadOuterXml(), OUTPUT_LANGUAGE); // add the command class's command enumeration values commandClassEnumerations.Add(commandClassEnumName, commandEnumPairs); } } } finally { reader.Dispose(); } Console.WriteLine("Done reading input file."); } finally { fileStream.Dispose(); } /*** STEP 2 (BACK END): WRITE COMMAND CLASSES AND COMMANDS AS ENUMERATIONS TO SOURCE FILES ***/ // clear out the output directory foreach (var fileToDelete in Directory.EnumerateFiles(OUTPUT_DIRECTORY_PATH)) { Console.WriteLine("Deleting old output file: " + fileToDelete); File.Delete(fileToDelete); } // generate the new output files switch (OUTPUT_LANGUAGE) { case OutputLanguage.Java: // generate Java enum source files GenerateJavaEnumFiles(OUTPUT_DIRECTORY_PATH, commandClassEnumDictionary, commandClassEnumerations, commandClassNewestVersionLookup); break; case OutputLanguage.JavaScript: // generate JavaScript enum source files GenerateJavaScriptEnumFiles(OUTPUT_DIRECTORY_PATH, commandClassEnumDictionary, commandClassEnumerations, commandClassNewestVersionLookup); break; default: throw new NotSupportedException(); } }
private static Task CheckForNewPodcast(Podcast podcast) { return(Task.Run(async() => { try { using (var xmlReader = XmlReader.Create(podcast.RssUrl, new XmlReaderSettings() { Async = true })) { var feedReader = new RssFeedReader(xmlReader); ISyndicationItem newestItem = null; bool foundItem = false; while (await feedReader.Read() && foundItem == false) { switch (feedReader.ElementType) { // Read Item case SyndicationElementType.Item: newestItem = await feedReader.ReadItem(); foundItem = true; break; } } if (newestItem == null) { throw new Exception($"Could not find newest item for podcast {podcast.RssUrl}"); } Uri downloadUri = newestItem.Links.FirstOrDefault(x => x.RelationshipType == "enclosure")?.Uri ?? null; if (downloadUri == null) { throw new Exception($"Could not find newest item enclosure for podcast {podcast.RssUrl}"); } CreateDirIfNotExist(_podcastConfig.DownloadFolder); CreateDirIfNotExist(Path.Combine(_podcastConfig.DownloadFolder, podcast.DownloadSubFolder)); string lastDlLog = Path.Combine(_podcastConfig.DownloadFolder, podcast.DownloadSubFolder, _podcastConfig.LastDownloadedFileName); string[] lastItems = File.Exists(lastDlLog) ? File.ReadAllLines(lastDlLog) : new string[] { }; string downloadFolder = Path.Combine(_podcastConfig.DownloadFolder, podcast.DownloadSubFolder); // **** Download newest podcast if (lastItems.Length == 0 || lastItems.First() != newestItem.Title) { await DownloadAsync(downloadUri, downloadFolder); if (lastItems == null || lastItems.Length == 0) { lastItems = new string[1]; } lastItems[0] = newestItem.Title; File.WriteAllLines(lastDlLog, lastItems); } } } catch (Exception ex) { _logger.Error(ex, $"Error downloading newest podcast for {podcast.RssUrl}"); } })); }
public static Profile ReadXml(Stream inputStream) { if (null == inputStream) { throw new ArgumentNullException("inputStream"); } Guid id = Guid.Empty; string name = null; int generation = 0; Guid?parentA = null; Guid?parentB = null; int eloRating = EloUtils.DefaultRating; int wins = 0; int losses = 0; int draws = 0; MetricWeights startMetricWeights = null; MetricWeights endMetricWeights = null; DateTime creationTimestamp = DateTime.Now; DateTime lastUpdateTimestamp = creationTimestamp; using (XmlReader reader = XmlReader.Create(inputStream)) { while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Id": id = Guid.Parse(reader.ReadElementContentAsString()); break; case "Name": name = reader.ReadElementContentAsString(); break; case "Generation": generation = reader.ReadElementContentAsInt(); break; case "ParentA": parentA = Guid.Parse(reader.ReadElementContentAsString()); break; case "ParentB": parentB = Guid.Parse(reader.ReadElementContentAsString()); break; case "EloRating": eloRating = reader.ReadElementContentAsInt(); break; case "Wins": wins = reader.ReadElementContentAsInt(); break; case "Losses": losses = reader.ReadElementContentAsInt(); break; case "Draws": draws = reader.ReadElementContentAsInt(); break; case "Creation": creationTimestamp = reader.ReadElementContentAsDateTime(); break; case "LastUpdated": lastUpdateTimestamp = reader.ReadElementContentAsDateTime(); break; case "MetricWeights": case "StartMetricWeights": startMetricWeights = MetricWeights.ReadMetricWeightsXml(reader.ReadSubtree()); break; case "EndMetricWeights": endMetricWeights = MetricWeights.ReadMetricWeightsXml(reader.ReadSubtree()); break; } } } } return(new Profile(id, name ?? GenerateName(id), generation, parentA, parentB, eloRating, wins, losses, draws, startMetricWeights, endMetricWeights ?? startMetricWeights, creationTimestamp, lastUpdateTimestamp)); }
public MainWindow() { InitializeComponent(); using (XmlReader reader = XmlReader.Create("Address.xml")) { String name = ""; String number = ""; String status = ""; while (reader.Read()) { /* Element들의 구조가 * Addresses - Address - Name * - Number * (- size of number list) * (- number list) * 이런 구조로 되어있으므로 * 현재 Element가 status에 뭔지 구분해서 * 각 알맞는 것에 추가한 후 * Address로 만들어서 AddressBook에 추가 * * xml이라서 유니코드도 지원하고 * C#에서 다른 언어 섞여있어도 잘 정렬해준다 */ switch (reader.NodeType) { case XmlNodeType.Element: status = reader.Name; break; case XmlNodeType.Text: if (status == "Name") { name = reader.Value; } else if (status == "Number") { number = reader.Value; } break; case XmlNodeType.EndElement: if (reader.Name == "Address") { AddressBook.Add(new Address(name, number)); } break; default: break; } } } using (XmlReader reader = XmlReader.Create("Call.xml")) { String time = ""; String number = ""; String state = ""; String status = ""; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: status = reader.Name; break; case XmlNodeType.Text: if (status == "Time") { time = reader.Value; } else if (status == "Number") { number = reader.Value; } else if (status == "State") { state = reader.Value; } break; case XmlNodeType.EndElement: if (reader.Name == "Call") { CallBook.Add(new Call(time, number, state)); } break; default: break; } } } RefreshCallBookList(); RefreshListView(); }
public void InvalidNamespaceErrorReport() { string content = @" <msb:Project xmlns:msb=`http://schemas.microsoft.com/developer/msbuild/2003`> <msb:Target Name=`t`> <msb:Message Text=`[t]`/> </msb:Target> </msb:Project> "; content = content.Replace("`", "\""); MockLogger logger = new MockLogger(); string errorMessage = String.Empty; bool exceptionThrown = false; try { Microsoft.Build.Evaluation.Project project = new Microsoft.Build.Evaluation.Project(XmlReader.Create(new StringReader(content))); } catch (InvalidProjectFileException ex) { exceptionThrown = true; // MSB4068: The element <msb:Project> is unrecognized, or not supported in this context. Assert.NotEqual(ex.ErrorCode, "MSB4068"); // MSB4041: The default XML namespace of the project must be the MSBuild XML namespace. Assert.Equal("MSB4041", ex.ErrorCode); } Assert.True(exceptionThrown); // "ERROR: An invalid project file exception should have been thrown." }
public void LoadAllFromXML() { //instantiate a reader XmlReader reader = XmlReader.Create(storageFile); E element = (E)Activator.CreateInstance(GetTypeForGenericE()); PropertyInfo property; //get generic class and type String className = GetNameForGenericE(); Type classType = GetTypeForGenericE(); //while the reader can read while (reader.Read()) { //depending on the node type, we switch to other things //a switch is nice here if we decide to deal with more //than Element and EndElement switch (reader.NodeType) { //in case we find an element case XmlNodeType.Element: String readerName = reader.Name; //create a new element to be added to //when it passes an object node with //the class name if (readerName == className) { element = (E)Activator.CreateInstance(classType); } else { //get the property read from the element via reflection property = classType.GetProperty(readerName); //if the property is valid //get the value, convert it to proper type //and store it into the element if (property != null) { String rawValue = reader.ReadString(); object value = Convert.ChangeType(rawValue, property.PropertyType); if (property.CanWrite) { property.SetValue(element, value); } } } break; case XmlNodeType.EndElement: //if we finished reading the element //we add it to the repo if (reader.Name == className) { entities.Add(element); } break; } //end switch } //end reader while reader.Close(); // logger.LogWarning("All loaded", "LoadAllFromXML"); }
/// <summary> /// This is used to transform a *.topic file into a *.html file using /// an XSLT transformation based on the presentation style. /// </summary> /// <param name="sourceFile">The source topic filename</param> private void XslTransform(string sourceFile) { TocEntry tocInfo; XmlReader reader = null; XmlWriter writer = null; XsltSettings settings; XmlReaderSettings readerSettings; XmlWriterSettings writerSettings; Encoding enc = Encoding.Default; FileItemCollection transforms; string content; string sourceStylesheet, destFile = Path.ChangeExtension(sourceFile, ".html"); try { readerSettings = new XmlReaderSettings(); readerSettings.ProhibitDtd = false; readerSettings.CloseInput = true; // Create the transform on first use if (xslTransform == null) { transforms = new FileItemCollection(project, BuildAction.TopicTransform); if (transforms.Count != 0) { if (transforms.Count > 1) { this.ReportWarning("BE0011", "Multiple topic " + "transformations found. Using '{0}'", transforms[0].FullPath); } sourceStylesheet = transforms[0].FullPath; } else { sourceStylesheet = templateFolder + presentationParam + ".xsl"; } xslStylesheet = workingFolder + Path.GetFileName(sourceStylesheet); tocInfo = BuildProcess.GetTocInfo(sourceStylesheet); // The stylesheet may contain shared content items so we // must resolve it this way rather than using // TransformTemplate. this.ResolveLinksAndCopy(sourceStylesheet, xslStylesheet, tocInfo); xslTransform = new XslCompiledTransform(); settings = new XsltSettings(true, true); xslArguments = new XsltArgumentList(); xslTransform.Load(XmlReader.Create(xslStylesheet, readerSettings), settings, new XmlUrlResolver()); } this.ReportProgress("Applying XSL transformation '{0}' to '{1}'.", xslStylesheet, sourceFile); reader = XmlReader.Create(sourceFile, readerSettings); writerSettings = xslTransform.OutputSettings.Clone(); writerSettings.CloseOutput = true; writerSettings.Indent = false; writer = XmlWriter.Create(destFile, writerSettings); xslArguments.Clear(); xslArguments.AddParam("pathToRoot", String.Empty, pathToRoot); xslTransform.Transform(reader, xslArguments, writer); } catch (Exception ex) { throw new BuilderException("BE0017", String.Format( CultureInfo.InvariantCulture, "Unexpected error " + "using '{0}' to transform additional content file '{1}' " + "to '{2}'. The error is: {3}\r\n{4}", xslStylesheet, sourceFile, destFile, ex.Message, (ex.InnerException == null) ? String.Empty : ex.InnerException.Message)); } finally { if (reader != null) { reader.Close(); } if (writer != null) { writer.Flush(); writer.Close(); } } // The source topic file is deleted as the transformed file // takes its place. File.Delete(sourceFile); // <span> and <script> tags cannot be self-closing if empty. // The template may contain them correctly but when written out // as XML, they get converted to self-closing tags which breaks // them. To fix them, convert them to full start and close tags. content = BuildProcess.ReadWithEncoding(destFile, ref enc); content = reSpanScript.Replace(content, "<$1$2></$1>"); // An XSL transform might have added tags and include items that // need replacing so run it through those options if needed. tocInfo = BuildProcess.GetTocInfo(destFile); // Expand <code> tags if necessary if (tocInfo.HasCodeBlocks) { content = reCodeBlock.Replace(content, codeBlockMatchEval); } // Colorize <pre> tags if necessary if (tocInfo.NeedsColorizing || tocInfo.HasCodeBlocks) { // Initialize code colorizer on first use if (codeColorizer == null) { codeColorizer = new CodeColorizer(shfbFolder + @"Colorizer\highlight.xml", shfbFolder + @"Colorizer\highlight.xsl"); } // Set the path the "Copy" image codeColorizer.CopyImageUrl = pathToRoot + "icons/CopyCode.gif"; // Colorize it and replace the "Copy" literal text with the // shared content include item so that it gets localized. content = codeColorizer.ProcessAndHighlightText(content); content = content.Replace(codeColorizer.CopyText + "</span", "<include item=\"copyCode\"/></span"); tocInfo.HasProjectTags = true; } // Use a regular expression to find and replace all tags with // cref attributes with a link to the help file content. This // needs to happen after the code block processing as they // may contain <see> tags that need to be resolved. if (tocInfo.HasLinks || tocInfo.HasCodeBlocks) { content = reResolveLinks.Replace(content, linkMatchEval); } // Replace project option tags with project option values if (tocInfo.HasProjectTags) { // Project tags can be nested while (reProjectTags.IsMatch(content)) { content = reProjectTags.Replace(content, fieldMatchEval); } // Shared content items can be nested while (reSharedContent.IsMatch(content)) { content = reSharedContent.Replace(content, contentMatchEval); } } // Write the file back out with the appropriate encoding using (StreamWriter sw = new StreamWriter(destFile, false, enc)) { sw.Write(content); } }
private void Button_CreateEntry(object sender, RoutedEventArgs e) { String project, mrNumber, titel, samplePhase, swRelease; List <Statement> statementList = null; List <String> CBBList = null; List <Measure> messureList = null; if (String.IsNullOrEmpty(CBProject.SelectedItem as String)) { MessageBox.Show("Please choose a Project"); return; } else { project = CBProject.SelectedItem as String; } if (String.IsNullOrEmpty(TBMRNumber.Text)) { MessageBox.Show("MR Number is missing"); return; } else { mrNumber = TBMRNumber.Text; } if (String.IsNullOrEmpty(TBTitel.Text)) { MessageBox.Show("Titel is missing"); return; } else { titel = TBTitel.Text; } if (String.IsNullOrEmpty(CBSamplePhase.SelectedItem as String)) { MessageBox.Show("Please choose a Sample Phase"); return; } else { samplePhase = CBSamplePhase.SelectedItem as String; } if (String.IsNullOrEmpty(CBSWRelease.SelectedItem as String)) { MessageBox.Show("Please choose a SW Release"); return; } else { swRelease = CBSWRelease.SelectedItem as String; } if (GridStellungnehmer.RowDefinitions.Count <= 1) { MessageBox.Show("Stellungnehmer fehlen"); return; } else { statementList = new List <Statement>(); for (int i = 2; i < GridStellungnehmer.Children.Count; i++) { statementList.Add(new Statement("symbol-question", (GridStellungnehmer.Children[i] as ListItem).GetName())); } } if (GridCCB.RowDefinitions.Count > 2) { CBBList = new List <string>(); for (int i = 2; i < GridCCB.Children.Count; i++) { CBBList.Add((GridCCB.Children[i] as ListItem).GetName()); } } if (GridMeasure.RowDefinitions.Count > 2) { messureList = new List <Measure>(); for (int i = 2; i < GridMeasure.Children.Count; i++) { messureList.Add(new Measure("symbol-question", (GridMeasure.Children[i] as ListItem).GetName())); } } ZipFile.ExtractToDirectory(@"C:\Projekte\XMindHelper\Beispiel\ICBWMDL.xmind", @"C:\Projekte\XMindHelper\Beispiel\extracted\"); XElement x = null; using (var reader = XmlReader.Create(@"C:\Projekte\XMindHelper\Beispiel\extracted\content.xml")) { XDocument doc = XDocument.Load(reader); XMap_Content xml = XMap_Content.ParseXmlNode(doc.Root); XNamespace ns = "urn:xmind:xmap:xmlns:content:2.0"; x = XMap_Content.CreateXmlNode(ns, xml); var target = doc.Root.Elements(); //Create MR ModificationRequest request = new ModificationRequest(titel, UInt16.Parse(mrNumber), "", statementList, messureList); //MR Muss nun in den aktuellen Baum eingehangen werden XElement projectNode = x.Descendants(ns + Constants.TITLE).Where(ee => ee.Value == project).FirstOrDefault(); if (projectNode == null) { //Knoten erzeugen der das Projekt beinhaltet, weil es bisher noch nicht benutzt wurde Topic projectTopic = new Topic(project); //MR Knoten erzeugen um dem Projekt zuordnen projectTopic.AddSubTopicToAttached(request.CreateMR()); //Implementierungsknoten suchen XElement implementNode = x.Descendants(ns + Constants.TITLE).Where(ee => ee.Value == "Implementierung").FirstOrDefault(); Topic implement = Topic.ParseXmlNode(implementNode.Parent); //Project nun dem Knoten der Implementierung hinzufügen implement.AddSubTopicToAttached(projectTopic); //aktullen Implementierungsknoten mit dem neuen ersetzen implementNode.Parent.ReplaceWith(Topic.CreateXmlNode(ns, implement)); } else { //Projekt ist schon vorhanden wir brauchen ihn nur in ein Topic zu parsen Topic projectTopic = Topic.ParseXmlNode(projectNode.Parent); //MR Knoten erzeungen und dem Projekt hinzufügen projectTopic.AddSubTopicToAttached(request.CreateMR()); //Alten Projektknoten mit dem neuen ersetzen projectNode.Parent.ReplaceWith(Topic.CreateXmlNode(ns, projectTopic)); } } x.Save(@"C:\Projekte\XMindHelper\Beispiel\extracted\content.xml"); File.Delete(@"C:\Projekte\XMindHelper\Beispiel\ICBWMDL.xmind"); ZipFile.CreateFromDirectory(@"C:\Projekte\XMindHelper\Beispiel\extracted\", @"C:\Projekte\XMindHelper\Beispiel\ICBWMDL.xmind"); Directory.Delete(@"C:\Projekte\XMindHelper\Beispiel\extracted\", true); }
/// <summary> /// Helper method that reads an input XML file and tries to construct /// a new spreadsheet from the it. /// </summary> /// <param name="filename"></param> private void LoadSpreadsheet(string filepath) { XmlReaderSettings readerSettings = new XmlReaderSettings { IgnoreWhitespace = true }; try { using (XmlReader reader = XmlReader.Create(filepath, readerSettings)) { //reading the auto-generated XML header reader.Read(); //first element will always be spreadhseet since previous checks in constructor/GetSavedVersion already checked reader.Read(); while (reader.Read()) { //stop reading if closing spreadsheet tag is reached if (reader.Name == "spreadsheet" && reader.NodeType == XmlNodeType.EndElement) { break; } string name; string contents; if (reader.Name == "cell") { //this should read in the cell's name reader.Read(); if (reader.Name == "name") { name = reader.ReadElementContentAsString(); //this should read in cell's contents if (reader.Name == "contents") { contents = reader.ReadElementContentAsString(); } else { throw new SpreadsheetReadWriteException("XML file's cell element did not have contents!"); } } else { throw new SpreadsheetReadWriteException("XML file's cell element did not have a name!"); } } else { throw new SpreadsheetReadWriteException("XML file contained an element other than a cell!"); } //checks for closing tag of cell if (reader.Name != "cell" || reader.NodeType != XmlNodeType.EndElement) { throw new SpreadsheetReadWriteException("XML file contained cell element without closing tag!"); } //loads each cell element LoadCell(name, contents); } } } catch (Exception e) { throw new SpreadsheetReadWriteException(e.Message); } // Set changed to false since nothing was truly changed. Changed = false; }
public static void Load() { objectIcons = new Dictionary <string, List <Tuple <string, Texture2D> > >(); Texture2D defaultSprite = Resources.Load <Texture2D>("Sprites/default"); List <Tuple <string, Texture2D> > defaultSpriteDictionary = new List <Tuple <string, Texture2D> >(); defaultSpriteDictionary.Add(new Tuple <string, Texture2D>("DEFAULT", defaultSprite)); objectIcons.Add("DEFAULT", defaultSpriteDictionary); string objectDataFolder = Directory.GetCurrentDirectory() + GlobalConstants.DATA_FOLDER + "Sprite Definitions"; string[] objectDataFiles = Directory.GetFiles(objectDataFolder, "*.xml", SearchOption.AllDirectories); Dictionary <string, Texture2D> sheets = new Dictionary <string, Texture2D>(); for (int i = 0; i < objectDataFiles.GetLength(0); i++) { List <Tuple <string, Texture2D> > tilesetIcons = new List <Tuple <string, Texture2D> >(); string tilesetName = "DEFAULT TILESET"; XmlReader reader = XmlReader.Create(objectDataFiles[i]); while (reader.Read()) { if (reader.Depth == 0 && reader.NodeType == XmlNodeType.Element && !reader.Name.Equals("Objects")) { break; } if (reader.Name.Equals("")) { continue; } if (reader.Name.Equals("TilesetName")) { tilesetName = reader.ReadElementContentAsString(); } if (reader.Name.Equals("Sheet")) { try { string sheetName = reader.ReadElementContentAsString(); string fileName = sheetName;// + ".png"; sheets.Add(sheetName, Resources.Load <Texture2D>("Sprites/" + fileName)); } catch (Exception e) { Console.Out.WriteLine(e.Message); Console.Out.WriteLine(e.StackTrace); } } if (reader.Name.Equals("ItemIcon")) { string name = reader.GetAttribute("Name"); string positionString = reader.GetAttribute("Position"); string[] xyStrings = positionString.Split(new char[] { ',' }); int x, y; int.TryParse(xyStrings[0], out x); int.TryParse(xyStrings[1], out y); int j = 0; foreach (KeyValuePair <string, Texture2D> sheetPair in sheets) { Color[] imageData = sheetPair.Value.GetPixels(); Rect sourceRectangle = new Rect(x * 16, y * 16, 16, 16); Color[] imagePiece = GetImageData(imageData, sheetPair.Value.width, sourceRectangle); Texture2D subTexture = new Texture2D(16, 16, TextureFormat.RGBA32, false, false); subTexture.SetPixels(imagePiece); subTexture.filterMode = FilterMode.Point; //subTexture.SetData<Color>(imagePiece); tilesetIcons.Add(new Tuple <string, Texture2D>(name + j, subTexture)); j += 1; } } } if (!objectIcons.ContainsKey(tilesetName)) { objectIcons.Add(tilesetName, tilesetIcons); } else { objectIcons[tilesetName].AddRange(tilesetIcons); } sheets.Clear(); reader.Close(); } Sprites = new Dictionary <string, List <Tuple <string, Sprite> > >(); foreach (KeyValuePair <string, List <Tuple <string, Texture2D> > > pair in objectIcons) { List <Tuple <string, Sprite> > newSprites = new List <Tuple <string, Sprite> >(); foreach (Tuple <string, Texture2D> tuple in pair.Value) { Sprite sprite = Sprite.Create(tuple.Second, new Rect(0, 0, SPRITE_SIZE, SPRITE_SIZE), Vector2.zero, SPRITE_SIZE); newSprites.Add(new Tuple <string, Sprite>(tuple.First, sprite)); } Sprites.Add(pair.Key, newSprites); } }
private void SendSMS_Click(object sender, RoutedEventArgs e) { SMS_Status_receive = false; sendorreceiveblock.Text = "Send"; main.Visibility = Visibility.Collapsed; SendBox.Visibility = Visibility.Visible; AddButton.Visibility = Visibility.Collapsed; DeleteButton.Visibility = Visibility.Collapsed; EditButton.Visibility = Visibility.Collapsed; SendList.Items.Clear(); using (XmlReader reader = XmlReader.Create("Send.xml")) { OutBox.Clear(); String time = ""; String number = ""; String content = ""; String status = ""; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: status = reader.Name; break; case XmlNodeType.Text: if (status == "Time") { time = reader.Value; } else if (status == "Number") { number = reader.Value; } else if (status == "Content") { content = reader.Value; } break; case XmlNodeType.EndElement: if (reader.Name == "Send") { OutBox.Add(new SMS(time, number, content)); } break; default: break; } InBox.Sort(delegate(SMS x, SMS y) //시간순으로 sort { if (x.Time == null && y.Time == null) { return(0); } else if (x.Time == null) { return(-1); } else if (y.Time == null) { return(1); } else { return(-(x.Time.CompareTo(y.Time))); } }); } foreach (var item in OutBox) { SMS temp = new SMS(item); String printtime = "" + item.Time[4] + item.Time[5] + "-" + item.Time[6] + item.Time[7] + " " + item.Time[8] + item.Time[9] + ":" + item.Time[10] + item.Time[11]; temp.Time = printtime; foreach (var address in AddressBook) { if (address.RepNumber == item.Number) { temp.Number = address.Name; } } temp.Content = temp.Content.Split('\n')[0]; SendList.Items.Add(temp); } reader.Close(); } }
private static List <KeyValuePair <string, byte> > ParseXmlForCommandClassCommands(string shortCommandClassName, string xml, OutputLanguage outputLanguage) { List <KeyValuePair <string, byte> > commandEnumPairs = new List <KeyValuePair <string, byte> >(); XmlReader reader = XmlReader.Create(new StringReader(xml)); while (reader.ReadToFollowing("cmd")) { // make sure we are at depth 1 (i.e. reading the correct "cmd" entries) if (reader.Depth != 1) { // invalid depth; skip this entry continue; } // retrieve command name and version string commandName = reader.GetAttribute("name"); string commandEnumValueAsString = reader.GetAttribute("key"); // validate entries if (commandName == null) { // command name missing; skip this entry continue; } if (commandEnumValueAsString == null || commandEnumValueAsString.Length < 3 || commandEnumValueAsString.Substring(0, 2).ToLowerInvariant() != "0x") { // enum value (command number) missing; skip this entry continue; } // try to parse the enumValue byte commandEnumValue; if (!byte.TryParse(commandEnumValueAsString.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out commandEnumValue)) { // enum value (command number) invalid; skip this entry continue; } // get the short command name string shortCommandName = ExtractShortCommandNameFromLongCommandName(shortCommandClassName, commandName); if (shortCommandName == null) { // if the commandName could not be reduced in size, we will ignore the command header shortCommandName = commandName; } // store the command class name as-is (in languages like Java with UPPER_CASE_CONSTANTS) or convert it to special casing (for languages like JavaScript) string commandEnumName = null; switch (outputLanguage) { case OutputLanguage.Java: { // store the short command name as-is commandEnumName = shortCommandName; } break; case OutputLanguage.JavaScript: { // convert the command name to a UpperCamelCase enumeration commandEnumName = ConvertUpperCaseUnderscoreSeparatedToUpperCamelCase(shortCommandName); } break; default: throw new ArgumentException("Output language is not supported.", nameof(outputLanguage)); } // if (commandEnumName == null) { // command name invalid; skip this entry continue; } // add this command to our list commandEnumPairs.Add(new KeyValuePair <string, byte>(commandEnumName, commandEnumValue)); } return(commandEnumPairs); }
private static void ExtractThemeContent(string xml, ThemeInfo theme, bool extractIncludes) { XmlReader xmlReader = XmlReader.Create(new StringReader(xml), new XmlReaderSettings { CheckCharacters = false, DtdProcessing = DtdProcessing.Ignore, IgnoreComments = true, IgnoreProcessingInstructions = true, IgnoreWhitespace = true, }); while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element) { // Found the first element string tagName = xmlReader.Name; // Extract all the xml namespaces bool hasAttributes = xmlReader.MoveToFirstAttribute(); while (hasAttributes) { if (xmlReader.Name.StartsWith("xmlns:")) { string namespaceDeclaration = xmlReader.ReadContentAsString(); theme.AddNamespace(xmlReader.Name, namespaceDeclaration); } hasAttributes = xmlReader.MoveToNextAttribute(); } if (extractIncludes) { theme.Includes = xmlReader.GetAttribute("Includes"); } string resourcesTag = tagName + ".Resources"; if (xmlReader.ReadToFollowing(resourcesTag)) { xmlReader.MoveToContent(); // TODO: I would have expected MoveToContent to move to the first item // within the current tag, but apparently the reader is still // positioned at the current tag, unless a Read is performed. xmlReader.Read(); while (xmlReader.EOF == false) { if (xmlReader.NodeType == XmlNodeType.Element) { string key = xmlReader.GetAttribute("x:Key"); if ((String.IsNullOrEmpty(key) == false) && (theme.ContainsKey(key) == false)) { string markup = xmlReader.ReadOuterXml(); theme.AddItem(key, markup); } else { xmlReader.Skip(); } } else { // No more items break; } } } // We only look at the resources of the root tag, and so we're done break; } } }
private async void Main_Drop(object sender, DragEventArgs e) { e.Handled = true; line.Visibility = Visibility.Hidden; if (e.Data.GetDataPresent("FileName")) { var files = e.Data.GetData("FileName") as string[]; foreach (var file in files) { var longPath = new StringBuilder(255); GetLongPathName(file, longPath, longPath.Capacity); var longPathString = longPath.ToString(); if (Path.GetExtension(longPathString) == ".txt") { ((MainViewModel)Application.Current.MainWindow.DataContext).ImportTxt.Execute(longPathString); } else { ApplicationCommands.Open.Execute(longPathString, this); } } e.Effects = e.AllowedEffects; return; } if (e.Data.GetDataPresent("FileContents")) { using (var contentStream = e.Data.GetData("FileContents") as MemoryStream) { ((MainViewModel)Application.Current.MainWindow.DataContext).ImportTxt.Execute(contentStream); } e.Effects = e.AllowedEffects; return; } var format = GetDragFormat(e); InfoOwnerData dragData = null; try { dragData = (InfoOwnerData)e.Data.GetData(typeof(InfoOwnerData)); } catch (SerializationException) { return; } e.Effects = DragDropEffects.Move; try { if (format == "siqquestion" && _insertionPosition != null) { Question question = null; if (dragData != null) { question = (Question)dragData.GetItem(); } else { var value = e.Data.GetData(DataFormats.Serializable).ToString(); using (var stringReader = new StringReader(value)) using (var reader = XmlReader.Create(stringReader)) { question = new Question(); question.ReadXml(reader); } } var themeViewModel = _insertionPosition.Item1; var index = _insertionPosition.Item2; if (themeViewModel.Questions.Any(questionViewModel => questionViewModel.Model == question)) { question = question.Clone(); } var questionViewModelNew = new QuestionViewModel(question); themeViewModel.Questions.Insert(index, questionViewModelNew); if (AppSettings.Default.ChangePriceOnMove) { RecountPrices(themeViewModel); } var document = (QDocument)DataContext; await dragData.ApplyData(document.Document); document.Navigate.Execute(questionViewModelNew); } else { e.Effects = DragDropEffects.None; } } finally { if (dragData != null) { dragData.Dispose(); } } }
public static (bool, bool) FetchBool(string XmlString, string VariableName) { /* * This method looks for a boolean with a given variable in a string of XML syntax. * It literally looks for <bool variable_name="XXX"> component and reads the text afterwards. * This means that you need to know the type and the name of the variable to extract. * Input arguments are: * -> XmlString, which is a string of ASCII-encoded syntax * -> VariableName, which is also a string, containing the variable with the given name. * Returns: * -fail, which is a boolean. Set to false if the string was found, and set to true when the string was found. * -The boolean value. True or false. Of couse, if fail is true, then the return varable is invalid. */ byte[] XmlByteArray = Encoding.ASCII.GetBytes(XmlString); // Step 1: From string to byte array. MemoryStream XmlStream = new MemoryStream(XmlByteArray); // Step 2: From byte array to stream XmlReaderSettings settings = new XmlReaderSettings(); // This is needed for the XmlReader //settings.Async = true; // We won't do this asynchronous stuff. XmlReader Reader = XmlReader.Create(XmlStream, settings); // Set up XmlReader object // Scan through the lot. bool VariableTypeMatch = false; // This is set to true when the xml string contains the type of variable we are looking for. bool FoundVariableWeWant = false; // This is set to true when we found the variable we are looking for in the input argument. bool ReadyToRetun = false; // Final semaphore for the return statement evaluation. bool BoolToReturn = false; // Output variable. do { switch (Reader.NodeType) { case XmlNodeType.Element: if (Reader.Name.Equals("boolean") == true) { // If we got here we have a variable type match. //Console.WriteLine("I found a string.\n"); VariableTypeMatch = true; // Once we found the variable type we want, scan through the attributes. while (Reader.MoveToNextAttribute()) { if (Reader.Name.Equals("variable_name") && Reader.Value.Equals(VariableName)) { // If we got here, we found the variable name we want. FoundVariableWeWant = true; //Console.WriteLine("Found the variable too!\n"); } //Console.Write("Attribute {0} is set to {1}\n", Reader.Name, Reader.Value); } } break; case XmlNodeType.Text: if (VariableTypeMatch == true && FoundVariableWeWant == true) { // If we got here, we found our variable! //Console.Write("...and the pulp is: {0}\n", Reader.Value); if (Reader.Value.Equals("True")) { // We capitalised in the xml string, we need to take this into account when comparing. BoolToReturn = true; ReadyToRetun = true; } if (Reader.Value.Equals("False")) { // Let's check for false values too. BoolToReturn = false; ReadyToRetun = true; } // If neither of these statements return a useful value, then the inside of the xml tag was corrupted. // ...and to make sure that nothing else gets read out VariableTypeMatch = false; FoundVariableWeWant = false; } break; case XmlNodeType.EndElement: //Console.Write("</{0}>", Reader.Name); break; } } while (Reader.Read()); // Send back the contents. if (ReadyToRetun == true) { // If we found our string, return it. return(false, BoolToReturn); } else { // If we got here, the string wasn't found. Indicate fail and push back an empty string return(true, BoolToReturn); // If nothing touched this one during execution, this will stay an empty string. } }
private void IndentXml(TextReader xmlContent, TextWriter writer) { char[] writeNodeBuffer = null; var settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; settings.IndentChars = " "; settings.CheckCharacters = true; using (var reader = XmlReader.Create(xmlContent)) using (var xmlWriter = XmlWriter.Create(writer, settings)) { bool canReadValueChunk = reader.CanReadValueChunk; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: xmlWriter.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); xmlWriter.WriteAttributes(reader, false); if (reader.IsEmptyElement) { xmlWriter.WriteEndElement(); } break; case XmlNodeType.Text: if (canReadValueChunk) { if (writeNodeBuffer == null) { writeNodeBuffer = new char[1024]; } int count; while ((count = reader.ReadValueChunk(writeNodeBuffer, 0, 1024)) > 0) { xmlWriter.WriteChars(writeNodeBuffer, 0, count); } } break; case XmlNodeType.CDATA: xmlWriter.WriteCData(reader.Value); break; case XmlNodeType.EntityReference: xmlWriter.WriteEntityRef(reader.Name); break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.XmlDeclaration: xmlWriter.WriteProcessingInstruction(reader.Name, reader.Value); break; case XmlNodeType.Comment: xmlWriter.WriteComment(reader.Value); break; case XmlNodeType.DocumentType: xmlWriter.WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value); break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: xmlWriter.WriteWhitespace(reader.Value); break; case XmlNodeType.EndElement: xmlWriter.WriteFullEndElement(); break; } } xmlWriter.Flush(); writer.Flush(); } }
public static (bool, double) FetchDouble(string XmlString, string VariableName) { /* * This function looks for a 1-by-1 matrix in the given XML string. * Input arguments are: * -> XmlString, which is a string of ASCII-encoded syntax * -> VariableName, which is also a string, containing the variable with the given name. * Returns: * -fail, which is a boolean. Set to false if the string was found, and set to true when the string was found. * -The The double-precision single value it extracted from the the xml data. */ byte[] XmlByteArray = Encoding.ASCII.GetBytes(XmlString); // Step 1: From string to byte array. MemoryStream XmlStream = new MemoryStream(XmlByteArray); // Step 2: From byte array to stream XmlReaderSettings settings = new XmlReaderSettings(); // This is needed for the XmlReader //settings.Async = true; // We won't do this asynchronous stuff. XmlReader Reader = XmlReader.Create(XmlStream, settings); // Set up XmlReader object // Scan through the lot. bool VariableTypeMatch = false; // This is set to true when the xml string contains the type of variable we are looking for. bool VariableNameMatch = false; // This is set to true when we found the variable we are looking for in the input argument. bool VariableRowsMatch = false; // Since Doubles are stored as a 1-by-1 matrix, we need this. bool VariableColsMatch = false; // Since Doubles are stored as a 1-by-1 matrix, we need this. bool ReadyToRetun = false; // Final semaphore for the return statement evaluation. double DoubleToReturn = 0F; // Output variable. do { switch (Reader.NodeType) { case XmlNodeType.Element: if (Reader.Name.Equals("matrix") == true) { // If we got here we have a variable type match. //Console.WriteLine("I found a string.\n"); VariableTypeMatch = true; // Once we found the variable type we want, scan through the attributes. while (Reader.MoveToNextAttribute()) { if (Reader.Name.Equals("variable_name") && Reader.Value.Equals(VariableName)) { // If we got here, we found the variable name we want. VariableNameMatch = true; //Console.WriteLine("Found the variable too!\n"); } if (Reader.Name.Equals("ncols") && Reader.Value.Equals("1")) { // Is this a single-column matrix? VariableColsMatch = true; //Console.WriteLine("Found the variable too!\n"); } if (Reader.Name.Equals("nrows") && Reader.Value.Equals("1")) { // Is this a single-row matrix? VariableRowsMatch = true; //Console.WriteLine("Found the variable too!\n"); } //Console.WriteLine("Matches: Type={0}, Name={1}, RowsMatch={2}, ColsMatch={3}\n", VariableTypeMatch, VariableNameMatch, VariableRowsMatch, VariableColsMatch); //Console.Write("Attribute {0} is set to {1}\n", Reader.Name, Reader.Value); } } break; case XmlNodeType.Text: if (VariableTypeMatch == true && VariableNameMatch == true && VariableRowsMatch == true && VariableColsMatch == true) { // If we got here, we found our variable! //Console.Write("...and the pulp is: {0}\n", Reader.Value); // If neither of these statements return a useful value, then the inside of the xml tag was corrupted. DoubleToReturn = double.Parse(Reader.Value, System.Globalization.CultureInfo.InvariantCulture); // Regional settings can override the decimal point and separation. //Console.WriteLine("DoubleToReturn: {0}\n", DoubleToReturn); ReadyToRetun = true; // We found our value! // ...and to make sure that nothing else gets read out VariableTypeMatch = false; VariableNameMatch = false; VariableRowsMatch = false; VariableColsMatch = false; } break; case XmlNodeType.EndElement: //Console.Write("</{0}>", Reader.Name); break; } } while (Reader.Read()); // Send back the contents. if (ReadyToRetun == true) { // If we found our string, return it. return(false, DoubleToReturn); } else { // If we got here, the string wasn't found. Indicate fail and push back an empty string return(true, DoubleToReturn); // If nothing touched this one during execution, this will stay an empty string. } }
private static void ParseLoop(XMLLogParser parser, TransientParserConfigs config, Stream input, CancellationToken cancellationToken) { using (var xmlReader = XmlReader.Create(input)) { // Don't just use XML's natual tree-creation setup... because we don't want the root element to have children. For large or streaming logs, it will become a resource hog var elements = new Stack <XElement>(); bool exitLoop = false; while (!exitLoop && !cancellationToken.IsCancellationRequested && xmlReader.Read()) { switch (xmlReader.NodeType) { case XmlNodeType.Element: var name = XName.Get(xmlReader.Name, xmlReader.NamespaceURI); var element = new XElement(name); if (elements.Count > 1) // Don't add children to root to ensure it doesn't become massive { elements.Peek().Add(element); } elements.Push(element); if (xmlReader.HasAttributes) { while (xmlReader.MoveToNextAttribute()) { var attName = XName.Get(xmlReader.Name, xmlReader.NamespaceURI); var att = new XAttribute(attName, xmlReader.Value); elements.Peek().Add(att); } xmlReader.MoveToElement(); } break; case XmlNodeType.EndElement: xmlElementCounter.Increment(); if (xmlReader.Name == elements.Peek().Name) { var finishedElement = elements.Pop(); if (elements.Count == 1) // Don't process the elements unless they're children of root. Anything else is a child element of a log element { using (processElementTimer.NewContext()) { if (ProcessElement(parser, config, finishedElement) != LogParserErrors.OK) { exitLoop = true; break; } } } } else { Console.Error.WriteLine($"Element {elements.Peek().Name} ended, but the name of the ending element {xmlReader.Name} doesn't match. Possibly out of sync..."); } break; case XmlNodeType.CDATA: xmlCDATACounter.Increment(); elements.Peek().Add(new XCData(xmlReader.Value)); break; case XmlNodeType.Text: xmlTextCounter.Increment(); elements.Peek().Add(new XText(xmlReader.Value)); break; case XmlNodeType.Whitespace: break; default: unknownXmlElementCounter.Increment(xmlReader.NodeType.ToString()); break; } } // Only do if cancellation wasn't requested because it means we ran to completion but never found root. Cancellation means we never will. if (elements.Count != 0 && !cancellationToken.IsCancellationRequested) { xmlRootUnfinishedCounter.Increment(); Console.Error.WriteLine("Root element didn't end"); } } }
private AccessControlList ParseAccessControlList(HttpResponse httpResponse, bool isBucket) { using (XmlReader xmlReader = XmlReader.Create(httpResponse.Content)) { AccessControlList acl = new AccessControlList(); bool innerOwner = false; Grant currentGrant = null; while (xmlReader.Read()) { if ("Owner".Equals(xmlReader.Name)) { if (xmlReader.IsStartElement()) { acl.Owner = new Owner(); } innerOwner = xmlReader.IsStartElement(); } else if ("ID".Equals(xmlReader.Name)) { if (innerOwner) { acl.Owner.Id = xmlReader.ReadString(); } else { CanonicalGrantee grantee = new CanonicalGrantee(); grantee.Id = xmlReader.ReadString(); currentGrant.Grantee = grantee; } } else if ("Grant".Equals(xmlReader.Name)) { if (xmlReader.IsStartElement()) { currentGrant = new Grant(); acl.Grants.Add(currentGrant); } } else if ("Canned".Equals(xmlReader.Name)) { GroupGrantee grantee = new GroupGrantee(); grantee.GroupGranteeType = this.ParseGroupGrantee(xmlReader.ReadString()); currentGrant.Grantee = grantee; } else if ("Permission".Equals(xmlReader.Name)) { currentGrant.Permission = this.ParsePermission(xmlReader.ReadString()); } else if ("Delivered".Equals(xmlReader.Name)) { if (isBucket) { currentGrant.Delivered = Convert.ToBoolean(xmlReader.ReadString()); } else { acl.Delivered = Convert.ToBoolean(xmlReader.ReadString()); } } } return acl; } }
public QueryResult ToQueryList(string queriesAsXmlString) { const string level1Element = "result"; var count = 0; var queries = new List<Query>(); var code = 0; var message = String.Empty; using (var sr = new StringReader(queriesAsXmlString)) { var reader = XmlReader.Create(sr); var doc = new XmlDocument(); doc.Load(reader); foreach (XmlNode node in doc.GetElementsByTagName("status")) { foreach (XmlAttribute attr in node.Attributes) { if (attr.Name == "code") { code = Int32.Parse(attr.Value); } if (attr.Name == "message") { message = attr.Value; } } } foreach (XmlNode node in doc.GetElementsByTagName(level1Element)) { Query query; var queryGuid = ""; var name = ""; var queryResult = ""; var queryMessage = ""; foreach (XmlAttribute attr in node.Attributes) { if (attr.Name == "QueryGUID") { queryGuid = attr.Value; } if (attr.Name == "Name") { name = attr.Value; } if (attr.Name == "QueryResultCode") { queryResult = attr.Value; } if (attr.Name == "QueryResultMessage") { queryMessage = attr.Value; } } if (queryGuid != "" && name != "") { query = new Query(queryGuid, name) { QueryResultCode = Convert.ToInt32(queryResult), QueryResultMessage = queryMessage }; queries.Add(query); count++; } else { throw new Exception("Invalid query param: QueryGUID or Name not found"); } foreach (XmlNode node2 in node.ChildNodes) { if (node2.Name == "param") { foreach (XmlNode param in node2.ChildNodes) { foreach (XmlAttribute a in param.Attributes) { var dir = ""; if (param.Name == "input") { dir = "in"; } if (param.Name == "output") { dir = "out"; } if (param.Name == "inherited") { dir = "inh"; } query.Parameters.Add(new QueryParameter(dir, a.Name, a.Value)); } } } if (node2.Name == "parent") { var a = node2.Attributes["QueryGUID"]; if (a != null) { query.ParentQueryGUID.Add(a.Value); } } if (node2.Name == "rettable") { var dt = new DataTable(); foreach (XmlNode row in node2.ChildNodes) { if (dt.Rows.Count == 0) { foreach (XmlAttribute a in row.Attributes) { dt.Columns.Add(a.Name); } } var arr = new List<string>(); foreach (XmlAttribute a in row.Attributes) { arr.Add(a.Value); } dt.Rows.Add(arr.ToArray()); } query.RetTable = dt; } } } } if (count == 0) { throw new Exception("Queries not found"); } // TODO брать сообщение из сервиса return new QueryResult(new ResultMessage(code, OID.DataProvider.Models.MessageType.Information, message), queries); }
/// <summary> /// Validates the xml against known schemas. /// </summary> public static XmlDocument ValidateXml(IProgressMonitor monitor, string xml, string fileName) { monitor.BeginTask(GettextCatalog.GetString("Validating XML..."), 1); bool error = false; XmlDocument doc = null; StringReader stringReader = new StringReader(xml); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationType = ValidationType.Schema; settings.ProhibitDtd = false; ValidationEventHandler validationHandler = delegate(object sender, System.Xml.Schema.ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { monitor.Log.WriteLine(args.Message); AddTask(fileName, args.Exception.Message, args.Exception.LinePosition, args.Exception.LineNumber, TaskSeverity.Warning); } else { AddTask(fileName, args.Exception.Message, args.Exception.LinePosition, args.Exception.LineNumber, TaskSeverity.Error); monitor.Log.WriteLine(args.Message); error = true; } }; settings.ValidationEventHandler += validationHandler; try { foreach (XmlSchemaCompletionData sd in XmlSchemaManager.SchemaCompletionDataItems) { settings.Schemas.Add(sd.Schema); } settings.Schemas.Compile(); XmlReader reader = XmlReader.Create(stringReader, settings); doc = new XmlDocument(); doc.Load(reader); } catch (XmlSchemaException ex) { monitor.ReportError(ex.Message, ex); AddTask(fileName, ex.Message, ex.LinePosition, ex.LineNumber, TaskSeverity.Error); error = true; } catch (XmlException ex) { monitor.ReportError(ex.Message, ex); AddTask(fileName, ex.Message, ex.LinePosition, ex.LineNumber, TaskSeverity.Error); error = true; } finally { if (stringReader != null) { stringReader.Dispose(); } settings.ValidationEventHandler -= validationHandler; } if (error) { monitor.Log.WriteLine(GettextCatalog.GetString("Validation failed.")); TaskService.ShowErrors(); } else { monitor.Log.WriteLine(GettextCatalog.GetString("XML is valid.")); } monitor.EndTask(); return(error? null: doc); }
/// <summary> /// Load the list (given by owner and sFieldName) from the given TextReader. /// </summary> public void ImportList(ICmObject owner, string sFieldName, TextReader reader, IProgress progress) { m_cache = owner.Cache; m_mdc = m_cache.MetaDataCache; m_wsf = m_cache.WritingSystemFactory; m_progress = progress; try { m_cache.MainCacheAccessor.BeginNonUndoableTask(); int flidList = m_mdc.GetFieldId(owner.ClassName, sFieldName, true); if (flidList == 0) { throw new Exception(String.Format("Invalid list fieldname (programming error): {0}", sFieldName)); } using (var xrdr = XmlReader.Create(reader)) { xrdr.MoveToContent(); if (xrdr.Name != owner.ClassName) { throw new Exception(String.Format("Unexpected outer element: {0}", xrdr.Name)); } if (!xrdr.ReadToDescendant(sFieldName)) { throw new Exception(String.Format("Unexpected second element: {0}", xrdr.Name)); } if (!xrdr.ReadToDescendant("CmPossibilityList")) { throw new Exception(String.Format("Unexpected third element: {0}", xrdr.Name)); } ICmPossibilityList list; int hvo = m_cache.MainCacheAccessor.get_ObjectProp(owner.Hvo, flidList); if (hvo == 0) { hvo = m_cache.MainCacheAccessor.MakeNewObject(CmPossibilityListTags.kClassId, owner.Hvo, flidList, -2); } ICmPossibilityListRepository repo = m_cache.ServiceLocator.GetInstance <ICmPossibilityListRepository>(); list = repo.GetObject(hvo); string sItemClassName = "CmPossibility"; xrdr.Read(); while (xrdr.Depth == 3) { xrdr.MoveToContent(); if (xrdr.Depth < 3) { break; } switch (xrdr.Name) { case "Description": SetMultiStringFromXml(xrdr, list.Description); break; case "Name": SetMultiUnicodeFromXml(xrdr, list.Name); break; case "Abbreviation": SetMultiUnicodeFromXml(xrdr, list.Abbreviation); break; case "Depth": list.Depth = ReadIntFromXml(xrdr); break; case "DisplayOption": list.DisplayOption = ReadIntFromXml(xrdr); break; case "HelpFile": list.HelpFile = ReadUnicodeFromXml(xrdr); break; case "IsClosed": list.IsClosed = ReadBoolFromXml(xrdr); break; case "IsSorted": list.IsSorted = ReadBoolFromXml(xrdr); break; case "IsVernacular": list.IsVernacular = ReadBoolFromXml(xrdr); break; case "ItemClsid": list.ItemClsid = ReadIntFromXml(xrdr); sItemClassName = m_mdc.GetClassName(list.ItemClsid); break; case "ListVersion": list.ListVersion = ReadGuidFromXml(xrdr); break; case "PreventChoiceAboveLevel": list.PreventChoiceAboveLevel = ReadIntFromXml(xrdr); break; case "PreventDuplicates": list.PreventDuplicates = ReadBoolFromXml(xrdr); break; case "PreventNodeChoices": list.PreventNodeChoices = ReadBoolFromXml(xrdr); break; case "UseExtendedFields": list.UseExtendedFields = ReadBoolFromXml(xrdr); break; case "WsSelector": list.WsSelector = ReadIntFromXml(xrdr); break; case "Possibilities": LoadPossibilitiesFromXml(xrdr, list, sItemClassName); break; case "HeaderFooterSets": throw new Exception("We don't (yet?) handle HeaderFooterSets for CmPossibilityList (programming issue)"); case "Publications": throw new Exception("We don't (yet?) handle Publications for CmPossibilityList (programming issue)"); default: throw new Exception(String.Format("Unknown field element in CmPossibilityList: {0}", xrdr.Name)); } } xrdr.Close(); if (m_mapRelatedDomains.Count > 0) { SetRelatedDomainsLinks(); } } } catch (Exception e) { MessageBoxUtils.Show(e.Message); } finally { m_cache.MainCacheAccessor.EndNonUndoableTask(); } }
/// <summary> /// Read an Deviceoptions from XML - do some sanity check /// </summary> /// <param name="xml">the XML action fragment</param> /// <returns>True if an action was decoded</returns> public Boolean fromXML(string xml) { /* * This can be a lot of the following options * try to do our best.... * * <deviceoptions name="Joystick - HOTAS Warthog"> * <!-- Reduce the deadzone --> * <option input="x" deadzone="0.015" /> * <option input="y" deadzone="0.015" /> * </deviceoptions> * */ XmlReaderSettings settings = new XmlReaderSettings( ); settings.ConformanceLevel = ConformanceLevel.Fragment; settings.IgnoreWhitespace = true; settings.IgnoreComments = true; XmlReader reader = XmlReader.Create(new StringReader(xml), settings); reader.Read( ); string name = ""; if (reader.HasAttributes) { name = reader["name"]; reader.Read( ); // try to disassemble the items while (!reader.EOF) { if (reader.Name.ToLowerInvariant( ) == "option") { if (reader.HasAttributes) { string input = reader["input"]; string deadzone = reader["deadzone"]; string saturation = reader["saturation"]; if (!string.IsNullOrWhiteSpace(input)) { string doID = DevOptionID(name, input); if (!string.IsNullOrWhiteSpace(deadzone)) { float testF; if (!float.TryParse(deadzone, out testF)) // check for valid number in string { deadzone = "0.00"; } if (!this.ContainsKey(doID)) { this.Add(doID, new DeviceOptionParameter(name, input, deadzone, saturation)); } else { // add deadzone value tp existing this[doID].Deadzone = deadzone; } } if (!string.IsNullOrWhiteSpace(saturation)) { float testF; if (!float.TryParse(saturation, out testF)) // check for valid number in string { saturation = "1.00"; } if (!this.ContainsKey(doID)) { this.Add(doID, new DeviceOptionParameter(name, input, deadzone, saturation)); } else { // add saturation value tp existing this[doID].Saturation = saturation; } } } else { //? option node has not the needed attributes log.ErrorFormat("Deviceoptions.fromXML: option node has not the needed attributes"); } } else { //?? option node has NO attributes log.ErrorFormat("Deviceoptions.fromXML: option node has NO attributes"); } } reader.Read( ); }//while } else { //?? if (!m_stringOptions.Contains(xml)) { m_stringOptions.Add(xml); } } return(true); }
public static Chart CreateChartFromXml(Stream inStream) { using var reader = XmlReader.Create(inStream); var chart = MusecloneChartFactory.Instance.CreateNew(); var timingInfo = new Dictionary <int, TimingInfo>(); var eventInfos = new List <EventInfo>(); EventInfo?curEvent = null; reader.MoveToContent(); #region Read Timing Information and Event Creation while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.EndElement: if (reader.Name == "event") { //Logger.Log($"End event block: {curEvent!.StartTimeMillis}, {curEvent!.EndTimeMillis}, {curEvent!.Type}, {curEvent!.Kind}"); eventInfos.Add(curEvent !); curEvent = null; } break; case XmlNodeType.Element: { if (reader.Name == "tempo") { int time = 0, deltaTime = 0, value = 500_000; long bpm = 120_00; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name) { case "time": { //string type = reader["__type"]; reader.Read(); // <time ...> time = reader.ReadContentAsInt(); } break; case "delta_time": { //string type = reader["__type"]; reader.Read(); // <delta_time ...> deltaTime = reader.ReadContentAsInt(); } break; case "val": { //string type = reader["__type"]; reader.Read(); // <delta_time ...> value = reader.ReadContentAsInt(); } break; case "bpm": { //string type = reader["__type"]; reader.Read(); // <delta_time ...> bpm = reader.ReadContentAsLong(); } break; } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "tempo") { //Logger.Log($"End tempo block: {time}, {deltaTime}, {value}, {bpm}"); if (!timingInfo.TryGetValue(time, out var info)) { timingInfo[time] = info = new TimingInfo(); } info.MusecaWhen = time; info.BeatsPerMinute = bpm / 100.0; break; } } } else if (reader.Name == "sig_info") { int time = 0, deltaTime = 0, num = 4, denomi = 4; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name) { case "time": { //string type = reader["__type"]; reader.Read(); // <time ...> time = reader.ReadContentAsInt(); } break; case "delta_time": { //string type = reader["__type"]; reader.Read(); // <delta_time ...> deltaTime = reader.ReadContentAsInt(); } break; case "num": { //string type = reader["__type"]; reader.Read(); // <delta_time ...> num = reader.ReadContentAsInt(); } break; case "denomi": { //string type = reader["__type"]; reader.Read(); // <delta_time ...> denomi = reader.ReadContentAsInt(); } break; } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "sig_info") { //Logger.Log($"End sig_info block: {time}, {deltaTime}, {num}, {denomi}"); if (!timingInfo.TryGetValue(time, out var info)) { timingInfo[time] = info = new TimingInfo(); } info.Numerator = num; info.Denominator = denomi; break; } } } switch (reader.Name) { case "event": curEvent = new EventInfo(); break; case "stime_ms": { reader.Read(); curEvent !.StartTimeMillis = reader.ReadContentAsLong(); } break; case "etime_ms": { reader.Read(); curEvent !.EndTimeMillis = reader.ReadContentAsLong(); } break; case "type": { reader.Read(); curEvent !.Type = reader.ReadContentAsInt(); } break; case "kind": { reader.Read(); curEvent !.Kind = reader.ReadContentAsInt(); } break; } } break; } } #endregion #region Construct :theori Timing Data foreach (var info in from pair in timingInfo orderby pair.Key select pair.Value) { tick_t position = chart.CalcTickFromTime(info.MusecaWhen / 1000.0); var cp = chart.ControlPoints.GetOrCreate(position, true); if (info.BeatsPerMinute > 0) { cp.BeatsPerMinute = info.BeatsPerMinute; } if (info.Numerator != 0 && info.Denominator != 0 && (cp.BeatCount != info.Numerator || cp.BeatKind != info.Denominator)) { cp = chart.ControlPoints.GetOrCreate(MathL.Ceil((double)position), true); cp.BeatCount = info.Numerator; cp.BeatKind = info.Denominator; } } #endregion #region Determine timing info from beat events if (false && timingInfo.Count == 0) { var barEvents = from e in eventInfos where e.Kind == 11 || e.Kind == 12 select e; // bpm related long lastBeatDurationMillis = 0, lastBeatStartMillis = 0, lastBpmStartMillis = 0; int bpmTotalBeats = 0; long runningBeatDurationTotal = 0; int numBeatsCounted = 0; // sig related int n = 4; int measure = 0, totalMeasures = 0, beatCount = 0, totalBeatsInMeasure = 0; long sigMeasureStartMillis = 0, sigCurrentMeasureStartMillis = 0, sigOffsetMillis = 0; tick_t offset = 0; var bpmChanges = new Dictionary <int, (long Millis, double BeatsPerMinute)>(); var timeSigChanges = new Dictionary <int, (int Numerator, int Denominator)>(); foreach (var e in barEvents) { long millis = e.StartTimeMillis; if (totalBeatsInMeasure > 0) { lastBpmStartMillis = lastBeatStartMillis; long beatDuration = millis - lastBeatStartMillis; if (lastBeatDurationMillis != 0) { // TODO(local): if this is within like a millisecond then maybe it's fine if (Math.Abs(beatDuration - lastBeatDurationMillis) > 10) { bpmChanges[bpmTotalBeats] = (lastBpmStartMillis, 60_000.0 / (runningBeatDurationTotal / (double)numBeatsCounted)); lastBpmStartMillis = lastBeatStartMillis; numBeatsCounted = 0; runningBeatDurationTotal = 0; } } lastBeatDurationMillis = beatDuration; } bpmTotalBeats++; numBeatsCounted++; runningBeatDurationTotal += millis - lastBeatStartMillis; lastBeatStartMillis = millis; if (e.Kind == 11) // measure marker { totalMeasures++; if (totalBeatsInMeasure == 0) // first one in the chart { sigOffsetMillis = millis; sigMeasureStartMillis = millis; beatCount++; totalBeatsInMeasure++; } else // check that the previous beat count matches `n` { if (beatCount != n) { timeSigChanges[totalMeasures - 1] = (beatCount, 4); totalBeatsInMeasure = 0; measure = 0; } // continue as normal totalBeatsInMeasure++; measure++; beatCount = 1; sigCurrentMeasureStartMillis = millis; } } else // beat marker { beatCount++; totalBeatsInMeasure++; } } bpmChanges[bpmTotalBeats] = (lastBeatStartMillis, 60_000.0 / (runningBeatDurationTotal / (double)numBeatsCounted)); chart.Offset = sigOffsetMillis / 1_000.0; foreach (var(measureIndex, (num, denom)) in timeSigChanges) { tick_t position = measureIndex; var cp = chart.ControlPoints.GetOrCreate(position, true); cp.BeatCount = num; cp.BeatKind = denom; } foreach (var(beatIndex, (timeMillis, bpm)) in bpmChanges) { int beatsLeft = beatIndex; tick_t? where = null; foreach (var cp in chart.ControlPoints) { if (!cp.HasNext) { where = cp.Position + (double)beatsLeft / cp.BeatCount; break; } else { int numBeatsInCp = (int)(cp.BeatCount * (double)(cp.Next.Position - cp.Position)); if (beatsLeft > numBeatsInCp) { beatsLeft -= numBeatsInCp; } else { where = cp.Position + (double)beatsLeft / cp.BeatCount; break; } } } if (where.HasValue) { var cp = chart.ControlPoints.GetOrCreate(where.Value, true); cp.BeatsPerMinute = bpm; } //else Logger.Log($"Bpm change at beat {beatIndex} (timeMillis) could not be created for bpm {bpm}"); } } #endregion var noteInfos = from e in eventInfos where e.Kind != 11 && e.Kind != 12 && e.Kind != 14 && e.Kind != 15 select e; foreach (var entity in noteInfos) { tick_t startTicks = chart.CalcTickFromTime(entity.StartTimeMillis / 1000.0); tick_t endTicks = chart.CalcTickFromTime(entity.EndTimeMillis / 1000.0); const int q = 192; startTicks = MathL.Round((double)(startTicks * q)) / q; endTicks = MathL.Round((double)(endTicks * q)) / q; tick_t durTicks = endTicks - startTicks; if (entity.Kind == 1 && entity.Type == 5) { chart[5].Add <ButtonEntity>(startTicks, durTicks); } else { switch (entity.Kind) { // "chip" tap note case 0: chart[entity.Type].Add <ButtonEntity>(startTicks); break; // hold tap note, ignore foot pedal bc handled above case 1: chart[entity.Type - 6].Add <ButtonEntity>(startTicks, durTicks); break; // large spinner case 2: { var e = chart[entity.Type % 6].Add <SpinnerEntity>(startTicks, durTicks); e.Large = true; } break; // large spinner left case 3: { var e = chart[entity.Type % 6].Add <SpinnerEntity>(startTicks, durTicks); e.Direction = LinearDirection.Left; e.Large = true; } break; // large spinner right case 4: { var e = chart[entity.Type % 6].Add <SpinnerEntity>(startTicks, durTicks); e.Direction = LinearDirection.Right; e.Large = true; } break; // small spinner case 5: { var e = chart[entity.Type].Add <SpinnerEntity>(startTicks); } break; // small spinner left case 6: { var e = chart[entity.Type].Add <SpinnerEntity>(startTicks); e.Direction = LinearDirection.Left; } break; // small spinner right case 7: { var e = chart[entity.Type].Add <SpinnerEntity>(startTicks); e.Direction = LinearDirection.Right; } break; } } } return(chart); }
public string DoExport(string blobUri, bool whatIf) { _log.Info("Starting SQL DAC Export Operation"); string requestGuid = null; bool exportComplete = false; string exportedBlobPath = null; //Setup Web Request for Export Operation WebRequest webRequest = WebRequest.Create(this.EndPointUri + @"/Export"); webRequest.Method = WebRequestMethods.Http.Post; webRequest.ContentType = @"application/xml"; //Create Web Request Inputs - Blob Storage Credentials and Server Connection Info ExportInput exportInputs = new ExportInput { BlobCredentials = new BlobStorageAccessKeyCredentials { StorageAccessKey = this.StorageKey, Uri = String.Format(blobUri, this.DatabaseName, DateTime.UtcNow.Ticks.ToString()) }, ConnectionInfo = new ConnectionInfo { ServerName = this.ServerName, DatabaseName = this.DatabaseName, UserName = this.UserName, Password = this.Password } }; //Perform Web Request DataContractSerializer dataContractSerializer = new DataContractSerializer(exportInputs.GetType()); _log.Info("http POST {0}", webRequest.RequestUri.AbsoluteUri); if (whatIf) { _log.Trace("Would have sent:"); using (var strm = new MemoryStream()) { dataContractSerializer.WriteObject(strm, exportInputs); strm.Flush(); strm.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(strm)) { _log.Trace(reader.ReadToEnd()); } } return(null); } else { _log.Info("Making Web Request For Export Operation..."); Stream webRequestStream = webRequest.GetRequestStream(); dataContractSerializer.WriteObject(webRequestStream, exportInputs); webRequestStream.Close(); //Get Response and Extract Request Identifier WebResponse webResponse = null; XmlReader xmlStreamReader = null; try { //Initialize the WebResponse to the response from the WebRequest webResponse = webRequest.GetResponse(); xmlStreamReader = XmlReader.Create(webResponse.GetResponseStream()); xmlStreamReader.ReadToFollowing("guid"); requestGuid = xmlStreamReader.ReadElementContentAsString(); _log.Info($"Export Request '{requestGuid}' submitted"); //Get Export Operation Status string last = null; while (!exportComplete) { List <StatusInfo> statusInfoList = CheckRequestStatus(requestGuid); var status = statusInfoList.FirstOrDefault().Status; if (!String.Equals(last, status, StringComparison.OrdinalIgnoreCase)) { _log.Info(status); } last = status; if (statusInfoList.FirstOrDefault().Status == "Failed") { _log.Error("Database export failed: {0}", statusInfoList.FirstOrDefault().ErrorMessage); exportComplete = true; } if (statusInfoList.FirstOrDefault().Status == "Completed") { exportedBlobPath = statusInfoList.FirstOrDefault().BlobUri; _log.Info("Export Complete - Database exported to: {0}", exportedBlobPath); exportComplete = true; } Thread.Sleep(5 * 1000); } return(exportedBlobPath); } catch (WebException responseException) { _log.Error("Request Falied:{0}", responseException.Message); if (responseException.Response != null) { _log.Error("Status Code: {0}", ((HttpWebResponse)responseException.Response).StatusCode); _log.Error("Status Description: {0}", ((HttpWebResponse)responseException.Response).StatusDescription); } return(null); } } }