Exemple #1
0
        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;
        }
Exemple #3
0
 /// <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();
         }
     }
 }
Exemple #4
0
 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();
     }
 }
Exemple #5
0
        /// <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();
                    }
                }
            }
        }
        /// <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() };
        }
Exemple #8
0
        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();
            }
        }