Xamarin C# for Android : Searching for an App and path - c#

GOAL : I need to find if an app is installed on a device AND find it's path..
I see using PackageManager, you can do this in general but I would like to refine it.
I know if you use com.google.chrome you can find chrome explorer installed,
but this fails when you look simply for Chrome.
On some devices Chrome (and other apps, like Opera, Mini,etc) is not installed as com.google.chrome.
So how would one find an app without the com.google and just use Chrome as the search criteria ?

Simple, just combine PackageManager and ApplicationInfo, and then check if app name contain your search string. Here is some example code:
var searchQuery = "chrome";
var flag = PackageInfoFlags.Activities;
var apps = PackageManager.GetInstalledApplications(flag);
foreach(var app in apps)
{
try
{
var appInfo = PackageManager.GetApplicationInfo(app.PackageName, 0);
var appLabel = PackageManager.GetApplicationLabel(appInfo);
if (appLabel.ToLower().Contains(searchQuery.ToLower()))
{
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Found it!");
builder.SetMessage(appLabel + " installed at: " + app.SourceDir);
builder.Show();
}
}
catch (PackageManager.NameNotFoundException e) { continue; }
}

Related

How do you launch a web authentication window within Unity for a UWP app?

I'm trying to use the Twitter Service from the UWPCommunityToolkit, which I have running as a standalone UWP (Universal Windows Platform) app, but when I import it into Unity (2017.2.0f3) as a library, it doesn't open the authentication window.
This is what shows up on the working standalone UWP app:
When in unity, it seems to go through the setup code, but not run this line properly:
var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);
https://github.com/Microsoft/UWPCommunityToolkit/blob/master/Microsoft.Toolkit.Uwp.Services/Services/Twitter/TwitterDataProvider.cs#L293
It just returns WebAuthenticationStatus.UserCancel, whereas on the standalone UWP, it'd return WebAuthenticationStatus.Success. Note, it also returns WebAuthenticationStatus.UserCancel on the standalone UWP app when the user clicks the close button on the pop up.
Is it possible to run WebAuthenticationBroker.AuthenticateAsync (https://learn.microsoft.com/en-us/windows/uwp/security/web-authentication-broker) in Unity? Are there any other ways to do web authentication on the Windows platform using Unity?
I've also tried TwitterKit, but unfortunately, it doesn't have support for Windows UWP (only iOS and Android).
Thanks!
LINQ to Twitter supports UWP. It has a UniversalAuthorizer that works like this:
private async void TweetButton_Click(object sender, RoutedEventArgs e)
{
var authorizer = new UniversalAuthorizer
{
CredentialStore = new InMemoryCredentialStore
{
ConsumerKey = "",
ConsumerSecret = ""
}
};
await authorizer.AuthorizeAsync();
var ctx = new TwitterContext(authorizer);
string userInput = tweetText.Text;
Status tweet = await ctx.TweetAsync(userInput);
ResponseTextBlock.Text = tweet.Text;
await new MessageDialog("You Tweeted: " + tweet.Text, "Success!").ShowAsync();
}
Check out the Samples folder for a complete listing: https://github.com/JoeMayo/LinqToTwitter

open window explorer folder from my results c#

iv made a web forum, as i have lots of folders on my local drive i can now search for any folders i want on webpage.
Now am looking to add a link to the results of the search so it takes me directly to the folder.
My code in c#:
protected void List_Dirs(string searchStr = null)
{
try
{
MainContentLocal.InnerHtml = "";
string[] directoryList = System.IO.Directory.GetDirectories("\\\\myfiles\\Web");
int x = 0;
foreach (string directory in directoryList)
{
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text = "Your Search for : <strong>" + SearchPhrase.Text + "</strong> returns ";
if(directoryP.ToLower().Contains(searchStr.ToLower()))
{
MainContentLocal.InnerHtml += directoryP + "<br />";
x++;
}
}
else
{
MainContentLocal.InnerHtml += directoryP + "<br />";
}
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text += "<strong>" + x.ToString() + "</strong> results";
UserInfo.CssClass = "userInfo";
}
}
catch(Exception DirectoryListExp)
{
MainContentLocal.InnerHtml = DirectoryListExp.Message;
}
}
When i enter something is search i will get a list of folders like:
Your Search for : project returns 2 results
job234 project234 Awards
job323 project game
now is there any way for me to click the result so i can open a window explore on the webpage
Thanks
You can create links like project234.
string folder = "\\\\myfiles\\Web";
if (string.IsNullOrWhiteSpace(Request["folder"])) {
// Folder clicked
folder = string.Format("{0}{1}", folder, Request["folder"]);
Process.Start(folder);
}
string[] directoryList = System.IO.Directory.GetDirectories(folder);
Then it will open it on the server. So if it really is local, than it will work. If there is no security problem. But I'm not sure. You can also use file:// links (as Ryan Mrachek notes), but browsers are not happy to let you open them.
If your result is a file, you can open that file programmatically through the Process class by invoking Process.Start("C:\\MyResults.txt"). This will open the results in the default text editor. In the same way, you can also open a web page by inserting passing a Url to Process.Start. I hope this is what wanted.
our file urls are malformed. It should be:
file:///c:/folder/
Please refer to The Bizarre and Unhappy Story of File URLs.
This works for me:
link
When you click Link, a new Windows Explorer window is opened to the specified location. But as you point out, this only works from a file:// URL to begin with.
A detailed explanation of what is going on can be found here. Basically this behavior by design for IE since IE6 SP1/SP2 and the only way you can change it is by explicitly disabling certain security policies using registry settings on the local machine.
So if you're an IT admin and you want to deploy this for your internal corporate LAN, this might be possible (though inadvisable). If you're doing this on some generic, public-facing website, it seems impossible.

Enumerate available WiFi Printers in my Windows Phone app

I know similar questions have been asked a lot, ie "can I print from my wp8?". Most folks seem content with the simple "no" response. I am looking to add this functionality into my app and I know it can be accomplished at some level - even if I can only support a very minimum printer set for now.
I've looked at the app PrintHand, and it appears to have the capabilities I need: print to wireless and Bluetooth printers.
I've been looking through the Bluetooth scenarios document a bit and I think this might help discover a Bluetooth printer. That's a start. Perhaps it will help in identifying wireless printers also.
I realize I need to start very small with this project and I want to first try to enumerate any wireless printers (I don't have a Bluetooth one yet) available on the current network. Would anybody happen to have a pointer in the right direction on how to get started or better yet, some related sample code?
Thanks so much!
Best I can give is my Github Repo which isn't related to Wifi printers, but Google cloud printing.
There isn't really a .net reference for using Google Cloud Print in their documentation, but the code works in Mono, and should be easy to move over to .NET and hence, Windows Phone.
MonoGCP
I was able to detect a nearby wireless printer using Simple Service Discovery Protocol.
Here is my sample function:
private const string SSDP_IP = "239.255.255.250";
private const string SSDP_PORT = "1900";
public async static void DiscoverAsync2()
{
var multicastIP = new HostName(SSDP_IP);
var found = false;
using (var socket = new DatagramSocket())
{
socket.MessageReceived += (sender, e) =>
{
var reader = e.GetDataReader();
var bytesRemaining = reader.UnconsumedBufferLength;
var receivedString = reader.ReadString(bytesRemaining);
// TODO: something useful with this new info
found = true;
};
await socket.BindEndpointAsync(null, string.Empty);
socket.JoinMulticastGroup(multicastIP);
while (true)
{
found = false;
using (var stream = await socket.GetOutputStreamAsync(multicastIP, SSDP_PORT))
{
var request = new StringBuilder();
request.AppendLine("M-SEARCH * HTTP/1.1");
request.AppendLine("HOST: " + SSDP_IP + ":" + SSDP_PORT);
request.AppendLine("MAN: \"ssdp:discover\"");
request.AppendLine("MX: 3");
request.AppendLine("ST: urn:schemas-upnp-org:device:Printer:1"); // use ssdp:all to get everything
request.AppendLine(); // without this extra blank line, query won't run properly
var buff = Encoding.UTF8.GetBytes(request.ToString());
await stream.WriteAsync(buff.AsBuffer());
await Task.Delay(5000);
if (!found)
break;
}
}
}

How to check for installed browsers using C# for newbies

I am building an app and its a simple one, all I want it to do is display os information in plain english and the architecture as well as check for installed browsers and then I'll add the ability for it to delete cookies and what not.
What Im stuck on is the browser detection part. Can anyone point me to some decent tutorials or how tos? Thanks.
Edit: OK I managed to finally scratch out some working code using the snippet provided by hcb below and the comments from the others (thanks everyone). So far it is doing exactly what I want so I thought id share what I have for those trying to do the same thing:
RegistryKey browserKeys;
browserKeys = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\WOW6432Node\Clients\StartMenuInternet");
if (browserKeys == null)
{
browserKeys = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Clients\StartMenuInternet");
}
string[] browserNames = browserKeys.GetSubKeyNames();
foreach (string browser in browserNames)
{
using (RegistryKey tempKey = browserKeys.OpenSubKey(browser))
{
foreach (string keyName in tempKey.GetValueNames())
{
if (tempKey.GetValue(keyName).ToString() == "Internet Explorer")
{
internetExplorerButton.Enabled = true;
internetExplorerButton.BackgroundImage = Properties.Resources.iExplorer;
if (internetExplorerButton.Enabled == true)
{
Label ieLabel = new Label();
ieLabel.Text = "Found!";
explorerLable.Text = ieLabel.Text;
}
}
To my extreme annoyance, I noticed that Google want to install their browser in the Local App Data. I managed to work this out writing the code again separately and checking:
Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Google\Update\Clients");
Edit2: Checking CurrentUser for Chrome seems to work fine for a few friends so it must be OK.
Like this:
RegistryKey browserKeys;
//on 64bit the browsers are in a different location
browserKeys = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\WOW6432Node\Clients\StartMenuInternet");
if (browserKeys == null)
browserKeys = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Clients\StartMenuInternet");
string[] browserNames = browserKeys.GetSubKeyNames();

How to open in default browser in C#

I am designing a small C# application and there is a web browser in it. I currently have all of my defaults on my computer say google chrome is my default browser, yet when I click a link in my application to open in a new window, it opens internet explorer. Is there any way to make these links open in the default browser instead? Or is there something wrong on my computer?
My problem is that I have a webbrowser in the application, so say you go to google and type in "stack overflow" and right click the first link and click "Open in new window" it opens in IE instead of Chrome. Is this something I have coded improperly, or is there a setting not correct on my computer
===EDIT===
This is really annoying. I am already aware that the browser is IE, but I had it working fine before. When I clicked a link it opened in chrome. I was using sharp develop to make the application at that time because I could not get c# express to start up. I did a fresh windows install and since I wasn't too far along in my application, I decided to start over, and now I am having this problem. That is why I am not sure if it is my computer or not. Why would IE start up the whole browser when a link is clicked rather than simply opening the new link in the default browser?
You can just write
System.Diagnostics.Process.Start("http://google.com");
EDIT: The WebBrowser control is an embedded copy of IE.
Therefore, any links inside of it will open in IE.
To change this behavior, you can handle the Navigating event.
For those finding this question in dotnet core. I found a solution here
Code:
private void OpenUrl(string url)
{
try
{
Process.Start(url);
}
catch
{
// hack because of this: https://github.com/dotnet/corefx/issues/10361
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
url = url.Replace("&", "^&");
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
throw;
}
}
}
After researching a lot I feel most of the given answer will not work with dotnet core.
1.System.Diagnostics.Process.Start("http://google.com"); -- Will not work with dotnet core
2.It will work but it will block the new window opening in case default browser is chrome
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
myProcess.Start();
Below is the simplest and will work in all the scenarios.
Process.Start("explorer", url);
public static void GoToSite(string url)
{
System.Diagnostics.Process.Start(url);
}
that should solve your problem
Did you try Processas mentioned here: http://msdn.microsoft.com/de-de/library/system.diagnostics.process.aspx?
You could use
Process myProcess = new Process();
try
{
// true is the default, but it is important not to set it to false
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
myProcess.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
My default browser is Google Chrome and the accepted answer is giving the following error:
The system cannot find the file specified.
I solved the problem and managed to open an URL with the default browser by using this code:
System.Diagnostics.Process.Start("explorer.exe", "http://google.com");
I'm using this in .NET 5, on Windows, with Windows Forms. It works even with other default browsers (such as Firefox):
Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });
Based on this and this.
Try this , old school way ;)
public static void openit(string x)
{
System.Diagnostics.Process.Start("cmd", "/C start" + " " + x);
}
using : openit("www.google.com");
Am I the only one too scared to call System.Diagnostics.Process.Start() on a string I just read off the internet?
public bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
{
Request = request;
string url = Request.Url;
if (Request.TransitionType != TransitionType.LinkClicked)
{ // We are only changing the behavoir when someone clicks on a link.
// Let the embedded browser handle this request itself.
return false;
}
else
{ // The user clicked on a link. Something like a filter icon, which links to the help for that filter.
// We open a new window for that request. This window cannot change. It is running a JavaScript
// application that is talking with the C# main program.
Uri uri = new Uri(url);
try
{
switch (uri.Scheme)
{
case "http":
case "https":
{ // Stack overflow says that this next line is *the* way to open a URL in the
// default browser. I don't trust it. Seems like a potential security
// flaw to read a string from the network then run it from the shell. This
// way I'm at least verifying that it is an http request and will start a
// browser. The Uri object will also verify and sanitize the URL.
System.Diagnostics.Process.Start(uri.ToString());
break;
}
case "showdevtools":
{
WebBrowser.ShowDevTools();
break;
}
}
}
catch { }
// Tell the browser to cancel the navigation.
return true;
}
}
This code was designed to work with CefSharp, but should be easy to adapt.
Take a look at the GeckoFX control.
GeckoFX is an open-source component
which makes it easy to embed Mozilla
Gecko (Firefox) into any .NET Windows
Forms application. Written in clean,
fully commented C#, GeckoFX is the
perfect replacement for the default
Internet Explorer-based WebBrowser
control.
dotnet core throws an error if we use Process.Start(URL). The following code will work in dotnet core. You can add any browser instead of Chrome.
var processes = Process.GetProcessesByName("Chrome");
var path = processes.FirstOrDefault()?.MainModule?.FileName;
Process.Start(path, url);
This opened the default for me:
System.Diagnostics.Process.Start(e.LinkText.ToString());
I tried
System.Diagnostics.Process.Start("https://google.com");
which works for most of the cases but I run into an issue having a url which points to a file:
The system cannot find the file specified.
So, I tried this solution, which is working with a little modification:
System.Diagnostics.Process.Start("explorer.exe", $"\"{uri}\"");
Without wrapping the url with "", the explorer opens your document folder.
In UWP:
await Launcher.LaunchUriAsync(new Uri("http://google.com"));
Open dynamically
string addres= "Print/" + Id + ".htm";
System.Diagnostics.Process.Start(Path.Combine(Environment.CurrentDirectory, addres));
update the registry with current version of explorer
#"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION"
public enum BrowserEmulationVersion
{
Default = 0,
Version7 = 7000,
Version8 = 8000,
Version8Standards = 8888,
Version9 = 9000,
Version9Standards = 9999,
Version10 = 10000,
Version10Standards = 10001,
Version11 = 11000,
Version11Edge = 11001
}
key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);
This works nicely for .NET 5 (Windows):
ProcessStartInfo psi = new ProcessStartInfo {
FileName = "cmd.exe",
Arguments = $ "/C start https://stackoverflow.com/",
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true
};
Process.Start(psi);
to fix problem with Net 6
i used this code from ChromeLauncher
,default browser will be like it
internal static class ChromeLauncher
{
private const string ChromeAppKey = #"\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe";
private static string ChromeAppFileName
{
get
{
return (string) (Registry.GetValue("HKEY_LOCAL_MACHINE" + ChromeAppKey, "", null) ??
Registry.GetValue("HKEY_CURRENT_USER" + ChromeAppKey, "", null));
}
}
public static void OpenLink(string url)
{
string chromeAppFileName = ChromeAppFileName;
if (string.IsNullOrEmpty(chromeAppFileName))
{
throw new Exception("Could not find chrome.exe!");
}
Process.Start(chromeAppFileName, url);
}
}
I'd comment on one of the above answers, but I don't yet have the rep.
System.Diagnostics.Process.Start("explorer", "stackoverflow.com");
nearly works, unless the url has a query-string, in which case this code just opens a file explorer window. The key does seem to be the UseShellExecute flag, as given in Alex Vang's answer above (modulo other comments about launching random strings in web browsers).
You can open a link in default browser using cmd command start <link>, this method works for every language that has a function to execute a system command on cmd.exe.
This is the method I use for .NET 6 to execute a system command with redirecting the output & input, also pretty sure it will work on .NET 5 with some modifications.
using System.Diagnostics.Process cmd = new();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("start https://google.com");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();

Categories