odd behavior with C# ftp client class - c#

I found an ftp client class in c# over a year ago and have been using it in a process that uploads files on a nightly basis. A few days ago we started having a problem where it would time out. I'm not well versed in this so I'm not sure why it's doing this.
When the program starts uploading a file it checks to see if it's logged in and if not, it calls the login method. In that method is this block of code.
if (this.resultCode != 230)
{
this.sendCommand("PASS " + password);
if (!(this.resultCode == 230 || this.resultCode == 202))
{
this.cleanup();
throw new FtpException(this.result.Substring(4));
}
}
On the line that says this.sendCommand("PASS"... it goes into this code.
private void sendCommand(String command)
{
if (this.verboseDebugging) Debug.WriteLine(command, "FtpClient");
Byte[] cmdBytes = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray());
clientSocket.Send(cmdBytes, cmdBytes.Length, 0);
this.readResponse();
}
If I let the program run, it times out. However if I step through it into the sendCommand method it executes fine. Does anyone know why it would work fine when I step through it? Nothing on our end has changed and I've been told nothing on the client's end has changed so I'm stumped. Thanks.

Let it run in debug mode and when it freezes hit pause so you can see exactly what line it's hung up on.

If it starts the transfer - it'll not need to login again, unless the connection interrupts and your client tries to reconnect which will result in relogin.
I strongly suggest into looking if the client supports "NOOP" command (used to keep the control connection alive while the data is transferred over data connection). That's the most common problem with FTP implementations.

Related

Coded UI WebTest, typed characters are sometimes omitted in edit fields

** POST UPDATED **
For our system and integration tests on a Microsoft Dynamics environment, we are using Visual Studio 2010 Coded UI. I am an unexperienced user of Visual Studio, but have experience with test automation.
Whenever the VS-Coded-UI-test is typing text in edit boxes, there is a change that one of the characters that has to be typed is omitted. An address field like Beverly Hills 90210 could easily become Beverly ills 90210, breaking my tests. It happens around 1 in the 200 characters (educated guess).
Has someone experienced this before? And where could the problem be located: Type rate of VS, Broken keyboard driver, Hiccup of the browser so it could not receive a text input properly, something else?
And is there a possibility to lower the typing rate of the test-driver in VS coded ui?
UPDATE, 2012-05-24:
Still not found a solution. I use now a work around that reduce the change of failing, but it is still not ideal.
Work around code (yes, it is dirty):
// put this method in a base class or easy accessable component
protected void ExecuteWithRetry(Action method, int maxRetryCount = 2)
{
try
{
method();
}
catch (Exception)
{
if (maxRetryCount > 0)
{
ExecuteWithRetry(method, maxRetryCount - 1);
}
else
{
throw;
}
}
}
Whenever I use a piece of code where an text field is set, I call this through this method:
UIMap.SetUserfieldsParams.EnterAddress = #"555 Sunset Boulevard";
UIMap.SetUserfieldsParams.EnterZIP = #"90210";
ExecuteWithRetry(UIMap.SetUserfields);
UPDATE, 2012-06-18: It seems to be caused by the impersonation we use. The logged on user to our web-application is directly extracted from the AD server by the user name that started IE. By starting IE through impersonation, we can do our tests with other users without (manually) log off and log on into Windows. We use impersonation by using Process.Start(ProcessStartInfo startInfo) in namespace System.Diagnostics.Process
My first guess is that it is happening because it is typing to fast and your application isn't ready to receive the next key. You can change the time between keys being entered by using KeyBoard.SendKeysDelay, the default on my machine at least is 10 ms.
Do you happen to have continue on error turned off? I am kind of surprised that you aren't getting an exception that stops the test at the point when the value is entered.

How do I close COM1 after I left it open?

I'm working in Visual Studio C#, and I opened up a serial port, but I didn't properly close it. Now I cannot run my program to try to close it. I know it was me that was using it, but somehow I've lost control of it..? Is there a way to close it otherwise?
I've tried exiting out of visual studio and it still says that my access is denied. I've unplugged and replugged in the actual object I'm using. My next step is to restart the computer, but I don't want to have to do that everytime I mess up (which is frequently!)
On a side-note, I'm working in a lab and do not have administrative access on this computer. Another note is that the error's text is "Access to the port 'COM1' is denied."
In response to those asking for code,.. comPort.Open(); What else are you looking for?
private void updateAccuSwayData() {
Console.WriteLine("Update thread started...");
comPort.Open();
comPort.WriteLine("Q");
Thread.Sleep(5);
while (!cancelRequested) {
//do stuff...
}
Console.WriteLine("Update thread halted.");
comPort.WriteLine("R");
comPort.Close();
}
In a nutshell, I ended my debugging session while it was in middle of something it seems. That's about all I know.
You'll likely need to reboot to clear this up, although one approach would be to use Process Explorer and search for a handle to \Device\Serial0. You can then see if closing this handle works, it may not however.
To work to keep this from happening in the future, you need to put the comPort.Close() call in a finally-block:
try
{
comPort.Open();
// ...
}
finally
{
// Almost always ensures the COM port will be cleaned up,
// however, the MSDN remarks state that the port may not
// be closed immediately.
comPort.Close();
}

What is the difference between running in VS 2010 and running a builded EXE?

As a school project we've created a C# XNA 4.0 Game that runs perfectly when run (in either Release or Debug) from Visual Studio 2010 itself. However, when it's built, the game inexplicably crashes at a certain point.
The responsible code portion seems to be this:
while( true )
{
if( Client.readInfo )
{
t.Stop();
t.Dispose();
// Save last good IP to file
string toWrite = IPinput.filledIn;
using( StreamWriter file = new StreamWriter( "multiplayer.dat", false ) )
{
file.WriteLine( toWrite );
}
ExitScreen();
using( LobbyScreen screen = new LobbyScreen( c ) )
{
screenManager.AddScreen( screen );
}
break;
}
else if( itTookToLong )
{
Client.killMe = true;
IPinput.Text = "Server IP: ";
IPinput.filledIn = "";
break;
}
}
This waits till the started Client thread makes the public static attribute readInfo true (which happens, because the server obtains the client) or a timer runs out after 10 seconds. Both things work perfectly fine when running through VS, but the game just stops responding when run as built EXE.
What could this be?!
Edit: I seem to have found the fix already, FINALLY. Adding Thread.Sleep(1); at the bottom of the above while(true) loop seems to fix all problems! Don't know why this is different between running an EXE and running from Visual Studio though, but hey it works.
Edit2: This site explains my whole problem: http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/
Thread.Sleep just accidentally fixed everything ;)
Hard to tell from the code you have posted, but I believe you need to make Client.readInfo field volatile. The reason that Thread.Sleep fixed your problem is that it puts a memory barrier as a side effect.
I suspect that there is a problem with permissions to write the file to disk. The .exe has different permissions when it us running than VS does.
Here is where I would start: add some try-catch blocks in your code so you can figure out where the exception is occurring. While troubleshooting, display the exception details on the screen.
As a temporary debugging strategy, you could also try this: add some kind of logging and record every step along the way here. Right after the line if( Client.readInfo ), test that you have arrived at that line. Right after the line string toWrite = IPinput.filledIn; look at the contents of the string toWrite, and so on.
If you'd rather, just for debugging purposes, you could throw those messages to yourself on the screen. I'm not familiar with XNA, but in any old web app you can usually do this with Response.Write.
Once you narrow down where the exact problem is, you can test further for what it is. And when you've fixed it, of course, you remove all this code.

RasConnectionNotification after computer resumes from sleep

I've got a project called DotRas on CodePlex that exposes a component called RasConnectionWatcher which uses the RasConnectionNotification Win32 API to receive notifications when connections on a machine change. One of my users recently brought to my attention that if the machine comes out of sleep mode, and attempts to redial the connection, the connection goes into a loop indicating the connection is already being dialed even though it isn't. This loop will not end until the application is restarted, even if done through a synchronous call which all values on the structs are unique for that specific call, and none of it is retained once the call completes.
I've done as much as I can to fix the problem, but I fear the problem is something I've done with the RasConnectionNotification API and using ThreadPool.RegisterWaitForSingleObject which might be blocking something else in Windows.
The below method is used to register 1 of the 4 change types the API supports, and the handle to associate with it to monitor. During runtime, the below method would be called 4 times during initialization to register all 4 change types.
private void Register(NativeMethods.RASCN changeType, RasHandle handle)
{
AutoResetEvent waitObject = new AutoResetEvent(false);
int ret = SafeNativeMethods.Instance.RegisterConnectionNotification(handle, waitObject.SafeWaitHandle, changeType);
if (ret == NativeMethods.SUCCESS)
{
RasConnectionWatcherStateObject stateObject = new RasConnectionWatcherStateObject(changeType);
stateObject.WaitObject = waitObject;
stateObject.WaitHandle = ThreadPool.RegisterWaitForSingleObject(waitObject, new WaitOrTimerCallback(this.ConnectionStateChanged), stateObject, Timeout.Infinite, false);
this._stateObjects.Add(stateObject);
}
}
The event passed into the API gets signaled when Windows detects a change in the connections on the machine. The callback used just takes the change type registered from the state object and then processes it to determine exactly what changed.
private void ConnectionStateChanged(object obj, bool timedOut)
{
lock (this.lockObject)
{
if (this.EnableRaisingEvents)
{
try
{
// Retrieve the active connections to compare against the last state that was checked.
ReadOnlyCollection<RasConnection> connections = RasConnection.GetActiveConnections();
RasConnection connection = null;
switch (((RasConnectionWatcherStateObject)obj).ChangeType)
{
case NativeMethods.RASCN.Disconnection:
connection = FindEntry(this._lastState, connections);
if (connection != null)
{
this.OnDisconnected(new RasConnectionEventArgs(connection));
}
if (this.Handle != null)
{
// The handle that was being monitored has been disconnected.
this.Handle = null;
}
this._lastState = connections;
break;
}
}
catch (Exception ex)
{
this.OnError(new System.IO.ErrorEventArgs(ex));
}
}
}
}
}
Everything works perfectly, other than when the machine comes out of sleep. Now the strange thing is when this happens, if a MessageBox is displayed (even for 1 ms and closed by using SendMessage) it will work. I can only imagine something I've done is blocking something else in Windows so that it can't continue processing while the event is being processed by the component.
I've stripped down a lot of the code here, the full source can be found at:
http://dotras.codeplex.com/SourceControl/changeset/view/68525#1344960
I've come for help from people much smarter than myself, I'm outside of my comfort zone trying to fix this problem, any assistance would be greatly appreciated!
Thanks! - Jeff
After a lot of effort, I tracked down the problem. Thankfully it wasn't a blocking issue in Windows.
For those curious, basically once the machine came out of sleep the developer was attempting to immediately dial a connection (via the Disconnected event). Since the network interfaces hadn't finished initializing, an error was returned and the connection handle was not being closed. Any attempts to close the connection would throw an error indicating the connection was already closed, even though it wasn't. Since the handle was left open, any subsequent attempts to dial the connection would cause an actual error.
I just had to make an adjustment in the HangUp code to hide the error thrown when a connection is closed that has already been closed.

Why does my WCF service method only work once I've called MessageBox.Show()?

I have a WCF service which provides a method that creates a file. Sometimes it takes a little while for this file to appear, and other methods which are relying on that file's existence fail if they are called immediately afterward. As a result, I want to check that the file has appeared before proceeding.
In my client class, I can call the service method and then loop until the file has appeared before proceeding - this works perfectly. But if I loop until the file has appeared while still inside the service method, it never finds that the file has been created - unless I call MessageBox.Show() before checking. If I do, it finds it almost immediately, just as if I had called it from the client.
The file definitely exists during the time that the service method is looking for it (Edit: doesn't use File.Exists() as I previously wrote) - so why can't it find it? And why does MessageBox.Show() fix this problem?
I'm assuming it must be a threading issue I don't understand, since it works from outside the service, and works if you call MessageBox.Show() (which blocks the UI thread?) but I'm at a bit of a loss, so any help would be greatly appreciated.
Further info: the service is hosted as a plugin by a running GUI application, if that's relevant to the threading issue. Thanks everyone.
Edit: Here's a version of the code. I didn't post this originally because it uses a third-party library, so I'm not sure how helpful it is:
// The WCF service, in which HasCompiled(name) never
// returns true unless MessageBox.Show() is called:
public void CompileScript(string name)
{
// CompileFile outputs a file to disk:
string debug = NWN2Toolset.NWN2ToolsetMainForm.Compiler.CompileFile(script.Name,GetModuleTempPath());
if (debug.Length > 0)
throw new InvalidDataException("'" + name + "' could not be compiled: " + debug);
// If the following line is commented out, this method never returns:
MessageBox.Show("blabla");
while (!HasCompiled(name));
}
public bool HasCompiled(string name)
{
NWN2GameModule module = GetModule();
OEIResRef cResRef = new OEIResRef(name);
IResourceEntry entry = module.Repository.FindResource(cResRef,resourceType);
return entry != null;
}
// The client class, in which HasCompiled(name) returns true almost immediately:
[Test]
public void TestCompilesScript()
{
service.AddScript(name,scriptContents);
service.CompileScript(name);
while (!service.HasCompiled(name)) {
Console.WriteLine("HasCompiled(" + name+ ") == false.");
}
Console.WriteLine("HasCompiled(" + name+ ") == true.");
}
I don't see your code so I can suggest the following:
either don't return the first method until the file created (you might need to change the default timeouts for WCF)
Or - only after the first call to the Service returns - loop against the service to see if the file exists.
Not seeing your code, I just can guess -
if you are using threads, messagenox.show makes the calls in a certain order (because the system waits for you to dismiss the messagebox).
Instead of looping in the client, you could implement a callback instead. There are lots of good examples out there - http://www.google.com/search?q=wcf+callback+example

Categories