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 override void Append(ErrorInfo error) { var pairs = new List<KeyValuePair<string, string>>(); foreach (AssemblyPart ap in Deployment.Current.Parts) { StreamResourceInfo sri = Application.GetResourceStream(new Uri(ap.Source, UriKind.Relative)); if (sri != null) { Assembly assembly = new AssemblyPart().Load(sri.Stream); pairs.Add(Message("Assembly", assembly.FullName)); pairs.Add(Message("ImageRuntimeVersion", assembly.ImageRuntimeVersion)); try { if (assembly.Location.Length != 0) { pairs.Add(Message("Location", assembly.Location)); } } catch { } } } error.AddDetail(this.Name, pairs); }
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 void Application_Startup(object sender, StartupEventArgs e) { var catalog = new AssemblyCatalog(typeof(App).Assembly); var aggregateCatalog = new AggregateCatalog(catalog); aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(ITopLevelWindow).Assembly)); aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(MainViewModel).Assembly)); aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(BaseViewModel).Assembly)); aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(IExpressionServiceBase).Assembly)); var container = new CompositionContainer(aggregateCatalog); this.Container = container; CompositionHost.Initialize(container); CompositionInitializer.SatisfyImports(this); var settings = UnitTestSystem.CreateDefaultSettings(); var testAssemblies = Deployment.Current.Parts.Where(p => p.Source.Contains("Tests")).ToList(); foreach (var assemblyPart in testAssemblies) { var assembly = new AssemblyPart().Load(GetResourceStream(new Uri(assemblyPart.Source, UriKind.Relative)).Stream); if (!settings.TestAssemblies.Contains(assembly)) { settings.TestAssemblies.Add(assembly); } } RootVisual = UnitTestSystem.CreateTestPage(settings); }
/// <summary> /// 获取流中的所有DLL。 /// 通过AppManifest.xaml获取包中包含的DLL列表。 /// 其格式为XML,再根据AssemblyPart节点获取所有的DLL名称。 /// </summary> /// <param name="stream"></param> /// <returns></returns> private static IEnumerable<AssemblyPart> GetParts(Stream stream) { List<AssemblyPart> assemblyParts = new List<AssemblyPart>(); var streamReader = new StreamReader(Application.GetResourceStream(new StreamResourceInfo(stream, null), new Uri("AppManifest.xaml", UriKind.Relative)).Stream); using (XmlReader xmlReader = XmlReader.Create(streamReader)) { xmlReader.MoveToContent(); while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "Deployment.Parts") { using (XmlReader xmlReaderAssemblyParts = xmlReader.ReadSubtree()) { while (xmlReaderAssemblyParts.Read()) { if (xmlReaderAssemblyParts.NodeType == XmlNodeType.Element && xmlReaderAssemblyParts.Name == "AssemblyPart") { AssemblyPart assemblyPart = new AssemblyPart(); //获取每个DLL的名称。并添加到AssemblyPart信息中。 assemblyPart.Source = xmlReaderAssemblyParts.GetAttribute("Source"); assemblyParts.Add(assemblyPart); } } } break; } } } return assemblyParts; }
public static Type GetAssemblyType(string assemblyName, string className) { StreamResourceInfo info = Application.GetResourceStream(new Uri(assemblyName, UriKind.Relative)); Assembly assembly = new AssemblyPart().Load(info.Stream); Type type = assembly.GetType(className); return type; }
private void Initialize() { foreach (AssemblyPart asmPart in Deployment.Current.Parts) { StreamResourceInfo sri = Application.GetResourceStream(new Uri(asmPart.Source, UriKind.Relative)); Assembly asm = new AssemblyPart().Load(sri.Stream); LoadControllers(asm); } }
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? } }
/// <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)); }
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); }
public void LoadNewAssemblyPartFromMemoryStream () { var assembly = new AssemblyPart ().Load (GetLibraryStream ()); Assert.IsNotNull (assembly); var type = assembly.GetType ("Foo.Bar"); Assert.IsNotNull (type); // a second time ? var a2 = new AssemblyPart ().Load (GetLibraryStream ()); Assert.IsTrue (Object.ReferenceEquals (assembly, a2), "twice"); }
public static IEnumerable<Type> GetTypes() { if (Types == null) { Types = new List<Type>(); foreach (AssemblyPart part in Deployment.Current.Parts) { StreamResourceInfo info = Application.GetResourceStream(new Uri(part.Source, UriKind.Relative)); Assembly assembly = new AssemblyPart().Load(info.Stream); Types.AddRange(assembly.GetTypes()); } } return Types; }
private void wcXap_OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if ((e.Error == null) && (e.Cancelled == false)) { var xap = new StreamResourceInfo(e.Result, null); System.Reflection.Assembly asm = new AssemblyPart().Load( Application.GetResourceStream( xap, new Uri("Eggs.dll", UriKind.Relative) ).Stream ); asm.GetType("Eggs").GetMethod("Start").Invoke(null, new object[] { (object) new Uri("http://localhost:35863/TicTacToe.Tests.xap"), (object) xap }); } }
/// <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); } }
public static List <MethodInfo> GetExtensionMethods(string name, DynamicMetaObject targetMO, DynamicMetaObject[] args) { List <MethodInfo> res = new List <MethodInfo>(); #if !SILVERLIGHT foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) { #else foreach (w.AssemblyPart ap in w.Deployment.Current.Parts) { StreamResourceInfo sri = w.Application.GetResourceStream(new Uri(ap.Source, UriKind.Relative)); Assembly a = new w.AssemblyPart().Load(sri.Stream); #endif Type[] types; try { types = a.GetTypes(); } catch (ReflectionTypeLoadException ex) { types = ex.Types; } foreach (Type t in types) { if (t != null && t.IsPublic && t.IsAbstract && t.IsSealed) { foreach (MethodInfo mem in t.GetMember(name, MemberTypes.Method, BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase)) { //Should test using mem.IsDefined(attr) but typeof(ExtenssionAttribute) in Microsoft.Scription.Extensions and System.Core are infact two different types //Type attr = typeof(System.Runtime.CompilerServices.ExtensionAttribute); if (mem.GetParameters().Length == args.Length && mem.GetParameters()[0].ParameterType == targetMO.RuntimeType) { if (RuntimeHelpers.ParametersMatchArguments( mem.GetParameters(), args)) { res.Add(mem); } } } } } } return(res); }
internal static void Initialize() { // populate the assembly names cache with the assemblies inside this XAP foreach (AssemblyPart ap in Deployment.Current.Parts) { StreamResourceInfo sri = Application.GetResourceStream(new Uri(ap.Source, UriKind.Relative)); Assembly a = new AssemblyPart().Load(sri.Stream); loadedAssemblyNamesCache.Add(a.FullName.Split(',').First()); } // populate the assembly names cache with the assembly parts referred from thisXAP foreach (var ep in Deployment.Current.ExternalParts) { string assemblyName = ep.Source.OriginalString.Replace(".zip", ""); loadedAssemblyNamesCache.Add(assemblyName); } }
public MainPage() { InitializeComponent(); var result = new StringBuilder(); StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("EmitMapperTests.SL.dll", UriKind.Relative)); var testFixtures = new AssemblyPart() .Load(streamInfo.Stream) .GetTypes() .Where(t => t.GetCustomAttributes(typeof(TestFixtureAttribute), false).Length > 0 ) .ToArray(); int cntAll = 0; int cntPassed = 0; foreach (var t in testFixtures) { var obj = Activator.CreateInstance(t); foreach (var mi in t.GetMethods() .Where(m => m.GetCustomAttributes(typeof(TestAttribute), false).Length > 0 && m.GetParameters().Length == 0) ) { result.Append("Executing " + t.ToString() + "." + mi.Name + "... "); try { cntAll++; mi.Invoke(obj, null); cntPassed++; result.AppendLine("OK"); } catch (Exception e) { result.AppendLine("ERROR"); result.AppendLine(e.ToString()); result.AppendLine("--------------------------------"); } } } result.AppendLine("Done. " + cntPassed + "(" + cntAll + ")"); txtOut.Text = result.ToString(); }
private void AddLoadedAssemblies() { foreach (AssemblyPart ap in Deployment.Current.Parts) { StreamResourceInfo sri = Application.GetResourceStream(new Uri(ap.Source, UriKind.Relative)); Assembly assembly = new AssemblyPart().Load(sri.Stream); if (assembly.FullName.Contains("Module") && !(assembly.FullName.Contains("Interfaces") || assembly.FullName.Contains("Services") || assembly.FullName.Contains("Framework"))) { _partsToInvestigate.Add(assembly); } if (assembly.FullName.Contains("Shell") && !(assembly.FullName.Contains("Interfaces") || assembly.FullName.Contains("Services") || assembly.FullName.Contains("Framework"))) { _partsToInvestigate.Add(assembly); } } }
private static bool IsNotSpecialAssembly(AssemblyPart ap) { if (ap.Source.Equals("System.Windows.Controls.dll", StringComparison.OrdinalIgnoreCase)) return false; if (ap.Source.Equals("System.Xml.Linq.dll", StringComparison.OrdinalIgnoreCase)) return false; if (ap.Source.Equals("System.Xml.Serialization.dll", StringComparison.OrdinalIgnoreCase)) return false; if (ap.Source.Equals("Microsoft.Silverlight.Testing.dll", StringComparison.OrdinalIgnoreCase)) return false; if (ap.Source.Equals("Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll", StringComparison.OrdinalIgnoreCase)) return false; if (ap.Source.Equals("StatLight.Client.Harness.MSTest.dll", StringComparison.OrdinalIgnoreCase)) return false; if (ap.Source.Equals("StatLight.Client.Harness.dll", StringComparison.OrdinalIgnoreCase)) return false; return true; }
/// <summary> /// we use the look in the deployment manifest to list and load all the assemblies contained /// this should be valid only for the XAP that startup the application, any dynamically /// loaded assembly won't be checked. /// /// todo: check for a better implementation /// </summary> /// <param name="domain"></param> /// <returns></returns> public static Assembly[] GetAssemblies(this AppDomain domain) { if (Assemblies == null) { lock (_syncLock) { if (Assemblies == null) { List<Assembly> assemblies = new List<Assembly>(); foreach (System.Windows.AssemblyPart ap in System.Windows.Deployment.Current.Parts) { System.Windows.Resources.StreamResourceInfo sri = System.Windows.Application.GetResourceStream(new Uri(ap.Source, UriKind.Relative)); Assembly assembly = new System.Windows.AssemblyPart().Load(sri.Stream); assemblies.Add(assembly); } Assemblies = assemblies.ToArray(); } } } return Assemblies; }
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> /// 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); } }
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); }
/// <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()); } } } }
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; } } }
public void DataTransferObject_PublicPropertySetterCallsOnPropertyChanged_Succeeds() { List<string> ignoredDtoProperties = new List<string> () { "Notifications" }; IDtoFactory dtoFactory = new DtoFactory (); foreach ( AssemblyPart assemblyPart in Deployment.Current.Parts ) { StreamResourceInfo sri = Application.GetResourceStream ( new Uri ( assemblyPart.Source, UriKind.Relative ) ); Assembly dtoAssembly = new AssemblyPart ().Load ( sri.Stream ); var allDtos = dtoAssembly.GetTypes () .Where ( t => typeof ( EditableDataTransferObject ).IsAssignableFrom ( t ) && !t.IsAbstract ) .Select ( t => new { Dto = dtoFactory.CreateDto ( t ), PropSet = t.GetProperties () .Select ( p => new { PropertyName = p.Name, PropertySetter = p.GetSetMethod () } ) .Where ( p => p.PropertySetter != null && !ignoredDtoProperties.Contains ( p.PropertyName ) ) } ); foreach ( var d in allDtos ) { INotifyPropertyChanged inpc = d.Dto; foreach ( var p in d.PropSet ) { // Setup event handler for the property being examined string changedPropertyName = String.Empty; // use named variable (as opposed to anonymous delegate) so we can unsubscribe PropertyChangedEventHandler inpcOnPropertyChanged = ( obj, e ) => changedPropertyName = e.PropertyName; inpc.PropertyChanged += inpcOnPropertyChanged; // Simulate property change by invoking setter directly p.PropertySetter.Invoke ( d.Dto, new object[] { null } ); Assert.AreEqual ( p.PropertyName, changedPropertyName, String.Format ( "Offending DTO type::property {0}::{1}", d.Dto.GetType (), p.PropertyName ) ); // Reset event handler inpc.PropertyChanged -= inpcOnPropertyChanged; } } } }
/// <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(); } }
// 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) { Assembly asm; object[] tuple = (object [])result.AsyncState; WebRequest wreq = (WebRequest)tuple [0]; ManifestAssemblyKind kind = (ManifestAssemblyKind)tuple [1]; int error_code = (kind == ManifestAssemblyKind.ExternalAssembly) ? 2152 : 2105; 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 ((kind != ManifestAssemblyKind.ExternalAssembly) && (wresp.ResponseUri != wreq.RequestUri)) { wresp.Close(); EmitError(error_code, "Redirection not allowed to download assemblies."); return; } using (Stream responseStream = wresp.GetResponseStream()) { byte [] buffer = AssemblyPart.StreamToBuffer(responseStream); if (IsZip(buffer)) { // unzip it. using (MemoryStream dest = new MemoryStream()) { using (MemoryStream source = new MemoryStream(buffer)) { ManagedStreamCallbacks source_cb; ManagedStreamCallbacks dest_cb; StreamWrapper source_wrapper; StreamWrapper dest_wrapper; source_wrapper = new StreamWrapper(source); dest_wrapper = new StreamWrapper(dest); source_cb = source_wrapper.GetCallbacks(); dest_cb = dest_wrapper.GetCallbacks(); // Zip files may contain multiple assemblies, all of which need to be loaded. Keep // attempting to open subsequent files until it fails. for (int i = 0; ; i++) { if (!NativeMethods.managed_unzip_stream_to_stream_nth_file(ref source_cb, ref dest_cb, i)) { break; } if (Load(dest.ToArray(), kind) == null) { EmitError(2153, String.Format("Error while loading '{0}'.", wreq.RequestUri)); } source.Position = 0; dest.SetLength(0); } } } } else { if (Load(buffer, kind) == null) { EmitError(2153, String.Format("Error while loading '{0}'.", wreq.RequestUri)); } } } Dispatcher.BeginInvoke(AsyncDownloadComplete); } catch (Exception e) { // we need to report everything since any error means CreateApplication won't be called EmitError(error_code, e.ToString()); } }