/// <summary> /// Files the name. </summary> /// <param name="dir">The dir.</param> /// <returns>System.String.</returns> private static string FileName(DirectoryInfo dir) { try { if (dir == null) { return(null); } FileInfo[] files = dir.GetFiles("*.addin"); if (files.Length > 0) { return(files[0].FullName); } if (dir.GetDirectories().Any()) { return(FileName(dir.GetDirectories()[0])); } } catch (IOException ex) { FileLogUtility.Error($"{ex.Source}:无效的插件!请联系软件开发商!"); } return(null); }
protected override void DoStop(BundleStopOptions option) { if (((base.State != BundleState.Starting) && (base.State != BundleState.Stopping)) && base.IsActive) { base.State = BundleState.Stopping; IBundleContext context = base.Context; Exception exception = null; try { if (this.Activator != null) { this.Activator.Stop(context); } } catch (Exception exception2) { FileLogUtility.Error(string.Format(Messages.ExceptionOccursWhenStopping, base.SymbolicName, base.Version)); FileLogUtility.Error(exception2); exception = exception2; } this.CheckValidState(); base.State = BundleState.Resolved; if (option == BundleStopOptions.General) { this.SavePersistent(); } base.Context.Dispose(); base.Context = null; if (exception != null) { throw exception; } } }
/// <summary> /// Search *.addin for dirName /// 搜索文件下面为*.addin 文件 /// </summary> /// <returns>错误返回NULL</returns> private static AddinMetadata SearchXml(string dirName) { string xmlpatch = dirName + "\\" + AddinFile; if (!File.Exists(xmlpatch)) { xmlpatch = dirName + "\\bin\\" + AddinFile; if (!File.Exists(xmlpatch)) { xmlpatch = FileName(new DirectoryInfo(dirName)); } } if (System.IO.File.Exists(xmlpatch)) { string xml = string.Empty; using (StreamReader reader = File.OpenText(xmlpatch)) { xml = reader.ReadToEnd(); } return((AddinMetadata)XmlConvertor.XmlToObject(typeof(AddinMetadata), xml)); } else { FileLogUtility.Error($"{dirName}:没有找到合适的插件配置文件"); return(null); } }
private void LogWhenAcquireLockFailed() { if (!this._lockAcquired) { FileLogUtility.Error(string.Format("AcquireTheLockTimeout", this._millisecondsTimeout)); } }
private void ResolveAndValidateAssembly(string bundlePath, List <IAssemblyMetadata> assemblyMetadata) { assemblyMetadata.RemoveAll(delegate(IAssemblyMetadata item) { try { AssemblyName name3; string assemblyFile = BundleUtility.FindAssemblyFullPath(bundlePath, item.Path, true); AssemblyName assemblyName = AssemblyName.GetAssemblyName(assemblyFile); if (assemblyName == null) { assemblyName = new AssemblyName { Name = Path.GetFileNameWithoutExtension(assemblyFile), Version = FrameworkConstants.DEFAULT_VERSION, CultureInfo = FrameworkConstants.DEFAULT_CULTURE }; } item.Path = assemblyFile; item.Version = assemblyName.Version; item.AssemblyName = assemblyName; if (this.TryToReplaceWithGlobalAssembly(item, out name3)) { FileLogUtility.Warn(string.Format(Messages.LocalAssemblyReplacedByGlobal, new object[] { item.AssemblyName, item.Owner.SymbolicName, item.Owner.Version, name3 })); item.IsDuplicatedWithGlobalAssembly = true; item.AssemblyName = name3; } return(false); } catch (Exception exception) { item.Owner.AssembliesFailedToLoad.Add(item); FileLogUtility.Error(string.Format(Messages.BundleAssemblyLoadFailed, new object[] { item.Path, item.Owner.SymbolicName, item.Owner.Version, exception.Message })); return(true); } }); }
/// <summary> /// 获取插件的配置。 /// </summary> /// <param name="bundle">插件。</param> /// <returns>插件的配置对象。</returns> private Configuration Get(IBundle bundle) { AssureConfigFileExist(bundle); // 确保文件存在 using (var locker = _configurations.Lock()) // 从缓存中获取 { if (locker.ContainsKey(bundle)) { return(locker[bundle]); } } var configFile = Path.Combine(bundle.Location, ConfigurationFile); try { // 获取配置对象 var configMap = new ExeConfigurationFileMap(); configMap.ExeConfigFilename = configFile; var bundleConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None); using (var locker = _configurations.Lock()) // 保存到缓存 { locker[bundle] = bundleConfiguration; } return(bundleConfiguration); } catch (ConfigurationErrorsException ex) { FileLogUtility.Error(string.Format("Failed to load the Bundle configuration file '{0}' for bundle '{1}'.", configFile, bundle.SymbolicName)); FileLogUtility.Error(ex); throw; } }
public virtual void Stop() { try { _state = BundleState.Stopping; EventManager.OnBundleChanged(new BundleEventArgs(BundleTransition.Stopping, this)); foreach (IBundleActivator activator in Acitvators) { if (activator == null) { throw new Exception("No activator for: " + Location); } activator.Stop(this.Context); } _activators = null; _framework.UnloadDomain(_domain); } catch (Exception ex) { FileLogUtility.Error(string.Format("{0}:{1}", ex.Message, "Bundle. Stop()")); throw new BundleException(ex.Message, ex); } _state = BundleState.Installed; EventManager.OnBundleChanged(new BundleEventArgs(BundleTransition.Stopped, this)); }
private void LogWhenAcquireLockFailed() { if (!_lockAcquired) { FileLogUtility.Error(string.Format(Messages.AcquireTheLockTimeout, _millisecondsTimeout)); } }
}/// <summary> /// 启动组件 /// </summary> /// <param name="bundle">组件</param> public void StartBundle(IBundle bundle) { if (bundle == null) { FileLogUtility.Error("Bundle is Null."); return; } bundle.Start(); }
// 处理菜单点击事件 private void MenuClicked(object sender, EventArgs e) { // 通过Tag属性获取WinShellMenu对象 var menu = (sender as ToolStripMenuItem).Tag as WinShellMenu; // 如果已经有一个TabPage显示,则直接选择该TabPage foreach (TabPage tab in WorkspaceTabControl.TabPages) { if (tab.Tag == menu) { WorkspaceTabControl.SelectedTab = tab; return; } } // 加载菜单对应的类型 Type menuClass = null; if (!string.IsNullOrEmpty(menu.ClassName)) { try { // 必须通过对应的插件来动态加载类型 menuClass = menu.Application.Bundle.LoadClass(menu.ClassName); } catch { FileLogUtility.Error(string.Format("Failed to load class '{0}' from bundle '{1}'.", menu.ClassName, menu.Application.Bundle.SymbolicName)); } } if (menuClass != null) { // 创建菜单对应的控件实例 Control control = (Control)System.Activator.CreateInstance(menuClass); Form form = control as Form; if (form != null) { form.TopLevel = false; form.WindowState = FormWindowState.Maximized; form.ControlBox = false; form.FormBorderStyle = FormBorderStyle.None; } // 创建一个标签页,并显示菜单对应的控件(窗体或用户控件) TabPage tabPage = new TabPage(menu.Text); // 将WinShellMenu与TabPage关联 tabPage.Tag = menu; tabPage.Controls.Add(control); WorkspaceTabControl.TabPages.Add(tabPage); tabPage.AutoScroll = true; WorkspaceTabControl.SelectedTab = tabPage; control.Dock = DockStyle.Fill; control.Visible = true; } }
public static bool Validate(ref string value, string name, string symbolicName, string extensionPoint, string defaultValue) { if (string.IsNullOrWhiteSpace(value)) { value = defaultValue; FileLogUtility.Error(string.Format("{0} is not specified in bundle {1} for extension point {2} so it's set to default {3}.", name, symbolicName, extensionPoint, defaultValue)); } return(true); }
public static bool Validate(string value, string name, string symbolicName, string extensionPoint) { if (string.IsNullOrWhiteSpace(value)) { FileLogUtility.Error(string.Format("{0} is not specified or not in correct format in bundle {1} for extension point {2} so it's or part of it's ignored.", name, symbolicName, extensionPoint)); return(false); } return(true); }
private void LogAssembliesFailedToLoaded(IBundleMetadata unresolvedNode) { Action <IAssemblyMetadata> action = null; if (unresolvedNode.AssembliesFailedToLoad.Count > 0) { if (action == null) { action = node => FileLogUtility.Error(string.Format(Messages.BundleLocalAssemblyResolvedFailed, unresolvedNode.SymbolicName, unresolvedNode.Version, node.Path)); } unresolvedNode.AssembliesFailedToLoad.ForEach(action); } }
protected override void DoStart(BundleStartOptions option) { if (((base.State != BundleState.Starting) && (base.State != BundleState.Stopping)) && !base.IsActive) { if (!base.IsResolved) { base.Framework.FrameworkAdaptor.State.Resolve(); if (!base.IsResolved) { throw new BundleException($"The bundle '{base.SymbolicName}, {base.Version}' is started failed since it can not be resolved."); } } if (LicenseService.RequireBundleLicenseValidation) { try { LicenseService.ValidateBundleLicense(base.BundleData, true); } catch (Exception exception) { FileLogUtility.Error(exception); return; } } if ((base.BundleData.Activator == null) || (base.BundleData.Activator.Policy != ActivatorPolicy.Lazy)) { base.State = BundleState.Starting; if (option != BundleStartOptions.Transient) { BundlePersistentData persistentData = this.GetPersistentData(); if ((persistentData != null) && (persistentData.State == BundleState.Active)) { this.CallTryStart(); return; } } this.CallTryStart(); if (option != BundleStartOptions.Transient) { this.SavePersistent(); } } else if (base.State != BundleState.Starting) { base.State = BundleState.Starting; base.Framework.EventManager.DispatchBundleLazyActivateEvent(this, new BundleLazyActivatedEventArgs(this)); } } }
public static void Save <T>(string file, T obj) { try { var serializer = new XmlSerializer(typeof(T)); var stream = new FileStream(file, FileMode.Create); serializer.Serialize(stream, obj); stream.Close(); } catch (Exception ex) { FileLogUtility.Error(string.Format(Messages.FailedToSavePersistence, file, ex.Message)); FileLogUtility.Error(ex); } }
/// <summary> /// 停止组件根据编号 /// </summary> /// <param name="id">组件编号</param> public void StopBundle(int id) { IBundle bundle = _bundleRepository.GetBundle(id); if (bundle == null) { FileLogUtility.Error($"Bundle not found.BundleId:{id}"); } if (bundle != null && bundle.State != BundleState.Active) { FileLogUtility.Error($"{bundle.SymbolicName}Bundle is not active."); } //判断是否为空 bundle?.Stop(); }/// <summary>
/// <summary> /// 利用主键来获取唯一信息。 /// </summary> /// <param name="keyValues">键值。</param> /// <returns>指定实体。</returns> public virtual T GetByKey(params object[] keyValues) { try { using (var context = NewDbContext()) { return(context.Set <T>().Find(keyValues)); } } catch (Exception ex) // 将异常信息记录到调试日志。 { FileLogUtility.Error(string.Format("Failed to get '{0}'.", typeof(T).Name)); FileLogUtility.Error(ex); return(null); } }
/// <summary> /// 设置查询表达式来获取实体集合。 /// </summary> /// <param name="predicate">查询条件表达式。</param> /// <returns>返回符合条件的实体集合。</returns> public virtual List <T> Get(Expression <Func <T, bool> > predicate) { try { using (var context = NewDbContext()) { return(context.Set <T>().Where(predicate).ToList()); // 过滤并获取实体集合。 } } catch (Exception ex) // 将异常信息记录到调试日志。 { FileLogUtility.Error(string.Format("Failed to get '{0}'s.", typeof(T).Name)); FileLogUtility.Error(ex); return(new List <T>()); } }
/// <summary> /// 从数据库获取所有的实体。 /// </summary> /// <returns>实体集合。</returns> public virtual List <T> GetAll() { try { using (var context = NewDbContext()) { return(context.Set <T>().ToList()); // 获取所有实体。 } } catch (Exception ex) // 将异常信息记录到调试日志。 { FileLogUtility.Error(string.Format("Failed to get '{0}'s.", typeof(T).Name)); FileLogUtility.Error(ex); return(new List <T>()); } }
public override void Stop() { try { this._state = BundleState.Stopping; EventManager.OnBundleChanged(new BundleEventArgs(BundleTransition.Stopping, this)); this._state = BundleState.Installed; EventManager.OnBundleChanged(new BundleEventArgs(BundleTransition.Stopped, this)); } catch (Exception ex) { //TracesProvider.TracesOutput.OutputTrace(ex.Message); FileLogUtility.Error(string.Format("{0}:{1}", ex.Message, "SystemBundle. Stop()")); } }
public void RemoveWeChatProxy(string name, IBundle bundle) { if (!string.IsNullOrEmpty(name)) { var serviceProxies = Activator.WeChatProxyContainer.ServiceWeChatProxies; var item = serviceProxies.Where(i => i.Name == name && i.Bundle == bundle).FirstOrDefault(); if (serviceProxies.Contains(item)) { serviceProxies.Remove(item); } } else { FileLogUtility.Error(string.Format("Name hould not be empty when calling RemoveWeChatProxy in IWeChatProxyService from Bundle {0}.", bundle.SymbolicName)); } }
private void InitSystemMenu() { if (BundleRuntime.Instance.State == BundleRuntimeState.Stopping) { return; } Action action = () => { _systemContextMenu.Items.Clear(); foreach (var node in _systemMenuNavigationService.NavigationNodes) { var menuItem = new MenuItem(); if (!string.IsNullOrEmpty(node.Icon)) { try { var uri = new Uri(node.Icon, UriKind.RelativeOrAbsolute); BitmapImage logo = new BitmapImage(); logo.BeginInit(); logo.UriSource = uri; logo.EndInit(); var image = new Image(); image.Source = logo; image.Height = 16; image.Width = 16; menuItem.Icon = image; } catch (Exception ex) { FileLogUtility.Error(string.Format("Failed to load icon '{0}' from bundle '{1}'", node.Icon, node.Bundle.SymbolicName)); FileLogUtility.Error(ex); } } menuItem.Header = node.Name; if (!string.IsNullOrEmpty(node.ToolTip)) { menuItem.ToolTip = node.ToolTip; } menuItem.Tag = node; menuItem.Click += SystemMenuClick; _systemContextMenu.Items.Add(menuItem); } }; Dispatcher.Invoke(action); }
/// <summary> /// 删除实体。 /// </summary> /// <param name="entity">实体对象。</param> /// <returns>如果删除成功,返回true,否则返回false。</returns> public virtual bool Delete(T entity) { try { using (var context = NewDbContext()) { context.Entry <T>(entity).State = System.Data.Entity.EntityState.Deleted; return(context.SaveChanges() > 0); } } catch (Exception ex) // 将异常信息记录到调试日志。 { FileLogUtility.Error(string.Format("Failed to delete '{0}'.", typeof(T).Name)); FileLogUtility.Error(ex); return(false); } }
/// <summary> /// Start Bundle /// </summary> public override void Start() { try { this._state = BundleState.Starting; EventManager.OnBundleChanged(new BundleEventArgs(BundleTransition.Starting, this)); this._state = BundleState.Active; EventManager.OnBundleChanged(new BundleEventArgs(BundleTransition.Started, this)); } catch (Exception ex) { this._state = BundleState.Installed; FileLogUtility.Error(string.Format("{0}:{1}", ex.Message, "SystemBundle. Start()")); } }
/// <summary> /// 停止 /// </summary> public void Stop() { if (!this._started) { return; } this.State = BundleRuntimeState.Stopping; try { this.Framework.Shutdown(); } catch (Exception ex) { FileLogUtility.Error("StopTheFrameworkFailed" + ex.Message); } this.State = BundleRuntimeState.Stopped; this._started = false; }
///// <summary> ///// Removes the system service. ///// </summary> ///// <param name="serviceType">Type of the service.</param> ///// <param name="serviceInstance">The service instance.</param> //public void RemoveSystemService(Type serviceType, object serviceInstance) //{ // if (this._systemBundle == null) // { // this._pendingSystemServices.RemoveAll((Framework.ServiceItem item) => item.ServiceInstance == serviceInstance && item.ServiceType == serviceType); // return; // } // this.ServiceContainer.RemoveService(this._systemBundle, serviceType, serviceInstance); //} ///// <summary> ///// 添加服务 ///// </summary> ///// <param name="serviceInstance">服务实例</param> ///// <param name="serviceTypes">服务类型</param> ///// <exception cref="System.ArgumentNullException"></exception> //public void AddSystemService(object serviceInstance, params Type[] serviceTypes) //{ // if (serviceTypes != null && serviceInstance != null) // { // if (this._systemBundle == null) // { // foreach (Type serviceType in serviceTypes) // { // this._pendingSystemServices.Add(new Framework.ServiceItem(serviceType, serviceInstance)); // } // return; // } // else // { // this.ServiceContainer.AddService(this._systemBundle, serviceInstance, serviceTypes); // } // return; // } // throw new ArgumentNullException(); //} ///// <summary> ///// Adds the system service. ///// </summary> ///// <param name="serviceType">Type of the service.</param> ///// <param name="serviceInstances">The service instances.</param> ///// <exception cref="System.ArgumentNullException"></exception> //public void AddSystemService(Type serviceType, params object[] serviceInstances) //{ // if (serviceType != null && serviceInstances != null) // { // if (this._systemBundle == null) // { // foreach (object serviceInstance in serviceInstances) // { // this._pendingSystemServices.Add(new Framework.ServiceItem(serviceType, serviceInstance)); // } // return; // } // else // { // this.ServiceContainer.AddService(this._systemBundle, serviceType, serviceInstances); // } // return; // } // throw new ArgumentNullException(); //} /// <summary> /// 启动 /// </summary> /// <param name="id">组件编号</param> /// <returns>IBundle</returns> public IBundle StartBundle(int id) { IBundle bundle = _bundleRepository.GetBundle(id); if (bundle == null) { FileLogUtility.Error(String.Format("Bundle not found.BundleId:{0}", id)); } if (bundle != null && bundle.State != BundleState.Installed) { FileLogUtility.Error(String.Format("Bundle is aready started:{0}", id)); } if (bundle != null) { bundle.Start(); } return(bundle); }
public void Stop() { if (_started) { State = BundleRuntimeState.Stopping; try { Framework.Stop(); } catch (Exception exception) { FileLogUtility.Error(Messages.StopTheFrameworkFailed); FileLogUtility.Error(exception); } State = BundleRuntimeState.Stopped; _started = false; } }
public virtual void Uninstall() { if (IsActive) { try { Stop(BundleStopOptions.Transient); } catch (Exception exception) { FileLogUtility.Error(string.Format(Messages.ExceptionOccursWhenUninstalling, SymbolicName, Version)); FileLogUtility.Error(exception); } } FileLogUtility.Debug(string.Format(Messages.BundleUninstalling, SymbolicName, Version)); DoLifecycleAction(() => DoUninstall(), Messages.UninstallAction); FileLogUtility.Debug(string.Format(Messages.BundleInState, SymbolicName, Version, State)); }
private void ServiceChanged(object sender, ServiceEventArgs e) { if (e.ServiceType.Equals(typeof(TServiceInterface).FullName)) { try { _defaultOrFirstService = BundleContext.GetFirstOrDefaultService <TServiceInterface>(); _serviceInstances = BundleContext.GetService <TServiceInterface>(); } catch (Exception exception) { FileLogUtility.Error(string.Format(Messages.GetServiceFailed, typeof(TServiceInterface).FullName)); FileLogUtility.Error(exception); _defaultOrFirstService = default(TServiceInterface); _serviceInstances = null; } } }
/// <summary> /// Get Xml For BundleData /// </summary> /// <param name="dirName">Name of the dir.</param> /// <returns>BundleData.</returns> internal static BundleData GetXmlForBundleData(string dirName) { BundleData result = new BundleData(); //获取配置信息 AddinMetadata metadata = SearchXml(dirName); //将配置信息加入组件信息中 if (null != metadata) { try { result.Name = metadata.Name; result.SymbolicName = metadata.Name; result.Path = metadata.Path; result.Runtime = GetRuntimeDataForRuntimeData(metadata); result.Extensions = GetXmlForExtensionData(metadata); result.PageSerivce = GetXmlForPageServiceData(metadata); result.Enable = metadata.Enabled; result.Immediate = metadata.Immediate; result.Description = metadata.Description; result.Activator = GetActivatorData(metadata); result.BundleInfo = GetBundleInfoData(metadata); result.StartLevel = metadata.StartLevel; result.Company = metadata.Company; result.Copyright = metadata.Copyright; result.Product = metadata.Product; result.AppSettings = metadata.AppSettings; if (metadata.AssemblyVersion == null) { metadata.AssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); } result.Version = metadata.AssemblyVersion; if (metadata.ApplicationMenu != null && !string.IsNullOrEmpty(metadata.ApplicationMenu.ApplicationIco)) { result.ApplicationIco = metadata.ApplicationMenu.ApplicationIco; } } catch (ArgumentNullException ex) { FileLogUtility.Error(dirName + ex.Message); } } return(result); }