C# application not running on different machines - c#

I have a C# application that loads fine on my development machine but fails to even start on Win2008 machine.
Checked Frameworks and they match up, Net 4.0
I immediately suspected the problem was arising from references to specific files that I was reading from and sure enough, using some test code I narrowed it down to a single line.
public static string[] salesArray = (File.ReadAllLines("sales.txt").ToArray());
If I comment out the above line, the test app starts, if I leave it in, it fails. Any ideas?
I am copying the Debug directory to the second machine (sales.txt) within it.
This is the entire code. The app does nothing but open a blank window.
namespace testServer
{
public partial class Form1 : Form
{
public static string[] salesArray = (File.ReadAllLines("sales.txt").ToArray());
public Form1()
{
InitializeComponent();
}
}
}

Two potential issues jump out:
1) The current working directory of the app isn't what you think it is:
If you can print/show this, you would know for sure.
http://msdn.microsoft.com/en-us/library/system.io.directory.getcurrentdirectory.aspx
Because you are specifying a relative path, the current working directory is what the file is being resolved against.
2) Perhaps permissions. You might right-click, 'Run as administrator' as a quick check into that theory.

You should use a better mechanism to find that file, and check for its existence (ie: File.Exists) prior to opening it.
This will also let you report to the user if there is a problem, such as the file not existing where you expect it to be.

Put an exception handler around the code. You can get the error message and can handle the failure gracefully.
It should handle all errors (file not found, file in use, permission errors, etc.).

Related

Running same C# application twice

The application is a form application and it is too complicated. It is mostly used to connect to a database with an user interface. It also uses third party dlls.
I copied my VS C# application`s bin folder to my desktop.
"C:\Users\asd\Desktop\bin"
After that, I made some changes in my solution and building it, I again copied the application`s bin file under C:\;
"C:\bin"
Now when I run "C:\Users\asd\Desktop\bin\Debug\LIVE.exe" and let it remain open I can`t run "C:\bin\Debug\LIVE.exe". There is no error when I try to open the second .exe file. It simply does nothing.
I want both of the applications to be open at the same time.
Depending on the application, there are ways to prevent execution of a second instance (I have actually implemented the described behaviour in production code) so check the production specs of the application to see if that's a desired behaviour on client machines.
Because it's using a database connection and third party DLLs, there may be other specific limitations in place preventing proper execution, so check whether any exceptions are being cuaght by hooking into the FirstChanceException (WARNING: Never use this code outside a debug context!)
#if DEBUG
static Program()
{
AppDomain.CurrentDomain.FirstChanceException += (sender, e) => { };
}
#endif
Insert this into your Program class, or whichever class houses the Main method (and rename it if it's not Program of course) and then breakpoint the opening of the handler - this will often catch lots of exceptions you're better off not worrying about, but it may also clue you in if there is a problem keeping your code from starting.
As always, make sure to run this from within VS's Debug, so as to see any exceptions as they occur.

Directory.Exists sensible to time?

I have the following piece of code in my application:
if (!Directory.Exists(myPath))
Directory.CreateDirectory(myPath);
If I run it in a regular unit test sometimes it passes, sometimes not. The directory is always there (I made sure of it, so technically it will never be "created" by code). But every once in a while Directory.Exists(myPath) returned false, which makes the code try to create the folder and then I get an UnauthorizedAccessException!
The funny thing here is if I put a breakpoint on the CreateDirectory, and then move the yellow arrow up back to test, the test returns true!
What's going on?
myPath is \\nameOfLocalMachine\sharedFolder. The share is reliable and constantly used... .NET 4.0
I just made a fiddler simulate 3000 sequentials requests. 175 failed... All with the same message:
Access to the path '\nameOfLocalMachine\sharedFolder\randomFileName.json' is denied
This mishap is pretty normal on Windows. Programs open a handle on a directory like this and specify delete sharing. Which permits anybody to delete the directory, even though the program is using it. The directory won't actually disappear from the file system until that handle is closed. What follows is that trying to recreate that directory cannot work, it still exists. Windows generates an "access denied" error, reported in your C# program with the UnauthorizedAccessException.
While that sounds like an obscure feature, every program in Windows does this. Every process has a default working directory, the value of Environment.CurrentDirectory. Creating a handle on such a directory ensures that it cannot disappear while the program is using it. There are other cases, FileSystemWatcher would be another example. Or a program busy iterating the directory. Anti-malware and search indexers are notorious for hard to diagnose sources of such errors.
Otherwise a standard hazard of a multi-tasking operating system. You are not the only one using the file system. Not repeatedly deleting and creating the same directory ought to be very high on your list. If this is absolutely necessary then rename the directory first before you delete it. You'd still fail to delete the renamed directory but you won't fail recreating it. You can delete it later, next time you need to do this. Much lower odds for trouble then. Because more time passed.

From a C# MVC controller action, is it possible to execute a gulp task

From a C# MVC controller action, is it possible to execute a gulp task and if so how would I go about doing this?
In my C# app, I'm trying to check if a given string (submitted in a form) is valid sass.
There are a couple of C# CSS parsers but I can't find one that can handle sass (*.scss).
In my projects I use a gulp task that compiles sass and reports any errors so I was wondering if there was a way I could utilize this to do the validation in my C# app i.e. add the text input from my C# app to a .scss file, get the gulp task to try and compile it, if it passes without errors then I know the sass is valid.
Maybe I'm barking up the wrong tree here but any help would be much appreciated.
Ok. There's a few things here (in your question) that a scaring the absolute crap out of me but I think the easiest summary of it is this :-
Given an ASP.NET MVC Controller, how can I call -another- .exe
process?
So assuming you still want to do this, ignoring security vun's and stuff (I'll just roll with you, here...) I think you need to run a new AppDomain and then in that app domain run your exe. If the exe fails, you can then capture the error message also.
Updated as per comments
Random code taken from first'ish google result:
try
{
//Create a new appdoamin for execute my exe in a isolated way.
AppDomain sandBox = AppDomain.CreateDomain("sandBox");
try
{
//Exe executing with arguments
sandBox.ExecuteAssembly(".exe file name with path");
}
finally
{
AppDomain.Unload(sandBox);//destry created appdomain and memory is released.
}
}
catch (Exception ex)//Any exception that generate from executable can handle
{
//Logger.log(ex.Message);
}
so here, you would run the gulp.exe and pass in your command line args, include the sass content (content saved to a file?).
Now, if the .exe isn't a .NET assembly, then you might need to use the Process method...
something like this.. (pseudo code)
Process app = new Process();
app.StartInfo.FileName = #"D:/Path to /My/Program to be run.exe";
app.Start();
Again - not testing, but this should be enough to get you started...
Do note -> running a Process requires serious security permissions on the server, so generally hosted servers (like Azure Websites Site etc) lock all this down to protected themselves. If you own the server, then go nuts.
Final Note:
I've never seen or used Node.
I've never seen or used gulp.

Using R(D)COM for integrating R with C#

I am trying to use R(D)Com interface. I have R 2.12.1 installed on machine. For using this interface in C#, I loaded rscproxy_1.3-1 package and then installed R_Scilab_DCOM3.0-1B5 on my machine. Also, I copied sciproxy.dll from Program Files\R(D)COM Server\Scilab to Program Files\R(D)COM Server\bin, as informed while installing the interface.
My Problem:
As a part of testing, I tried the code from blog post http://vvella.blogspot.com/2010/08/integrate-c-net-and-r-taking-best-of.html. But my form application failed due to exception raised by statement rconn.Init(“R”). The exception text was Exception from HRESULT: 0x80040013 I tried to run samples from Programs->R->R(D)COM Server->Server 01 Basic Test. On launched form, I clicked button “Start R” but it failed with error printed in text box as “Initializing R...Function call failed Code: -2147221485 Text: installation problem: unable to load connector”
I tried this:
I tried to troubleshoot it with the help of Index html page, and there under installation section, I found that there must be rproxy.dll under installed R/Bin folder. Also, HKEY_LOCAL_MACHINE\Software\R-core\R\InstallPath should point to installation folder.
Things lacking on my machine are
the installed R/bin folder doesn’t
contain rproxy.dll. Where can I get
this dll? Or is it sciproxy.dll
instead?
HKEY_LOCAL_MACHINE\Software\R-core\R\InstallPath
points to installation folder, but
there is no entry under
HKEY_CURRENT_USER\Software.
I can guess there is something fishy about installation, or registering COM server. But I am not successful in figuring it out.
Could you please tell me where am I going wrong?
thanks,
Kapil
Oh god I remember this being a huge pain in the arse. Lets see if I can remember... And before I start, I warn you that I just "got this working" and never cared to work out if I could remove parts from the process.
Downloads are available from http://rcom.univie.ac.at/download.html . If I remember correctly, the RandFriends package is all you need, it installs a crapload (just install it all) but is simple. Alternatively, I think if you install the 'rscproxy' package in R you can just download the 'statconnDCOM' and install that. Memory is hazy, but I know one of these methods results in an annoying splash screen everytime you run your C# executable, and one doesn't. Although that could have just been some setting I played with.
Now, I can't remember how you verify that stuff has installed successfully. Pretty sure it comes with examples though. Once that is started, get your C# project open. Reference the following projects,
StatConnectorCommonLib
STATCONNECTORSRVLib
In your code, you will probably want to implement a IStatConnectorCharacterDevice so you get the R output coming back out in C#. Your code to initialise will then look something like,
private StatConnector _StatConn;
private IStatConnectorCharacterDevice _CharDevice;
private Whatever()
{
// declare
_StatConn = new StatConnectorClass();
_CharDevice = new MyCharDevice();
// init R, wire up char device
_StatConn.Init("R");
_StatConn.SetCharacterOutputDevice(_CharDevice);
}
Then you should be able to just use the functions as needed
_StatConn.EvaluateNoReturn("x <- 3");
var returnObj = _StatConn.Evalute("1 + 1");
Hope that helps.
tl;dr download RAndFriends, do fresh install with that
I had a similar problem calling R.Init(), I found R.GetErrorText() returns the actual error message

How can I launch a program from memory in C#?

I have some UI application that lives in the user's task bar that is written in C#. The EXE for the tool is checked in to our source control system on a number of projects that use it so we are able to update the version they run with by checking in updated EXE.
The problem is that when the users get the latest revision of the exe, the program is often running, and the sync fails on their machine. I want to fix it so the program doesn't lock the exe and any dependent DLL's when it runs so they can sync without having to shut down the program.
Currently, I have a program that takes an executable as a parameter and will launch it from memory by reading the assembly contents into memory ahead of time. Unfortunetly, this totally fails when it comes to the DLL's that the program requires.
The code I have right now looks something like this:
public class ExecuteFromMemory
{
public static void Main(string[] args)
{
//Figure out the name of the EXE to launch and the arguments to forward to it
string fileName = args[0];
string[] realArgs = new string[args.Length - 1];
Array.Copy(args, 1, realArgs, 0, args.Length - 1);
//Read the assembly from the disk
byte[] binary = File.ReadAllBytes(fileName);
//Execute the loaded assembly using reflection
Assembly memoryAssembly = null;
try
{
memoryAssembly = Assembly.Load(binary);
}
catch (Exception ex)
{
//Print error message and exit
}
MethodInfo method = memoryAssembly.EntryPoint;
if (method != null && method.IsStatic)
{
try
{
method.Invoke(null, new object[] { realArgs });
}
catch(Exception ex)
{
//Print error message and exit
}
}
else
{
//Print error message and exit
}
}
}
My question is, am I doing something totally stupid? Is there a better way to handle this? If not, what should I do to support handling external dependencies?
For example, the above code fails to load any dependent files if you try to run 'Foo.exe' that uses functions from 'Bar.dll', the 'Foo.exe' will be overwriteable, but 'Bar.dll' is still locked and can't be overwritten.
I tried getting the list of referenced assemblies from the 'GetReferencedAssemblies()' method on the loaded assmebly, but that doesn't seem to give any indication where the assemblies should be loaded from... Do I need to search for them myself? If so, what's the best way to do this?
It seems like other people might have come across this before, and I don't want to re-invent the wheel.
-
Update:
The EXE is checked in because thats how we distribute our in-house tools to the teams that use them. Its not optimal for this use-case, but I don't have the opportunity to change that policy.
Disclaimer: I don't use Windows, though I am familiar with its strange way of locking things.
In order to update your application while it is running, you'll likely need to have two processes: The executable itself, and an update “helper” application that will finish the update process. Let's say that your application is ProcessA.exe and your update helper is Updater.exe. Your main program will download a new copy of the executable, saving it with a random name. Then you run your updater program, which watches for the termination of your current process. When your process terminates, it displays a quick window showing the status of the update, moving the new executable into the place of the old one, and then restarting that program.
It'd be more elegant to be able to emulate POSIX filesystem semantics and be able to delete the currently-running process disk image and replace it with a new file, but I don't know if that is even possible on Windows. On a POSIX system, you can delete an in-use file and it won't actually be deleted until any remaining file handles are closed, though you can then reuse the filename.
You might want to check out an article written at CodeProject that talks about this. It also has a follow-up article.
Good luck!
Does the program need to keep running while updating?
Typically to update a program which is running you would copy over any of the files that are to be replaced to a temporary folder. Then shut down the old instance, delete it and move the new files over to the correct locations then re-launch it.
This allows for minimal down time of the application since the longest part is usually the copy and the file move is very fast if the temporary folder is on the same logical drive.
Although Michael's answer is one way of doing this, there are tools out there that are explicitly for managing what's installed on the desktop.
What you are doing with the exe being checked into source control is not normal. If you have a windows domain controller, you can use Group Policy to push programs down to the client. Alternatively, you could use something like Altiris to handle it.
If you must continue the way you are going then you have two options. One, using a helper / loader app which does a version check on launch. This is similar to how firefox works.
The second way is to build a helper service that sits in memory and polls every so often for updates. This is how Google Chrome, Adobe, etc work.

Categories

Resources