Opening a Link/File through button click event - c#

I am still new to the WPF/XAML coding and while learning I encountered another problem. I decided I want to add buttons on the UserControl, that I would like to make them do a few different things. On one of them, I want to open the local default browser and open a webpage link, and in another button, I want to start a local exe/rpm file from a directory in my project called "tools".
For opening the link I tried - WebBrowserTask which is an unrecognized event/task
For the running of the application - Process.Start("thelocation/thefile.exe/rdp"). After that, I tried guiding it to the proper path, but my project doesn't recognize the folder and files inside.
Both tries were unsuccessful.

Try this:
public void DoSomething
{
const string webpageUrl = "https://stackoverflow.com/questions/55778625/";
const string localFile = #"C:\Windows\notepad.exe";
var localTools = $#"{AppDomain.CurrentDomain.BaseDirectory}Tools\SomeTools.exe";
Process.Start(webpageUrl);
Process.Start(localFile);
Process.Start(localTools);
}
to opening an web page your address must be start with http://...

Related

Revit API: Use String as Button Assembly Name with Current Path

I'm not entirely sure at all why this is happening...
So I have a ExternalCommand and an application for making a ribbon tab and button. These two programs are in the same solution and under the same namespace, which allows me to have fewer files to deal with. When I create a button for my command, I want to put in the current path of the application that is currently running. I do this with Directory.GetCurrentDirectory() + \AddInsAll\Ribbon17.dll (where AddInsAll is the folder and Ribbon17 is the dll, obviously). I use # when necessary to avoid escape sequences. This string contains the exact assembly name needed, but Revit tells me "Assembly does not exist." If I replace this String variable with the hard coded C:\ProgramData\Autodesk\Revit\Addins\2017\AddInsAll\Ribbon17.dll it works. I want it obviously more robust than that. My code will be below, thanks in advance.
FYI: I have a TaskDialog showing when it first runs, and the fullPath that it returns is exacly the same as the hard coded path. I have to do a replace (Program Files to ProgramData) due to some weird bug with the get directory. Also, I add "\AddInsAll\Ribbon17.dll" to the end of the string because the CurrentDirectory goes only to Addins\2017. Finally, if you think the problem is due to the #'s, I have already tried putting it and taking it off of variables and none of the attempts work. But if you think of them is the problem, I welcome the advice. Thanks.
public class RibApp : IExternalApplication
{
public Result OnStartup(Autodesk.Revit.UI.UIControlledApplication application)
{
// Create a custom ribbon tab
String tabName = "Add-Ins";
String fakeFullPath = #Directory.GetCurrentDirectory() + #"\AddInsAll\Ribbon17.dll";
String fullPath = fakeFullPath.Replace(#"\Program Files\", #"\ProgramData\");
TaskDialog.Show("Hi", #fullPath);
application.CreateRibbonTab(tabName);
//Create buttons and panel
// Create two push buttons
PushButtonData CommandButton = new PushButtonData("Command17", "Command",
#fullPath, "Ribbon17.Command");
I suggest you skip the # and replace each backslash \ by a forward slash /.
KISS!
Better still, use an approach similar to the CreateRibbonTab implementation in the HoloLens Escape Path Waypoint JSON Exporter.

MSDN OneNote Api: Navigate to never before opened page without opening a OneNote Application Window

My goal is to be able to use C# to programmatically open any .one section file and get all of the section's page ids. In a simple case (one where I have created and recently used the section), this can done with the following code:
using Microsoft.Office.Interop.OneNote;
class Program
{
public static void ProcessOnenoteFile()
{
Application onenoteApp = new Application();
string filepath = #"C:\Users\Admin\Documents\OneNote Notebooks\My Notebook\testsection.one";
string sectionId;
onenoteApp.OpenHierarchy(filepath, null, out sectionId);
string hierarchy;
onenoteApp.GetHierarchy(sectionId, HierarchyScope.hsPages, out hierarchy);
File.WriteAllText(#"C:\hierarchy.txt", hierarchy);
}
}
From here I can parse the xml to find all the pageIds and I am good to go.
The problem, however, is that I want to do this with files I am getting from somebody else and have never opened before. When I run the same code on those files, I cannot find any pageIds in the hierarchy, and therefore, I cannot process any pages. A fix that seems to work is to use the navigateTo method to open the section file in OneNote before trying to get the hierarchy.
...
string sectionId;
onenoteApp.OpenHierarchy(filepath, null, out sectionId);
onenoteApp.NavigateTo(sectionId);
string hierarchy
...
This, however, is quite annoying as I need to open the OneNote application. Since I have many .one section files to process it would be a lot of random information flashing across the screen which is not necessary and might confuse the end users of my program. Is there a way I can achieve the same result of adding pageIds to the hierarchy without needing to open the OneNote Application? At the very least, is there a way I can hide the application?
UPDATE:
I just noticed that using the Publish command also updates the hierarchy with pageIds, however, this solution is still not ideal as it requires me to make anotehr file.
Also, looking more closely at the xml export, I saw that there is a an attribute called "areAllPagesAvailable" which is set to false for me on all the files I have yet to open in OneNote.
WooHoo! After a couple hours of just playing around and Google Searching the different methods, I have found what I am after.
Solution: SyncHierarchy(sectionId);
...
string sectionId;
onenoteApp.OpenHierarchy(onenoteFile, null, out sectionId, CreateFileType.cftSection);
onenoteApp.SyncHierarchy(sectionId);
string hierarchy;
onenoteApp.GetHierarchy(sectionId, HierarchyScope.hsPages, out hierarchy);
...

Constant save file directory

I have a VS2012 in C# solution with 4 projects in 4 layer structure(Presentation, BusinessLogic, DomainModel, DataAccess) and wanted to give the user the option to select the database's file's path at the Login form, which is in the Presentation layer (it is then used when a creating connection to the Database in a static method in the DataAccess layer). And the path would be saved and used the next time the application runs.
A bit more workflow example would be:
User starts the application and the login form appears;
User chooses the Database's file path with a FolderBrowserDialog or
OpenDirectoryDialog;
User works on the application then ends it;
User starts the application and the Database's file path is the one
he picked before;
User works on the application then ends it;
User starts the application and picks another file;
User works on the application then ends it;
User starts the application and the Database's file path is the one
he picked before.
Codewise I don't want to go passing along that string (path) all around my code for each method that needs to create a connection and such.
So any ideas on how to directly save it in the method that's directly using it? If not only when the user wants to change it then just forcing the user to pick the file when the starts the application.
Currently what I'm doing is forcing the user to put the file he wants in the solution's directory with a specific name before starting the application when he wants to use another Database file. For that I'm using:
public static string path;
public static OleDbConnection createConnection()
{
path = DirProject() + "\\Calibrações Equipamentos ULSM.accdb";
OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();
builder["Provider"] = "Microsoft.ACE.OLEDB.12.0";
builder["Data Source"] = path;
return new OleDbConnection(builder.ConnectionString);
}
private static string DirProject()
{
string DirDebug = System.IO.Directory.GetCurrentDirectory();
string DirProject = DirDebug;
for (int counter_slash = 0; counter_slash < 3; counter_slash++)
{
DirProject = DirProject.Substring(0, DirProject.LastIndexOf(#"\"));
}
return DirProject;
}
Configuration (=data) is not saved into a method (=code). It's usually saved into a configuration file. You can leverage .NET's application and user settings mechanism to achieve what you want.
Use User Settings
How To: Write User Settings at Run Time with C#
How To: Read Settings at Run Time With C#

How to get the (.lnk) shortcut filepath in a program which started by the shortcut?

I have a c# program which open *.postfix file.
If a user runs a (.lnk)shortcut which points to my type of file, my program will open the target.
So, how could my program know it is started by a (.lnk)shortcut (and get it's file path)?
In some circumstances,i need to replace the .lnk file.
Thanks!
Edited
First, thanks to guys who answered my question.
By following #Anders answer, i find out my problem lays here.
I made some changes to windows registry, so browser knows to throw customized protocol string to certain program.
some thing like this..
[InternetShortcut]
URL=myProtocol://abcdefg.....
That's maybe why i lost lpTitle. :(
I'm going to try this way:
Whenever my program invoked, of course fed with %1, program checks current opened explorer(Window), and try to get it's current path with IWebBrowserApp. With that path and desktop of course, scan and analyze *.lnk to determine which one to replace.
I think this will probably work, but not be sure. I will try.
continued
In native code you can call GetStartupInfo, if the STARTF_TITLEISLINKNAME bit is set in STARTUPINFO.dwFlags then the path to the .lnk is in STARTUPINFO.lpTitle. I don't know if there is a .NET way to get this info, you probably have to P/Invoke...
You don't. There's no way to do it. End of story.
So this has been brought to my attention due to a recent downvote. There's an accepted answer showing an idea that gets the path to the launching shortcut most of the time. However my answer is to the whole. OP wants the link to the shortcut so he can change it. That is what can't be done most of the time.
Most likely case is the shortcut file exists in the start menu but is unwritable. However other cases involve the shortcut coming from another launching application that didn't even read it from a disk but from a database (I've seen a lot of corporate level restricted application launch tools). I also have a program that launches programs from shortcuts not via IShellLink but by parsing the .lnk file (because it must not start COM for reasons) and launching the program contained. It doesn't pass STARTF_TITLEISLINKNAME because it's passing an actual title.
If you're using Visual Studio Setup Project to build an installer and do the file type association, you should follow these instructions http://www.dreamincode.net/forums/topic/58005-file-associations-in-visual-studio/
Open up your solution in Visual studio.
Add a Setup Project to your solution by file , add project,New project, Setup & Deployment projects,Setup project
Right-click on your setup project in the "Solution Explorer" window,Select view,then select file types.
you'll see the "file types" window displayed in Visual studio.At the top of the window will be "File types on target machine"
Right-click on "File types on target machine".the menu will pop up with Add "file type" Click on this.
you'll see "New document Type#1" added,and "&open"underneath it.
The "new document type#1" can be anything you want - change it to something descriptive.although the user never sees this,never use something common- be as unique as possible,Because you can overlay current file associations without even realizing it.For example,you might think"pngfile" might be a useful name- but using that will now send all"*.png" files to your application,instead of to an image viewer.A good practice maybe "YourCompantName.Filetype",where your company name is your name of your company's name, and "Filetype" is a descriptive text of your file.
In the "properties" window for your new type,you will need to change a few properties.:
Command:Change to the application that you want to run.If you click on the "..." and you will proberly want to locate and use the "primary Output..." File
Description: This is the description of the file type(if it doesn't describe it's self"
Extensions:This your list of extensions for you chosen Program.Separate each one with a ","
Icon:This will associate the icon with your file type,This shows up in the window explorer.
Now we move to that "&open ".This is an action that is available if your right-click on the file.The default action("&Open" is currently set as the default) is what happens when you double click on the file.Right click on your "New document type#1" to add actions,but for the moment,lets define our "&open" action
Click on "&Open".You will see in the properties window "Name","Arguments","Verbs". Verb is hidden from the user,but is the key that is stored in the registry.Leave it same as the name,But without the "&".The default for"Arguments" is "%1",Which means to pass the full path and filename to your application.You can add other stuff here as well,if you need to pass flags to your application to do special stuff.All this infomaton is getting passed to your application on the command line,so you'll need to be familiar with the "Environment.CommandLine" object.
If you need to set a different action as your default,just right click on the action and "set as default"
Basically, you'll pass the file path as an argument to your program. Then if it's a console application or Windows Forms , you should check the arguments in Program.Main
static void Main(string[] args)
{
//if file association done with Arguments %1 as per forum post above
//you file path should be in args[0]
string filePath = null;
if(args != null && args.Length > 0)
filePath = args[0];
}
For a WPF application you'll need to handle that in the StartUp event for your Application
void App_Startup(object sender, StartupEventArgs e)
{
string filePath = null;
if ((e.Args != null) && (e.Args.Length > 0))
{
filePath = e.Args[0];
}
}

Silverlight 2 - Download file - IE Blocks file download

I'm having a problem with IE only in my Silverlight application. Since Silverlight 2 doesn't include a mechanism for file downloads I was left to my own devices to come up with a solution. The way I did it was as follows:
HtmlPage.Window.Navigate(new Uri(sb.ToString(), UriKind.Relative));
My StringBuilder contains the relative url with query string to a *.ashx handler on the server that reads the query string, gets some data from the database, and returns an Excel file.
When I do this I get a blocked file download bar in IE only. I understand that this is a new security "feature" in IE and that it is being blocked because it believes that the download wasn't triggered by the user interaction with the web page. The users can choose to allow the download and that setting seems to be remembered for the rest of the session. However next time they open the page it happens again. Even if the site is in the Trusted zone and even if the popup blocker is configured to allow popups for the site.
Does anyone know how to make IE know that the user did in fact request this file?
I had exactly the same problem. The solution for me was to not use HtmlPage.Window.Navigate, but to instead use a HyperlinkButton and dynamically set the NavigateUri property.
Saving and restoring the app state as suggested above didn't work. Well, it did, but it was impossible to determine when it needed to be done and when it didn't. So, ultimately, it didn't really work.
See this discussion on codeplex....
http://slideshow2.codeplex.com/Thread/View.aspx?ThreadId=60242
Try HtmlPage.PopupWindow instead of HtmlPage.Window.Navigate. This has helped me get around IE's "Automatic prompting for file downloads" setting being disabled by default for Internet zone sites.
This is my code solution to open URL for download and override Automatic prompting for file downloads option issue in IE 8.
It also use HyperlinkButton, but all is called from code:
public class BrowserHelper
{
private sealed class HyperlinkButtonCaller : HyperlinkButton
{
public static void OpenUrl(Uri url)
{
var button = new HyperlinkButtonCaller()
{
NavigateUri = url
};
button.OnClick();
}
}
public static void OpenUrl(Uri url)
{
if (url == null)
{
throw new ArgumentNullException("url");
}
HyperlinkButtonCaller.OpenUrl(url);
}
}
BrowserHelper.OpenUrl(new Uri(ClientGlobalInfo.Current.ApplicationUrl, "myhandler.ashx"));
In my case only happended the first time (using IE 7), maybe that happens on your local dev instance?
I think there's not much you can do, even MSDN pages tells you that "a message will appear on top of...", things that could mitigate this:
Warn the user that the message will be shown, then once he clicks the app is reset (Store the current app state in the isolated storage, when you receive the reset reload the app with the settings).
Open a popup, and in the popup include and standard HTML button to download.
HTH
Braulio

Categories

Resources