private HtmlElement EmbedResourceInTag(string tagName, string mimeType, string filename) { var block = HtmlPage.Document.CreateElement(tagName); block.SetAttribute("type", mimeType); string scriptOrStyle = DynamicApplication.GetResource(filename); var ieScriptOrStyleSet = false; if (HtmlPage.BrowserInformation.UserAgent.Contains("MSIE")) { if (tagName == "script") { block.SetProperty("text", scriptOrStyle); ieScriptOrStyleSet = true; } else if (tagName == "style") { (block.GetProperty("styleSheet") as ScriptObject).SetProperty("cssText", scriptOrStyle); ieScriptOrStyleSet = true; } } if (!ieScriptOrStyleSet) { var textNode = HtmlPage.Document.Invoke("createTextNode", new string[] { scriptOrStyle }); (block as ScriptObject).Invoke("appendChild", new object[] { textNode }); } return(block); }
/// <summary> /// Called by Silverlight host when it instantiates our application /// </summary> public DynamicApplication() { if (_Current != null) { throw new Exception("Only one instance of DynamicApplication can be created"); } _Current = this; _UIThreadId = Thread.CurrentThread.ManagedThreadId; Startup += new StartupEventHandler(DynamicApplication_Startup); }
public static void LoadByExtension(string fileExtension) { var path = string.Format("init{0}", fileExtension); var code = DynamicApplication.GetResource(path); if (code == null) { return; } var dyneng = DynamicApplication.Current.Engine; dyneng.Engine = dyneng.Runtime.GetEngineByFileExtension(fileExtension); dyneng.Engine.CreateScriptSourceFromString(code, path).Execute(dyneng.CreateScope()); }
/// <summary> /// Scrapes the HTML page and populates the "Code" structure. /// </summary> public void GetScriptTags() { var scriptTags = HtmlPage.Document.GetElementsByTagName("script"); foreach (ScriptObject scriptTag in scriptTags) { var e = (HtmlElement)scriptTag; var type = (string)e.GetAttribute("type"); if (type == null || !LanguageFound(GetLanguageNameFrom(type))) { continue; } if (DynamicApplication.Current.InitParams.ContainsKey("xamlid")) { if (e.CssClass == null || !e.CssClass.Contains(DynamicApplication.Current.InitParams["xamlid"])) { continue; } } else if (e.CssClass != string.Empty) { continue; } var src = (string)e.GetAttribute("src"); bool defer = (bool)e.GetProperty("defer"); string language = GetLanguageNameFrom(type).ToLower(); _LangConfig.LanguagesUsed[language] = true; var sc = new ScriptCode(language, defer); if (src != null) { sc.External = DynamicApplication.MakeUri(src); } else { var innerHtml = (string)e.GetProperty("innerHTML"); if (innerHtml != null) { sc.Inline = RemoveMargin(innerHtml); } } Code.Add(sc); } }
/// <summary> /// Gets a Stream for a file from the given "xap" file. /// </summary> /// <param name="xap">a StreamResourceInfo representing a XAP file</param> /// <param name="relativeUri">a string respresenting a relative URI</param> /// <returns>a Stream for the file, or null if it did not find the file</returns> protected override Stream GetFileInternal(object xap, Uri relativeUri) { relativeUri = new Uri(NormalizePath(relativeUri.ToString()), UriKind.Relative); StreamResourceInfo sri = null; if (xap == null) { sri = Application.GetResourceStream(relativeUri); } else { sri = Application.GetResourceStream((StreamResourceInfo)xap, relativeUri); } return(sri == null? DynamicApplication.GetManifestResourceStream(relativeUri.ToString()) : sri.Stream); }
/// <summary> /// Called by Silverlight host when it instantiates our application /// </summary> public DynamicApplication() { if (_Current != null) { throw new Exception("Only one instance of DynamicApplication can be created"); } _Current = this; _UIThreadId = Thread.CurrentThread.ManagedThreadId; _HtmlPageUri = HtmlPageUri; Settings.ReportUnhandledErrors = true; AppManifest = new DynamicAppManifest(); LanguagesConfig = DynamicLanguageConfig.Create(AppManifest.Assemblies); Startup += new StartupEventHandler(DynamicApplication_Startup); }
/// <summary> /// Gets a Stream for a file from the given "xap" file. /// </summary> /// <param name="xap">a StreamResourceInfo representing a XAP file</param> /// <param name="relativeUri">a string respresenting a relative URI</param> /// <returns>a Stream for the file, or null if it did not find the file</returns> protected override Stream GetFileInternal(object xap, Uri relativeUri) { relativeUri = new Uri(NormalizePath(relativeUri.ToString()), UriKind.Relative); StreamResourceInfo sri = null; // TODO: Application.GetResourceStream always returns null when called from // a non-UI thread. Should dispatch to the UI thread but block this thread until // the call completes. if (xap == null) { sri = Application.GetResourceStream(relativeUri); } else { sri = Application.GetResourceStream((StreamResourceInfo)xap, relativeUri); } return(sri == null? DynamicApplication.GetManifestResourceStream(relativeUri.ToString()) : sri.Stream); }
private IReplFormatter GetReplFormatter(Repl instance) { _neutralFormatter = new LanguageNeutralFormatter(this); if (_engine.Setup.FileExtensions.Count > 0) { string path = string.Format("repl_formatter{0}", _engine.Setup.FileExtensions[0]); string code = DynamicApplication.GetResource(path); if (code != null) { var scope = _engine.CreateScope(); try { _engine.CreateScriptSourceFromString(code, path).Execute(scope); var CreateReplFormatter = scope.GetVariable <Func <Repl, IReplFormatter, IReplFormatter> >("create_repl_formatter"); if (CreateReplFormatter != null) { return(CreateReplFormatter(this, _neutralFormatter)); } } catch (Exception e) { DynamicApplication.Current.HandleException(this, e); } } } return(_neutralFormatter); }
/// <summary> /// Gets a file out of the download cache. This does not download the /// file if it is not in the cache; use "DownloadAndCache" before /// using this method download the file and cache it. /// </summary> /// <param name="baseUri"> /// URI to base relative URI's off of. If null, it defaults to the HTML /// page's URI. /// </param> /// <param name="relativeUri">URI relative to the base URI</param> /// <returns>A stream for the URI</returns> protected override Stream GetFileInternal(object baseUri, Uri relativeUri) { // check in the XAP first // TODO: Can this check happen further up? if (!relativeUri.IsAbsoluteUri) { var stream = XapPAL.PAL.VirtualFilesystem.GetFile(relativeUri); if (stream != null) { return(stream); } } var fullUri = DynamicApplication.MakeUri((Uri)baseUri, relativeUri); if (_cache.Has(fullUri)) { return(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(_cache[fullUri]))); } else { return(null); } }
/// <summary> /// Gets a file out of the download cache. This does not download the /// file if it is not in the cache; use "DownloadAndCache" before /// using this method download the file and cache it. /// </summary> /// <param name="baseUri"> /// URI to base relative URI's off of. If null, it defaults to the HTML /// page's URI. /// </param> /// <param name="relativeUri">URI relative to the base URI</param> /// <returns>A stream for the URI</returns> protected override Stream GetFileInternal(object baseUri, Uri relativeUri) { if (!relativeUri.IsAbsoluteUri) { // TODO: HttpVirtualFilesystem shouldn't manage all these checks, // needs to be re-organized. // check in the XAP first var stream = XapPAL.PAL.VirtualFilesystem.GetFile(relativeUri); if (stream != null) { return(stream); } // also check any ZIP files if (HtmlPage.IsEnabled && (DynamicApplication.Current != null && DynamicApplication.Current.ScriptTags != null)) { foreach (var zip in DynamicApplication.Current.ScriptTags.ZipPackages) { var relUriStr = relativeUri.ToString(); var dirname = Path.GetDirectoryName(relUriStr); if (dirname.Length == 0) { continue; } var dirs = dirname.Split('/'); if (dirs.Length == 0) { continue; } var toplevelDir = dirs[0]; if (toplevelDir != Path.GetFileNameWithoutExtension(zip.ToString())) { continue; } var rest = relUriStr.Split(new string[] { toplevelDir + "/" }, StringSplitOptions.None); if (rest.Length <= 1) { continue; } var pathToFileInZip = rest[1]; var file = XapPAL.PAL.VirtualFilesystem.GetFile( new StreamResourceInfo(GetFileInternal(baseUri, zip), null), pathToFileInZip ); if (file != null) { return(file); } } } } var fullUri = DynamicApplication.MakeUri((Uri)baseUri, relativeUri); if (_cache.Has(fullUri)) { byte[] bytes = _cache.GetBinary(fullUri); string strContent = _cache.Get(fullUri); return(new MemoryStream( strContent != null ? System.Text.Encoding.UTF8.GetBytes(strContent) : bytes )); } else { return(null); } }
/// <summary> /// Scrapes the HTML page and populates the "Code" structure. /// </summary> public void FetchScriptTags() { if (!HtmlPage.IsEnabled) { return; } var scriptTags = HtmlPage.Document.GetElementsByTagName("script"); foreach (ScriptObject scriptTag in scriptTags) { var e = (HtmlElement)scriptTag; var type = (string)e.GetAttribute("type"); var src = (string)e.GetAttribute("src"); string language = null; // Find the language by either mime-type or script's file extension if (type != null) { language = GetLanguageByType(type); } else if (src != null) { language = GetLanguageByExtension(Path.GetExtension(src)); } // Only move on if the language was found if (language != null) { var initParams = DynamicApplication.Current.InitParams; // Process this script-tag if ... if ( // it's class is "*" ... OR (e.CssClass == "*") || // the xamlid initparam is set and matches this tag's class ... OR (initParams.ContainsKey("xamlid") && initParams["xamlid"] != null && e.CssClass != null && e.CssClass == initParams["xamlid"]) || // the xamlid initparam is not set and this tag does not have a class (!initParams.ContainsKey("xamlid") && (e.CssClass == null || e.CssClass.Length == 0)) ) { bool defer = (bool)e.GetProperty("defer"); _LangConfig.LanguagesUsed[language] = true; var sc = new ScriptCode(language, defer); if (src != null) { sc.External = DynamicApplication.MakeUri(src); } else { var innerHtml = (string)e.GetProperty("innerHTML"); if (innerHtml != null) { // IE BUG: inline script-tags have an extra newline at the front, // so remove it ... if (HtmlPage.BrowserInformation.Name == "Microsoft Internet Explorer" && innerHtml.IndexOf("\r\n") == 0) { innerHtml = innerHtml.Substring(2); } sc.Inline = innerHtml; } } Code.Add(sc); } // Lastly, check to see if this is a zip file } else if (src != null && ((type != null && type == "application/x-zip-compressed") || Path.GetExtension(src) == ".zip")) { ZipPackages.Add(DynamicApplication.MakeUri(src)); } } }
/// <summary> /// Finds the script-tag that corresponds with this Silverlight control, /// and download the src if need be. When the downloads complete (or /// if there is nothing to download), set the RootVisual to the xaml /// content. /// </summary> public static void Load() { // If there is no xamlid, then this control doesn't process XAML // script tags. if (!DynamicApplication.Current.InitParams.ContainsKey("xamlid")) { return; } // Look for the element with an id matching the value of xamlid, // and abort if it's not found. var id = DynamicApplication.Current.InitParams["xamlid"]; if (id == null) { return; } var xamlScriptTag = (HtmlElement)HtmlPage.Document.GetElementById(id); if (xamlScriptTag == null) { return; } // Fetch the external URI. var src = (string)xamlScriptTag.GetProperty("src"); // Define XAML now so "onComplete" can close over it. string xaml = null; Action onComplete = () => { // Fetch innerHTML if inline, or the downloaded file otherwise xaml = src == string.Empty ? (string)xamlScriptTag.GetProperty("innerHTML") : BrowserPAL.PAL.VirtualFilesystem.GetFileContents(DynamicApplication.MakeUri(src)); // Rewrite the XAML to remove CDATA or <?xml line var r = new StringReader(xaml); var w = new StringWriter(); string line; while ((line = r.ReadLine()) != null) { if (line.Trim() == "<![CDATA[" || line.Trim() == "]]>" || line.Contains("<?xml")) { continue; } w.WriteLine(line); } xaml = w.ToString(); // set the RootVisual DynamicApplication.Current.LoadRootVisualFromString(xaml); }; // If src is set, download the src and invoke onComplete when the // download is finished. Otherwise, just invoke onComplete. if (src == string.Empty) { onComplete.Invoke(); } else { ((HttpVirtualFilesystem)HttpPAL.PAL.VirtualFilesystem). DownloadAndCache(new List <Uri>() { DynamicApplication.MakeUri((string)src) }, onComplete); } }
/// <summary> /// Finds the script-tag that corresponds with this Silverlight control, /// and download the src if need be. When the downloads complete (or /// if there is nothing to download), set the RootVisual to the xaml /// content. /// </summary> public static void Load() { // If there is no xamlid, then this control doesn't process XAML // script tags. if (!DynamicApplication.Current.InitParams.ContainsKey("xamlid")) { return; } // Look for the element with an id matching the value of xamlid, // and abort if it's not found. var id = DynamicApplication.Current.InitParams["xamlid"]; if (id == null) { return; } var xamlScriptTag = (HtmlElement)HtmlPage.Document.GetElementById(id); if (xamlScriptTag == null) { return; } // Make sure it has the proper mime-type var type = (string)xamlScriptTag.GetAttribute("type"); if (type != "application/xaml+xml" && type != "application/xml+xaml") { return; } // Fetch the external URI. var src = (string)xamlScriptTag.GetAttribute("src"); // Should the loading of the XAML be deferred? bool defer = (bool)xamlScriptTag.GetProperty("defer"); // Define XAML now so "onComplete" can close over it. string xaml = null; Action onComplete = () => { // Only load "non-deffered" script-tags. Being deffered just means // the XAML isn't loaded, but it is already downloaded (if it was // an external script-tag), so users can just get it from the virtual // file-system. Inline XAML which is deferred can only be accessed by // getting it from the DOM. if (defer) { return; } // Fetch innerHTML if inline, otherwise get the contents from the download cache xaml = (src == null || src.Length == 0 ? (string)xamlScriptTag.GetProperty("innerHTML") : BrowserPAL.PAL.VirtualFilesystem.GetFileContents(DynamicApplication.MakeUri(src)) ).Trim(); // set the RootVisual DynamicApplication.Current.LoadRootVisualFromString(AddNamespaces(StripCDATA(xaml))); }; // If src is set, download the src and invoke onComplete when the // download is finished. Otherwise, just invoke onComplete. if (src == null || src.Length == 0) { onComplete.Invoke(); } else { ((HttpVirtualFilesystem)HttpPAL.PAL.VirtualFilesystem). DownloadAndCache(new List <Uri>() { DynamicApplication.MakeUri((string)src) }, onComplete); } }