Friday, October 25, 2013

http connect A?t commands GHI Fez mainboard GPRS

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 Gadgeteer.Modules.Seeed;

using System.Net;


namespace GadgeteerApp1
{
    public partial class Program
    {
        private static int likes = 0;
        private static int motions = 0;
        private static int motions2 = 0;
        private static int calls = 0;

        // This method is run when the mainboard is powered up or reset.  
        void ProgramStarted()
        {
            /*******************************************************************************************
            Modules added in the Program.gadgeteer designer view are used by typing
            their name followed by a period, e.g.  button.  or  camera.
           
            Many modules generate useful events. Type += to add a handler to an event, e.g.:
                button.ButtonPressed +=
           
            If you want to do something periodically, use a GT.Timer and handle its Tick event, e.g.:
                GT.Timer timer = new GT.Timer(1000); // every second (1000ms)
                timer.Tick +=
                timer.Start();
            *******************************************************************************************/

            /* Create a listener that outputs to the console screen, and
              * add it to the debug listeners. */
         


            // Use Debug.Print to show messages in Visual Studio's "Output" window during debugging.
            Debug.Print("Program Started");
       

            #region buttonPress demo0
            initGRPS();
            button.ButtonPressed += new Button.ButtonEventHandler(button_ButtonPressed);
            #endregion

            #region temperatureHumidity demo1
            temperatureHumidity.MeasurementComplete += new TemperatureHumidity.MeasurementCompleteEventHandler(temperatureHumidity_MeasurementComplete);
            #endregion

            #region appTimer demo1
            Timer MyTimer = new Timer(new TimerCallback(ClockTimer_Tick), null, 16000, 16000);
            #endregion

            #region motion demo2
         
           motion_Sensor.Motion_Sensed += new Motion_Sensor.Motion_SensorEventHandler(motion_Sensor_Motion_Sensed);
           motion_Sensor2.Motion_Sensed += new Motion_Sensor.Motion_SensorEventHandler(motion_Sensor_Motion_Sensed2);
            #endregion
           // gps.Enabled = true;
         //   gps.PositionReceived += new GPS.PositionReceivedHandler(gps_PositionReceived);

           

            #region TCP AT
            //SendRequest("Friday1");
            #endregion

        }

        void gps_PositionReceived(GPS sender, GPS.Position position)
        {
            Debug.Print(position.Latitude.ToString());
        }
        void cellularRadio_ModuleInitialized(CellularRadio sender)
        {
            Debug.Print("cellularRadio_Module INITIALIZED");
        }

        private void initGRPS()
        {
            cellularRadio.DebugPrintEnabled = true;
            cellularRadio.PowerOn(8);
           
        }
        private void SendRequest(string msg)
        {


            initGRPS();
     
          // DoCellularTCP();
          //  DoCellularTCPIP();
            DoCellularAT();
          //  SparkFunProducts10138();
           // cellularRadio.GprsNetworkRegistrationChanged += new CellularRadio.GprsNetworkRegistrationChangedHandler(cellularRadio_GprsNetworkRegistrationChanged);
        }

        void SparkFunProducts10138()
        {
            //https://www.sparkfun.com/products/10138
            //APN:pta
            //mmsc http://mmsc.mobile.attt.net
            // mms port 80
CellularRadio.ReturnedState rs;
rs = cellularRadio.SendATCommand("AT");
//OK ;test serial communications
rs = cellularRadio.SendATCommand("AT+CPIN?");
//+CPIN: READY ; make sure SIM card is ready
//OK
rs = cellularRadio.SendATCommand("AT+SFUN=SID");
//+ICCID: XXXXXXXXXXXXXXXXXXXX ; Read SIM card serial number if you need it
rs = cellularRadio.SendATCommand("AT+CSQ");
//+CSQ: 16,99 ;Check Quality of service, first number must be > 0 but not 99
//OK
rs = cellularRadio.SendATCommand("AT+AIPDCONT=\"pta\"");
//+AIPDCONT: "internet”,“”,“” ; set APN server, check with your SIM card provider
//OK
rs = cellularRadio.SendATCommand("AT+AIPA=1");
//+AIPA: 1,10.110.234.135,0,0,0 ;Connect with APN server
//OK
rs = cellularRadio.SendATCommand("AT+AIPO=1,,\"www.google.com\",80,0,,1");
//+AIPO: 1,“10.110.234.135”,4770,“74.125.227.17”,80,0,30,1,0,64000,8,7300,5720,-500,0) ;Connect to web server
//OK
rs = cellularRadio.SendATCommand("AT+AIPW=1,\"474554202f20485454502f312e300d0a0d0a\"");
//+AIPW: 1,0,7300,5720,18 ; Send "GET / HTTP/1.0\r\n\r\n” string to web server. It must be converted to ASCII HEX format
//;You should get several lines of reply back from the server, also in ASCII HEX format
//+AIPRTCP: 1,0,6708,5720,768,“485454502F312E3020323030204F4B0D0A446174653A205468752C2…"");
rs = cellularRadio.SendATCommand("AT+AIPC=1");
//+AIPC: 1
//OK ; Disconnect from the server
        }

        void DoCellularTCP()
        {
            //https://www.ghielectronics.com/community/forum/topic?id=10047&page=3

            CellularRadio.ReturnedState rs =
            cellularRadio.ConnectTCP("deals.somee.com", 80);
           // rs = cellularRadio.SendTcpData("msg=123");

            //http://www.propox.com/download/docs/SIM900_Application_Note.pdf
            rs=cellularRadio.SendATCommand("AT+CIPSEND");
          //  rs = cellularRadio.SendATCommand("CIPSEND");
            rs = cellularRadio.SendTcpData("GET / HTTP/1.1\r\nHost:deals.somee.com\r\nConnection: close\r\n\r\n");

            rs = cellularRadio.SendTcpData("GET / HTTP/1.1\r\nHost:deals.somee.com\r\nConnection: close\r\n\r\n");

            rs = cellularRadio.SendTcpData("GET / HTTP/1.1\r\nHost:deals.somee.com\r\n\r\n");

            rs = cellularRadio.SendTcpData("GET / HTTP/1.1\r\nHost:www.deals.somee.com\r\nConnection: close\r\n\r\n");

            rs = cellularRadio.SendTcpData("GET / HTTP/1.1\r\nHost:www.deals.somee.com\r\n\r\n");
            rs = cellularRadio.SendTcpData("GET /ASMInput.aspx HTTP/1.1\r\n");
rs = cellularRadio.SendTcpData("GET / HTTP/1.1\r\nHost:deals.somee.com:80\r\nConnection: close\r\n\r\n");
            //- See more at: https://www.ghielectronics.com/community/forum/topic?id=10047&page=3#sthash.eNWP93aT.dpuf
           // cellularRadio.SendTcpData("msg=123");

            rs=cellularRadio.DisconnectTCP();
        }

        void DoCellularTCPIP()
        {
            //https://www.ghielectronics.com/community/forum/topic?id=10047&page=3
            CellularRadio.ReturnedState rs = cellularRadio.ConnectTCP("66.197.198.196", 80);
            rs = cellularRadio.SendTcpData("GET /ASMInput.aspx HTTP/1.1\r\n");
            rs = cellularRadio.SendTcpData("GET / HTTP/1.1\r\nHost:deals.somee.com:80\r\nConnection: close\r\n\r\n");
            //- See more at: https://www.ghielectronics.com/community/forum/topic?id=10047&page=3#sthash.eNWP93aT.dpuf
            // cellularRadio.SendTcpData("msg=123");
            rs=cellularRadio.DisconnectTCP();
        }
      //  public ReturnedState ConfigureTCPServer(int port)
      //  {
      //      return SendATCommand("AT+CIPSERVER=1," + port);
     //   }
        void DoCellularAT()
        {
            // cellularRadio.AttachGPRS("internet","","");
            //cellularRadio.SendTcpData()
            //cellularRadio.SendATCommand("AT+SAPBR=3,1,\"APN\",\"******\"");#sthash.lOttujsU.dpuf

            CellularRadio.ReturnedState rs;
           



            #region moreat
            /*
rs = cellularRadio.SendATCommand("AT+CLPORT=\"TCP\",\"80\"");
            rs = cellularRadio.SendATCommand("AT+CIPCSGP=1,\"internet\",\"\",\"\"");
            rs = cellularRadio.SendATCommand("AT+CGDCONT=1,\"internet\",\"\",\"\"");
            rs = cellularRadio.SendATCommand("AT+CGATT=1");
            rs = cellularRadio.SendATCommand("AT+CSNS=4");
            rs = cellularRadio.SendATCommand("AT+CIPSERVER=1,2100");
            //- See more at: https://www.ghielectronics.com/community/forum/topic?id=11774#sthash.0bDMV1Jj.dpuf
             */
            #endregion

            #region figuredAT
           /* rs = cellularRadio.SendATCommand("AT+CIPMUX=1");
            Thread.Sleep(2000);
rs = cellularRadio.SendATCommand("AT+CSTT=\"internet\""); //rs = cellularRadio.SendATCommand("AT+CSTT=\"your APN here\"")
   Thread.Sleep(2000);
rs = cellularRadio.SendATCommand("AT+CGDCONT=1,\"IP\",\"internet\",\"\",0,0"); ////rs = cellularRadio.SendATCommand("AT+CGDCONT=1,\"IP\",\"your APN here\",\"\",0,0")
   Thread.Sleep(2000);
rs = cellularRadio.SendATCommand("AT+CIICR");
   Thread.Sleep(4000); //Wait 5 seconds. This brings up the GPRS wireless connection so it take a bit of time.
rs = cellularRadio.SendATCommand("AT+CIFSR");
   Thread.Sleep(2000); // IP address retrieved from service provide should display!
rs = cellularRadio.SendATCommand("AT+CIPSERVER=1,\"80\""); //Service provider must provide you with this valid port number!
Thread.Sleep(2000); // Debug window should display SERVER OK!
//15. Attempt a socket connection to IP shown with your computer. Typed characters will display in the debug window. - See more at: https://www.ghielectronics.com/community/forum/topic?id=11774#sthash.0bDMV1Jj.dpuf
         
            * */
             #endregion

///// rs = cellularRadio.SendATCommand("at+cipstart=\"TCP\",\"deals.somee.com\",\"80\"");

// rs=cellularRadio.SendATCommand("AT+CIPSTART=\"TCP\",\"66.197.198.196\", \"8500\""); // Start up the connection
// rs = cellularRadio.SendATCommand("AT+CIPSTART=\"TCP\",\"deals.somee.com/\", \"8500\""); // Start up the connection


            //// Sets how connected lines are presented
            rs = cellularRadio.SendATCommand("AT+COLP=1");
            Thread.Sleep(2000);
            // Enable GPRS network registration status
            rs = cellularRadio.SendATCommand("AT+CGREG=1");
            Thread.Sleep(2000);
            // Enable GSM network registration status
            rs = cellularRadio.SendATCommand("AT+CREG=1");
            Thread.Sleep(2000);
            /*
             * Attach GPRS Test
             */
           
          //  rs = cellularRadio.AttachGPRS("internet", "", "");
            Thread.Sleep(8000);
            // pta works on isaac's chip
            rs = cellularRadio.SendATCommand("AT+CSTT=\"" + "pta" + "\",\"" + "" + "\",\"" + "" + "\"");
           // rs = cellularRadio.SendATCommand("AT+CSTT=\"" + "internet" + "\",\"" + "" + "\",\"" + "" + "\"");

            Thread.Sleep(4000);
            rs = cellularRadio.SendATCommand("AT+CIICR");
            Thread.Sleep(3000);

            rs = cellularRadio.SendATCommand("AT+CIFSR");


            Thread.Sleep(2000);
            rs = cellularRadio.SendATCommand("AT+CIPSTATUS");
            Thread.Sleep(2000);


       
////// rs = cellularRadio.SendATCommand("AT+CIPSTART=\"TCP\",\"66.197.198.196\", \"80\""); // Start up the connection
            rs = cellularRadio.SendATCommand("AT+CIPSTART=\"TCP\",\"deals.somee.com\", \"80\""); // Start up the connection
Thread.Sleep(1000);
// rs = cellularRadio.SendATCommand("AT+CIPMODE=1"); // data mode???
Thread.Sleep(1000);
//rs = cellularRadio.SendATCommand("AT+CIPSEND");
//rs = cellularRadio.SendTcpData("GET /ASMAT.aspx HTTP/1.1 Host:deals.somee.com\r\n\r\n"); // bad request
//Thread.Sleep(4000);
rs = cellularRadio.SendTcpData("GET /ASMAT.aspx?msg=hello HTTP/1.1\r\nHost:deals.somee.com\r\nConnection: close\r\n\r\n");
//Thread.Sleep(4000);
//rs = cellularRadio.SendTcpData("GET /ASMAT.aspx?msg=world HTTP/1.1\r\nHost:deals.somee.com\r\n");
//Thread.Sleep(5000);
//rs = cellularRadio.SendTcpData("POST /ASMAT.aspx HTTP/1.1\r\nHost:deals.somee.com\r\n");


Thread.Sleep(5000);
rs = cellularRadio.DisconnectTCP();
return;
            //   rs = cellularRadio.SendATCommand("AT+CIPSERVER=1," + "80");
           // Thread.Sleep(1000);
         //   rs = cellularRadio.SendATCommand("AT+CIPSEND");
            Thread.Sleep(2000);
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            Thread.Sleep(1000);
            rs = cellularRadio.SendTcpData("GET /ASMAT.aspx HTTP/1.1\r\nHost: deals.somee.com" + (char)26 + "\r");

         
            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            Thread.Sleep(1000);
            rs = cellularRadio.SendTcpData("GET /ASMAT.aspx HTTP/1.1\r\nHost: deals.somee.com\r\n\r\n");
            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            Thread.Sleep(1000);
            rs = cellularRadio.SendTcpData("GET /ASMAT.aspx HTTP/1.1 Host:deals.somee.com\r\n\r\n");

            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("AT+CIPSEND");

            Thread.Sleep(1000);
            rs = cellularRadio.SendTcpData("GET /ASMAT.aspx HTTP/1.1 Host:deals.somee.com\r\n");
            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            Thread.Sleep(1000);
            rs = cellularRadio.SendTcpData("GET /ASMAT.aspx HTTP/1.1 Host:deals.somee.com\r\n" + (char)26);
            Thread.Sleep(1000);
           
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            Thread.Sleep(1000);
            rs = cellularRadio.SendTcpData("GET /ASMAT.aspx HTTP/1.1\r\nHost:deals.somee.com\r\nConnection: close\r\n\r\n");
            Thread.Sleep(1000);
            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            rs = cellularRadio.SendTcpData("GET /ASMAT.aspx HTTP/1.1 host:deals.somee.com\r" + (char)26);
            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            Thread.Sleep(1000);
            /*
            rs = cellularRadio.SendTcpData("GET / HTTP/1.1 host:deals.somee.com" + (char)26);
            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            Thread.Sleep(1000);
            rs = cellularRadio.SendTcpData("GET / HTTP/1.1 host:deals.somee.com\r\n" + (char)26);
            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            Thread.Sleep(1000);
            rs = cellularRadio.SendTcpData("GET / HTTP/1.1 host:deals.somee.com\r\n\r\n" + (char)26);
            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("GET / HTTP/1.1 host:deals.somee.com\r\r" + (char)26);
            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("AT+CIPSEND");                              
            Thread.Sleep(1000);          
            rs = cellularRadio.SendATCommand("GET / HTTP/1.1 host:deals.somee.com\r\n\r\n" + (char)26);
            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("AT+CIPSEND");

            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("GET / HTTP/1.1 host:deals.somee.com\r\n" + (char)26);
            Thread.Sleep(1000);
            rs = cellularRadio.SendATCommand("AT+CIPSEND");

            Thread.Sleep(1000);
           // rs = cellularRadio.SendATCommand("GET / HTTP/1.1 host:deals.somee.com" + (char)26);
            Thread.Sleep(1000);


            //- See more at: https://www.ghielectronics.com/community/forum/topic?id=8721#sthash.slxw7wOv.dpuf
            rs = cellularRadio.SendTcpData("GET / HTTP/1.1 host:deals.somee.com\r\n\r\n" + (char)26);
           
           
            rs = cellularRadio.SendTcpData("GET / HTTP/1.1 host:deals.somee.com\r\n\r\n");
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            rs = cellularRadio.SendTcpData("GET / HTTP/1.1 host:deals.somee.com\r\n");
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            rs = cellularRadio.SendTcpData("GET / HTTP/1.1 host:deals.somee.com");
            */
            /*
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            rs = cellularRadio.SendATCommand("GET / HTTP/1.1 host:deals.somee.com\r\n\r\n");

            rs = cellularRadio.SendTcpData("GET / HTTP/1.1 host:deals.somee.com\r\n\r\n");
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            rs = cellularRadio.SendTcpData("GET /ASMInput.aspx HTTP/1.1 host:deals.somee.com\r\n\r\n");
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            rs = cellularRadio.SendATCommand("GET / HTTP/1.1 host:deals.somee.com\r\n\r\n");
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            rs = cellularRadio.SendATCommand("GET /ASMInput.aspx HTTP/1.1 host:deals.somee.com\r\n\r\n");
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            rs = cellularRadio.SendTcpData("GET / HTTP/1.1\r\n");
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            rs = cellularRadio.SendTcpData("Host: " + "deals.somee.com" + "\r\n");
            rs = cellularRadio.SendTcpData("\r\n");
            rs = cellularRadio.SendATCommand("AT+CIPSEND");

            //rs = cellularRadio.SendATCommand("AT+MIPTSEND=1");
            rs = cellularRadio.SendTcpData("GET / HTTP/1.1 host:deals.somee.com\r\n");
            rs = cellularRadio.SendTcpData("GET / HTTP/1.1 host:www.deals.somee.com\r\n");
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            rs = cellularRadio.SendATCommand("GET / HTTP/1.1\r\n");
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            rs = cellularRadio.SendATCommand("GET / HTTP/1.1\r\n");

         
            rs = cellularRadio.SendTcpData("GET /ASMInput.aspx HTTP/1.1 host:www.deals.somee.com\r\n");

            rs = cellularRadio.SendTcpData("GET /ASMInput.aspx HTTP/1.1 host:www.deals.somee.com\r\n");
            rs = cellularRadio.SendATCommand("GET /ASMInput.aspx HTTP/1.1 host:www.deals.somee.com\r\n");


            rs = cellularRadio.SendATCommand("GET deals.somee.com/ASMInput.aspx HTTP/1.1\r\n");
            rs = cellularRadio.SendTcpData("GET deals.somee.com/ASMInput.aspx HTTP/1.1\r\n");
            rs = cellularRadio.SendATCommand("AT+CIPSEND");
            rs = cellularRadio.SendATCommand("GET deals.somee.com/ASMInput.aspx HTTP/1.1\r\n");
            rs = cellularRadio.SendTcpData("GET deals.somee.com/ASMInput.aspx HTTP/1.1\r\n");
             * */
            rs = cellularRadio.DetachGprs();
            rs=cellularRadio.DisconnectTCP();

            // WebRequest request = WebRequest.Create("deals.somee.com");
      // request.KeepAlive = false;
            // WebResponse response = request.GetResponse();
            // response.Close();
        }
        void cellularRadio_GprsNetworkRegistrationChanged(CellularRadio sender, CellularRadio.NetworkRegistrationState networkState)
        {
            Debug.Print(networkState.ToString());

            //WebRequest request = WebRequest.Create("http://deals.somee.com/ASMInput.aspx?msg=101");
            // request.KeepAlive = false;
           // WebResponse response = request.GetResponse();
           // response.Close();

            cellularRadio.ConnectTCP("http://deals.somee.com/ASMInput.aspx", 80);
        }
   

        //public void SMTP(string from, string to, string bcc, string subject, string body)
        //{
        //    MailMessage mailMsg = new MailMessage();
        //    mailMsg.From = new MailAddress(from);
        //    mailMsg.To.Add(to);
        //    mailMsg.Subject = subject;
        //    mailMsg.IsBodyHtml = true;
        //    mailMsg.BodyEncoding = Encoding.UTF8;
        //    mailMsg.Body = body;
        //    mailMsg.Priority = MailPriority.Normal;
        //    // Smtp configuration
        //    SmtpClient client = new SmtpClient();
        //    client.Credentials = new NetworkCredential("danielsuperbaby@gmail.com", "xxx");

        //    client.UseDefaultCredentials = true;

        //    client.Port = 587; // 587; //or use 465          
        //    client.Host = "smtp.gmail.com";
        //    //client.Host = "smtp.trash.com";
        //    client.EnableSsl = true;

        //    client.DeliveryMethod = SmtpDeliveryMethod.Network;


        //    object userState = mailMsg;
        //    try
        //    {
        //        //you can also call client.Send(msg)
        //        client.SendAsync(mailMsg, userState);
        //    }
        //    catch (SmtpException ex)
        //    {
        //        //Response.Write(ex.Message);
        //        //Response.Write(ex.Source);
        //        Response.Write("An error occurred while processing your request. Please try again.");
        //    }


        //}

        void ClockTimer_Tick(object sender)
        {
            DateTime now = DateTime.Now;
            Debug.Print(now.ToString("MM/dd/yyyy hh:mm:ss"));

            #region temperatureHumidity
            temperatureHumidity.RequestMeasurement();
            #endregion
       
         
        }

        void temperatureHumidity_MeasurementComplete(TemperatureHumidity sender, double temperature, double relativeHumidity)
        {

            Debug.Print("Temp: " + temperature);
            Debug.Print("Humidity: " + relativeHumidity);
        }
       
        void button_ButtonPressed(Button sender, Button.ButtonState state)
        {
            Debug.Print("Likes: " + (++likes));
           // Debug.Print(gps.LastPosition.Latitude.ToString());
            SendRequest("Friday1");
            return;
            /*
            #region temperatureHumidity
             temperatureHumidity.RequestMeasurement();
            #endregion

            #region gpssensor
           //  Debug.Print("GPS: " + gps.LastPosition);
            #endregion

            */
            #region TCP
            //cellularRadio.ConfigureTCPServer()

            //    cellularRadio.ConnectTCP()

            //        cellularRadio.SendTcpData()


            #endregion
            #region sms
           
            CellularRadio.ReturnedState smsstate = cellularRadio.SendSms("18189837669", "Hi Isaac Demo" + DateTime.Now);

          //  CellularRadio.ReturnedState smsstate = cellularRadio.SendSms("13106179559", "Hi Dave" + DateTime.Now);
          //  CellularRadio.ReturnedState smsstate2 = cellularRadio.SendSms("12133443848", "Hi Demo " + (++calls));
            Thread.Sleep(2000);
            return;
           
            /*

         
          //  CellularRadio.ReturnedState smsstate = cellularRadio.SendSms("12134537941", "Hi Maulik");

              CellularRadio.ReturnedState smsstate = cellularRadio.SendSms("18189837671", "Hi there - from Isaac Testing");

            if( smsstate != GTM.Seeed.CellularRadio.ReturnedState.OK)
            {
                Debug.Print("Retrieve clock failed");
            }
         
            Debug.Print("calls sent: " + calls++);

             */

            #endregion
        }


        static void motion_Sensor_Motion_Sensed(Motion_Sensor sender, Motion_Sensor.Motion_SensorState state)
        {
           
         
            Debug.Print("ONE: " + (motions++) + " Time: " + (DateTime.Now));
          //  Debug.Print(sender.SensorStillActive.ToString());
           
        }

        void motion_Sensor_Motion_Sensed2(Motion_Sensor sender, Motion_Sensor.Motion_SensorState state)
        {
            Debug.Print("TWO: " + (motions2++) + " Time: " + (DateTime.Now));
           // Debug.Print(sender.SensorStillActive.ToString());

        }

        public static void cellularRadio_CallConnected(CellularRadio sender, string number)
        {
            Debug.Print("calls sensed: " + calls++);
        }
    }
}

Saturday, October 19, 2013

webrequest gadgeteer

I had a similar problem and fixed it with
request.KeepAlive = false;

http://geekswithblogs.net/WindowsEmbeddedCookbook/archive/2009/01/16/http-request-class-for-the-.net-microframework.aspx

http://netmftoolbox.codeplex.com/SourceControl/latest#Samples/Visual C#/SMTP Client/Program.cs


http://netmftoolbox.codeplex.com/wikipage?title=Toolbox.NETMF.NET.HTTP_Client&referringTitle=Available%20classes

Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress

http://forums.netduino.com/index.php?/topic/2964-every-2nd-webrequest-fails/

webRequest.AllowAutoRedirect = true;
*****
private static void InitNetworking()             {                 // First Display some information about networking                 NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();                 if (networkInterfaces.Length == 0)                     return;                 foreach (NetworkInterface ni in networkInterfaces)                 {                     if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)                     {                         ni.EnableStaticIP("192.168.0.253", "255.255.255.0", "192.164.0.244");                         ni.EnableStaticDns(new string[] { "4.2.2.1", "4.2.2.2" });                         //ni.EnableStaticIP("192.168.253.2", "255.255.255.0", "192.164.243.1");                         //ni.EnableStaticDns(new string[] { "4.2.2.1", "4.2.2.2" });                     }                 } - See more at: https://www.ghielectronics.com/community/forum/topic?id=12552&page=2#sthash.qdM6vyGs.dpuf

http://netmftoolbox.codeplex.com/wikipage?title=Toolbox.NETMF.NET.SMTP_Client

*********
private void testHttpGet(){
 var ServerName = "google.com";
 var HttpClient webClient = new HttpClient(new IntegratedSocket(ServerName, 80)); }
 var response = WebClient.Get("/");
 if(response.ResponseCode != 200) {//Something went horribly wrong in the ether
  Debug.Print("FARK!!!!");
  continue;
 }
 //HTTP Sucess parse response
 if(response.ResponseBody == "\r\n\r\n"){//Empty Response Body Discard
  continue;
 }
 Debug.Print(response.ResponseBody);
}

***********
<%@ Page Language="C#" AutoEventWireup="true"  ValidateRequest="false" %>

<%@ Import Namespace = "System.Data" %>
<%@ Import Namespace = "System.Text" %>
<%@ Import Namespace = "System.Net" %>
<%@ Import Namespace = "System.Net.Mail" %>
<%@ Import Namespace = "System.IO" %>

<%@ Register Assembly="RichTextEditor" Namespace="AjaxControls" TagPrefix="cc1" %>





   
   
     


   

    <% if (isPreview) {%>
   

    <%} %>
   

   
   
   
">

   
Back to Custom Greetings

   
   
   

   
    greetings image
   
   

   
    Your Email:
   
            ID="RegularExpressionValidator1" runat="server" ErrorMessage="Please enter a valid email address" ControlToValidate="YourEmail" validationexpression="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
        CssClass="validmargin0">

       
       
   
     

        Recepient Email:
     
                ID="RegularExpressionValidator2" runat="server" ErrorMessage="Please enter a valid email address" ControlToValidate="RecepientEmail" validationexpression="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
        CssClass="validmargin0">

               

   
    

    Your Name:
            runat="server" Width="180px" TabIndex="3">
                    runat="server" ErrorMessage="You must enter a message for the greeting." ControlToValidate="eBody" CssClass="validmargin0">
   
   
   

    Your Message:
     
   
   
   
   
   

                onclick="Preview_Click"  OnClientClick="javascript:CopyText();" TabIndex="5"/>
       
       

   
   
        
        <% if (isPreview) {%>
       
        <%=BuildGreeting()%>
       
       
 

       

           

               
               
           
       
       
        <%} %>
   
   
   
   



<% if (!isPreview) {%>


<%} %>


    <% if (isPreview) {%>
   
    <%} %>
   






***
http://en.kioskea.net/forum/affich-178809-how-to-connect-internet-with-sim-card
*****
Development tool : Microsoft Visual C# Express 2010
Micro framework:  Microsoft .NET Micro Framework 4.1 SDK
The Gadgeteer core, mainboard SDk and module driver(GHI)

Wednesday, July 24, 2013

find all columns in database named ASMCRMDEV_MSCRM matching string %selling%

use  [Database]

GO
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%selling%'

ORDER BY schema_name, table_name;

--Also could do the same for views by querying sys.views:

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.views AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%_productcodetypeidname%'

ORDER BY schema_name, table_name;



-- find all occurrences in stored procs  
select top 10 * from sys.syscomments where text like '%Fact_Purchase_Order%'
  
-- find all occurrences in objects , views, etc,
  SELECT
referencing_schema_name = SCHEMA_NAME(o.SCHEMA_ID),
referencing_object_name = o.name,
referencing_object_type_desc = o.type_desc,
referenced_schema_name,
referenced_object_name = referenced_entity_name,
referenced_object_type_desc = o1.type_desc,
referenced_server_name, referenced_database_name
--,sed.* -- Uncomment for all the columns
FROM
sys.sql_expression_dependencies sed
INNER JOIN
sys.objects o ON sed.referencing_id = o.[object_id]
LEFT OUTER JOIN
sys.objects o1 ON sed.referenced_id = o1.[object_id]
WHERE

referenced_entity_name like '%Fact_Purchase_Order%'

Friday, June 7, 2013

"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\svcutil.exe" http://devservices.gamefly.com:99/ApplicationDirectoryService/ApplicationDirectoryService.svc?wsdl
In Javascript you may need to unbind an event. In JQuery this could be done with the .off() method.

Eg:

$("body").off('keydown');

unbinds the keydown handler from the HTML body


Wednesday, May 29, 2013

Transmitting Intervaled Screen Captures

This article shows how  to periodically capture the entire desktop and store it to files and optionally transmit the captured files on the Internet. The code is in C# and so the program only supports operating systems where C# desktop apps could run: mainly Windows-based systems.

I've chosen a hidden Windows app as my main driver. You could have very well chosen a console or a service process as your main driver. The app is hidden from ordinary users (of course there are ways to detect that the app is running in the background).

The app starts a timer and on timed-interval checks for the existence of a resource or an event to determine whether it should gracefully terminate or do another screen capture. The external resource in our case is a text file that the administrator could dump into a known or configured folder. The existence of the file signals to the app that it ought to terminate;  otherwise the app captures the entire desktop and dumps it to a file in the configured folder.

The "timer repetition interval", "folder name", "capture base file name", "termination file name",  "maximum number of files to write" are configured in app.config.

The capture file name is computed as: configured capture base file name + Counter + .extension.
Above the Counter is an integer that is incremented in our app. When the Counter reaches "maximum number of files to write" the Counter is reset to 0 and we would override the previously written files.

On my next article I will touch upon transmitting the captured files to the Internet. From that point possibilities are only limited by our imagination: the app could be used as a monitoring tool, replace rudimentary video conferencing tools, etc.

The C# code is listed below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
using System.Text;
using System.Drawing.Imaging;
using System.IO;
using System.Configuration;

namespace WindowsFormsApplication1
{
    static class Program
    {
        ///



        /// The main entry point for the application.
        ///
        [STAThread]
        static void Main()
        {
              Timer MyTimer = new Timer();
              //  mins converted to milliseconds
              MyTimer.Interval = (Convert.ToInt32(ConfigurationManager.AppSettings["CaptureMinutesInterval"]) * 60 * 1000);
                MyTimer.Tick += new EventHandler(Timer_Tick);
                MyTimer.Start();
                Application.Run();

        }
        static int counter = 0;
        private static void Timer_Tick(object sender, EventArgs e)
        {
            if (File.Exists(ConfigurationManager.AppSettings["FilePath"] + ConfigurationManager.AppSettings["EndFile"]))
            {
                Application.Exit();
                return;
            }


            if (!System.IO.Directory.Exists(ConfigurationManager.AppSettings["FilePath"]))
            {
                System.IO.Directory.CreateDirectory(ConfigurationManager.AppSettings["FilePath"]);
            }

         
            int screenWidth = Screen.GetBounds(new Point(0, 0)).Width;
            int screenHeight = Screen.GetBounds(new Point(0, 0)).Height;

            // Rectangle bounds = Screen.GetBounds(Point.Empty);
            using (Bitmap bitmap = new Bitmap(screenWidth, screenHeight))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight));
                }
                // could use other extensions
                bitmap.Save(ConfigurationManager.AppSettings["FilePath"] + ConfigurationManager.AppSettings["CapBaseName"] + counter +
                    ".png", ImageFormat.Png);
                counter++;
                if (Convert.ToInt32(ConfigurationManager.AppSettings["MaxFiles"]) > counter)
                {
                    counter = 0;
                }
            }
        }
    }
}




 
   
   
   
   
   
 
 

Monday, January 7, 2013

Receiving and returning JSON data in C# and MVC

Suppose you have a C# class as follows:
    [Serializable]
    public class Spec
    {
        public string ID { get; set; }
        public int TypeID { get; set; }
        public string Value { get; set; }
        public int ForID { get; set; }
    }

To send an array of Specs from Javascript on the browser to an MVC controller you may issue:

         $.ajax({
            url: "/Create/UpdateSpecs",
            cache: false,
            data: { "SkuID": PID, "Specs": JSON.stringify(aspecs)
            },
            type: "POST"
        });

1) /Create/UpdateSpecs is your server-side endpoint.

2) JSON.stringify is from the JSON library. You may need to download jquery.json-2.2.js (or newer) if you you need to support older browsers.

3) To construct an array of Specs in Javascript you may issue something like the following code snippet where aspecs is your array of specs in Javascript and cnt is your array index:
aspecs[cnt] = { "ID": item.attr("id"), "TypeID": item.attr("typeid"), "Value": item.val(), "ForID": item.attr("for") };

On the C# MVC side, below, Specs has your JSON array that you could convert to a C# array by
calling JsonConvert.DeserializeObject and casting as array of Specs as follows:

 (Spec[])JsonConvert.DeserializeObject(Specs);

1) Important: You must have a reference to the library:
Newtonsoft.Json

2) The C# method returns a JsonResult. The return could be a complex data structure or a basic or intrinsic type.

        [HttpPost]
        public JsonResult UpdateSpecs(int SkuID, string Specs)
        {
            if (!string.IsNullOrEmpty(Specs))
            {
                Spec[] args = (Spec[])JsonConvert.DeserializeObject(Specs);

                ProductBinder UIBinder = new ProductBinder();


                return this.Json(UIBinder.UpdateSpecs(args, SkuID));
            }
            else
            {
                return null;
            }
        }