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 (C1StreamReader streamReader = new C1StreamReader(zipFileSystem.GetFileStream(filename))) { string fileContent = streamReader.ReadToEnd(); installElement = XElement.Parse(fileContent); } } catch (Exception ex) { return new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex); } return null; }
/// <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; }
/// <summary> /// This should be a part of the I/O layer /// </summary> public static void LoadFromPath(this XslCompiledTransform xslCompiledTransform, string path, XsltSettings settings, XmlResolver stylesheetResolver) { using (C1StreamReader streamReader = new C1StreamReader(path)) { using (XmlReader xmlReader = XmlReader.Create(streamReader)) { xslCompiledTransform.Load(xmlReader, settings, stylesheetResolver); } } }
/// <summary> /// This should be a part of the I/O layer /// </summary> public static void LoadFromPath(this XslCompiledTransform xslCompiledTransform, string path) { using (C1StreamReader streamReader = new C1StreamReader(path)) { using (XmlReader xmlReader = XmlReader.Create(streamReader)) { xslCompiledTransform.Load(xmlReader); } } }
/// <summary> /// This should be a part of the I/O layer /// </summary> public static XmlSchema AddFromPath(this XmlSchemaSet xmlSchemaSet, string targetNamespace, string path) { using (C1StreamReader streamReader = new C1StreamReader(path)) { using (XmlReader xmlReader = XmlReader.Create(streamReader)) { return xmlSchemaSet.Add(targetNamespace, xmlReader); } } }
/// <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(); } }
/// <exclude /> public override void Uninstall() { using (Stream xsltFileStream = this.UninstallerContext.ZipFileSystem.GetFileStream(this.UninstallXsltFilePath)) { using (TextReader xsltTextReader = new C1StreamReader(xsltFileStream)) { XDocument xslt = XDocument.Load(xsltTextReader); ConfigurationServices.TransformConfiguration(xslt, false); } } }
public override object Execute(ParameterList parameters, FunctionContextContainer context) { string relativePath = parameters.GetParameter<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)) { using (var reader = XmlReader.Create(streamReader)) { return XElement.Load(reader); } } }
/// <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 void ValidateConfiguration() { XElement typesElement = this.Configuration.SingleOrDefault(f => f.Name == "Types"); if (typesElement == null) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingElement")); } if (typesElement == null) return; foreach (XElement typeElement in typesElement.Elements("Type")) { XAttribute typeAttribute = typeElement.Attribute("type"); if (typeAttribute == null) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingAttribute").FormatWith("type"), typeElement); continue; } string interfaceTypeName = typeAttribute.Value; interfaceTypeName = TypeManager.FixLegasyTypeName(interfaceTypeName); foreach (XElement dataElement in typeElement.Elements("Data")) { XAttribute dataScopeIdentifierAttribute = dataElement.Attribute("dataScopeIdentifier"); if (dataScopeIdentifierAttribute == null) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingAttribute").FormatWith("dataScopeIdentifier"), typeElement); continue; } DataScopeIdentifier dataScopeIdentifier; try { dataScopeIdentifier = DataScopeIdentifier.Deserialize(dataScopeIdentifierAttribute.Value); } catch (Exception) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.WrongDataScopeIdentifier").FormatWith(dataScopeIdentifierAttribute.Value), dataScopeIdentifierAttribute); continue; } CultureInfo locale = null; // null => do not use localization bool allLocales = false; bool currentLocale = false; XAttribute localeAttribute = dataElement.Attribute("locale"); if (localeAttribute != null) { if (localeAttribute.Value == "*") { allLocales = true; } else if (localeAttribute.Value == "?") { currentLocale = true; } else { try { locale = CultureInfo.CreateSpecificCulture(localeAttribute.Value); } catch (Exception) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.WrongLocale").FormatWith(localeAttribute.Value), localeAttribute); continue; } } } XAttribute dataFilenameAttribute = dataElement.Attribute("dataFilename"); if (dataFilenameAttribute == null) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingAttribute").FormatWith("dataFilename"), typeElement); continue; } if (!this.InstallerContext.ZipFileSystem.ContainsFile(dataFilenameAttribute.Value)) { _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingFile").FormatWith(dataFilenameAttribute.Value), dataFilenameAttribute); continue; } XDocument doc; try { using (var stream = this.InstallerContext.ZipFileSystem.GetFileStream(dataFilenameAttribute.Value)) using (var reader = new C1StreamReader(stream)) { doc = XDocument.Load(reader); } } catch (Exception ex) { _validationResult.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex)); continue; } XAttribute isDynamicAddedAttribute = typeElement.Attribute("isDynamicAdded"); bool isDynamicAdded = isDynamicAddedAttribute != null && (bool)isDynamicAddedAttribute; var dataType = new DataType { InterfaceTypeName = interfaceTypeName, DataScopeIdentifier = dataScopeIdentifier, Locale = locale, AddToAllLocales = allLocales, AddToCurrentLocale = currentLocale, IsDynamicAdded = isDynamicAdded, Dataset = doc.Root.Elements("Add") }; _dataTypes.Add(dataType); } } }
/* * 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) { var readerSettings = new XmlReaderSettings(); readerSettings.XmlResolver = null; readerSettings.DtdProcessing = DtdProcessing.Parse; readerSettings.CheckCharacters = false; List<string> xsltFilePaths = GetTransformationsInPriority().ToList(); if (xsltFilePaths.Count == 0) { return buffer; } // Detection doctype buffer.Seek(0, SeekOrigin.Begin); var line = new C1StreamReader(buffer).ReadLine(); var doctype = line.Contains("<!DOCTYPE"); buffer.Seek(0, SeekOrigin.Begin); 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 = new C1StreamReader(inputStream).ReadToEnd(); C1File.WriteAllText(tempFilePath, markup); throw new InvalidOperationException( "Incorrect xml markup, source saved in '{0}'".FormatWith(tempFilePath), xmlException); } } Verify.That(outputStream != null, "NullRef"); return outputStream; }
/// <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); }
/// <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() }; }
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(); } }
internal static void ValidateXslt(List<PackageFragmentValidationResult> validationResults, Func<XElement> elementProvider, string elementName, Func<XAttribute> xsltPathAttributeProvider, Func<string> xsltFilePathProvider, IZipFileSystem zipFileSystem, bool validateResultingConfigurationFile) { if (elementProvider() == null) { validationResults.AddFatal( GetResourceString("ConfigurationTransformationPackageFragmentInstaller.MissingElement") .FormatWith(elementName)); return; } string xslFilePath = xsltFilePathProvider(); if (xslFilePath == null) { validationResults.AddFatal( GetResourceString("ConfigurationTransformationPackageFragmentInstaller.MissingAttribute") .FormatWith(_xsltFilePathAttributeName), elementProvider()); return; } if (zipFileSystem.ContainsFile(xslFilePath) == false) { validationResults.AddFatal( GetResourceString("ConfigurationTransformationPackageFragmentInstaller.PathDoesNotExist") .FormatWith(xslFilePath), xsltPathAttributeProvider()); return; } if(!PathUtil.WritePermissionGranted(ConfigurationServices.FileConfigurationSourcePath)) { validationResults.AddFatal( GetResourceString("NotEnoughNtfsPermissions") .FormatWith(ConfigurationServices.FileConfigurationSourcePath)); return; } using (Stream xsltFileStream = zipFileSystem.GetFileStream(xslFilePath)) { using (TextReader xsltTextReader = new C1StreamReader(xsltFileStream)) { XDocument xslt = null; try { xslt = XDocument.Load(xsltTextReader); } catch (Exception ex) { validationResults.AddFatal( GetResourceString("ConfigurationTransformationPackageFragmentInstaller.UnableToParsXslt") .FormatWith(xslFilePath, ex.Message), xsltPathAttributeProvider()); } if (xslt != null && validateResultingConfigurationFile) { try { ConfigurationServices.TransformConfiguration(xslt, true); } //catch (ConfigurationException ex) //{ // validationResults.AddFatal( // GetResourceString("ConfigurationTransformationPackageFragmentInstaller.XsltWillGeneratedInvalid") // .FormatWith(xsltFilePathProvider(), ex.Message), xsltPathAttributeProvider()); //} catch (Exception ex) { validationResults.AddFatal( GetResourceString("ConfigurationTransformationPackageFragmentInstaller.XsltWillGeneratedInvalid") .FormatWith(xslFilePath, ex.Message), xsltPathAttributeProvider()); } } } } }