I'm using SharpDevelop and had by my bad moved the App.xaml to an Subdirectory.
When i try to start/debug the Application, C# says, that my Application has no entry points or a static main method (CS5001).
An Edit < Undo or an movint to the default main folder will be not working.
Whats wrong?
Edit
On Project-Settings, no Classes/Methods are listened:
App.xaml
<Application x:Class="SongManager.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="Boot">
</Application>
App.xaml.cs
using System;
using System.Windows;
using SmuleTools;
namespace SongManager {
public partial class App : Application {
private Account user;
public App() {
}
public Account getAccount() {
return this.user;
}
[STAThread]
private void Boot(object sender, StartupEventArgs e) {
Login login = new Login();
login.AuthSuccess((Object result) => {
this.user = (Account) result;
Manager window = new Manager(this);
window.Show();
login.Close();
});
login.Show();
}
}
}
The Solution is a little bit tricky, but easy.
After moving the main .xaml file, the Build action will be lost - These are not in the Project/Compiler settings!
Step-by-Step:
(red mark) Click on your .xaml file (for sample, App.xaml)
(blue mark) Go to the Properties window (on the right side!)
(green mark) Change Other > Build action to ApplicationDefinition
Screenshot
That is it!
Try to add a Main() method to your App class:
[STAThread]
public static void Main()
{
App application = new App();
application.Run();
}
By default, there should be one generated when you build the application.
Related
I created an app with Windows Template Studio on Visual Studio 2017.
The app is mainly a NavigationDrawer with different pages.
Everything was ok, until I wanted to add a login page.
So I created the XAML of the login page, etc. But now I want it to show before the NavigationDrawer page on app startup.
I seeked some documentation about the App.xaml.cs to know what to change to do that but, because of the use of Windows Template Studio, the code is not really vanilla anymore.
I tried a few things and the only thing I'm able to do right now is to change the shell page of the NavigationDrawer to my Login page.
That's not exactly what I want because my first intention was to make the app unavailable until you log in, and because the NavigationDrawer is still usable the user can still do what he wants to.
My app.xaml.cs looks like this :
using System;
using BasePosteMobilite.Services;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
namespace BasePosteMobilite
{
public sealed partial class App : Application
{
private Lazy<ActivationService> _activationService;
private ActivationService ActivationService
{
get { return _activationService.Value; }
}
public App()
{
InitializeComponent();
// Deferred execution until used. Check https://msdn.microsoft.com/library/dd642331(v=vs.110).aspx for further info on Lazy<T> class.
_activationService = new Lazy<ActivationService>(CreateActivationService);
}
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
if (!args.PrelaunchActivated)
{
await ActivationService.ActivateAsync(args);
}
}
protected override async void OnActivated(IActivatedEventArgs args)
{
await ActivationService.ActivateAsync(args);
}
private ActivationService CreateActivationService()
{
return new ActivationService(this, typeof(ViewModels.LoginViewModel), new Lazy<UIElement>(CreateShell));
}
private UIElement CreateShell()
{
return new Views.ShellPage();
}
}
}
ShellPage.xaml.cs :
using System;
using BasePosteMobilite.ViewModels;
using Windows.UI.Xaml.Controls;
namespace BasePosteMobilite.Views
{
// TODO WTS: Change the icons and titles for all NavigationViewItems in ShellPage.xaml.
public sealed partial class ShellPage : Page
{
private ShellViewModel ViewModel
{
get { return ViewModelLocator.Current.ShellViewModel; }
}
public ShellPage()
{
InitializeComponent();
DataContext = ViewModel;
ViewModel.Initialize(shellFrame, navigationView, KeyboardAccelerators);
}
}
}
ViewModel.Initialize :
public void Initialize(Frame frame, WinUI.NavigationView navigationView, IList<KeyboardAccelerator> keyboardAccelerators)
{
_navigationView = navigationView;
_keyboardAccelerators = keyboardAccelerators;
NavigationService.Frame = frame;
NavigationService.NavigationFailed += Frame_NavigationFailed;
NavigationService.Navigated += Frame_Navigated;
_navigationView.BackRequested += OnBackRequested;
}
You can create a project with login required feature and you will see the following code from ActivateAsync method:
var silentLoginSuccess = await IdentityService.AcquireTokenSilentAsync();
if (!silentLoginSuccess || !IdentityService.IsAuthorized())
{
await RedirectLoginPageAsync();
}
That's it. If you want to redirect to your own page, write the detectation code under ActivationService.ActivateAsync(args) method. If you see the customer is not logged in. Call redirect login method. Here is the code from template studio about redirectlogin:
public async Task RedirectLoginPageAsync()
{
var frame = new Frame();
NavigationService.Frame = frame;
Window.Current.Content = frame;
await ThemeSelectorService.SetRequestedThemeAsync();
NavigationService.Navigate<Views.LogInPage>();
}
I am learning basics of windows service. I have created a very simple one.
using System.ServiceProcess;
namespace WindowsServiceBasic
{
public partial class OmerService : ServiceBase
{
public OmerService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
System.Diagnostics.Debugger.Launch();
WriteLog("START");
}
protected override void OnStop()
{
System.Diagnostics.Debugger.Launch();
WriteLog("STOP");
}
private void WriteLog(string durum)
{
eventLog1.WriteEntry(performanceCounter1.RawValue.ToString());
}
}
}
using System;
using System.IO;
using System.ServiceProcess;
namespace WindowsServiceBasic
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
private static void Main()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new OmerService()
};
ServiceBase.Run(ServicesToRun);
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e != null && e.ExceptionObject != null)
{
string createText = e.ToString();
File.WriteAllText(#"c:\omerlog.txt", createText);
}
}
}
}
The first time my service (AServis) starts successfully but when I click the restart it crashes. Since my service is very simple It should have been worked properly. I try to log the error, put try catch but I could not find anything. I am trying to attach process, it debugs stop event but after stop debug suddenly finishes and start process crashes. Could you please help me what is the reason and how can I debug and log error.
Thanks in advance
I saw that it was stuck in
public OmerService()
{
InitializeComponent();
}
I could see the issue adding System.Diagnostics.Debugger.Launch(); statement.
public OmerService()
{
System.Diagnostics.Debugger.Launch();
InitializeComponent();
}
The standard trick I use in this situation is to add a call to System.Diagnostics.Debugger.Break in my start up code. Now, when you start the service as normal (through the Service Control Manager (SCM)), the call to the Break will cause Windows to launch the JIT debugger, which should prompt you to choose the debugger you wish to attach to the process (e.g., Visual Studio), which will then enable you to debug your code as normal.
Also see this: Easier way to debug a Windows service.
i am working with wpf application ,i have changed my entry point Main() to another file ,there is no error but MainWindow.xaml is not opening .Code is :
class AppStart : Application
{
[STAThread()]
static void Main()
{
//Console.WriteLine("New entry point added");
new App();
}
public void App()
{
StartupUri = new System.Uri("MainWindow.xaml", UriKind.Relative);
Run();
}
}
Can anyone explain what could be the reason?
Solved it i was using wrong constructor name ..it should be AppStart() but i was writing App()..
I want to let the users to select only the following extension files: .jpg,.png, .tiff, .gif, .png. using Windows Explorer Context Menu I followed this link:http://www.codeproject.com/Articles/15171/Simple-shell-context-menu?msg=4779433#xx4779433xx and I could register and un-register successfully for .jpg file.
When I click on the command fileCopytoDirAnothing is happening i.e the function is not working. (I followed the same approach using console application with my function it works).
Where & How should i call the function during the 'fileCopytoDirA click?? Any help?
![enter image description here][1]
Code to register in the registry:
InitializeComponent();
string menuCommand = string.Format("\"{0}\" \"%L\"", Application.Current);
FileShellExtension.Register("OISjpegfile", "fileCopytoDirA", "fileCopytoDirA", menuCommand);
Function to be executed during click:
static void fileCopytoDirA(string filePath)
{
try
{
File.Copy(filePath, System.IO.Path.Combine(#"C:\Test\Directories\", System.IO.Path.GetFileName(filePath)), true);
}
catch (Exception ex)
{
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
return;
}
}
Function to un register the registry entries during WPF application close:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
FileShellExtension.Unregister("OISjpegfile", "fileCopytoDirA");
}
[1]: http://i.stack.imgur.com/eAN5F.png
Edit afterMetadingsanswer:
App()
{
InitializeComponent();
string menuCommand = string.Format("\"{0}\" \"%L\"", System.Reflection.Assembly.GetExecutingAssembly().Location);
FileShellExtension.Register("OISjpegfile", "fileCopytoDirA", "fileCopytoDirA", menuCommand);
}
[STAThread]
public static void Main(string args)
{
if (string.IsNullOrEmpty(args))
{
// Run your Main Form
// (blocks until Form1 is closed)
Window3 window = new Window3();
App app = new App();
app.Run(window);
}
else
{
// Run the context menu action
fileCopytoDirA(args);
}
// exit
}
static void fileCopytoDirA(string args)
{
try
{
File.Copy(args, System.IO.Path.Combine(#"C:\Test\Directories\", System.IO.Path.GetFileName(args)), true);
}
catch (Exception ex)
{
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
return;
}
}
The (simple) registry setting is that your application is executed by arguments, as it would be called in a console:
app.exe "TheJpegFile.jpg"
So the entry point is static void Main(string args), from there you can call fileCopytoDirA(args). There is no magic way Explorer calls a function by its name. You can either implement the COM interfaces, as for example this project does, or you go the quick and dirty way, by redirecting your Main; if there is not an argument, run the (windows forms) application - if there is an argument, do the action and exit:
using System;
using System.Windows.Forms;
public static class Program {
public static void Main(string args) {
if (string.IsNullOrEmpty(args)) {
// Run your Main Form
// (blocks until Form1 is closed)
Application.Run(new Form1());
}
else {
// Run the context menu action
fileCopytoDirA(args);
}
// exit
}
}
The FileShellExtension.Register function is defined as
public static void Register(string fileType,
string shellKeyName, string menuText, string menuCommand)
So the arguments are
string fileType - the HKC registry key for the file extension
string shellKeyName - just a registry key name for Explorer to distinguish shell extensions
string menuText - what the user can see in Explorer's context menu
string menuCommand - the shell command Explorer executes just like you can do in a console or by a link
P.S: In WPF it's similar, but you create new YourApp class (derived from System.Windows.Application) and then call Run.
Assuming Application.xaml looks like
<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
</Application>
and your application class is in namespace WpfApplication1 named App, and you have a Window1.xaml, the q'n'd looks like
namespace WpfApplication1
{
public partial class App : Application
{
App()
{
InitializeComponent();
}
[STAThread]
static void Main(string args)
{
if (string.IsNullOrEmpty(args)) {
// Run your Main Form
// (blocks until Form1 is closed)
Window1 window = new Window1();
App app = new App();
app.Run(window);
}
else {
// Run the context menu action
fileCopytoDirA(args);
}
// exit
}
static void fileCopytoDirA(string args) {
// this your part ;)
}
}
}
Btw. I took the WPF Main part from this source and it seems to be important that you remove the StartupURI="Window1.xaml" attribute from your Application.xaml, that it looks now like
<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</Application>
I have implemented a splashscreen for my project, it works well as desired.. but in my project i have an option of logout for user,this displays start page where a different login is provided(which is the starting screen..i.e, "chooselogin.xaml"). So when the user clicks on "choose a different login" while he already selected one in the application.. again the splashscreen appears, which is not required and looks odd.
the following code is what i think leading to problem... guys
public partial class Chooselogin : Window
{
public Chooselogin()
{
new SplashWindow().ShowDialog();
InitializeComponent();
}
......
This code is my "App.xaml"..
<Application x:Class="WpfApplication1.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Chooselogin.xaml">
<Application.Resources>
<ResourceDictionary Source="/Themes/ExpressionDark.xaml"/>
</Application.Resources>
The splash screen code is as follows..
public partial class SplashWindow : Window
{
Thread loadingThread;
Storyboard Showboard;
Storyboard Hideboard;
private delegate void ShowDelegate(string txt);
private delegate void HideDelegate();
ShowDelegate showDelegate;
HideDelegate hideDelegate;
public SplashWindow()
{
InitializeComponent();
showDelegate = new ShowDelegate(this.showText);
hideDelegate = new HideDelegate(this.hideText);
Showboard = this.Resources["showStoryBoard"] as Storyboard;
Hideboard = this.Resources["HideStoryBoard"] as Storyboard;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
loadingThread = new Thread(load);
loadingThread.Start();
}
private void load()
{
Thread.Sleep(1000);
this.Dispatcher.Invoke(showDelegate, "Loading assets...please wait");
Thread.Sleep(2000);
//do some loading work
this.Dispatcher.Invoke(hideDelegate);
Thread.Sleep(2000);
this.Dispatcher.Invoke(showDelegate, "Loading profiles..");
Thread.Sleep(2000);
//do some loading work
this.Dispatcher.Invoke(hideDelegate);
Thread.Sleep(2000);
this.Dispatcher.Invoke(showDelegate, "Loading Data... almost done");
Thread.Sleep(2000);
this.Dispatcher.Invoke(hideDelegate);
//close the window
Thread.Sleep(2000);
this.Dispatcher.Invoke(DispatcherPriority.Normal,
(Action)delegate() { Close(); });
}
private void showText(string txt)
{
txtLoading.Text = txt;
BeginStoryboard(Showboard);
}
private void hideText()
{
BeginStoryboard(Hideboard);
}
}
The splash screen is supposed to be opened at start of application.. please help guys..
How about something simple like this?:
public partial class Chooselogin : Window
{
private static bool isFirstTime = true;
public Chooselogin()
{
if (isFirstTime)
{
new SplashWindow().ShowDialog();
isFirstTime = false;
}
InitializeComponent();
}
...
}
Now it will only display the splash screen once.
I recommend reading this post by Kent Boogaart
Example from the post
"WPF provides a SplashScreen class. It is simple by design and addresses the main goal of splash screens: immediate feedback. By virtue of forgoing the WPF stack and instead relying on Windows Imaging Component (WIC) to display images, it provides the quickest path to getting a splash on the screen short of writing your own native bootstrapper."