Open a browser with a specific URL by Console application - windows

I'm doing a console application in Visual Studio, but I have a little problem.
If I want to open a browser with a specified URL when any key is pressed, how can I do that?
Thanks

If you want to cover also .Net Core applications.Thanks to Brock Allen
https://brockallen.com/2016/09/24/process-start-for-urls-on-net-core/
public static void OpenBrowser(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("cmd", $"/c start {url}") { CreateNoWindow = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
throw;
}
}
}

Use the ProcessStartInfo class instance to set of values that are used to start a process.
Something like this:
using System;
using System.Diagnostics;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var psi = new ProcessStartInfo("iexplore.exe");
psi.Arguments = "http://www.google.com/";
Process.Start(psi);
}
}
}

Related

How can I test my C# Console App using XUnit, the App contain Command line arguments

I have a Program, it's C# Console App, The function of the program is to open a file and search for a specific line and edit it.
I can run the program without Parameter and the local file will be edited, or i can run the program with a parameter to Specify the path of the file I want to modify, or i can run the program with a parameter to get help.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
namespace BuildIncrement
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(args.Length);
string filePath = "version.h";
if (args.Length > 0)
{
if (args[0].Contains("path"))
{
var argsArray = args[0].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (argsArray.Length > 1)
{
filePath = argsArray[1];
}
}
else if (args[0].Contains("help"))
{
Console.WriteLine("To run the Program please type --path");
return;
}
}
if (File.Exists(filePath) == false)
{
Console.WriteLine("Fehler: Die Datei existiert nicht!");
return;
}
List<string> lines = File.ReadAllLines(filePath).ToList();
string line = lines.Where(i => i.Contains("BUILD_NUM")).FirstOrDefault();
//foreach (string line in lines)
int buildNr = 0;
if (line != null)
{
string[] lineparts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (lineparts.Length > 2)
{
string Nr = lineparts[2];
if (int.TryParse(Nr, out buildNr))
{
}
buildNr++;
int index = lines.IndexOf(line);
lines.RemoveAt(index);
lines.Insert(index, line.Replace(Nr, buildNr.ToString()));
}
}
File.WriteAllLines(filePath, lines);
Console.WriteLine($"Build-Nr wurde auf {buildNr} aktualisiert!");
}
}
}
Rectify your code and write the logic in different methods. Call these methods in Main. Then You can use Xunit [Fact] to test your code.
It is perfectly possible to call the Main method and supply arguments to it. (You do have to make it a public method).
[Fact]
public void MyTest()
{
string[] args = new string[] { "MyFile.txt" };
Program.Main(args);
// Assertions about the result
}

Xamarin Push Notification

Receiving and opening notifications with the app in the background increments the number of Data sent.
In addition the notification is not showing when the app is killed or when it is in the foreground.
Below is my code, the source code is from Gerald Versluis https://github.com/jfversluis/XFFCMPushNotificationsSample
using System;
using Xamarin.Forms;
using Plugin.FirebasePushNotification;
using Xamarin.Forms.Xaml;
namespace FCMTest
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
CrossFirebasePushNotification.Current.Subscribe("all");
CrossFirebasePushNotification.Current.OnTokenRefresh += Current_OnTokenRefresh;
CrossFirebasePushNotification.Current.OnNotificationReceived += Current_OnNotificationReceived;
CrossFirebasePushNotification.Current.OnNotificationOpened += Current_OnNotificationOpened;
//CrossFirebasePushNotification.Current.OnNotificationAction += Current_OnNotificationAction;
}
private void Current_OnTokenRefresh(object source, FirebasePushNotificationTokenEventArgs e)
{
System.Diagnostics.Debug.WriteLine($"Token from function OnTokenRefresh: {e.Token}");
}
private void Current_OnNotificationReceived(object source, FirebasePushNotificationDataEventArgs d)
{
System.Diagnostics.Debug.WriteLine("Received");
foreach (var data in d.Data)
{
System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
}
}
/*private void Current_OnNotificationAction(object source, FirebasePushNotificationResponseEventArgs d)
{
System.Diagnostics.Debug.WriteLine("Opened");
foreach (var data in d.Data)
{
System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
}
}*/
private void Current_OnNotificationOpened(object source, FirebasePushNotificationResponseEventArgs d)
{
System.Diagnostics.Debug.WriteLine("Opened");
foreach (var data in d.Data)
{
System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
}
}
protected override void OnStart()
{
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
}
using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
using System;
using System.Collections.Generic;
namespace FCMDispatcher
{
class Program
{
static void Main(string[] args)
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("fcm-test-98fe5-firebase-adminsdk-oknwc-c290af4ff0.json")
});
// This registration token comes from the client FCM SDKs.
var registrationToken = "d8yECxIhJXQ:APA91bFGXSrnUVcP07TlN4HpvfstWwEdPQaj4wr6Z3Q-7JqcJJjrFy9LkWdlfzcCNDrZeVy55IDTWxvp5Gfyv8318uRRmIPo6Gp2IQnyUDSHqGLdTF8RMmlwyaECTKWDnmhClMLV8In9";
// See documentation on defining a message payload.
var message = new Message()
{
Data = new Dictionary<string, string>()
{
{"myData", "One more try to say Succeded!"},
},
Token = registrationToken,
//Topic = "all",
Notification = new Notification()
{
Title = "Test from code",
Body = "Here is your test!"
}
};
// Send a message to the device corresponding to the provided
// registration token.
string response = FirebaseMessaging.DefaultInstance.SendAsync(message).Result;
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
}
}
}
Try adding priority with high or max to your Data Payload.
Data = new Dictionary<string, string>()
{
{"myData", "One more try to say Succeded!"},
{"priority", "high"},
},
This complex condition must match to show your notification:
https://github.com/CrossGeeks/FirebasePushNotificationPlugin/blob/d86266a9f45687b418f5f1e69c348681d1ff6e27/Plugin.FirebasePushNotification/DefaultPushNotificationHandler.android.cs#L151

How to use CDO.Message to send email in Classic ASP from Windows Docker IIS 2019

My team is tasked with migrating a Classic ASP application from a Windows 2008 Server to a Docker container (mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019), with as little code-change as possible. The application uses Server.CreateObject("CDO.Message") to send email.
That line, however, results in the following error: 006~ASP 0177~Server.CreateObject Failed~800401f3/. I am given to understand from this thread, that this is because the cdosys.dll file is missing from this Windows Docker image.
It appears that the cdosys.dll file is absent in Windows Docker images, generally. I tried installing just a ton of windows features (everything .NET that was available), but none of them appear to contain this file. A team member has attempted to manually register the dll, as well, without success.
How can I use CDO.Message to send email from my Windows Docker container?
Make a wrapper class that implements the CDO.MESSAGE API.
We wrapped around System.Net.Mail
using System.Net.Mail;
using System.Runtime.InteropServices;
namespace AspClassicMail
{
[System.Runtime.InteropServices.ComVisible(true)]
[ProgId("AspClassicMail.Message")]
public class Message
{
private MailMessage mailMessage;
public string To {
get
{
return mailMessage.To.ToString();
}
set {
mailMessage.To.Clear();
mailMessage.To.Add(value.Replace(';', ','));
}
}
public string Subject {
get
{
return mailMessage.Subject;
}
set
{
mailMessage.Subject = value;
}
}
public string CC
{
get
{
return mailMessage.CC.ToString();
}
set
{
mailMessage.CC.Clear();
mailMessage.CC.Add(value.Replace(';', ','));
}
}
public string Bcc
{
get
{
return mailMessage.Bcc.ToString();
}
set
{
mailMessage.Bcc.Clear();
mailMessage.Bcc.Add(value.Replace(';', ','));
}
}
public string From
{
get
{
return mailMessage.From.Address;
}
set
{
mailMessage.From = new MailAddress(value);
}
}
public string ReplyTo
{
get
{
return mailMessage.ReplyToList.ToString();
}
set
{
mailMessage.ReplyToList.Clear();
mailMessage.ReplyToList.Add(value.Replace(';',','));
}
}
public string textbody
{
get
{
return mailMessage.Body;
}
set
{
mailMessage.IsBodyHtml = false;
mailMessage.Body = value;
}
}
public string HTMLBody
{
get
{
return mailMessage.Body;
}
set
{
mailMessage.IsBodyHtml = true;
mailMessage.Body = value;
}
}
public Message()
{
mailMessage = new MailMessage();
}
public void send()
{
SmtpClient smtpClient = new SmtpClient("YOUR MAIL SERVER");
smtpClient.Send(mailMessage);
}
}
}
You may need to include a property for "Configuration" as well. We just removed the configuration from the ASP files instead.
You can either place it in an MSI package and set the DLL class to Register "vsdrpCOM" or run RegAsm.exe from your .NET framework folder.
ASP Classic code just needs updated to replace Server.CreateObject("CDO.Message") with Server.CreateObject("AspClassicMail.Message")

Exception "System.ObjectDisposedException: Safe handle has been closed" after unsuccessfully NTAccount.Translate

I have this problem on a asp.net website, but it should be general for .Net Core on windows computer.
If I try to translate an nonexistent Domain, I’ll get an exception, it’s OK, but then, all next calls with correct domain name throw an exception also "System.ObjectDisposedException: Safe handle has been closed".
I'm asking about some workaround, because name translation does ‘not work until restart of application.
This behavior can be reproduced with
Microsoft.NETCore.App 2.2.0
System.Security.Principal.Windows 4.5.1
class Program
{
static string Translate(string gName)
{
try
{
var nt = new NTAccount(gName);
if (nt.IsValidTargetType(typeof(SecurityIdentifier)))
{
var si = (SecurityIdentifier)(nt).Translate(typeof(SecurityIdentifier));
return si.ToString();
}
}
catch (Exception ex)
{
Console.Write(ex.ToString()+"\n\n");
}
return "";
}
static void Main(string[] args)
{
var si= new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
var na = si.Translate(typeof(NTAccount));
var knownName = na.ToString();
foreach (var aName in new[] { knownName,
#"DOMAIN_NOT_ESISTS\Benutzer",
knownName })
{
Console.WriteLine(aName);
Console.WriteLine(Translate(aName));
}
Console.ReadKey();
}
}

How do I register an app to run on Windows startup using Squirrel.Windows?

Is there a way to register an installed app to run on Windows startup when using Squirrel.Windows to build the installer?
Thanks!
I just found out about Custom Squirrel Events and we can handle those to create/remove the appropriate registry for our app to run at windows startup.
using Microsoft.Win32;
using Squirrel;
using System.IO;
public static class UpdateManagerExtensions
{
private static RegistryKey OpenRunAtWindowsStartupRegistryKey() =>
Registry.CurrentUser.OpenSubKey(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
public static void CreateRunAtWindowsStartupRegistry(this UpdateManager updateManager)
{
using (var startupRegistryKey = OpenRunAtWindowsStartupRegistryKey())
startupRegistryKey.SetValue(
updateManager.ApplicationName,
Path.Combine(updateManager.RootAppDirectory, $"{updateManager.ApplicationName}.exe"));
}
public static void RemoveRunAtWindowsStartupRegistry(this UpdateManager updateManager)
{
using (var startupRegistryKey = OpenRunAtWindowsStartupRegistryKey())
startupRegistryKey.DeleteValue(updateManager.ApplicationName);
}
}
Use case
string updateUrl = //...
using (var mgr = new UpdateManager(updateUrl)))
{
SquirrelAwareApp.HandleEvents(
onInitialInstall: v =>
{
mgr.CreateShortcutForThisExe();
mgr.CreateRunAtWindowsStartupRegistry();
},
onAppUninstall: v =>
{
mgr.RemoveShortcutForThisExe();
mgr.RemoveRunAtWindowsStartupRegistry();
});
}
It can also be done by adding a shortcut to the user's Startup folder:
private void OnInitialInstall(UpdateManager mgr)
{
mgr.CreateShortcutForThisExe();
mgr.CreateShortcutsForExecutable("MyApp.exe", ShortcutLocation.StartUp, false);
mgr.CreateShortcutsForExecutable("MyApp.exe", ShortcutLocation.Desktop, false);
mgr.CreateShortcutsForExecutable("MyApp.exe", ShortcutLocation.StartMenu, false);
mgr.CreateUninstallerRegistryEntry();
}

Resources