/// <inheritdoc/>
        public EntityResult GetEntity(UrlResolver parent, SageContext context, string resourceUri)
        {
            string resourceName = this.GetResourceName(resourceUri);
                XmlReaderSettings settings = CacheableXmlDocument.CreateReaderSettings(parent);

            CacheableXmlDocument resourceDoc;

            // first check if we have a registered provider for the specified resour name
            if (providers.ContainsKey(resourceName))
            {
                XmlProvider provider = providers[resourceName];
                log.DebugFormat("Found a specific resource provider for {0}: {1}",
                    resourceUri,
                    Util.GetMethodSignature(provider.Method));

                resourceDoc = provider(context, resourceUri);
            }
            else
            {
                string sourcePath = context.Path.Expand(resourceName);
                if (sourcePath == null || !File.Exists(sourcePath))
                    throw new FileNotFoundException(string.Format("The specified resource '{0}' doesn't exist.", resourceUri));

                resourceDoc = context.Resources.LoadXml(sourcePath);
            }

            XmlReader reader = XmlReader.Create(new StringReader(resourceDoc.OuterXml), settings, resourceUri);
            return new EntityResult { Entity = reader, Dependencies = resourceDoc.Dependencies };
        }
Exemple #2
0
        /// <inheritdoc/>
        public EntityResult GetEntity(UrlResolver parent, SageContext context, string uri)
        {
            var request = WebRequest.Create(uri);
            request.Timeout = timeout;

            if (!string.IsNullOrWhiteSpace(accept))
                request.Headers.Add(HttpRequestHeader.AcceptEncoding, accept);

            if (!string.IsNullOrWhiteSpace(acceptLanguage))
                request.Headers.Add(HttpRequestHeader.AcceptLanguage, acceptLanguage);

            var result = new EntityResult();
            try
            {
                WebResponse response = request.GetResponse();
                result.Entity = new StreamReader(response.GetResponseStream());
            }
            catch (Exception ex)
            {
                XmlDocument document = new XmlDocument();
                document.InnerXml = string.Format("<error uri=\"{0}\">{1}</error>", uri, ex.Message);
                result.Entity = new XmlNodeReader(document);
            }

            return result;
        }
Exemple #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ViewCache"/> class.
 /// </summary>
 /// <param name="context">The current context.</param>
 public ViewCache(SageContext context)
 {
     this.context = context;
     if (context.ProjectConfiguration != null)
     {
         config = context.ProjectConfiguration.ViewCaching;
         this.Directory = context.MapPath(config.Directory);
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="DictionaryFileCollection"/>, using the specified context.
        /// </summary>
        /// <param name="context">The <see cref="SageContext"/> under which this <see cref="DictionaryFileCollection"/> 
        /// is being created and used.</param>
        public DictionaryFileCollection(SageContext context)
        {
            this.context = context;

            CategoryInfo info = context.ProjectConfiguration.Categories[this.Category];
            this.Locales = new List<string>(info.Locales);

            this.Refresh();
        }
        /// <summary>
        /// Gets an <see cref="EntityResult"/> that represents the actual resource mapped from the specified <paramref name="uri"/>.
        /// </summary>
        /// <param name="parent">The <see cref="UrlResolver"/> that owns this resolved and calls this method.</param>
        /// <param name="context">The current <see cref="SageContext"/> under which this code is executing.</param>
        /// <param name="uri">The uri to resolve.</param>
        /// <returns>
        /// An object that represents the resource mapped from the specified <paramref name="uri"/>.
        /// </returns>
        public EntityResult GetEntity(UrlResolver parent, SageContext context, string uri)
        {
            string sourcePath = uri.Replace(Scheme + "://", string.Empty);
            EntityResult result = null;
            Stopwatch sw = new Stopwatch();
            long time = sw.TimeMilliseconds(() => result = this.GetClientResourceReader(context, sourcePath));
            log.DebugFormat("Time taken to get resource reader for '{0}': {1}ms", uri, time);

            return result;
        }
Exemple #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewModel"/> class.
        /// </summary>
        /// <param name="viewConfiguration">The view configuration associated with this view input.</param>
        public ViewModel(ViewConfiguration viewConfiguration)
        {
            Contract.Requires<ArgumentException>(viewConfiguration != null);

            context = viewConfiguration.Context;

            this.Action = viewConfiguration.Info.Action;
            this.ViewConfiguration = viewConfiguration;
            this.ModuleResults = new Dictionary<string, List<ModuleResult>>();
            this.Resources = new List<Resource>();
        }
Exemple #7
0
        public static XmlNode Process(SageContext context, XmlNode node)
        {
            Contract.Requires<ArgumentNullException>(node != null);
            Contract.Requires<ArgumentNullException>(context != null);

            XmlNode result;

            switch (node.NodeType)
            {
                case XmlNodeType.Document:
                    result = NodeEvaluator.Process(context, ((XmlDocument) node).DocumentElement);
                    break;

                case XmlNodeType.Element:
                    result = node.OwnerDocument.CreateElement(node.Name, node.NamespaceURI);

                    XmlNodeList attributes = node.SelectNodes("@*");
                    XmlNodeList children = node.SelectNodes("node()");

                    foreach (XmlAttribute attribute in attributes)
                    {
                        XmlNode processed = NodeEvaluator.GetNodeHandler(attribute)(context, attribute);
                        if (processed != null)
                            result.Attributes.Append((XmlAttribute) processed);
                    }

                    foreach (XmlNode child in children)
                    {
                        XmlNode processed = NodeEvaluator.GetNodeHandler(child)(context, child);
                        if (processed != null)
                            result.AppendChild(processed);
                    }

                    break;

                case XmlNodeType.Attribute:
                case XmlNodeType.Text:
                    result = node.CloneNode(true);
                    if (node.SelectSingleNode("ancestor::sage:literal", Sage.XmlNamespaces.Manager) == null)
                    {
                        result.Value = context.ProcessText(result.Value);
                    }

                    break;

                default:
                    result = node.CloneNode(true);
                    break;
            }

            return result;
        }
        public static SageContext InstanceContext()
        {
            DbContextOptions <SageContext> options;

            var builder = new DbContextOptionsBuilder <SageContext>();

            builder.UseInMemoryDatabase("InMemoryEmployeeTest");

            options = builder.Options;

            SageContext SageDataContex = new SageContext(options);

            SageDataContex.Database.EnsureDeleted();
            SageDataContex.Database.EnsureCreated();

            return(SageDataContex);
        }
Exemple #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MsXsltTransform"/> class, using the specified 
        /// <paramref name="stylesheetMarkup"/>.
        /// </summary>
        /// <param name="context">The current context.</param>
        /// <param name="stylesheetMarkup">The markup to initialize the transform with.</param>
        public MsXsltTransform(SageContext context, XmlDocument stylesheetMarkup)
        {
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(stylesheetMarkup != null);

            UrlResolver resolver = new UrlResolver(context);

            processor = new XslCompiledTransform();

            try
            {
                processor.Load(stylesheetMarkup, XsltSettings.TrustedXslt, resolver);
                dependencies.AddRange(resolver.Dependencies);
            }
            catch (Exception ex)
            {
                ProblemInfo problem = this.DetectProblemType(ex);
                throw new SageHelpException(problem, ex);
            }
        }
        private static void RewritePath(HttpApplication application)
        {
            try
            {
                SageContext context = new SageContext(application.Context);

                string requestPath = context.Request.Path;
                string localizedPath = context.Path.Localize(requestPath);
                if (localizedPath != requestPath)
                {
                    context.HttpContext.RewritePath(localizedPath);
                    if (context.IsDeveloperRequest)
                        context.Response.AddHeader("OriginalFilePath", requestPath);
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Failed to rewrite path: {0}", ex.Message);
            }
        }
Exemple #11
0
        internal static string ReadFile(SageContext context, params string[] arguments)
        {
            if (arguments.Length == 0)
            {
                log.ErrorFormat("Invalid call to read file; file path argument missing.");
                return string.Empty;
            }

            var filePath = context.MapPath(context.Path.Expand(arguments[0]));
            var convert = Convert.None;
            var pretty = false;

            if (arguments.Length >= 2)
            {
                if (arguments[1] == "xml-json")
                    convert = Convert.XmlToJson;
                else
                    log.ErrorFormat("The convert argument value '{0}' is not valid. Valid values are '{1}'.", arguments[1], "xml-json");
            }

            if (arguments.Length >= 3)
            {
                pretty = arguments[2].EqualsAnyOf("pretty", "true", "yes", "1");
            }

            if (!File.Exists(filePath))
            {
                log.WarnFormat("File '{0}' (mapped to '{1}') doesn't exist.", arguments[1], filePath);
                return string.Empty;
            }

            var content = File.ReadAllText(filePath);
            if (convert == Convert.XmlToJson)
            {
                var document = new XmlDocument();
                document.LoadXml(content);
                content = document.DocumentElement.ToJson(pretty);
            }

            return content;
        }
        private static void RewritePath(HttpApplication application)
        {
            try
            {
                SageContext context = new SageContext(application.Context);
                string requestedPath = context.Request.PhysicalPath;

                string rewrittenPath = context.Path.Resolve(requestedPath);
                if (rewrittenPath != requestedPath)
                {
                    string relativePath = context.Path.GetRelativeWebPath(rewrittenPath, true);
                    context.HttpContext.RewritePath(relativePath);
                    if (context.IsDeveloperRequest)
                        context.Response.AddHeader("OriginalFilePath", requestedPath);
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Failed to rewrite path: {0}", ex.Message);
            }
        }
Exemple #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SaxonXsltTransform"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="stylesheetMarkup">The stylesheet markup.</param>
        /// <exception cref="SageHelpException"></exception>
        public SaxonXsltTransform(SageContext context, XmlDocument stylesheetMarkup)
        {
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(stylesheetMarkup != null);

            UrlResolver resolver = new UrlResolver(context);

            processor = new Processor();

            XdmNode input = processor.NewDocumentBuilder().Build(stylesheetMarkup);
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(XmlReader.Create(stylesheetMarkup.OuterXml)).Load();

            try
            {
                //this.processor.Load(stylesheetMarkup, XsltSettings.TrustedXslt, resolver);
                dependencies.AddRange(resolver.Dependencies);
            }
            catch //(Exception ex)
            {
                //ProblemInfo problem = this.DetectProblemType(ex);
                //throw new SageHelpException(problem, ex);
            }
        }
Exemple #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlResource"/> class, using the specified resource path and context.
        /// </summary>
        /// <param name="path">The path to the XML resource.</param>
        /// <param name="context">The current <see cref="SageContext"/> under which this class is being created.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="path"/> is <c>null</c> or <paramref name="context"/> is <c>null</c>.
        /// </exception>
        public XmlResource(string path, SageContext context)
        {
            Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(path));
            Contract.Requires<ArgumentNullException>(context != null);

            this.context = context;

            this.FilePath = path;
            this.Name = new ResourceName(path, context.ProjectConfiguration.Categories[context.Category]);
            this.SourceDirectory = Path.GetDirectoryName(path);

            if (UrlResolver.GetScheme(path) == "file")
            {
                this.TargetDirectory = Path.Combine(this.SourceDirectory, context.ProjectConfiguration.PathTemplates.GlobalizedDirectory);
            }
            else
            {
                string converted = path.ReplaceAll(convertScheme, "$1/$2");
                string expanded = Path.Combine(context.ProjectConfiguration.PathTemplates.GlobalizedDirectoryForNonFileResources, converted);

                this.SourceDirectory =
                this.TargetDirectory = context.Path.Resolve(Path.GetDirectoryName(expanded));
            }
        }
Exemple #15
0
 /// <inheritdoc/>
 public override void Transform(
     XmlNode inputXml, XmlWriter outputWriter, SageContext context, Dictionary<string, object> arguments = null)
 {
     Contract.Requires<ArgumentNullException>(inputXml != null);
     Contract.Requires<ArgumentNullException>(inputXml != null);
     Contract.Requires<ArgumentNullException>(context != null);
 }
Exemple #16
0
        /// <summary>
        /// Creates a new <see cref="XsltTransform"/>, using the specified <paramref name="context"/> and <paramref name="stylesheetMarkup"/>.
        /// </summary>
        /// <param name="context">The context under which this code is executing.</param>
        /// <param name="stylesheetMarkup">The XSLT markup for the transform to create.</param>
        /// <returns>
        /// A new <see cref="XsltTransform"/> initialized with the <paramref name="stylesheetMarkup"/>.
        /// </returns>
        public static XsltTransform Create(SageContext context, XmlDocument stylesheetMarkup)
        {
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(stylesheetMarkup != null);

            XsltTransform result = new MsXsltTransform(context, stylesheetMarkup);
            foreach (string key in extensions.Keys)
            {
                result.Arguments.AddExtensionObject(key, extensions[key]);
            }

            return result;
        }
Exemple #17
0
 /// <summary>
 /// Transforms the specified <paramref name="inputXml"/> into the specified <paramref name="outputWriter"/>.
 /// </summary>
 /// <param name="inputXml">The input XML to transform.</param>
 /// <param name="outputWriter">The output writer to transform to.</param>
 /// <param name="context">The current context.</param>
 /// <param name="arguments">Optional transform arguments.</param>
 public abstract void Transform(
     XmlNode inputXml, XmlWriter outputWriter, SageContext context, Dictionary<string, object> arguments = null);
Exemple #18
0
 public UserController(ILogger <UserController> logger, SageContext sageContext)
 {
     _logger = logger;
     _db     = sageContext;
     _rnd    = new Random();
 }
Exemple #19
0
 public AddressesController(SageContext context)
 {
     _db = context;
 }
Exemple #20
0
        /// <summary>
        /// Processes any dynamic expressions embedded in the specified <paramref name="value"/>, using the
        /// specified <paramref name="context"/>.
        /// </summary>
        /// <param name="value">The value to process.</param>
        /// <param name="context">The context to use.</param>
        /// <returns>Processed version of the specified <paramref name="value"/>.</returns>
        public static string Process(string value, SageContext context)
        {
            Match match;

            const string Marker = "^^|_o_|^^";

            while ((match = dynamicExpression.Match(value)).Success)
            {
                string escape = match.Groups[1].Value;
                string wrapped = match.Groups[2].Value;
                string content = match.Groups[3].Value;
                string replacement;

                if (escape != string.Empty)
                {
                    replacement = Marker + wrapped;
                }
                else if (variables.ContainsKey(content))
                {
                    replacement = TextEvaluator.InvokeVariable(context, content);
                }
                else
                {
                    replacement = TextEvaluator.ProcessChunk(context, content);
                }

                value = value.Replace(match.Groups[0].Value, replacement);
            }

            return value.Replace(Marker, "$");
        }
Exemple #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TextEvaluator" /> class, using the specified <paramref name="context"/>.
 /// </summary>
 /// <param name="context">The context to use with this instance.</param>
 public TextEvaluator(SageContext context)
 {
     this.context = context;
 }
        private static void CopyXslElements(SageContext context, string stylesheetPath, CacheableXmlDocument targetDocument)
        {
            CacheableXmlDocument fromDocument = context.Resources.LoadXml(stylesheetPath);
            targetDocument.AddDependencies(fromDocument.Dependencies);

            string xpathOthers = string.Join(" | ",
                new[] { "/*/xsl:preserve-space", "/*/xsl:strip-space", "/*/xsl:namespace-alias", "/*/xsl:attribute-set" });

            XmlNodeList paramNodes = fromDocument.SelectNodes("/*/xsl:param", XmlNamespaces.Manager);
            XmlNodeList variableNodes = fromDocument.SelectNodes("/*/xsl:variable", XmlNamespaces.Manager);
            XmlNodeList templateNodes = fromDocument.SelectNodes("/*/xsl:template", XmlNamespaces.Manager);
            XmlNodeList includeNodes = fromDocument.SelectNodes("/*/xsl:include", XmlNamespaces.Manager);
            XmlNodeList scriptNodes = fromDocument.SelectNodes("/*/msxsl:script", XmlNamespaces.Manager);
            XmlNodeList otherNodes = fromDocument.SelectNodes(xpathOthers, XmlNamespaces.Manager);

            string stylesheetDirectory = Path.GetDirectoryName(stylesheetPath);

            // recursively add any includes
            foreach (XmlElement includeElem in includeNodes)
            {
                string includeHref = includeElem.GetAttribute("href");
                Uri includeHrefUri = new Uri(includeHref, UriKind.RelativeOrAbsolute);
                string includePath = includeHrefUri.IsAbsoluteUri ? includeHref : string.Join("/", stylesheetDirectory, includeHref);

                ModuleConfiguration.CopyXslElements(context, includePath, targetDocument);
                targetDocument.AddDependencies(includePath);
            }

            // templates
            foreach (XmlNode xslNode in templateNodes)
                targetDocument.DocumentElement.AppendChild(targetDocument.ImportNode(xslNode, true));

            foreach (XmlNode xslNode in scriptNodes)
                targetDocument.DocumentElement.AppendChild(targetDocument.ImportNode(xslNode, true));

            XmlNode firstNode = targetDocument.SelectSingleNode("/*/xsl:template[1]", XmlNamespaces.Manager);
            foreach (XmlNode xslNode in variableNodes)
                firstNode = targetDocument.DocumentElement.InsertBefore(targetDocument.ImportNode(xslNode, true), firstNode);

            // other nodes before variables or templates, params before other nodes
            foreach (XmlNode xslNode in otherNodes)
                firstNode = targetDocument.DocumentElement.InsertBefore(targetDocument.ImportNode(xslNode, true), firstNode);

            foreach (XmlNode xslNode in paramNodes)
                targetDocument.DocumentElement.InsertBefore(targetDocument.ImportNode(xslNode, true), targetDocument.DocumentElement.SelectSingleNode("*"));

            foreach (XmlAttribute attrNode in fromDocument.DocumentElement.Attributes)
                targetDocument.DocumentElement.SetAttribute(attrNode.Name, attrNode.InnerText);
        }
Exemple #23
0
 /// <summary>
 /// Gets the resolved physical path of this resource.
 /// </summary>
 /// <param name="context">The context under which this method is executed.</param>
 /// <returns>
 /// The resolved physical path of this resource
 /// </returns>
 public virtual string GetResolvedPhysicalPath(SageContext context)
 {
     return context.Path.Resolve(this.Path);
 }
Exemple #24
0
 public BaseRepository(SageContext SageContex)
 {
     SageContext = SageContex;
 }
        /// <summary>
        /// Gets the element with module's defaults, if one is provided in the module's resource directory.
        /// </summary>
        /// <param name="context">The context under which the code is executing.</param>
        /// <returns>The element with module's defaults, if one is provided in the module's resource directory.</returns>
        internal XmlElement GetDefault(SageContext context)
        {
            string documentPath = context.Path.GetModulePath(this.Key, this.Name + ".xml");
            if (File.Exists(documentPath))
            {
                XmlDocument document = context.Resources.LoadXml(documentPath);
                return document.SelectSingleElement(string.Format("/mod:{0}", this.Name), XmlNamespaces.Manager);
            }

            return null;
        }
 public PessoaRepository(SageContext SageContext) : base(SageContext)
 {
 }
Exemple #27
0
 public BaseRepository(SageContext ctx)
 {
     DbContext = ctx;
 }
Exemple #28
0
 public CustomersController(SageContext context)
 {
     _db = context;
 }
Exemple #29
0
        /// <summary>
        /// Invokes the function with the specified <paramref name="name"/> using the specified
        /// <paramref name="context"/> and <paramref name="arguments"/>.
        /// </summary>
        /// <param name="context">The context to use when invoking the function.</param>
        /// <param name="name">The name of the function to invoke.</param>
        /// <param name="arguments">The arguments to use when invoking the function.</param>
        /// <returns>The result of function invocation.</returns>
        public static string InvokeFunction(SageContext context, string name, string arguments)
        {
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(name));

            if (!functions.ContainsKey(name))
                throw new ArgumentException(string.Format("The function with name '{0}' is undefined.", name), "name");

            string[] args = Util.SplitArguments(',', arguments).ToArray();
            return functions[name](context, args);
        }
Exemple #30
0
        /// <summary>
        /// Gets the resolved web-accessible path of this resource.
        /// </summary>
        /// <param name="context">The context under which this method is executed.</param>
        /// <returns>
        /// The resolved web-accessible path of this resource
        /// </returns>
        public virtual string GetResolvedWebPath(SageContext context)
        {
            var uri = new Uri(this.Path, UriKind.RelativeOrAbsolute);
            if (uri.IsAbsoluteUri)
                return this.Path;

            string physicalPath = this.GetResolvedPhysicalPath(context);
            return context.Path.GetRelativeWebPath(physicalPath, true);
        }
Exemple #31
0
        /// <summary>
        /// Invokes the variable with the specified <paramref name="name"/> using the specified
        /// <paramref name="context"/>.
        /// </summary>
        /// <param name="context">The context to use when invoking the variable.</param>
        /// <param name="name">The name of the variable to invoke.</param>
        /// <returns>The result of variable invocation.</returns>
        public static string InvokeVariable(SageContext context, string name)
        {
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(name));

            if (!variables.ContainsKey(name))
                throw new ArgumentException(string.Format("The variable with name '{0}' is undefined.", name), "name");

            return variables[name](context, name);
        }
Exemple #32
0
        /// <summary>
        /// Generates an <see cref="XmlElement" /> that represent a this resource.
        /// </summary>
        /// <param name="ownerDocument">The owner document to use to create the element.</param>
        /// <param name="context">The context under which this method is executed, used to resolve the paths and load resources with.</param>
        /// <returns>
        /// An <see cref="XmlElement" /> that represent this resource.
        /// </returns>
        public virtual XmlNode ToXml(XmlDocument ownerDocument, SageContext context)
        {
            Contract.Requires<ArgumentNullException>(ownerDocument != null);
            Contract.Requires<ArgumentNullException>(context != null);

            XmlDocumentFragment result = ownerDocument.CreateDocumentFragment();
            List<string> webPaths = new List<string>();

            if (this.Unmerge)
            {
                if (codeFile == null)
                {
                    codeFile = CodeFile.Create(
                        this.GetResolvedPhysicalPath(context),
                        this.GetResolvedWebPath(context));
                }

                foreach (string dependency in codeFile.Dependencies)
                {
                    string webPath = context.Path.GetRelativeWebPath(dependency, true);
                    webPaths.Add(webPath);
                }
            }
            else
            {
                webPaths.Add(this.GetResolvedWebPath(context));
            }

            if (this.Type == ResourceType.CSS)
            {
                foreach (string webPath in webPaths)
                {
                    XmlElement link = ownerDocument.CreateElement("xhtml:link", XmlNamespaces.XHtmlNamespace);
                    link.SetAttribute("type", "text/css");
                    link.SetAttribute("rel", "stylesheet");
                    link.SetAttribute("href", webPath);
                    result.AppendChild(link);
                }
            }
            else if (this.Type == ResourceType.JavaScript)
            {
                foreach (string webPath in webPaths)
                {
                    XmlElement script = ownerDocument.CreateElement("xhtml:script", XmlNamespaces.XHtmlNamespace);
                    script.SetAttribute("type", "text/javascript");
                    script.SetAttribute("src", webPath);
                    result.AppendChild(script);
                }
            }
            else if (this.Type == ResourceType.Icon)
            {
                XmlElement icon = ownerDocument.CreateElement("xhtml:link", XmlNamespaces.XHtmlNamespace);
                icon.SetAttribute("rel", "icon");
                icon.SetAttribute("href", webPaths[0]);
                result.AppendChild(icon);
            }
            else
            {
                string documentPath = context.Path.Resolve(this.Path);
                XmlDocument document = context.Resources.LoadXml(documentPath);
                XmlElement importedElement = (XmlElement) ownerDocument.ImportNode(document.DocumentElement, true);
                if (!string.IsNullOrWhiteSpace(this.Name))
                {
                    var nameAttribute = ownerDocument.CreateAttribute("sage", "name", XmlNamespaces.SageNamespace);
                    nameAttribute.InnerText = this.Name;
                    importedElement.SetAttributeNode(nameAttribute);
                }

                result.AppendChild(importedElement);
            }

            return result;
        }
Exemple #33
0
        private static string ProcessChunk(SageContext context, string value)
        {
            List<string> values = new List<string>();

            // process all embedded variables, save their values in results and substitute them with placeholders
            string result = variableExpression.Replace(value, delegate(Match varMatch)
            {
                string varName = varMatch.Groups["name"].Value;
                string varValue = variables.ContainsKey(varName)
                    ? TextEvaluator.InvokeVariable(context, varName)
                    : Undefined;

                values.Add(varValue);
                return string.Format("@@V{0}", values.Count - 1);
            });

            // recursively process functions that don't contain any brackets, until there are no more of them left
            Match functMatch, valuesMatch;
            while ((functMatch = functionExpression.Match(result)).Success)
            {
                string functionName = functMatch.Groups["name"].Value;
                string functionArguments = functMatch.Groups["arguments"].Value;

                string functionValue = Undefined;
                if (functions.ContainsKey(functionName))
                {
                    while ((valuesMatch = valueExpression.Match(functionArguments)).Success)
                    {
                        int index = int.Parse(valuesMatch.Groups["index"].Value);
                        string resultValue = values.Count > index ? values[index] : Undefined;
                        functionArguments = functionArguments.Replace(valuesMatch.Groups[0].Value, resultValue);
                    }

                    functionValue = TextEvaluator.InvokeFunction(context, functionName, functionArguments);
                }

                values.Add(functionValue);
                result = result.Replace(functMatch.Groups[0].Value, string.Format("@@V{0}", values.Count - 1));
            }

            // convert any remaining placeholders into result values
            while ((valuesMatch = valueExpression.Match(result)).Success)
            {
                int index = int.Parse(valuesMatch.Groups["index"].Value);
                string resultValue = values.Count > index ? values[index] : Undefined;
                result = result.Replace(valuesMatch.Groups[0].Value, resultValue);
            }

            return result;
        }
Exemple #34
0
        public void Run()
        {
            var extensionConfigPath = arguments["extension"].Trim();
            var workingDirectory = arguments["directory"].Trim();

            if (!File.Exists(extensionConfigPath))
            {
                log.ErrorFormat("The extension configuration file '{0}' doesn't exist", extensionConfigPath);
                return;
            }

            if (!Directory.Exists(workingDirectory))
            {
                log.ErrorFormat("Directory '{0}' doesn't exist", workingDirectory);
                return;
            }

            var builder = new ExtensionBuilder();
            var fileInfo = new FileInfo(extensionConfigPath);
            var extensionConfig = ProjectConfiguration.Create(fileInfo.FullName);

            if (string.IsNullOrEmpty(extensionConfig.Name))
            {
                log.ErrorFormat("The extension needs a name, build cancelled");
                return;
            }

            log.InfoFormat("Building extension {0}.", extensionConfig.Name);

            var extensionFile = Path.Combine(fileInfo.DirectoryName, extensionConfig.Name + ".zip");
            builder.BuildExtension(fileInfo.DirectoryName, extensionFile);

            var projectFiles = Directory
                .GetFiles(workingDirectory, "Project.config", SearchOption.AllDirectories)
                .Where(s => s != fileInfo.FullName && !s.Contains(@"\bin\"));

            foreach (var projectFile in projectFiles)
            {
                var projectInfo = new FileInfo(projectFile);
                var projectConfig = ProjectConfiguration.Create(projectInfo.FullName);

                if (projectConfig.Dependencies.Contains(extensionConfig.Name))
                {
                    var httpContext = new HttpContextMock("/");
                    var projectContext = new SageContext(httpContext, delegate(string path)
                    {
                        path = path.ReplaceAll("^~?/", string.Empty).ReplaceAll("/", "\\");
                        if (!Path.IsPathRooted(path))
                            path = Path.Combine(projectInfo.DirectoryName, path);

                        return path;

                    },	projectConfig);

                    string installPath = Path.Combine(projectContext.Path.ExtensionPath, Path.GetFileName(extensionFile));
                    File.Copy(extensionFile, installPath, true);
                }
            }
        }
Exemple #35
0
        public bool ParseArguments(string[] args)
        {
            arguments = new NameValueCollection();
            foreach (string arg in args)
            {
                if (arg.StartsWith("-targetpath:"))
                {
                    arguments["targetPath"] = arg.Substring(12).Trim('"');
                }

                if (arg.StartsWith("-category:"))
                {
                    arguments["category"] = arg.Substring(10).Trim('"');
                }

                if (arg.StartsWith("-reportpath:"))
                {
                    arguments["reportpath"] = arg.Substring(12).Trim('"');
                }

                if (arg.StartsWith("-emitsummary:"))
                {
                    arguments["emitSummary"] = arg.Substring(13) == "1" ? "1" : "0";
                }

                if (arg.StartsWith("-merge:"))
                {
                    arguments["mergeAssets"] = arg.Substring(7).ContainsAnyOf("yes", "1", "true") ? "1" : "0";
                }
            }

            if (arguments["targetPath"] != null && arguments["category"] != null)
            {
                HttpContextMock httpContext = new HttpContextMock("sage");

                context = new SageContext(httpContext, arguments["category"], this.MapPath);
                categoryPath = context.Path.GetPhysicalCategoryPath(arguments["category"]);

                return true;
            }

            return false;
        }
Exemple #36
0
        /// <summary>
        /// Creates an <see cref="XsltTransform"/> instance initialized with the document loaded from the 
        /// specified <paramref name="stylesheetPath"/>.
        /// </summary>
        /// <param name="context">The context under which this code is executing.</param>
        /// <param name="stylesheetPath">The path to the <c>XSLT stylesheet</c>.</param>
        /// <returns>
        /// An <see cref="XsltTransform"/> instance initialized with the document loaded from the 
        /// specified <paramref name="stylesheetPath"/>.
        /// </returns>
        public static XsltTransform Create(SageContext context, string stylesheetPath)
        {
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(stylesheetPath));

            string key = string.Format(CacheKeyFormat, stylesheetPath);
            XsltTransform cachedItem = context.Cache.Get(key) as XsltTransform;

            if (cachedItem != null)
                return cachedItem;

            XsltTransform result = null;
            log.DebugFormat("XSLT create '{0}'", stylesheetPath);
            long milliseconds = new Stopwatch().TimeMilliseconds(() =>
            {
                CacheableXmlDocument stylesheetDocument = ResourceManager.LoadXmlDocument(stylesheetPath, context);
                XsltTransform.OmitNamespacePrefixResults(stylesheetDocument);

                result = XsltTransform.Create(context, stylesheetDocument);
                result.dependencies.AddRange(stylesheetDocument.Dependencies);

                IEnumerable<string> fileDependencies = result.Dependencies.Where(d => UrlResolver.GetScheme(d) == "file").ToList();
                result.LastModified = Kelp.Util.GetDateLastModified(fileDependencies);
                context.Cache.Insert(key, result, new CacheDependency(fileDependencies.ToArray()));
            });

            log.DebugFormat("XSLT create complete: {0}ms", milliseconds);

            return result;
        }
        private static void Initialize(SageContext context)
        {
            if (initialized)
                return;

            string definitionPath = context.Path.GetModulePath("SyntaxHighlighter", "SyntaxHighlighter.xml");
            XmlDocument definitionDoc = context.Resources.LoadXml(definitionPath);
            XmlNode definitionRoot = definitionDoc.SelectSingleNode("//mod:definitions", nm);

            languages = new Dictionary<string, LanguageDefinition>();
            foreach (XmlElement languageElement in definitionRoot.SelectNodes("mod:language", nm))
            {
                LanguageDefinition definition = new ModularLanguageDefinition(languageElement);
                languages.Add(definition.Name, definition);
            }

            foreach (XmlElement languageElement in definitionRoot.SelectNodes("mod:xmllanguage", nm))
            {
                LanguageDefinition definition = new ModularXmlLanguageDefinition(languageElement);
                languages.Add(definition.Name, definition);
            }

            initialized = true;
        }
Exemple #38
0
 public CompanyRepository(SageContext ctx) : base(ctx)
 {
 }