public List <T> AddNew <T>(IEnumerable <T> datas) where T : class, IData { List <T> result = new List <T>(); foreach (IData data in datas) { CheckInterface(data.GetType()); IFile file = (IFile)data; string filename = CreateSystemPath(Path.Combine(file.FolderPath, file.FileName)); FileSystemFile fileSystemFile = Activator.CreateInstance(_fileSystemFileTypeWithInterface) as FileSystemFile; fileSystemFile.SetDataSourceId(_context.CreateDataSourceId(new FileSystemFileDataId(filename), _fileInterfaceType)); fileSystemFile.FolderPath = file.FolderPath; fileSystemFile.FileName = file.FileName; fileSystemFile.SystemPath = filename; using (C1StreamReader streamReader = new C1StreamReader(file.GetReadStream())) { using (C1StreamWriter streamWriter = new C1StreamWriter(fileSystemFile.GetNewWriteStream())) { streamWriter.Write(streamReader.ReadToEnd()); } } FileSystemFileStreamManager.WriteFileToDisk(fileSystemFile); result.Add(fileSystemFile as T); } return(result); }
private static string ParseMarkup(string markup, Tidy tidy, out TidyMessageCollection tidyMessages) { string result; tidyMessages = new TidyMessageCollection(); byte[] htmlByteArray = Encoding.UTF8.GetBytes(markup); using (var inputStream = new MemoryStream(htmlByteArray)) { using (var outputStream = new MemoryStream()) { tidy.Parse(inputStream, outputStream, tidyMessages); outputStream.Position = 0; using (var sr = new C1StreamReader(outputStream)) { result = sr.ReadToEnd(); } } } if (tidyMessages.Errors > 0) { var errorMessageBuilder = new StringBuilder(); foreach (TidyMessage message in tidyMessages) { if (message.Level == MessageLevel.Error) { errorMessageBuilder.AppendLine(message.ToString()); } } throw new InvalidOperationException($"Failed to parse html:\n\n{errorMessageBuilder}"); } return(result); }
/// <exclude /> public static string OutputBodyDescendants(XDocument source) { string bodyInnerXhtml = ""; XmlWriterSettings settings = CustomizedWriterSettings(); using (var memoryStream = new MemoryStream()) { using (XmlWriter writer = XmlWriter.Create(memoryStream, settings)) { XNamespace xhtml = "http://www.w3.org/1999/xhtml"; XElement bodyElement = source.Descendants(xhtml + "body").First(); foreach (XNode element in bodyElement.Nodes()) { element.WriteTo(writer); } writer.Flush(); memoryStream.Position = 0; var sr = new C1StreamReader(memoryStream); bodyInnerXhtml = sr.ReadToEnd(); } } bodyInnerXhtml = bodyInnerXhtml.Replace(" xmlns=\"http://www.w3.org/1999/xhtml\"", ""); var prefixToUriLookup = new Dictionary <string, string>(); int lastLength = -1; while (bodyInnerXhtml.Length != lastLength) { lastLength = bodyInnerXhtml.Length; MatchCollection matchCollection = _customNamespaceDeclarations.Matches(bodyInnerXhtml); foreach (Match match in matchCollection) { string prefix = match.Groups["prefix"].Value; if (!prefixToUriLookup.ContainsKey(prefix)) { prefixToUriLookup.Add(prefix, match.Groups["uri"].Value); } } if (matchCollection.Count > 0) { bodyInnerXhtml = _customNamespaceDeclarations.Replace(bodyInnerXhtml, "<$1$2>"); } } foreach (var prefixInfo in prefixToUriLookup) { Regex namespacePrefixedElement = new Regex("<(" + prefixInfo.Key + @":[a-zA-Z0-9\._]*?)([^>]*?)( ?/?)>", RegexOptions.Compiled); bodyInnerXhtml = namespacePrefixedElement.Replace(bodyInnerXhtml, "<$1$2 xmlns:" + prefixInfo.Key + "=\"" + prefixInfo.Value + "\"$3>"); } return(bodyInnerXhtml); }
public static string Decrypt(string encryptedValue) { Verify.ArgumentNotNullOrEmpty(encryptedValue, "encryptedValue"); byte[] encodedSequence = HexStringToByteArray(encryptedValue); // TDeclare the streams used // to decrypt to an in memory // array of bytes. MemoryStream msDecrypt = null; CryptoStream csDecrypt = null; C1StreamReader srDecrypt = null; // Declare the RijndaelManaged object // used to decrypt the data. RijndaelManaged rima = null; try { // Create a RijndaelManaged object // with the specified key and IV. rima = new RijndaelManaged(); rima.Key = _encryptionKey; rima.IV = RijndaelIV; // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = rima.CreateDecryptor(); // Create the streams used for decryption. msDecrypt = new MemoryStream(encodedSequence); csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); srDecrypt = new C1StreamReader(csDecrypt); // Read the decrypted bytes from the decrypting stream // and place them in a string. return(srDecrypt.ReadToEnd()); } finally { if (srDecrypt != null) { srDecrypt.Close(); } if (csDecrypt != null) { csDecrypt.Close(); } if (msDecrypt != null) { msDecrypt.Close(); } if (rima != null) { rima.Clear(); } } }
/// <summary> /// Returns all text from the stream associated with the provided IFile /// </summary> public static string ReadAllText(this IFile file) { using (Stream fileStream = GetReadStream(file)) { using (C1StreamReader sr = new C1StreamReader(fileStream)) { return(sr.ReadToEnd()); } } }
public static string LoadFile(string relativePath) { string path = Path.Combine(PathUtil.Resolve("~"), relativePath); if (!C1File.Exists(path)) { throw new FileNotFoundException("File not found. Ensure path is relative (that it does not start with '/').", path); } using (var streamReader = new C1StreamReader(path)) { return(streamReader.ReadToEnd()); } }
/// <summary> /// Cleans HTML documents or fragments into XHTML conformant markup /// </summary> /// <param name="xmlMarkup">The html to clean</param> /// <returns></returns> public static XDocument TidyXml(string xmlMarkup) { try { return(XhtmlDocument.Parse(xmlMarkup)); } catch (Exception) { // take the slow road below... } byte[] xmlByteArray = Encoding.UTF8.GetBytes(xmlMarkup); Tidy tidy = GetXmlConfiguredTidy(); List <string> namespacePrefixedElementNames = LocateNamespacePrefixedElementNames(xmlMarkup); AllowNamespacePrefixedElementNames(tidy, namespacePrefixedElementNames); AllowHtml5ElementNames(tidy); TidyMessageCollection tidyMessages = new TidyMessageCollection(); string xml = ""; using (MemoryStream inputStream = new MemoryStream(xmlByteArray)) { using (MemoryStream outputStream = new MemoryStream()) { tidy.Parse(inputStream, outputStream, tidyMessages); outputStream.Position = 0; C1StreamReader sr = new C1StreamReader(outputStream); xml = sr.ReadToEnd(); } } if (tidyMessages.Errors > 0) { StringBuilder errorMessageBuilder = new StringBuilder(); foreach (TidyMessage message in tidyMessages) { if (message.Level == MessageLevel.Error) { errorMessageBuilder.AppendLine(message.ToString()); } } throw new InvalidOperationException(string.Format("Failed to parse html:\n\n{0}", errorMessageBuilder.ToString())); } xml = RemoveDuplicateAttributes(xml); return(XDocument.Parse(xml)); }
/// <exclude /> public static string GetDocumentAsString(this XDocument document) { Verify.ArgumentNotNull(document, "document"); using (var ms = new MemoryStream()) { using (var sw = new C1StreamWriter(ms)) { document.Save(sw); ms.Seek(0, SeekOrigin.Begin); using (var sr = new C1StreamReader(ms)) { return(sr.ReadToEnd()); } } } }
private static string RijndaelDecrypt(byte[] bytes) { using (var rima = new RijndaelManaged()) { rima.Key = _encryptionKey; rima.IV = RijndaelIV; // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = rima.CreateDecryptor(); // Create the streams used for decryption. using (var msDecrypt = new MemoryStream(bytes)) using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) using (var srDecrypt = new C1StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. return(srDecrypt.ReadToEnd()); } } }
public static PackageFragmentValidationResult LoadInstallXml(string zipFilename, out XElement installElement) { installElement = null; ZipFileSystem zipFileSystem = null; try { zipFileSystem = new ZipFileSystem(zipFilename); } catch (Exception ex) { return(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex)); } string filename = string.Format("~/{0}", PackageSystemSettings.InstallFilename); if (zipFileSystem.ContainsFile(filename) == false) { return(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format("Installation file '{0}' is missing from the zip file", filename))); } try { using (var stream = zipFileSystem.GetFileStream(filename)) using (var streamReader = new C1StreamReader(stream)) { string fileContent = streamReader.ReadToEnd(); installElement = XElement.Parse(fileContent); } } catch (Exception ex) { return(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex)); } return(null); }
public static string Decrypt(string encryptedValue) { Verify.ArgumentNotNullOrEmpty(encryptedValue, nameof(encryptedValue)); byte[] encodedSequence = HexStringToByteArray(encryptedValue); using (var rima = new RijndaelManaged()) { rima.Key = _encryptionKey; rima.IV = RijndaelIV; // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = rima.CreateDecryptor(); // Create the streams used for decryption. using (var msDecrypt = new MemoryStream(encodedSequence)) using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) using (var srDecrypt = new C1StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. return(srDecrypt.ReadToEnd()); } } }
/// <summary> /// Cleans HTML documents or fragments into XHTML conformant markup /// </summary> /// <param name="htmlMarkup">The html to clean</param> /// <returns>A fully structured XHTML document, incl. html, head and body elements.</returns> public static TidyHtmlResult TidyHtml(string htmlMarkup) { byte[] htmlByteArray = Encoding.UTF8.GetBytes(htmlMarkup); Tidy tidy = GetXhtmlConfiguredTidy(); List <string> namespacePrefixedElementNames = LocateNamespacePrefixedElementNames(htmlMarkup); Dictionary <string, string> namespacePrefixToUri = LocateNamespacePrefixToUriDeclarations(htmlMarkup); List <string> badNamespacePrefixedElementNames = namespacePrefixedElementNames.Where(s => namespacePrefixToUri.Where(d => s.StartsWith(d.Key)).Any() == false).ToList(); AllowNamespacePrefixedElementNames(tidy, namespacePrefixedElementNames); AllowHtml5ElementNames(tidy); TidyMessageCollection tidyMessages = new TidyMessageCollection(); string xhtml = ""; using (MemoryStream inputStream = new MemoryStream(htmlByteArray)) { using (MemoryStream outputStream = new MemoryStream()) { tidy.Parse(inputStream, outputStream, tidyMessages); outputStream.Position = 0; C1StreamReader sr = new C1StreamReader(outputStream); xhtml = sr.ReadToEnd(); } } if (tidyMessages.Errors > 0) { StringBuilder errorMessageBuilder = new StringBuilder(); foreach (TidyMessage message in tidyMessages) { if (message.Level == MessageLevel.Error) { errorMessageBuilder.AppendLine(message.ToString()); } } throw new InvalidOperationException(string.Format("Failed to parse html:\n\n{0}", errorMessageBuilder.ToString())); } if (xhtml.IndexOf("<html>") > -1) { xhtml = xhtml.Replace("<html>", "<html xmlns=\"http://www.w3.org/1999/xhtml\">"); } if (xhtml.IndexOf("xmlns=\"http://www.w3.org/1999/xhtml\"") == -1) { xhtml = xhtml.Replace("<html", "<html xmlns=\"http://www.w3.org/1999/xhtml\""); } xhtml = RemoveDuplicateAttributes(xhtml); xhtml = RemoveXmlDeclarations(xhtml); xhtml = UndoLowerCasingOfElementNames(xhtml, namespacePrefixedElementNames); xhtml = UndoLowerCasingOfNamespacePrefixes(xhtml, namespacePrefixToUri); StringBuilder messageBuilder = new StringBuilder(); foreach (TidyMessage message in tidyMessages) { if (message.Level == MessageLevel.Warning) { messageBuilder.AppendLine(message.ToString()); } } List <string> badNamespacePrefixes = badNamespacePrefixedElementNames.Select(n => n.Substring(0, n.IndexOf(':'))).Union(LocateAttributeNamespacePrefixes(xhtml)).Distinct().Where(f => IsValidXmlName(f)).ToList(); XDocument outputResult; if (badNamespacePrefixedElementNames.Any()) { string badDeclared = string.Join(" ", badNamespacePrefixes.Select(p => string.Format("xmlns:{0}='#bad'", p)).ToArray()); XDocument badDoc = XDocument.Parse(string.Format("<root {0}>{1}</root>", badDeclared, xhtml)); badDoc.Descendants().Attributes().Where(e => e.Name.Namespace == "#bad").Remove(); badDoc.Descendants().Where(e => e.Name.Namespace == "#bad").Remove(); outputResult = new XDocument(badDoc.Root.Descendants().First()); } else { outputResult = XDocument.Parse(xhtml, LoadOptions.PreserveWhitespace); } return(new TidyHtmlResult { Output = outputResult, ErrorSummary = messageBuilder.ToString() }); }
/* * Moth knows about the ugly parameters, please refactor! * We should probably supply XSLT params by webcontrol markup... */ public static MemoryStream Transform(MemoryStream buffer, String mode, String browser, String platform) { List <string> xsltFilePaths = GetTransformationsInPriority().ToList(); if (xsltFilePaths.Count == 0) { return(buffer); } // Detection doctype buffer.Seek(0, SeekOrigin.Begin); string line; using (var reader = new StreamReader(buffer, Encoding.UTF8, true, 1024, true)) { line = reader.ReadLine(); } var doctype = line.Contains("<!DOCTYPE"); buffer.Seek(0, SeekOrigin.Begin); var readerSettings = new XmlReaderSettings { XmlResolver = null, DtdProcessing = DtdProcessing.Parse, CheckCharacters = false }; MemoryStream outputStream = null; int xsltCount = xsltFilePaths.Count; for (int i = 0; i < xsltCount; i++) { string xsltFilePath = xsltFilePaths[i]; bool isFirst = (i == 0); MemoryStream inputStream = isFirst ? buffer : outputStream; inputStream.Position = 0; outputStream = new MemoryStream(); /* * Hardcoding a parameter for masterfilter.xsl * TODO: parametersetup in webcontrol markup! */ var transformer = GetCachedTransformation(xsltFilePath); var argList = new XsltArgumentList(); if (!string.IsNullOrEmpty(mode)) { argList.AddParam("mode", "", mode); } if (!string.IsNullOrEmpty(browser)) { argList.AddParam("browser", "", browser); } if (!string.IsNullOrEmpty(platform)) { argList.AddParam("platform", "", platform); } argList.AddParam("version", "", RuntimeInformation.ProductVersion.ToString()); argList.AddParam("doctype", "", doctype.ToString()); argList.AddParam("appVirtualPath", "", GetAppRootPath()); var reader = XmlReader.Create(inputStream, readerSettings); var writer = XmlWriter.Create(outputStream, transformer.OutputSettings); try { transformer.Transform(reader, argList, writer); } catch (XmlException xmlException) { string tempFilePath = TempDirectoryFacade.GetTempFileName(".xml"); inputStream.Position = 0; string markup; using (var sr = new C1StreamReader(inputStream)) { markup = sr.ReadToEnd(); } C1File.WriteAllText(tempFilePath, markup); throw new InvalidOperationException( $"Incorrect xml markup, source saved in '{tempFilePath}'", xmlException); } } Verify.That(outputStream != null, "NullRef"); return(outputStream); }