Different Behavior When Stepping Through Code And When Running Normally

I have a FEZ Panda connected to a WIZ5100 and it seems to work great. I’ve built the example server and connected to it, I’ve even modified the code to accept GET variables and feed them back.

BUT - I have this line of code in a new project that connects to a web server: socket.Connect(new IPEndPoint(theIP, port));

Now, when I run the code it give me this error:

An unhandled exception of type ‘System.Exception’ occurred in GHIElectronics.NETMF.W5100.dll

Additional information: Timeout occurs during connection establishment

What’s really interesting is that when I set a breakpoint on this line or before this line then step through the code, it works PERFECTLY.

Anyone else encounter something like this? Am I missing something obvious?
Thanks so much for your help!

No code, so I am assuming things…
Maybe you are doing something before you have established a connection…didn’t give it enough time.

Can you put this in a small test code that we can run here?

[quote]What’s really interesting is that when I set a break-point on this line or before this line then step through the code, it works PERFECTLY.

I think you have hit upon the most likely cause. When you are debugging you are giving everything a very long time to happen. If your code fails when not debugging then you have a very large clue that it is ‘time’ related.

The next step is to look at what you are doing that might take more time than your allowing. I think Gus has point out the most likely cause.

I’ll upload the entire script this evening when I get home, but am I wrong in assuming that the socket.Connect() method is a blocking call so nothing else should be happening while it is waiting for a connection?

I had the same idea Gus, and I think you’re right but I’m not sure how to give a blocking call more time.

Thanks for your help so far!

You are right. It is a blocking socket.

You can’t/don’t :slight_smile:

Remember, I didn’t see any code so I was guessing an answer. Maybe GHI neds to give it some delay internally and this is why we need to see the code, and even better, try it here.

Do you have the W5100 connected and accessible through Wiznet_W5100.Enable()?

Yes, the W5100 works fine AFAIK because I have built and run the sample server application provided. I can access the server in the example without problem and the application I am writing works great as long as I am stepping through the code rather than running it normally. Here is the method I am having trouble with and the configuration I’m using:

Setup in Main():

            byte[] ip = { 10, 0, 1, 25 };
            byte[] subnet = { 255, 255, 255, 0 };
            byte[] gateway = { 10, 0, 1, 1 };
            byte[] mac = { 43, 185, 44, 2, 206, 127 };

            WIZnet_W5100.Enable(SPI.SPI_module.SPI1, (Cpu.Pin)FEZ_Pin.Digital.Di6, (Cpu.Pin)FEZ_Pin.Digital.Di7, true);

            NetworkInterface.EnableStaticIP(ip, subnet, gateway, mac);
            NetworkInterface.EnableStaticDns(new byte[] { 10, 0, 1, 1 });

            string response = request(" Pushed&Description=Pushed", "");

The request method mentioned above parses out the relevant data from the url and calls the below method to create the socket connection.


private static Socket ConnectSocket(String server, Int32 port)
            IPAddress theIP = IPAddress.Parse(server);
            // Create socket and connect to the server's IP address and port
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.ReceiveTimeout = 10000;
            socket.SendTimeout = 10000;
            socket.Connect(new IPEndPoint(theIP, port));
            return socket;

This invariable ends badly in
An unhandled exception of type ‘System.Exception’ occurred in GHIElectronics.NETMF.W5100.dll

Additional information: Timeout occurs during connection establishment

and the system refers to the “socket.Connect()” line as the one causing the exception.

NOTE: I added in the socket.ReceiveTimeout = 10000; and socket.SendTimeout = 10000; just to see if it had any effect. It didn’t.

I would LOVE your feedback.

string response = request(" Pushed&Description=Pushed", "");

What does your request method look like? Also make sure to use mac address of your device.

Joe: How would I discover the mac address of my device. I was under the impression I would have to set that myself.

I tried this:

WIZnet_W5100.Enable(SPI.SPI_module.SPI1, (Cpu.Pin)FEZ_Pin.Digital.Di6, (Cpu.Pin)FEZ_Pin.Digital.Di7, true);

            byte[] physicalAddressBytes = NetworkInterface.PhysicalAddress;

            String s = new String(System.Text.Encoding.UTF8.GetChars(physicalAddressBytes)); 

And got back NULL.

Here’s the contents of my request method:

public static string request(String URL, String Referer)
            // Check for HTTP and remove it from the URL
            if (URL.IndexOf("http://") != 0) { return ""; }
            URL = URL.Substring(7);

            // Get Server
            String Server = URL.Substring(0, URL.IndexOf("/"));

            // Get Path
            String Path = URL.Substring(URL.IndexOf("/"));

            // Get Port
            Int32 Port = 80;
            if (Server.IndexOf(':') != -1)
                String[] sServer = Server.Split(new char[] { '|' });
                Server = sServer[0];
                Port = Str_Int_Func.StrVal(sServer[1]);

            // Server settings
            const Int32 BufferSize = 128;

            // String used to hold the response
            String Response = String.Empty;

            // Create Socket, used in a using block so Socket is automaticly closed
            using (Socket requestSocket = ConnectSocket(Server, Port))
                // Create request header
                String request = "GET " + Path + " HTTP/1.1\r\n";                                       // Request URI
                request += "Host: " + Server + "\r\n";                                                  // HTTP1.1 Host
                request += "Connection: Close\r\n";                                                     // HTTP1.1 Close connection after request
                request += "Accept-Charset: utf-8;\r\n";                                     // HTTP1.1 Accept-Charset
                request += "Accept: application/rss+xml, application/xhtml+xml, text/html\r\n";         // HTTP1.1 Accept
                request += "Pragma:	no-cache\r\n";
                request += "Cache-Control: no-cache\r\n";
                request += "User-Agent: StudioMonitor .01 (.NET Micro Framework 4.1)\r\n";

                if (Referer != String.Empty)
                    request += "Referer: " + Referer + "\r\n";                                          // HTTP1.1 Referer

                request += "\r\n";                                                                      // End of header

                if (requestSocket == null)
                    return "Failed To Connect.";

                // Send request header
                Byte[] requestData = Encoding.UTF8.GetBytes(request);
                requestSocket.Send(requestData, requestData.Length, 0);

                // Buffer used for recieving 
                Byte[] recBuffer = new Byte[BufferSize];

                // Wait 30 seconds for data 
                DateTime timeoutAt = DateTime.Now.AddSeconds(30);
                while (requestSocket.Available == 0 && DateTime.Now < timeoutAt)

                // Recieve Data
                while (requestSocket.Poll(2 * 1000000, SelectMode.SelectRead))
                    // Clear recieve buffer
                    Array.Clear(recBuffer, 0, recBuffer.Length);

                    // Read data into buffer
                    Int32 bytesRead = requestSocket.Receive(recBuffer);


                    // Check if we have bytes in the buffer, if not, stop reading
                    if (bytesRead == 0)

                    // Add recieved data to the response string
                        //Response = Response + new String(Encoding.UTF8.GetChars(recBuffer));
                        char[] receivedData = System.Text.UTF8Encoding.UTF8.GetChars(recBuffer);
                        string str = new string(receivedData);

                    catch { }

                    Debug.Print("Bytes Read: " + bytesRead.ToString());
                    if (bytesRead < 128)


                // Get response header
                String ResponseHeader = String.Empty;
                if (Response.IndexOf("\r\n\r\n") != -1) { ResponseHeader = Response.Substring(0, Response.IndexOf("\r\n\r\n")); }

                // Check for a location header
                if (ResponseHeader.IndexOf("Location: ") != -1)
                    // Get Location
                    Int32 LocationStart = ResponseHeader.IndexOf("Location: ") + 10;
                    Int32 LocationEnd = ResponseHeader.IndexOf("\r\n", LocationStart);

                    String newLocation = ResponseHeader.Substring(LocationStart, LocationEnd - LocationStart);

                    // Retrieve and return from the new location
                    //return GetXML(newLocation, URL);
                    Debug.Print("Redirect NOT IMPLEMENTED");

                // Strip header from response
                if (Response.IndexOf("\r\n\r\n") != -1)
                    Response = Response.Substring(Response.IndexOf("\r\n\r\n") + 4);

                // Return Response
                return Response;

When you’re talking about the MAC address for a Wiz5100 device, you MUST make it up :slight_smile: Wiz do not provide you with a MAC address for their devices. Be aware that this MUST be unique, largely this is limited to your own network, so if you have two or more Wiz5100 devices you have to make sure you keep these unique. (if you only have one, you’re less likely to run into conflicts :slight_smile:

Thanks Brett,
LOL, that was my assumption all along, I’ve normally been setting the MAC manually to something that couldn’t be shared with another device on my network.

I’ve gotten some really interesting, and rather some far fetched suggestions for reasons for this problem, but no one who has volunteered that they’ve gotten something similar working. Does anyone know if the GHIElectronics.NETMF.Net.Sockets.connect() method works?

I’m willing to try all suggestions though. Thanks so much for all your help so far!

That’s why I asked if you you are sure that the reset pin connected and configured correctly.
The reason I ask for that is because when you deploy the first time, it will work fine because the chip might be reset and initialized correctly. But it will not always be the case and the chip might not work correctly, so the reset signal is the first thing you need to check with such behavior.

Please remind me,are you using a custom made Wiz5100 board or the Ethernet shield?

I must have missed that post, looking back through I don’t see it, but I will definitely look into that! I’m using the WIZnet W5100 Network Module with Mag Jack - WIZ811MJ. I’ve got the three SPI lines run, plus the chip select and the reset line.

You can see in an above post how it’s configured (which pins, etc).

I know for a fact that it doesn’t run EVER when not stepping through the code… and it ALWAYS works when stepping. As the GHINetMF assemblies are binaries I’m having a terrible time determining when the error is occurring. I’m still thinking it’s a timing issue in the connect() method.

Remember I have built and used the code here: [url]microframeworkprojects.com - This website is for sale! - microframeworkprojects Resources and Information. and it has consistently run perfectly.

Here’s a little more corroborating data. I have a VERY simliar problem with using the DNS.GetHostEntry() method. Works fine when stepping, returns nothing (not an exception, just an empty string) when running normally.

Thanks everyone for your time on this thus far. When we finally nail this thing I will do a full writeup to make sure to help others.

Have you look at the following:


It is different shield but the information might be applicable to your case. Also there are some code examples as well.

Could it be that the clock is too high on SPI for his wiring? It works fine for us because of the short wires but then longer wires require extra delay.

Can you post a picture of your setup?