Error in .Net Gadgeteer

Hi guys new to .Net Gadgeteer.
I am trying to find solution for few error can any one help me?

using System;
using Microsoft.SPOT;

using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Microsoft.SPOT.Net.NetworkInformation;
using System.Net;
using System.Text;
using Microsoft.SPOT.Time;
using Amqp;
using Amqp.Framing;
using Gadgeteer.Modules.GHIElectronics;

namespace GadgeteerApp18
{
public partial class Program
{
GT.Timer timer;
HttpWebRequest httpReq;
const string sbNamespace = “https://neweventhub.servicebus.windows.net/”;
const string keyName = “SendRule”;
const string keyValue = “Tq9rQ4Wf3lOY0u3GaWhTn64tK4sxQKp+48NMgGTy7zc=”;
const string entity = “connectmeeventhub”;
// This method is run when the mainboard is powered up or reset.
void ProgramStarted()
{

        Debug.Print("Program Started");
        Mainboard.SetDebugLED(false);

            
            NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;
            NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
            
            timer = new GT.Timer(1000); // every second (1000ms)
            timer.Tick += timer_Tick;

            EthernetSetup();

        
        }

        void OnNetworkDown(GTM.Module.NetworkModule sender, GTM.Module.NetworkModule.NetworkState state)
        {
            Debug.Print("Network down.");
        }

        void OnNetworkUp(GTM.Module.NetworkModule sender, GTM.Module.NetworkModule.NetworkState state)
        {
            Debug.Print("Network up.");
            string eventhubname = "connectmeeventhub";
            SenderLink sendLink = null;
            if (sendLink == null)
            {

                var address = new Address("neweventhub.servicebus.windows.net", 5671, "RootManageSharedAccessKey", "+SAfiS1eVFODhouYtx/U2vITzrbeLGIlQJ1ZnTrUB34=", "/", "AMQPS");

                // create connection
                var connection = new Connection(address);//await address.ConnectAsync();

                // create session
                var session = new Session(connection);

              [title]  // if no partition id is presented, the message distribution will be managed by Event Hub
                sendLink = new SenderLink(session, "send-link:" + eventhubname, "connectmeeventhub/Partitions/0");
            }

            double LS = tempHumidSI70.TakeMeasurement().Temperature;
            //double LS = ReadProportion();
            //double LV = lightSense.ReadVoltage();
            double LV = tempHumidSI70.TakeMeasurement().RelativeHumidity;
            Debug.Print("Reading Proportion" + LS.ToString());
            Debug.Print("Reading Voltage" + LV.ToString());

            string eventhubHost = "amqps://RootManageSharedAccessKey:+SAfiS1eVFODhouYtx/U2vITzrbeLGIlQJ1ZnTrUB34=@ neweventhub.servicebus.windows.net";

            // create address

            Random rnd = new Random();
            // while (true)
            //{
            double temperature = LS;
            // construct message
            var messageValue = Encoding.UTF8.GetBytes(temperature.ToString());

            // here, AMQP supports 3 types of body, here we use Data.
            var message = new Message() { BodySection = new Data() { Binary = messageValue } };
            sendLink.Send(message);
            Debug.Print("Sent");

        }[/title][title][/title]



        void timer_Tick(GT.Timer timer)
        {

            ethernetJ11D.NetworkUp += OnNetworkUp;
            ethernetJ11D.NetworkDown += OnNetworkDown;
     
            //} //await sendLink.SendAsync(message);
        }

        

       
        private void EthernetSetup()
        {
            // Code to connect to network using DHCP
            ethernetJ11D.NetworkInterface.EnableDhcp();
            ethernetJ11D.NetworkInterface.EnableDynamicDns();
            ethernetJ11D.NetworkInterface.Open();

        }

        private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
        {
            Debug.Print("network is " + (e.IsAvailable ? "Available" : "Isn't Available"));
        }

        private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            Debug.Print("Network Address Change to: " + ethernetJ11D.NetworkInterface.IPAddress);
            if (ethernetJ11D.NetworkInterface.IPAddress != "0.0.0.0")
            {
                timer.Start();
            }
        }



   
Network down.
Network down.
Network down.
Network down.
Network down.
GC: 46msec 298272 bytes used, 7041396 bytes available
Type 0F (STRING              ):   1848 bytes
Type 11 (CLASS               ):  22104 bytes
Type 12 (VALUETYPE           ):   2400 bytes
Type 13 (SZARRAY             ):   7500 bytes
  Type 01 (BOOLEAN             ):     24 bytes
  Type 03 (U1                  ):   1248 bytes
  Type 04 (CHAR                ):   1008 bytes
  Type 07 (I4                  ):   1044 bytes
  Type 0F (STRING              ):     96 bytes
  Type 11 (CLASS               ):   3996 bytes
  Type 12 (VALUETYPE           ):     84 bytes
Type 15 (FREEBLOCK           ): 7041396 bytes
Type 17 (ASSEMBLY            ):  47328 bytes
Type 18 (WEAKCLASS           ):     96 bytes
Type 19 (REFLECTION          ):    636 bytes
Type 1B (DELEGATE_HEAD       ): 141228 bytes
Type 1C (DELEGATELIST_HEAD   ):  46008 bytes
Type 1D (OBJECT_TO_EVENT     ):    360 bytes
Type 1E (BINARY_BLOB_HEAD    ):  15828 bytes
Type 1F (THREAD              ):   2304 bytes
Type 20 (SUBTHREAD           ):    240 bytes
Type 21 (STACK_FRAME         ):   2976 bytes
Type 22 (TIMER_HEAD          ):    144 bytes
Type 23 (LOCK_HEAD           ):    120 bytes
Type 24 (LOCK_OWNER_HEAD     ):     48 bytes
Type 26 (WAIT_FOR_OBJECT_HEAD):     48 bytes
Type 27 (FINALIZER_HEAD      ):    144 bytes
Type 28 (MEMORY_STREAM_HEAD  ):     36 bytes
Type 29 (MEMORY_STREAM_DATA  ):    396 bytes
Type 31 (IO_PORT             ):    180 bytes
Type 34 (APPDOMAIN_HEAD      ):     72 bytes
Type 36 (APPDOMAIN_ASSEMBLY  ):   6228 bytes



even Error like 
 #### Exception System.Net.Sockets.SocketException - CLR_E_FAIL (16) ####
    #### Message: 
    #### Microsoft.SPOT.Net.Security.SslNative::SecureRead [IP: 0000] ####
    #### Microsoft.SPOT.Net.Security.SslStream::Read [IP: 0040] ####
    #### Amqp.TcpTransport+SslSocket::Amqp.ITransport.Receive [IP: 0007] ####
    #### Amqp.TcpTransport::Receive [IP: 000a] ####
    #### Amqp.Framing.Reader::ReadBuffer [IP: 0009] ####
    #### Amqp.Framing.Reader::ReadFrameBuffer [IP: 0007] ####
    #### Amqp.Connection+Pump::PumpThread [IP: 003a] ####
    #### SocketException ErrorCode = -1
    #### SocketException ErrorCode = -1
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in Microsoft.SPOT.Net.Security.dll
    #### SocketException ErrorCode = -1
    #### SocketException ErrorCode = -1
    #### Exception System.Net.Sockets.SocketException - CLR_E_FAIL (20) ####
    #### Message: 
    #### Microsoft.SPOT.Net.Security.SslNative::SecureRead [IP: 0000] ####
    #### Microsoft.SPOT.Net.Security.SslStream::Read [IP: 0040] ####
    #### Amqp.TcpTransport+SslSocket::Amqp.ITransport.Receive [IP: 0007] ####
    #### Amqp.TcpTransport::Receive [IP: 000a] ####
    #### Amqp.Framing.Reader::ReadBuffer [IP: 0009] ####
    #### Amqp.Framing.Reader::ReadFrameBuffer [IP: 0007] ####
    #### Amqp.Connection+Pump::PumpThread [IP: 003a] ####
    #### SocketException ErrorCode = -1
    #### SocketException ErrorCode = -1
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in Microsoft.SPOT.Net.Security.dll
The thread '<No Name>' (0x10) has exited with code 0 (0x0).
    #### SocketException ErrorCode = -1
    #### SocketException ErrorCode = -1
The thread '<No Name>' (0x14) has exited with code 0 (0x0).

HI

Thank you for reply I will so the Code Tags and repost the code.

Meanwhile I have question that .Net Gadgter is not suppose to store value.

How Am I getting error over memory as u can see in the ouput posted by me?

My network is down than why is mempry full?

When I am run .Net Gadgeteer read data from sensor it is working for hours. But when trying to post the same data over internet it is give error?

Can you please explain it to me ?
what might be wrong?

Thank you in Advance

@ KevinNaik

Which board do you use?

@ Wolfgang

FEZ Spider. v4.3 .netmf

HI guys,

I am sending another code as I have divided my Above code to understand whats wrong.
Sensor are reading fine and alright even there is no error occurring.

But whenever trying to send data through Http or AMQP The error of memory pops up.

void timer_Tick(GT.Timer timer)
{
// string sburl = “https://firsteventhb-ns.servicebus.windows.net/firsteventhb/publishers/device1/messages”;
Mainboard.SetDebugLED(false);
var req = HttpHelper.CreateHttpPostRequest(“https://firsteventhb-s.servicebus.windows.net/firsteventhb/publishers/device1/messages”, null, null);
req.SendRequest();
Debug.Print(“success” + DateTime.Now.ToString());
Mainboard.SetDebugLED(true);
}

Error

In Http two errors occuring one is SSL(after updating SSl Seed it works for sometime) and another is Memory slowly gets full.
In AMQP Out of Memory

Thank you in Advance

Code tags are square brackets as you kind of used in your edited first post.

So every second you post. Perhaps you should try every 10 seconds and see how that helps. I suspect some are failing and not completing in time. You should also separate the timer and a sending thread and only send new data when there is not a previous one running. You basically have everything running with no checks in a timer, very likely to be a bad practice.

@ Bett

Thanks for you reply

But can you help me with issue of memory why is it getting full.

Thank you in Advance

Memory gets ‘full’ when you are holding references to too many allocations, or allocations that are too large. In your case, it may be that there are too many objects in memory that are still connected to a ‘live’ variable in your program. If you say:



then 1024 bytes will be locked in memory until the variable 'foo' goes out of scope, at which point the garbage collector can reclaim it.  In NETMF libraries, there are lots of hidden allocations. For instance, when doing HTTP or AMQP calls (even async ones), those libraries make (relatively large) allocations that will stay locked in memory until the network operation completes.  Doing too many network operations back-to-back (as Brett describes) means that you are filling up memory with allocations that cannot be released until the operations complete.  You are filling memory faster than it can be reclaimed by the garbage collector.

If you make requests more slowly, they have time to complete and the underlying allocations can then be reclaimed by the garbage collector.

If, instead, you are just making too many large allocations, then there may be no easy solution - you are working in a constrained environment. But the first thing to do is as Brett suggested - make sure there is only one request in flight at any given time.

@ mcalsyn - Thank you It was very useful for understanding

Is there any commands for Garbage Collector like Java

Or is that also constraint and have to use trial and error method. Because i try 1.5 Minutes time.
But it stops after 3 hours.

Even if you can send me keywords for Http authentication in v 4.3 it would be helpful for SSL.

Thank you

@ andre.m - Sorry My Bad

I meant Http Certification Authentication.

Because few error code I checked in forum is giving me description of SSL problem.

Even if you can throw some light on SSL update Seed why is it required and is it possible to do it by code without MFDepoly

@ andre.m - Thank you

So rebooting using code can solve my problem of SSL by Catching exception??

Right??

Guys

As per your advice I tired running code with 30 second and 100 second.

Its is running fine but memory is till an issue.

30 second program ran for 2 hours and thn died down

100 second program would have died in 4 hours.

What can be the reason??

Thank you in Advance

@ Brett -

I understood what your saying.

I did that before but error was there. So decided to check each component and thn found that http and amqp has memory leaking somewhere so tried to minimize my code as much as possible.

thank you

@ andre.m -

HI tried rebooting but is not solving my problem.

it’s because of your code… Sorry, that’s blunt, but that’s how it is.

Please follow Andre’s suggestion and start figuring out how memory is being retained. Something in your code is being kept and not permitted to clean up. When you understand what that is, you’ll keep memory constant. Refresh your familiarity with the detail about GC in @ mcalsyn’s post too, that’ll help you understand the behaviour

@ Brett -

Its ok Brett but can you guide me to code it properly.

And my memory is lost under head "Type 1E (BINARY_BLOB_HEAD "

Can you help or guide me what to do ?

Thank you

sure. But first, how about you show us some debug stats, analysis in what is going on, and what mods you’ve made to the code you posted the other day taking the feedback we have already given you is ?

using System;
//using System.Collections;
//using System.Threading;
using Microsoft.SPOT;
//using Microsoft.SPOT.Presentation;
//using Microsoft.SPOT.Presentation.Controls;
//using Microsoft.SPOT.Presentation.Media;
//using Microsoft.SPOT.Presentation.Shapes;
//using Microsoft.SPOT.Touch;

//using Gadgeteer.Networking;
using GT = Gadgeteer;
//using GTM = Gadgeteer.Modules;
//using Gadgeteer.Modules.GHIElectronics;
using System.Net;
using System.Text;
using System.IO;
using Microsoft.SPOT.Net.NetworkInformation;

namespace Https
{
public partial class Program
{
GT.Timer timer; // Timer
HttpWebRequest req;
void ProgramStarted()
{
Mainboard.SetDebugLED(true); // LED to Glow indicating Program start
//wifisetup();
NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
ethernetsetup();
timer = new GT.Timer(60000);
timer.Tick += timer_Tick;
}

   void timer_Tick(GT.Timer timer)
        {
            double Temperature = tempHumidSI70.TakeMeasurement().Temperature;
            double Relativehumidity = tempHumidSI70.TakeMeasurement().RelativeHumidity;
            Senddata(Temperature, Relativehumidity);
            Debug.GC(true);
        }

    private void Senddata(double Temperature, double Relativehumidity)
    {

        string sburl = "https://firsteventhb-ns.servicebus.windows.net/firsteventhb/publishers/device1/messages";

        req = (HttpWebRequest)WebRequest.Create(sburl);
        req.Headers.Add("Authorization", "SharedAccessSignature sr=https%3a%2f%2ffirsteventhb-ns.servicebus.windows.net%2ffirsteventhb%2fpublishers%2fdevice1%2fmessages&sig=NcvkPH6jTltngdRoTdypb41GJe4IuzYIDB2atlH4R4c%3d&se=1440540017&skn=SendRule");

        req.Method = "POST";
        req.ContentType = "application/atom+xml;type=entry;charset=utf-8";
        req.Timeout = 6000;
        req.KeepAlive = true;

        Debug.Print("Request created");

        string postData = "{\"Partition light\":" + DateTime.UtcNow + "}";

        byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
        req.ContentLength = postDataBytes.Length;
        try
        {
            using (Stream postStream = req.GetRequestStream())
            {
                postStream.Write(postDataBytes, 0, postDataBytes.Length);
            }
            Debug.Print("Request submitted");

            using (var response = (HttpWebResponse)req.GetResponse())
            {
                var responseValue = string.Empty;
                Debug.Print("Code: " + response.StatusCode.ToString());
                if (response.StatusCode != HttpStatusCode.Created)
                {
                    Debug.Print("Description: " + response.StatusDescription);
                }
                else
                {
                    Debug.Print("SUCCESS");
                }
            }
        }
        catch (Exception ex)
        {
            Debug.Print(ex.Message);
        }
    }

    private void ethernetsetup()
    {
        // Code to connect to network using DHCP

        ethernetJ11D.NetworkInterface.EnableDhcp();
        ethernetJ11D.NetworkInterface.EnableDynamicDns();
        ethernetJ11D.NetworkInterface.Open();
    }


    private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
    {
        Debug.Print("network is " + (e.IsAvailable ? "Available" : "Isn't Available"));
    }

    private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
    {
        Debug.Print("Network Address Change to: " + ethernetJ11D.NetworkInterface.IPAddress);
        if (ethernetJ11D.NetworkInterface.IPAddress != "0.0.0.0")
        {
            //Debug.Print("Set Device Clock");
            //SetDeviceClock();

            timer.Start();
        }
        else
        {
           

        }
    }
}

}

In timer I have only temperature reading thats all.

OK, so another pointer for you. Code Tags. Best used when you have the code in the paste buffer, you hit the code tag, you then paste the code in.

I notice you haven’t protected the send process at all, just got a long running timer. You really need to do that - set a flag, clear the flag as you exit. If you get into the send routine and the flag is already set, don’t try to send again, just log the fact and bail.

You have some diagnostics (debug.print) in your code. What is the output you see ? And did you do any memory profiling and see how it changes over time ? Helping us by debugging this yourself will be necessary, as you’re unlikely to find someone who will just take your code, build a web service like yours, and then test it for you.

@ brett

I know what you are saying but I am beginner level coder using .NETMF for first time. So sorry for inconvenience.

I am trying best to implement what you are saying.

Thank you will try out solutions you have asked to do.