Create a customized path address (wpf) - c#

Goal:
I want to achieve the path address, as string, of the application created in Visual studio 2010. The path is from unit (c or d unit) to the name of the application.
Problem:
I can't create a customized path address in runtime. I don't want a full path address that is from unit to the name of the picture.
--No to this path address
"D:\work\Modul3\Assignment3\Assignment3\bin\Debug\logotyp_vp_final.jpg"
--Yes, requested path
"D:\work\Modul3\Assignment3"
Please remember that this application and its name of the application and the address can be changed from time to time.
namespace Assignment3
{
/// <summary>
/// Interaction logic for FlightForm.xaml
/// </summary>
public partial class FlightForm : Window
{
public delegate void TakeOffHandler(object source, TakeOffEventArgs e);
public delegate void ChangeHandler(object source, ChangeRouteEventArgs e);
public event TakeOffHandler TakeOffEvent;
public event ChangeHandler ChangeEvent;
public FlightForm()
{
InitializeComponent();
Title = "Flight ";
cmbStatus.Visibility = Visibility.Hidden;
btnLand.Visibility = Visibility.Hidden;
string fullPath;
fullPath = System.IO.Path.GetFullPath("logotyp_vp_final.jpg");
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(fullPath);
image.EndInit();
image1.Source = image;
System.Windows.Shapes.Path path = new System.Windows.Shapes.Path();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
cmbStatus.Visibility = Visibility.Visible;
btnLand.Visibility = Visibility.Visible;
btnStart.Visibility = Visibility.Hidden;
TakeOffEvent(this, new TakeOffEventArgs("a", "b", DateTime.Now.ToString()));
ChangeEvent(this, new ChangeRouteEventArgs("aa", "bb", "cc"));
}
}
}
namespace Assignment3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class ControlTower : Window
{
public ControlTower()
{
InitializeComponent();
}
private FlightForm myFlightForm;
private void btnSendNextAirplane_Click(object sender, RoutedEventArgs e)
{
myFlightForm = new FlightForm();
myFlightForm.TakeOffEvent += new FlightForm.TakeOffHandler(PrintOutTakeOff);
myFlightForm.ChangeEvent += new FlightForm.ChangeHandler(PrintOutChange);
myFlightForm.Show();
}
public void PrintOutTakeOff(object source, TakeOffEventArgs e)
{
lstDisplay.Items.Add(new { FlightCode = e.FlightCode, Status = e.Status, Time = e.Time });
}
public void PrintOutChange(object source, ChangeRouteEventArgs e)
{
string test = e.FlightCode + e.Status + e.Time;
MessageBox.Show(test);
}
}
}

To get the path of where the application is executing from:
string localPath = new Uri( Assembly.GetExecutingAssembly().CodeBase ).LocalPath;
string currentDirectory = Path.GetDirectoryName( localPath );
edit
It sounds like you are attempting to access images outside of your project. As this may work in your sandbox environment, a better practice is to include the images as a part of your project and access them as an embedded resource.
Here's a good read to get you started: Adding and Editing Resources (Visual C#)
Walk-through of adding an image as an embedded resource
Add the file to your project, typically something along the lines of:
+solution
+project
+Resources <-- this is Visual Studio's default folder name for resources
+SomeDirectory
-logotyp_vp_final.jpg
Then:
go to your project's properties
click to the resources tab on the left side
select the images resource on the top nav bar.
select to add a resource > add existing file. Browse to the file you just put into your project and select to add it.
The file will now show up under your Resources tab of your project's properties. Change the name of your file in the Resources tab to be more meaningful.
Now that the file is an embedded resource of your project, you can access it by the following in code:
var MyFile = Properties.Resources.logotyp_vp_final

Something like this should work:
var fullPath = System.IO.Path.GetFullPath("..\\..\\logotyp_vp_final.jpg");

Related

C# application UI Text localization not working

I have a context menu application where I have a base project SampleContextMenu.Base and a child project SampleContextMenu.Menu.
In SampleContextMenu.Menu, I have created a context menu for which I set a text like this.
sampleItem.Text = "Open In";
Now I want to globalize this string. So I created 3 resource files called UiStrings.resx, UiStrings.de-DE.resx, and UiStrings.fr-FR.resx.
In the class SampleContextMenu.cs, I have the following code now,
// Resource path
private string strResourcesPath = Application.StartupPath + "/Resources";
// string to store current culture which is comon in all the forms
private string strCulture = "en-US";
//resourcemanager which retrivesthe strings
//from the resource files
private static ResourceManager rm;
private void GlobalizeApp()
{
SetCulture();
SetResource();
}
private void SetCulture()
{
CultureInfo objCI = new CultureInfo(strCulture);
Thread.CurrentThread.CurrentCulture = objCI;
}
private void SetResource()
{
rm = new ResourceManager("SampleContextMenu.Menu.UiStrings", typeof(SampleContextMenu).Assembly);
}
protected override ContextMenuStrip CreateMenu()
{
// some code to create menu
strCulture = Read("language");
GlobalizeApp();
sampleItem.Text = rm.getString("0000");
}
EDIT
For me now even if the language is de or fr, it still shows stirng for the default( i.e. En)

C# Streamreader problems

I'm building a program that has you input a number and remembers it when you re-open the program. It uses a text file to save the number in. I'm using streamreader to read the text file to get the number you entered last, but it always throws an exception. Where should I put the text file or change my code so it can read and edit the text? Here is my code:
namespace Cookie_Clicker
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void tb_TextBox(object sender, RoutedEventArgs e)
{
}
private void add_Click(object sender, RoutedEventArgs e)
{
try
{
using (StreamReader sr = new StreamReader("cookies.txt"))
{
int data = Convert.ToInt16(sr.ReadToEnd());
tb.Text = Convert.ToString(data + 1);
}
}
catch (Exception)
{
MessageBox.Show("Your cookie text file is missing!");
}
}
private void reset_Click(object sender, RoutedEventArgs e)
{
}
}
}
Every time it says "Your cookie text file is missing!"
Problem 1: You are not specifying proper path of your input file.
Solution 1: You need to get the Currentpath of your application from where it is running and then combine it with the filename using Path.Combine() method.
Try This:
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"cookies.txt");
using (StreamReader sr = new StreamReader(path))
{
int data = Convert.ToInt16(sr.ReadToEnd());
tb.Text = Convert.ToString(data + 1);
}
Suggestion : You need to always display the Error message in Catch block to identify the problem.
You can call ToString() on Exception object to get the complete exception info.
catch (Exception ex)
{
MessageBox.Show(ex.ToSTring();
}
To answer your question:
Where should I put the text file...?
You haven't specified a path to cookies.txt so the program will look for it in the same directory where it's running. If you change cookies.txt to include a path, for example C:\dev\cookies.txt, then you can store the file wherever you like.
That will allow you to get past the file not found error and address any other problems you have in there.

WPF How to get second clicked file path for Single Instance App

I created my WPF single instance app by using the Microsoft.VisualBasic dll method. However I'm facing some difficulty to get the file path for second clicked file which associated with my app.
For example, I have two file "First.my" and "Second.my". When I click on file "First.my" it will launch my app and pop up message box to show "First.my" file path. Since my app is single instance app, when I click on file "Second.my" it should show the file path for "Second.my" but it still showing the file path for "First.my"..
Does anyone know how to pass the associate file path in single instance app?
Below is my code:
class WindowsFormsApp : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
private App _wpfApp;
public WindowsFormsApp()
{
IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
{
MessageBox.Show("First File");
//Get 1st click file path
GetFilePath();
_wpfApp = new App();
_wpfApp.Run();
return false;
}
protected override void OnStartupNextInstance(Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs e)
{
MessageBox.Show("Second File");
//Get 2nd click file path
GetFilePath();
}
protected void GetFilePath()
{
if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData != null &&
AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData.Length > 0)
{
var filePath = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];
var uri = new Uri(filePath);
MessageBox.Show(uri.LocalPath);
}
}
}

How to open new windows from main GUI and and pass vairable to the new window

I have an application with a Listbox with files and a menu. When I right-click an item from my listbox I have a menu for example Send. When I press 'Send' I want another window to open (I already have the new window) and in the new window I want to have the item-path that I selected (I have this path in the main window).
private void MenuItemSend_Click(object sender, RoutedEventArgs e)
{
if (listBoxFiles.SelectedIndex == -1)
{
return;
}
string filePath = (listBoxFiles.SelectedItem).ToString(); --- my file path
StatisticsWindow sForm = new StatisticsWindow();
sForm.ShowDialog(); -- open the new window
}
How can I do it ?
Thanks
Why don't you create a constructor for the window?
Instead of
new IpStatisticsWindow();
this:
new IpStatisticsWindow(filePath);
// In the IpStatisticsWindow class
public IpStatisticsWindow(string path)
{
//do something with path
}
You could of course also create a property or a method which handles it, then you can pass it there, e.g.
IPsForm.Path = filePath;
IPsForm.HandlePath(filePath);

c# - WPF command-line argument for opening file gives infinite loop

This is a weird one! I am working on an application that reads vCard files, which contain contact etc. information for a person. Each file may contain separate 'sections' that each contain the details for one person, which are separated by BEGIN:VCARD [data here] END:VCARD.
To enable my users to view all of the different details, I've allowed my program to populate the textboxes in my app with the details and then open a new Window and do this with that one, but for each of the different sections in the file.
The problem comes about when my program opens when a vCard file has been double clicked in Explorer. It keeps looping through the vCard. I don't know what to do, but below is my problematic code:
public void readVcard(string fname)//Reads vCard and then loops through sections
{
try
{
using (StreamReader r = new StreamReader(fname))
{
string input = File.ReadAllText(fname);//read through file
String[] vArray = input.Split(new string[] { "BEGIN:VCARD" }, StringSplitOptions.None);
int i;
for (i = 1; i < vArray.Length; i++)
{
MainWindow a = new MainWindow();
a.parser(vArray[i]); //Parser is the function that populates the app
a.Show();
}
return;
}
}...
This function is called from here:
void MainWindow_Loaded(object sender, RoutedEventArgs e)//Processes a file when opened externally
{
if (Application.Current.Properties["ArbitraryArgName"] != null)
{
string fname = Application.Current.Properties["ArbitraryArgName"].ToString();
readVcard(fname);
}
}
If anyone could help, it would be greatly appreciated.
I think that Artyom is on the right track.
Every time you create another MainWindow and load it you will be getting the current applications argurment and jumping back in to readVcard, which will process the same vCard that you are already processing and open yet another MainWindow which will continue the process.
Consider moving all of the code you have inside of MainWindow_Loaded() to the Startup event for your application. That way it will only get called once when your program first loads, instead of every time you create a new window.
To do this you need to register for the event in your App.xaml file like so:
<Application x:Class="MyProgram.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="Application_Startup">
</Application>
And then in the code behind App.xaml you put your code for reading the vCard. Like this:
namespace MyProgram
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
if (Application.Current.Properties["ArbitraryArgName"] != null)
{
string fname = Application.Current.Properties["ArbitraryArgName"].ToString();
readVcard(fname);
}
}
}
}
When you create and show new MainWindow (a.Show()), the MainWindow_Loaded event fires again and it again calls a readVcard method. So there is an infinite loop.
Or may be not really infinite, because, I belive, some time later a StackOverflowException may happen.
You just need to review startup logic, so readVcard will launch not in the MainWindow_Loaded event, but, for example, in the Main method (in program.cs file). Or you may add some flag, which will be set when readVcard method first called.
I get it! I've now got the following code in App.xaml.cs:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
if (e.Args != null && e.Args.Count() > 0)
{
this.Properties["ArbitraryArgName"] = e.Args[0];
}
base.OnStartup(e);
if (Application.Current.Properties["ArbitraryArgName"] != null)
{
string fname = Application.Current.Properties["ArbitraryArgName"].ToString();
MainWindow mw = new MainWindow();
mw.readVcard(fname);
}
}
}
It works fine! Thanks everyone. BTW the following blog contains the command-line info I originally used if anyone needs it: http://blogs.msdn.com/b/avip/archive/2008/10/27/wpf-supporting-command-line-arguments-and-file-extensions.aspx.

Categories

Resources