public static void AllowMultipleApplication(bool flag = false) { if (flag) { Process.Start(ResourceAssembly.Location); Process.GetCurrentProcess().Kill(); } else { int openedAppId = 0; string assemblyName = ResourceAssembly.GetName().Name; Process process = Process.GetProcessesByName(assemblyName).FirstOrDefault(); if (process != null) { openedAppId = process.Id; } if (((IEnumerable <Process>)Process.GetProcesses()).Count(e => e.ProcessName.Equals(assemblyName)) <= 1) { return; } int num = (int)MessageBox.Show("Uygulama zaten çalışıyor...", assemblyName, MessageBoxButton.OK, MessageBoxImage.Asterisk); Process.GetCurrentProcess().Kill(); Task.Delay(4000); if (openedAppId.Equals(0)) { return; } ((IEnumerable <Process>)Process.GetProcessesByName(assemblyName)).Where(e => e.Id != openedAppId) .ToList().ForEach(p => p.Kill()); } }
/// <summary> /// 注入 /// </summary> protected override void RegisterTypes(IContainerRegistry containerRegistry) { //Config var localConfig = FileUtil.LoadFromJsonFile <GlobalConfig>(Service.Models.ResourcesMap.LocationDic[Location.GlobalConfigFile]); //Version var version = ResourceAssembly.GetName().Version; var appData = new AppData { Version = $"{version.Major}.{version.Minor}.{version.Build}", Config = localConfig ?? new GlobalConfig() }; Logger.Instance.Main.Info($"[ Version ] v{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"); //Settings containerRegistry.RegisterInstance(appData.Config); containerRegistry.RegisterInstance(appData); //Dialog containerRegistry.RegisterDialogWindow <DialogWindow>(); containerRegistry.RegisterDialog <MessageDialog, MessageDialogViewModel>(); RegisterTypesByServiceCollection(containerRegistry); }
/// <summary> /// Registers string resources in the resource service. /// </summary> /// <param name="baseResourceName">The base name of the resource file embedded in the assembly.</param> /// <param name="assembly">The assembly which contains the resource file.</param> /// <example><c>ResourceService.RegisterStrings("TestAddin.Resources.StringResources", GetType().Assembly);</c></example> public void RegisterStrings(string baseResourceName, Assembly assembly) { RegisterNeutralStrings(new ResourceManager(baseResourceName, assembly)); ResourceAssembly ra = new ResourceAssembly(this, assembly, baseResourceName, false); resourceAssemblies.Add(ra); ra.Load(); }
/// <summary> /// Registers image resources in the resource service. /// </summary> /// <param name="baseResourceName">The base name of the resource file embedded in the assembly.</param> /// <param name="assembly">The assembly which contains the resource file.</param> /// <example><c>ResourceService.RegisterImages("TestAddin.Resources.BitmapResources", GetType().Assembly);</c></example> public static void RegisterImages(string baseResourceName, Assembly assembly) { RegisterNeutralImages(new ResourceManager(baseResourceName, assembly)); ResourceAssembly ra = new ResourceAssembly(assembly, baseResourceName, true); resourceAssemblies.Add(ra); ra.Load(); }
private static Uri ResourceUri(string path) { var sb = new StringBuilder(); sb.Append(@"pack://application:,,,/"); sb.Append(ResourceAssembly.GetName().Name); sb.Append(";component/Resources/"); sb.Append(path); return(new Uri(sb.ToString(), UriKind.Absolute)); }
public static void Abort(string message) { MessageBox.Show( message, ResourceAssembly.GetName().Name, MessageBoxButton.OK, MessageBoxImage.Error ); Current.Shutdown(); }
protected override void RegisterTypes(IContainerRegistry containerRegistry) { //Dialog containerRegistry.RegisterDialogWindow <DialogWindow>(); containerRegistry.RegisterDialog <MessageDialog, MessageDialogViewModel>(); //Command containerRegistry.RegisterSingleton <IApplicationCommands, ApplicationCommands>(); //Work Area containerRegistry.Register <WorkControl>(); //Code Completion containerRegistry.RegisterInstance(new XsdParser()); //Config var localConfig = FileHelper.LoadFromJsonFile <XamlConfig>(ResourcesMap.LocationDic[Location.GlobalConfigFile]); if (localConfig != null) { //check history file if (localConfig.Files == null) { localConfig.Files = new List <string>(); } else { localConfig.Files.RemoveAll(f => !FileHelper.Exists(f) || Path.GetExtension(f).ToLower() != ".xaml"); } //check reference file if (localConfig.References == null) { localConfig.References = new List <string>(); } else { localConfig.References.RemoveAll(f => !FileHelper.Exists(AppDomain.CurrentDomain.BaseDirectory + f) || Path.GetExtension(f).ToLower() != ".dll"); } } //version var version = ResourceAssembly.GetName().Version; var appData = new AppData { Config = localConfig ?? new XamlConfig(), Version = string.Format("{0}.{1}.{2}", version.Major, version.Minor, version.Build) }; if (_xamlFiles != null && _xamlFiles.Length > 0) { appData.Config.Files.RemoveAll(f => _xamlFiles.Any(xf => Path.GetFullPath(xf).ToLower() == Path.GetFullPath(f).ToLower())); appData.Config.Files.InsertRange(0, _xamlFiles); } containerRegistry.RegisterInstance(appData); }
private void Application_Startup(object sender, StartupEventArgs e) { #if DEBUG InstallUtils.RegisterApp(); #else SquirrelAwareApp.HandleEvents( onAppUpdate: v => InstallUtils.ReregisterApp(), onInitialInstall: v => InstallUtils.RegisterApp(), onAppUninstall: v => { InstallUtils.KillOtherInstances(); InstallUtils.UnregisterApp(); Current.Shutdown(); } ); #endif websocket = new WebsocketUtils(); notification = new NotificationUtils(); pushHistory = new List <JObject>(); contextMenu = new System.Windows.Forms.ContextMenu() { MenuItems = { new System.Windows.Forms.MenuItem("&Settings", (a, b) => { SettingsWindow settings = new SettingsWindow(); settings.Logout += OnLogout; settings.Show(); }), new System.Windows.Forms.MenuItem("-"), new System.Windows.Forms.MenuItem("&Exit", (a, b) => { Current.Shutdown(); }) } }; icon = new System.Windows.Forms.NotifyIcon() { Visible = true, Text = ResourceAssembly.GetName().Name, Icon = Notiwin.Properties.Resources.Tray, ContextMenu = contextMenu }; websocket.LoginError += OnLoginError; websocket.Data += OnData; NotificationActivator.Action += OnAction; NotificationActivator.Initialize(); NetworkUtils.ConnectionChanged += OnNetworkChange; OpenLoginWindow(openHidden: true); Init(); }
/// <summary> /// Initializes a new instance of ResourceStringDecorator. /// </summary> public ResourceStringDecorator() { // Registers Perspective.Wpf resources ResourceAssembly.Register(); // LocalizedChildren refers to an instance field // So that it works fine when ResourceStringDecorator are imbricated // and that's why ResourceStringDecorator doesn't use ResourceStringCoordinator _localizedChildren = new List <ResourceLink>(); SetValue(LocalizedChildrenProperty, _localizedChildren); CultureManager.Current.UICultureChanged += CultureManager_GlobalCultureChanged; }
public static string BuildVersion() { StringBuilder Version = new StringBuilder(); Version .Append(ResourceAssembly.GetName().Version.Major).Append(".") .Append(ResourceAssembly.GetName().Version.Minor).Append(".") .Append(ResourceAssembly.GetName().Version.Build); #if DEBUG Version.Append(" (调试版)"); #endif return(Version.ToString()); }
public string GetScriptBody() { using (var stream = ResourceAssembly.GetManifestResourceStream(ResourceName)) { if (stream == null) { throw new ArgumentException(nameof(ResourceName), $"There is no Embedded Resource '{ResourceName}' in {ResourceAssembly}"); } using (var reader = new StreamReader(stream)) { return(reader.ReadToEnd()); } } }
/// <summary> /// Check if end of application session should be canceled or not /// (we may have gotten here through unhandled exceptions - so we /// display it and attempt CONTINUE so user can save his data. /// </summary> /// <param name="e"></param> protected override void OnSessionEnding(SessionEndingCancelEventArgs e) { base.OnSessionEnding(e); try { try { Logger.Error(string.Format(CultureInfo.InvariantCulture, "The {0} application received request to shutdown: {1}.", ResourceAssembly.GetName(), e.ReasonSessionEnding.ToString())); } catch { } var mainWin = GetMainWindow(); var appVM = GetWorkSpace(); if (mainWin != null && appVM != null) { if (mainWin.DataContext != null && appVM.Files != null) { // Close all open files and check whether application is ready to close if (appVM.Exit_CheckConditions(mainWin) == true) { e.Cancel = false; } else { e.Cancel = appVM.ShutDownInProgressCancel = true; } } } } catch (Exception exp) { Logger.Error(exp); } try { _Container.Dispose(); _Container = null; } catch (Exception exp) { Logger.Error(exp); } }
/// <summary> /// Gets a certificate from the application resources. /// </summary> /// <param name="resourceName">The name of the resource containing the certificate.</param> private static X509Certificate2 LoadCertificateFromResources(string resourceName) { X509Certificate2 Certificate = new X509Certificate2(); using (Stream stream = ResourceAssembly.GetManifestResourceStream($"CAcertInstall.Resources.{resourceName}")) { byte[] Data = new byte[stream.Length]; stream.Read(Data, 0, Data.Length); Certificate.Import(Data); } return(Certificate); }
public static string loadResourceString(string name) { name = "FavoriteCims.resources." + name; UnmanagedMemoryStream stream = (UnmanagedMemoryStream)ResourceAssembly.GetManifestResourceStream(name); if (stream == null) { return(null); } StreamReader read = new StreamReader(stream); return(read.ReadToEnd()); }
public static byte[] loadResourceData(string name) { name = "FavoriteCims.resources." + name; UnmanagedMemoryStream stream = (UnmanagedMemoryStream)ResourceAssembly.GetManifestResourceStream(name); if (stream == null) { return(null); } BinaryReader read = new BinaryReader(stream); return(read.ReadBytes((int)stream.Length)); }
protected override void OnStartup(StartupEventArgs e) { AppMainMutex = new Mutex(true, ResourceAssembly.GetName().Name, out var createdNew); if (createdNew) { RegisterEvents(); base.OnStartup(e); } else { MessageBox.Show("请不要重复打开,程序已经运行\n如果一直提示,请到\"任务管理器-详细信息(win7为进程)\"里结束本程序", "警告", MessageBoxButton.OK, MessageBoxImage.Warning); Current.Shutdown(); } }
public InlineScriptActionFromFileInAssembly(string resourceName, Assembly resourceAssembly = null) { ResourceAssembly = resourceAssembly ?? Assembly.GetEntryAssembly(); var candidates = ResourceAssembly.GetManifestResourceNames().Where(name => name.EndsWith(resourceName)).ToArray(); if (!candidates.Any()) { throw new ArgumentException($"There is no embedded resource in {ResourceAssembly.GetName().Name} like {resourceName}. Available resources are:{Environment.NewLine}{string.Join(Environment.NewLine, ResourceAssembly.GetManifestResourceNames().OrderBy(x => x))}"); } if (candidates.Length > 1) { throw new ArgumentException($"There are {candidates.Length} embedded resources in {ResourceAssembly.GetName().Name} like {resourceName}, which one do you want?{Environment.NewLine}{string.Join(Environment.NewLine, candidates.OrderBy(x => x))}"); } ResourceName = candidates.Single(); }
protected string ReadInEmbeddedResource(string filename) { string[] res = ResourceAssembly.GetManifestResourceNames(); filename = filename.Replace("/", "."); var res_filename = ResourcePath + "." + filename; var file = res.Where(r => res_filename == r).FirstOrDefault(); if (file == null) { return(null); } var stream = ResourceAssembly.GetManifestResourceStream(file); string file_content = new StreamReader(stream).ReadToEnd(); return(file_content); }
/// Get list of embedded streams URIs. For example, for embedded stream "AAA.BBB" the URI will be "embed:///AAA.BBB" public string[] GetEmbeddedResources() { Dictionary <string, bool> s = new Dictionary <string, bool>(); foreach (var name in ResourceAssembly.GetManifestResourceNames()) { s[name] = true; } foreach (var n in _embed) { s[n.Key] = true; } List <string> ret = new List <string>(); foreach (var pair in s) { ret.Add("embed:///" + pair.Key); } return(ret.ToArray()); }
byte[] ReadResourceBytes(string url) { if (url.IsEmpty()) { return(new byte[0]); } if (url.StartsWith("resource:")) { if (ResourceAssembly == null) { throw new Exception($"Failed to load '{url}' as no resourceAssembly is specified for this WebView."); } if (ResourceNamespace.IsEmpty()) { throw new Exception($"Failed to load '{url}' as no resource namespace is specified for this WebView."); } return(ResourceAssembly.ReadEmbeddedResource(ResourceNamespace, url.TrimStart("resource:"))); } if (url.Contains(":")) { return(new byte[0]); // External URL } if (!MergeExternalResources) { return(new byte[0]); } var file = Device.IO.File(url); if (!file.Exists()) { throw new Exception("Web resource file not found: '" + url + "'."); } return(file.ReadAllBytes()); }
protected override void OnStartup(StartupEventArgs e) { mutex = new Mutex(true, ResourceAssembly.GetName().Name, out createNew); if (createNew) { base.OnStartup(e); // UI线程未捕获异常处理事件(UI主线程) DispatcherUnhandledException += App_DispatcherUnhandledException; // 非UI线程未捕获异常处理事件(例如自己创建的一个子线程) AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Task线程内未捕获异常处理事件 TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; } else { MessageBox.Show("请不要重复打开,程序已经运行\n如果一直提示,请到\"任务管理器-详细信息(win7为进程)\"里结束本程序", " 警告", MessageBoxButton.OK, MessageBoxImage.Warning); Current.Shutdown(); } }
private void Application_Startup(object sender, StartupEventArgs e) { try { if (!Directory.Exists("BuildFiles")) { Directory.CreateDirectory("BuildFiles"); } string[] resourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames(); for (int i = 0; i <= resourceNames.Count() - 1; i++) { string ext = Path.GetExtension(resourceNames[i]); if (ext.In(HelperFuncs.ValidBuildFileExtensions)) { string file = GetFileNameFromResource(resourceNames[i]); if (!File.Exists($"BuildFiles/{file}")) { using (var fileStream = File.Create($"BuildFiles/{file}")) { Stream buildStream = ResourceAssembly.GetManifestResourceStream(resourceNames[i]); buildStream.Seek(0, SeekOrigin.Begin); buildStream.CopyTo(fileStream); } } } } } catch (Exception ex) { //Likely due to insufficient permissions MessageBox.Show($"An error occurred during setup: {ex.Message}", "Setup Error"); } }
/// <summary> /// Registers image resources in the resource service. /// </summary> /// <param name="baseResourceName">The base name of the resource file embedded in the assembly.</param> /// <param name="assembly">The assembly which contains the resource file.</param> /// <example><c>ResourceService.RegisterImages("TestAddin.Resources.BitmapResources", GetType().Assembly);</c></example> public void RegisterImages(string baseResourceName, Assembly assembly) { RegisterNeutralImages(new ResourceManager(baseResourceName, assembly)); ResourceAssembly ra = new ResourceAssembly(this, assembly, baseResourceName, true); resourceAssemblies.Add(ra); ra.Load(); }
/// <summary> /// Loads an icon from the combined resources and returns an <see cref="System.Drawing.Icon">Icon</see> instance to the caller. /// </summary> /// <param name="bmpNamespace">bitmap namespace used for loading the resource</param> /// <param name="name">name of the icon file/resource</param> /// <returns>Returns an <see cref="System.Drawing.Icon">Icon</see> instance to the caller.</returns> /// <remarks>The bitmap namespace will be combined with the <see cref="DefaultNamespace">DefaultNamespace</see> property.</remarks> public Icon LoadIcon(string bmpNamespace, string name) { string fullNamePrefix = CombineResource(DefaultNamespace, bmpNamespace); return(new Icon(ResourceAssembly.GetManifestResourceStream(CombineResource(fullNamePrefix, name)))); }
public static void RegisterStrings(string baseResourceName, Assembly assembly) { RegisterNeutralStrings(new ResourceManager(baseResourceName, assembly)); ResourceAssembly item = new ResourceAssembly(assembly, baseResourceName, false); resourceAssemblies.Add(item); item.Load(); }
private void Application_Startup(object sender, StartupEventArgs e) { string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SentinelsJson"); string file = ""; if (e.Args.Length > 0) { if (File.Exists(e.Args[0])) { file = e.Args[0]; } } if (SystemParameters.HighContrast) { if (Settings.HighContrastTheme == NO_HIGH_CONTRAST) { ColorScheme ncs; MessageDialog md = new MessageDialog(); md.Message = "It appears that you have Windows High Contrast mode activated. Did you want to activate High Contrast mode in SentinelsJson as well?"; md.OkButtonText = "Yes"; md.CancelButtonText = "No"; md.Image = MessageDialogImage.Question; md.Title = "SentinelsJson - High Contrast Mode"; // check the control color if (SystemColors.ControlColor == Colors.Black) { // black color scheme? if (SystemColors.WindowTextColor == Colors.White) { ncs = ColorScheme.GetHighContrastScheme(HighContrastOption.WhiteOnBlack); md.ColorScheme = ncs; if (md.ShowDialog() == MessageDialogResult.OK) { // white on black Settings.HighContrastTheme = "1"; } } else { ncs = ColorScheme.GetHighContrastScheme(HighContrastOption.GreenOnBlack); md.ColorScheme = ncs; if (md.ShowDialog() == MessageDialogResult.OK) { // green on black Settings.HighContrastTheme = "2"; } } } else { ncs = ColorScheme.GetHighContrastScheme(HighContrastOption.BlackOnWhite); md.ColorScheme = ncs; if (md.ShowDialog() == MessageDialogResult.OK) { // black on white Settings.HighContrastTheme = "3"; } } try { Settings.Save(Path.Combine(appDataPath, "settings.json")); } catch (UnauthorizedAccessException) { MessageBox.Show("The settings file for SentinelsJson could not be saved. Please check the permissions for your AppData folder.", "Settings Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch (System.Security.SecurityException) { MessageBox.Show("The settings file for SentinelsJson could not be saved. Please check the permissions for your AppData folder.", "Settings Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch (IOException) { MessageBox.Show("The settings file for SentinelsJson could not be saved. Please check the permissions for your AppData folder.", "Settings Error", MessageBoxButton.OK, MessageBoxImage.Error); } } } foreach (string s in ResourceAssembly.GetManifestResourceNames()) { Console.WriteLine(s); } MainWindow mw = new MainWindow(); MainWindow = mw; if (file != "") { mw.OpenFile(file); } mw.Show(); }
/// <summary> /// Opens a stream with the given name. /// </summary> /// <param name="name">The name of the stream.</param> /// <returns> /// A <seealso cref="NamedStream" />. /// </returns> /// <exception cref="NotImplementedException"></exception> public NamedStream Open(string name) { var stream = ResourceAssembly.GetManifestResourceStream(name); return(new NamedStream(name, stream)); }