/// <summary> /// 从XAP包中返回程序集信息 /// </summary> /// <param name="packageStream">Xap Stream</param> /// <returns>入口程序集</returns> public static Assembly LoadAssemblyFromXap(Stream packageStream) { // 加载AppManifest.xaml Stream stream = Application.GetResourceStream(new StreamResourceInfo(packageStream, null), new Uri("AppManifest.xaml", UriKind.Relative)).Stream; XmlReader xmlReader = XmlReader.Create(stream); // 读取程序集信息 Assembly entryAssembly = null; string entryAssemblyName = string.Empty; var assemblyPartInfos = new List<AssemblyPartInfo>(); while (xmlReader.Read()) { switch (xmlReader.NodeType) { case XmlNodeType.Element: if (xmlReader.Name == "Deployment") { // 入口程序集名称 entryAssemblyName = xmlReader.GetAttribute("EntryPointAssembly"); } else if (xmlReader.Name == "AssemblyPart") { var name = xmlReader.GetAttribute("x:Name"); var source = xmlReader.GetAttribute("Source"); assemblyPartInfos.Add(new AssemblyPartInfo { Name = name, Source = source }); } break; default: break; } } var assemblyPart = new AssemblyPart(); // 加载程序集 foreach (var assemblyPartInfo in assemblyPartInfos) { StreamResourceInfo streamInfo = Application.GetResourceStream(new StreamResourceInfo(packageStream, "application/binary"), new Uri(assemblyPartInfo.Source, UriKind.Relative)); // 入口程序集 if (assemblyPartInfo.Name == entryAssemblyName) { entryAssembly = assemblyPart.Load(streamInfo.Stream); } // 其他程序集 else { assemblyPart.Load(streamInfo.Stream); } } return entryAssembly; }
public void Defaults () { AssemblyPart ap = new AssemblyPart (); Assert.AreEqual (String.Empty, ap.Source, "Source"); ap.Source = "../../../bad.dll"; Assert.AreEqual ("../../../bad.dll", ap.Source, "Source/relative"); Assert.Throws<NullReferenceException> (delegate { ap.Load (null); }, "Load(null)"); Assert.IsNull (ap.Load (Stream.Null)); }
private void Application_Startup(object sender, StartupEventArgs e) { if (!HtmlPage.Document.QueryString.ContainsKey(ResourceManager.CultureParamName)) { RootVisual = new MainPage(); return; } string localeName = HtmlPage.Document.QueryString[ResourceManager.CultureParamName]; WebClient client = new WebClient(); client.OpenReadCompleted += delegate(object sender1, OpenReadCompletedEventArgs e1) { AssemblyPart part = new AssemblyPart(); part.Load(e1.Result); ResourceManager.SetCulture(localeName); RootVisual = new MainPage(); }; string absoluteUri = HtmlPage.Document.DocumentUri.AbsoluteUri; string address = absoluteUri.Substring(0, absoluteUri.LastIndexOf("/")); client.OpenReadAsync( new Uri( string.Format("{0}/ClientBin/{1}/Bonus.Praxis.SilverlightLocalization.resources.dll", address, localeName), UriKind.Absolute)); }
private static void ProcessResults(Stream result) { var manifest = Application.GetResourceStream( new StreamResourceInfo(result,null), new Uri("AppManifest.xaml", UriKind.Relative)); var appManifest = new StreamReader(manifest.Stream).ReadToEnd(); var reader = XmlReader.Create(new StringReader(appManifest)); Assembly asm = null; while (reader.Read()) { if(!reader.IsStartElement("AssemblyPart")) continue; reader.MoveToAttribute("Source"); reader.ReadAttributeValue(); if(!reader.Value.EndsWith(".dll")|| !reader.Value.StartsWith("Sydney")) continue; var assemblyStream = new StreamResourceInfo(result, "application/binary"); var si = Application.GetResourceStream(assemblyStream, new Uri(reader.Value, UriKind.Relative)); var p = new AssemblyPart(); asm = p.Load(si.Stream); break; } if(asm==null) return; var type = (from t in asm.GetTypes() where t.FullName.StartsWith("Sydney") select t).FirstOrDefault(); Activator.CreateInstance(type); }
public static Assembly ToAssembly(this FileInfo file) { AssemblyPart part = new AssemblyPart(); using (var stream = file.OpenRead()) { return part.Load(stream); } }
static void Client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { AssemblyPart part = new AssemblyPart(); Assembly assembly = part.Load(e.Result); string controlName = (e.UserState as object[])[0] as string; int id = (int)(e.UserState as object[])[1]; instance = new EntityWindow(assembly, controlName, id); instance.Show(); }
/// <summary> /// Registers the assemblies from a xap file stream. The assemblies are added to a local /// cache which will be used by the <see cref="GetLoadedAssemblies()"/> method. /// </summary> /// <param name="xapStream">The xap stream.</param> /// <param name="registerInBackground">If <c>true</c>, the assembly will be loaded in the background.</param> /// <returns>List of assemblies in the xap files.</returns> /// <remarks> /// This method requires that the xap stream contains an <c>AppManifest.xaml</c>. /// </remarks> /// <exception cref="ArgumentNullException">The <paramref name="xapStream"/> is <c>null</c>.</exception> public static void RegisterAssembliesFromXap(Stream xapStream, bool registerInBackground = false) { Argument.IsNotNull("xapStream", xapStream); try { string appManifest = new StreamReader(Application.GetResourceStream(new StreamResourceInfo(xapStream, null), new Uri("AppManifest.xaml", UriKind.Relative)).Stream).ReadToEnd(); var deploy = XDocument.Parse(appManifest).Root; var parts = (from assemblyParts in deploy.Elements().Elements() select assemblyParts).ToList(); foreach (var xe in parts) { string source = xe.Attribute("Source").Value; var asmPart = new AssemblyPart(); var streamInfo = Application.GetResourceStream(new StreamResourceInfo(xapStream, "application/binary"), new Uri(source, UriKind.Relative)); var assembly = asmPart.Load(streamInfo.Stream); if ((assembly != null) && !_externalAssemblies.Contains(assembly)) { _externalAssemblies.Add(assembly); var action = new Action(() => { Log.Debug("Initializing types for assembly '{0}'", assembly.FullName); TypeCache.InitializeTypes(false, assembly); RegisterAssemblyWithVersionInfo(assembly); Log.Debug("Initialized types for assembly '{0}'", assembly.FullName); }); if (registerInBackground) { TaskHelper.RunAndWait(new [] {action}); } else { action(); } } } } catch (Exception) { // TODO: Add logging? } }
public virtual ICommandAssembly Add(string name, byte[] contents, IKnownTypeHolder knownTypeHolder) { if (!list.ContainsKey(name)) { using (var memoryStream = new MemoryStream(contents)) { var part = new AssemblyPart(); Assembly assembly = part.Load(memoryStream); list[name] = new CommandAssembly(assembly, knownTypeHolder); } } return list[name]; }
private void LoadAndConfigureModule(Stream stream) { var part = new AssemblyPart(); var assembly = part.Load(stream); _actualEntryPoint = (IEntryPoint)Activator.CreateInstance( assembly.GetExportedTypes().First( x => typeof(IEntryPoint).IsAssignableFrom(x)) ); ServiceLocator.Current.GetInstance<IAssemblySource>() .Add(assembly); }
/// <summary> /// Loads each of the external part with name from the filenames param /// </summary> /// <param name="fileNames">An enumerable of external part file names, e.g. Telerik.Window.Controls.zip</param> private void LoadExternalParts(IEnumerable<string> fileNames, Action<int> loadProgressCallback) { foreach (string fileName in fileNames) { //if (loadedAssemblyNamesCache.Contains(fileName.Replace(".zip", ""))) continue; if (AssemblyCache.HasLoadedAssembly(fileName.Replace(".zip", ""))) continue; Stream fileStream = SynchronousDownloader.DownloadFile(new Uri(fileName, UriKind.Relative)) as Stream; var assemblyStream = Application.GetResourceStream(new StreamResourceInfo(fileStream, "application / binary"), new Uri(fileName.Replace(".zip", ".dll"), UriKind.Relative)).Stream; Deployment.Current.Dispatcher.BeginInvoke(new Action(() => { var part = new AssemblyPart(); var loadedAssembly = part.Load(assemblyStream); AssemblyCache.AddAssemblyName(loadedAssembly.FullName.Split(',').First()); })); int filesDownloaded = fileNames.ToList().IndexOf(fileName) + 1; int filesCount = fileNames.Count(); int progress = (int)(filesDownloaded / (double)filesCount * 100); loadProgressCallback(progress); } }
public void Add () { int n = Deployment.Current.Parts.Count; AssemblyPartCollection apc = new AssemblyPartCollection (); Assert.Throws<ArgumentNullException> (delegate { apc.Add (null); }, "Add(null)"); AssemblyPart ap1 = new AssemblyPart (); ap1.Load (AssemblyPartTest.GetLibraryStream ()); Assert.AreEqual (String.Empty, ap1.Source, "Source-1"); apc.Add (ap1); Assert.AreEqual (1, apc.Count, "Count-1"); AssemblyPart ap2 = new AssemblyPart (); ap2.Load (AssemblyPartTest.GetLibraryStream ()); Assert.AreEqual (String.Empty, ap2.Source, "Source-2"); apc.Add (ap2); Assert.AreEqual (2, apc.Count, "Count-2"); // no side effect on deployment Assert.AreEqual (n, Deployment.Current.Parts.Count, "Deployment.Current.Parts.Count"); }
/// <summary> /// 加载数据包 /// </summary> /// <param name="strXapName">xap包名称</param> private void LoadData(string strXapName) { string sDllSourceName = string.Empty; AssemblyPart asmPart = null; List<XElement> deploymentParts = new List<XElement>(); try { #region "直接加载xap包中的dll" dtstart = DateTime.Now; using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication()) { //打开本地xap包流 IsolatedStorageFileStream sXapfileStream = store.OpenFile(strXapName, FileMode.Open, FileAccess.Read); if (sXapfileStream.Length == 0) { //IosManager.DeletFile(ApplicationPath, "SMT.SAAS.Platform.Main.xap"); List<string> dllNames = new List<string>(); dllNames.Add("SMT.SAAS.Platform.xap"); DownLoadDll(dllNames); } #region Original Code StreamResourceInfo srXapSri = new StreamResourceInfo(sXapfileStream, "application/binary"); Stream manifestStream = Application.GetResourceStream(srXapSri, new Uri("AppManifest.xaml", UriKind.Relative)).Stream; string appManifest = new StreamReader(manifestStream).ReadToEnd(); manifestStream.Close(); //Linq to xml XElement deploymentRoot = XDocument.Parse(appManifest).Root; deploymentParts = (from assemblyParts in deploymentRoot.Elements().Elements() select assemblyParts).ToList(); //检测所有包是否在本地,不在,就从服务器上下载 bool canStart = true; List<string> dllDelete = new List<string>(); foreach (XElement xElement in deploymentParts) { if (xElement.Attribute("Source").Value.Contains("zip") && !IosManager.ExistsFile(strApplicationPath + @"/" + xElement.Attribute("Source").Value)) { dllDelete.Add(xElement.Attribute("Source").Value); canStart = false; } } if (!canStart) { DownLoadDll(dllDelete); return; } StreamResourceInfo streamInfo; //Assembly assemblyViewModel = null; string message = string.Empty; foreach (XElement xElement in deploymentParts) { try { sDllSourceName = xElement.Attribute("Source").Value; dtstart = DateTime.Now; //setLoadmingMessage( "正在加载:" + DllSourceName); if (!sDllSourceName.Contains("zip")) { //直接加载dll asmPart = new AssemblyPart(); asmPart.Source = sDllSourceName; streamInfo = Application.GetResourceStream(new StreamResourceInfo(sXapfileStream, "application/binary"), new Uri(sDllSourceName, UriKind.Relative)); if (sDllSourceName == "SMT.SAAS.Platform.dll") { asmMain = asmPart.Load(streamInfo.Stream); } else { var a = asmPart.Load(streamInfo.Stream); message = message + a.FullName + System.Environment.NewLine + "从DLL文件中直接加载程序集: "+a.FullName; } streamInfo.Stream.Close(); } else { //加载zip包 //setLoadmingMessage("正在加载:" + DllSourceName); if (sDllSourceName.Contains("zip")) { //打开本地zip包流 IsolatedStorageFileStream zipfileStream = IosManager.GetFileStream(strApplicationPath + @"/" + sDllSourceName); streamInfo = Application.GetResourceStream(new StreamResourceInfo(zipfileStream, "application/binary"), new Uri(sDllSourceName.Replace("zip", "dll"), UriKind.Relative)); asmPart = new AssemblyPart(); asmPart.Source = sDllSourceName.Replace("zip", "dll"); var a = asmPart.Load(streamInfo.Stream); streamInfo.Stream.Close(); message = message + a.FullName + System.Environment.NewLine + "从Zip文件中加载程序集: " + a.FullName; SMT.SAAS.Main.CurrentContext.AppContext.SystemMessage("从Zip文件中加载程序集: " + a.FullName); } } dtend = DateTime.Now; string strmsg = "加载成功:" + sDllSourceName + " 加载耗时: " + (dtend - dtstart).Milliseconds.ToString() + " 毫秒"; SMT.SAAS.Main.CurrentContext.AppContext.SystemMessage(strmsg); } catch (Exception ex) { string strmsg = "加载失败:" + sDllSourceName + " 错误信息: " + ex.ToString(); SMT.SAAS.Main.CurrentContext.AppContext.SystemMessage(strmsg); SMT.SAAS.Main.CurrentContext.AppContext.ShowSystemMessageText(); setLoadmingMessage("系统加载出错,请联系管理员"); HtmlPage.Window.Invoke("loadCompletedSL", new string[] { "false", strmsg }); return; } } message = string.Empty; ; #endregion } #endregion setLoadmingMessage("系统检测更新完毕,正在打开单据,请稍后..."); //return; if (isFirstUser == true) { //MainPage = asmMain.CreateInstance("SMT.SAAS.Platform.Xamls.MainPage") as UIElement; uMainPage = asmMain.CreateInstance("SMT.SAAS.Platform.Xamls.MVCMainPage") as UIElement; if (uMainPage == null) { MessageBox.Show("系统加载错误,请清空silverlight缓存后再试,或联系管理员"); setLoadmingMessage("系统加载错误,请清空silverlight缓存后再试,或联系管理员"); return; } AppContext.AppHost.SetRootVisual(uMainPage); } } catch (Exception ex) { HtmlPage.Window.Invoke("loadCompletedSL", new string[] { "false", ex.ToString() }); this.txtUserMsg.Text=@"silverlight本地存储异常,请右键点击silverlight" +System.Environment.NewLine+"选择应用程序存储,然后点击全部删除后刷新页面再试"; SMT.SAAS.Main.CurrentContext.AppContext.SystemMessage(sDllSourceName + " 加载系统出错:" + ex.ToString()); SMT.SAAS.Main.CurrentContext.AppContext.ShowSystemMessageText(); } }
private void LoadAssemblyPart(Object state) { string XapName = FilePath + @"/" + LoadXapName; string DllSourceName = string.Empty; AssemblyPart asmPart = null; List<XElement> deploymentParts = new List<XElement>(); try { #region "直接加载xap包中的dll" dtstart = DateTime.Now; using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication()) { //打开本地xap包流 IsolatedStorageFileStream XapfileStream = store.OpenFile(XapName, FileMode.Open, FileAccess.Read); if (XapfileStream.Length == 0) { //IosManager.DeletFile(ApplicationPath, "SMT.SAAS.Platform.Main.xap"); List<string> dllNames = new List<string>(); dllNames.Add(LoadXapName); DownLoadDll(dllNames); } #region Original Code StreamResourceInfo XapSri = new StreamResourceInfo(XapfileStream, "application/binary"); Stream manifestStream = Application.GetResourceStream(XapSri, new Uri("AppManifest.xaml", UriKind.Relative)).Stream; string appManifest = new StreamReader(manifestStream).ReadToEnd(); manifestStream.Close(); //Linq to xml XElement deploymentRoot = XDocument.Parse(appManifest).Root; deploymentParts = (from assemblyParts in deploymentRoot.Elements().Elements() select assemblyParts).ToList(); //检测所有包是否在本地,不在,就从服务器上下载 bool canStart = true; List<string> dllDelete = new List<string>(); foreach (XElement xElement in deploymentParts) { if (xElement.Name.LocalName != "AssemblyPart" && xElement.Name.LocalName != "ExtensionPart") continue; if (xElement.Attribute("Source").Value.Contains("zip") && !IosManager.ExistsFile(FilePath + @"/" + xElement.Attribute("Source").Value)) { dllDelete.Add(xElement.Attribute("Source").Value); canStart = false; } } if (!canStart) { DownLoadDll(dllDelete); return; } StreamResourceInfo streamInfo; //Assembly assemblyViewModel = null; foreach (XElement xElement in deploymentParts) { try { if (xElement.Name.LocalName != "AssemblyPart" && xElement.Name.LocalName != "ExtensionPart") continue; DllSourceName = xElement.Attribute("Source").Value; if (DllSourceName.Contains("SMT.SaaS.FrameworkUI")) { } dtstart = DateTime.Now; //form.setLoadmingMessage( "正在加载:" + DllSourceName); if (!DllSourceName.Contains("zip")) { //if (alreadyLoadedAssemblysList.Contains(DllSourceName)) continue; //直接加载dll asmPart = new AssemblyPart(); asmPart.Source = DllSourceName; streamInfo = Application.GetResourceStream(new StreamResourceInfo(XapfileStream, "application/binary"), new Uri(DllSourceName, UriKind.Relative)); string xapshotName = LoadXapName.Replace(".xap", ""); string dllshotName= DllSourceName.Replace(".dll", ""); if (XapName.ToUpper().Contains("XAP") && xapshotName.ToUpper() == dllshotName.ToUpper()) { asmMain = asmPart.Load(streamInfo.Stream); } else { var a = asmPart.Load(streamInfo.Stream); } //alreadyLoadedAssemblysList.Add(DllSourceName); streamInfo.Stream.Close(); } else { //加载zip包 if (DllSourceName.Contains("zip")) { string dllName = DllSourceName.Replace("zip", "dll"); //if (alreadyLoadedAssemblysList.Contains(dllName)) continue; //打开本地zip包流 IsolatedStorageFileStream zipfileStream = IosManager.GetFileStream(FilePath + @"/" + DllSourceName); streamInfo = Application.GetResourceStream(new StreamResourceInfo(zipfileStream, "application/binary"), new Uri(DllSourceName.Replace("zip", "dll"), UriKind.Relative)); asmPart = new AssemblyPart(); asmPart.Source = DllSourceName.Replace("zip", "dll"); var a = asmPart.Load(streamInfo.Stream); streamInfo.Stream.Close(); SMT.SAAS.Main.CurrentContext.AppContext.SystemMessage("从Zip文件中加载程序集: " + a.FullName); //alreadyLoadedAssemblysList.Add(dllName); } } dtend = DateTime.Now; NotifyMsg("正在加载" + DllSourceName); //string strmsg = "加载成功:" + DllSourceName + " 加载耗时: " + (dtend - dtstart).Milliseconds.ToString() + " 毫秒"; //SMT.SAAS.Main.CurrentContext.AppContext.SystemMessage(strmsg); } catch (Exception ex) { string strmsg = "加载失败:" + DllSourceName + " 错误信息: " + ex.ToString(); SMT.SAAS.Main.CurrentContext.AppContext.logAndShow(strmsg); NotifyMsg("系统加载出错,请联系管理员"+System.Environment.NewLine+ex.ToString()); return; } } #endregion } #endregion NotifyMsg("系统检测更新完毕,请您登录系统"); } catch (Exception ex) { NotifyMsg(@"silverlight本地存储异常,请右键点击silverlight ,选择应用程序存储,然后点击全部删除后刷新页面再试"); SMT.SAAS.Main.CurrentContext.AppContext.SystemMessage(DllSourceName + " 加载系统出错:" + ex.ToString()); SMT.SAAS.Main.CurrentContext.AppContext.ShowSystemMessageText(); } }
// note: throwing MoonException from here is NOT ok since this code is called async // and the exception won't be reported, directly, to the caller void AssemblyGetResponse (IAsyncResult result) { object[] tuple = (object []) result.AsyncState; WebRequest wreq = (WebRequest) tuple [0]; int error_code = (int) tuple [1]; try { HttpWebResponse wresp = (HttpWebResponse) wreq.EndGetResponse (result); if (wresp.StatusCode != HttpStatusCode.OK) { wresp.Close (); EmitError (error_code, String.Format ("Error while downloading the '{0}'.", wreq.RequestUri)); return; } if (wresp.ResponseUri != wreq.RequestUri) { wresp.Close (); EmitError (error_code, "Redirection not allowed to download assemblies."); return; } Stream responseStream = wresp.GetResponseStream (); AssemblyPart a = new AssemblyPart (); Assembly asm = a.Load (responseStream); if (asm == null) { // it's not a valid assembly, try to unzip it. using (MemoryStream ms = new MemoryStream ()) { ManagedStreamCallbacks source_cb; ManagedStreamCallbacks dest_cb; StreamWrapper source_wrapper; StreamWrapper dest_wrapper; responseStream.Seek (0, SeekOrigin.Begin); source_wrapper = new StreamWrapper (responseStream); dest_wrapper = new StreamWrapper (ms); source_cb = source_wrapper.GetCallbacks (); dest_cb = dest_wrapper.GetCallbacks (); // the zip files I've come across have a single file in them, the // dll. so we assume that any/every zip file will contain a single // file, and just get the first one from the zip file directory. if (NativeMethods.managed_unzip_stream_to_stream_first_file (ref source_cb, ref dest_cb)) { ms.Seek (0, SeekOrigin.Begin); asm = a.Load (ms); } } } wresp.Close (); if (asm != null) Dispatcher.BeginInvoke (new AssemblyRegistration (AssemblyRegister), asm); else EmitError (2153, String.Format ("Error while loading '{0}'.", wreq.RequestUri)); } catch (Exception e) { // we need to report everything since any error means CreateApplication won't be called EmitError (error_code, e.ToString ()); } }
private Assembly LoadAssemblyFromXap(string relativeUri, Stream xapPackageStream) { StreamResourceInfo xapPackageSri = new StreamResourceInfo(xapPackageStream, null); StreamResourceInfo assemblySri = Application.GetResourceStream(xapPackageSri, new Uri(relativeUri, UriKind.Relative)); AssemblyPart assemblyPart = new AssemblyPart(); return assemblyPart.Load(assemblySri.Stream); }
private static Assembly LoadAssembly(StreamResourceInfo xapPackageSri, AssemblyPart assemblyPart) { Stream assemblyStream = Application.GetResourceStream(xapPackageSri, new Uri(assemblyPart.Source, UriKind.Relative)).Stream; return assemblyPart.Load(assemblyStream); }
/// <summary> /// this function try to load an assembly from the stream in argument /// </summary> /// <param name="stream">a stream to load</param> /// <returns>an instance of a .NET assembly or null</returns> /// <remarks> /// - this function MUST NOT alter in any way the stream /// </remarks> private static Assembly TryGetAssembly(Stream stream) { try { AssemblyPart assemblyLoader = new AssemblyPart(); Assembly assembly = assemblyLoader.Load(stream); stream.Position = 0; return assembly; } catch (Exception) { return null; } }
private void LoadAndConfigureModule(Stream stream) { var part = new AssemblyPart(); var assembly = part.Load(stream); _assemblySource.Add(assembly); }
void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { try { m_XapIsLoaded = true; ItemsComboBox.Items.Clear(); ItemsComboBox.Items.Add(new NoneItemControl()); string appManifest = new StreamReader(Application.GetResourceStream(new StreamResourceInfo(e.Result, null), new Uri("AppManifest.xaml", UriKind.Relative)).Stream).ReadToEnd(); XElement deploymentRoot = XDocument.Parse(appManifest).Root; List<XElement> deploymentParts = (from assemblyParts in deploymentRoot.Elements().Elements() select assemblyParts).ToList(); foreach (XElement xElement in deploymentParts) { string source = xElement.Attribute("Source").Value; AssemblyPart asmPart = new AssemblyPart(); StreamResourceInfo streamInfo = Application.GetResourceStream(new StreamResourceInfo(e.Result, "application/binary"), new Uri(source, UriKind.Relative)); var asm = asmPart.Load(streamInfo.Stream); if (asm != null && asm.ManifestModule != null) { ItemsComboBox.Items.Add(new ItemControlBase(false) { Text = asm.ManifestModule.ToString(), Tag = asm }); } } if (ItemsComboBox.Items.Count > 0) { ItemsComboBox.SelectedIndex = 0; } } catch { } }
public void LoadNewAssemblyPartFromFixedLengthStream () { AssemblyPart ap = new AssemblyPart (); Assert.IsNull (ap.Load (GetLibraryFixedStream (0)), "0"); Assert.IsNull (ap.Load (GetLibraryFixedStream (1)), "1"); Assert.IsNull (ap.Load (GetLibraryFixedStream (10)), "10"); Assert.IsNull (ap.Load (GetLibraryFixedStream (100)), "100"); Assert.IsNull (ap.Load (GetLibraryFixedStream (1000)), "1000"); }
private static IEnumerable<Assembly> getAssemblies(Stream stream) { if (stream == null) return null; System.Windows.Resources.StreamResourceInfo xapStreamInfo = new System.Windows.Resources.StreamResourceInfo(stream, null); Uri uri = new Uri("AppManifest.xaml", UriKind.Relative); System.Windows.Resources.StreamResourceInfo resourceStream = Application.GetResourceStream(xapStreamInfo, uri); if (resourceStream == null) return null; List<Assembly> list = null; using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(resourceStream.Stream)) { if (!reader.ReadToFollowing("AssemblyPart")) { return list; } list = new List<Assembly>(); do { string attribute = reader.GetAttribute("Source"); if (attribute != null) { AssemblyPart item = new AssemblyPart(); item.Source = attribute; System.Windows.Resources.StreamResourceInfo assemblyResourceStream = Application.GetResourceStream(xapStreamInfo, new Uri(item.Source, UriKind.Relative)); if (assemblyResourceStream == null || assemblyResourceStream.Stream == null) continue; Assembly assembly = item.Load(assemblyResourceStream.Stream); if (assembly != null) list.Add(assembly); } } while (reader.ReadToNextSibling("AssemblyPart")); } return list; }
/// <summary> /// Open Resource Xap file Complete hander. /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Event Args</param> private void OpenReadResourceXapCompleted(object sender, OpenReadCompletedEventArgs e) { try { if ((e.Error == null) && (!e.Cancelled)) { // Load the Localized resources. StreamResourceInfo streamInfo = new StreamResourceInfo(e.Result, null); if (streamInfo != null) { // Get resource Manifest file. Uri manifiestURl = new Uri(appResourceManifestFilename, UriKind.RelativeOrAbsolute); if (manifiestURl != null) { StreamResourceInfo resourceInfo = Application.GetResourceStream(streamInfo, manifiestURl); if (resourceInfo != null) { StreamReader resourceReader = new StreamReader(resourceInfo.Stream); if (resourceReader != null) { string appManifest = resourceReader.ReadToEnd(); if (!String.IsNullOrEmpty(appManifest)) { XElement resourcesElements = XDocument.Parse(appManifest).Root; if (resourcesElements != null) { // Get names of all resources in manifest file. List<XElement> ResourceParts = new List<XElement>(); foreach (XElement assemblyElement in resourcesElements.Elements().Elements()) ResourceParts.Add(assemblyElement); // Load the resources. Assembly resourceAssembly = null; foreach (XElement resourceElement in ResourceParts) { string assemblyName = resourceElement.Attribute("Source").Value; if ((!string.IsNullOrEmpty(assemblyName)) && (assemblyName.ToLower().EndsWith("resources.dll", StringComparison.OrdinalIgnoreCase))) { // only load resources assemblies AssemblyPart resourcePart = new AssemblyPart(); StreamResourceInfo resourceStreamInfo = Application.GetResourceStream(new StreamResourceInfo(e.Result, "application/binary"), new Uri(assemblyName, UriKind.RelativeOrAbsolute)); if (resourceStreamInfo != null)// Load resource assembles resourceAssembly = resourcePart.Load(resourceStreamInfo.Stream); } } } } } } } } } } catch { } finally { if (e.UserState != null) { if (e.UserState is EventHandler) { EventHandler callbackEvent = e.UserState as EventHandler; if (callbackEvent != null) callbackEvent(sender, new EventArgs()); } } } }
public void LoadApplication(Stream appStream) { var assemblyPart = new AssemblyPart(); var loadedAssembly = assemblyPart.Load(appStream); Type[] assemblyTypes; if (loadedAssembly == null) { throw new TypeLoadException("Invalid class library specified"); } try { assemblyTypes = loadedAssembly.GetTypes(); } catch (Exception) { throw new TypeLoadException("Unable to load library types"); } App = FindBaseApp(assemblyTypes); IsLoaded = true; }
/// <summary> /// 根据AssemblyPart信息,从XAP流中读取具体DLL信息,并加载到AppDomain中。 /// </summary> /// <param name="sourceStream"></param> /// <param name="assemblyPart"></param> private static void LoadAssemblyFromStream(Stream sourceStream, AssemblyPart assemblyPart) { StreamResourceInfo resourceStream = Application.GetResourceStream(new StreamResourceInfo(sourceStream, null), new Uri(assemblyPart.Source, UriKind.Relative)); //此处有可能找不到对应的DLL 文件流 if (resourceStream != null) { var assebblyinfo = assemblyPart.Load(resourceStream.Stream); Platform.Logging.Logger.Current.Log(assebblyinfo.FullName, Logging.Category.Info, Logging.Priority.Low); Debug.WriteLine(assebblyinfo.FullName); } }
protected override void OnLoadCallback(TestableOpenReadCompletedEventArgs e) { // Setup initial conditions. if (State == LoaderState.LoadError) return; var resultStream = e.Result; var assembliesList = new List<Assembly>(); // Retrieve the AppManifest.xaml text. var info = GetInfo(resultStream, null, AppManifestXaml); var appManifest = new StreamReader(info.Stream).ReadToEnd(); // Extract each of the <AssemblyPart> items from the manifest. var xDeploymentRoot = XDocument.Parse(appManifest).Root; if (xDeploymentRoot == null) throw new Exception("Failed to read the application manifest."); var entryPointAssembly = GetEntryPointAssembly(xDeploymentRoot); var ns = xDeploymentRoot.Name.Namespace; var deploymentParts = ( from assemblyParts in xDeploymentRoot.Descendants(ns + "AssemblyPart") select assemblyParts ).ToList(); // Load the deployment. foreach (var xElement in deploymentParts) { // Extract the 'Source=' value from the <AssemblyPart>. var source = xElement.Attribute(AttrSource).ValueOrNull(); if (source != null) { var streamInfo = GetInfo(resultStream, AppBinary, source); var assemblyPart = new AssemblyPart(); if (source == entryPointAssembly) { // The source DLL matches the control being instantiated...load into memory and hold onto a reference of it. RootAssembly = assemblyPart.Load(streamInfo.Stream); assembliesList.Add(RootAssembly); } else { // This is not the DLL containing the control being instantiated, rather it is a dependent DLL. // Load it into memory. var assembly = assemblyPart.Load(streamInfo.Stream); assembliesList.Add(assembly); } } } // Finish up. Assemblies = assembliesList; }
void TryLoadXap(Stream xapStream) { try { StreamResourceInfo xapSri = new StreamResourceInfo(xapStream, "application/x-silverlight-app"); var manifestSri = Application.GetResourceStream(xapSri, _manifestUri); foreach (var asmUri in GetAssemblyUrisFromDeploymentXamlStream(manifestSri.Stream)) { var assemblySri = Application.GetResourceStream(xapSri, asmUri); var asmPart = new AssemblyPart(); asmPart.Load(assemblySri.Stream); } } catch (Exception ex) { // TODO : notify error } }
private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory) { extensionsElement.AssertName("extensions"); foreach (var addElement in extensionsElement.Elements("add")) { string prefix = addElement.GetOptionalAttribute("prefix", null); if (prefix != null) { prefix = prefix + "."; } string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null)); if (type != null) { this.ConfigurationItemFactory.RegisterType(Type.GetType(type, true), prefix); } string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null); if (assemblyFile != null) { try { #if SILVERLIGHT && !WINDOWS_PHONE var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else string fullFileName = Path.Combine(baseDirectory, assemblyFile); InternalLogger.Info("Loading assembly file: {0}", fullFileName); Assembly asm = Assembly.LoadFrom(fullFileName); #endif this.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error loading extensions: {0}", exception); if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception); } } continue; } string assemblyName = addElement.GetOptionalAttribute("assembly", null); if (assemblyName != null) { try { InternalLogger.Info("Loading assembly name: {0}", assemblyName); #if SILVERLIGHT && !WINDOWS_PHONE var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else Assembly asm = Assembly.Load(assemblyName); #endif this.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error loading extensions: {0}", exception); if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception); } } continue; } } }
private Assembly GetAssemblyFromPackage(string assemblyName, Stream xap) { // Local variables Uri assemblyUri = null; StreamResourceInfo resPackage = null; StreamResourceInfo resAssembly = null; AssemblyPart part = null; // Initialize assemblyUri = new Uri(assemblyName, UriKind.Relative); resPackage = new StreamResourceInfo(xap, null); resAssembly = Application.GetResourceStream(resPackage, assemblyUri); // Extract an assembly part = new AssemblyPart(); Assembly a = part.Load(resAssembly.Stream); return a; }
private static void LoadAssemblyFromStream(Stream sourceStream, AssemblyPart assemblyPart) { Stream assemblyStream = Application.GetResourceStream( new StreamResourceInfo(sourceStream, null), new Uri(assemblyPart.Source, UriKind.Relative)).Stream; assemblyPart.Load(assemblyStream); }
private static void LoadToAssemblyPart(Stream assemblyStream, string name) { var part = new AssemblyPart { Source = name }; var assembly = part.Load(assemblyStream); LoadedAssemblies.Add(name, assembly); }