예제 #1
0
        //public string ToInsertSQL(bool replaceComma, string TableName)
        //{
        //  string sql = "";
        //  sql = string.Format("insert into {0} (POS_FECHA, EQP_ESN, COD_EVENTO,", TableName);
        //  sql = string.Format("{0} POSICION, POS_VELOCIDAD, POS_RUMBO, DATA) VALUES (", sql);
        //  sql = string.Format("{0} '{1}', '{2}'", sql, ReportDate.ToString("yyyy-MM-dd HH:mm:ss"), IMEI);
        //  if (replaceComma)
        //    sql = string.Format("{0}, {1}, PointFromText('POINT({2} {3})')", sql, EventCode, ReportPosition.Longitude.getValue().ToString().Replace(',', '.'), ReportPosition.Latitude.getValue().ToString().Replace(',', '.'));
        //  else
        //    sql = string.Format("{0}, {1}, PointFromText('POINT({2} {3})')", sql, EventCode, ReportPosition.Longitude.getValue(), ReportPosition.Latitude.getValue());
        //  if (replaceComma)
        //    sql = string.Format("{0}, {1}, {2}", sql, Speed.ToString().Replace(',', '.'), ReportPosition.Head.ToString().Replace(',', '.'));
        //  else
        //    sql = string.Format("{0}, {1}, {2}", sql, Speed, ReportPosition.Head);
        //  sql = string.Format("{0},'{1}')", sql, JsonConvert.SerializeObject(Data));
        //  return sql;
        //}
        public static bool TryParse(byte[] messageSBD, string imei, out IridiumExtremeBinaryReport report, string packetType)
        {
            int ival;
              double dval;

              report = new IridiumExtremeBinaryReport();
              JObject json = new JObject();
              try
              {
            if (packetType == "MO")
            {
              ICDMOPacket MOpacket = new ICDMOPacket();
              ICDMOPacket.TryParse(messageSBD, out MOpacket);
              ICDMOMessageType type = ICDMOMessageType.Unknown;
              if (MOpacket.rheader != null)
              {
            report.IMEI = imei;
            report.protocolType = (int)MOpacket.rheader.protocolType;
            report.protocolVersion = (int)MOpacket.rheader.ProtocolVersionNumber;
            report.EventCode = (int)MOpacket.rheader.MessageType;
            report.type_message = packetType;
            type = MOpacket.rheader.MessageType;
              }
              else
              {
            report.IMEI = imei;
            report.protocolType = (int)MOpacket.header.protocolType;
            report.protocolVersion = (int)MOpacket.header.ProtocolVersionNumber;
            report.EventCode = (int)MOpacket.header.MessageType;
            report.type_message = packetType;
            type = MOpacket.header.MessageType;
              }
              switch (type)
              {
            case ICDMOMessageType.SwitchOn:
              report.inbox = true;
              break;
            case ICDMOMessageType.AutomaticPositionReport:
              report.inbox = true;
              report.posiciones = true;
              break;
            case ICDMOMessageType.Emergency:
              report.inbox = true;
              report.posiciones = true;
              break;
              }
              foreach (ICDDataBlock d in MOpacket.body.datablocks)
              {
            switch (d.BlockType)
            {
              case ICDBlockType.Location://automatic report position
                var location = (DataBlock_Location)d;
                report.ReportPosition = location.position;
                DateTime dt;
                try
                {
                 dt = new DateTime((int)location.GPSTimestampUTCYear, (int)location.GPSTimestampUTCMonth, (int)location.GPSTimestampUTCDay, (int)location.GPSTimestampUTCHours, (int)location.GPSTimestampUTCMinutes, (int)location.GPSTimestampUTCSeconds);
                 report.ReportDate = dt;
                }
                catch (Exception ex)
                {
                  report.ReportDate = new DateTime();//DateTime.Now;
                }
                report.Speed = 0;

                //string json5 = new JavaScriptSerializer().Serialize(location);
                //JObject json = JObject.FromObject(location);
                json["Location"] = JObject.FromObject(new {
                  Type = location.BlockType.ToString(),
                  DateTime = report.ReportDate,
                  VelocityDirection = location.VelocityDirection,
                  SpeedOverGround = location.SpeedOverGround,
                  CourseOverGround = location.CourseOverGround,
                  AltitudeSign = location.AltitudeSign,
                  Altitude = location.Altitude,
                  LatitudeAccuracyMeasurement = location.LatitudeAccuracyMeasurement,
                  LatitudeAccuracy = location.LatitudeAccuracy,
                  LongitudeAccuracyMeasurement = location.LongitudeAccuracyMeasurement,
                  LongitudeAccuracy =  location.LongitudeAccuracy,
                  AltitudeAccuracyMeasurement = location.AltitudeAccuracyMeasurement,
                  AltitudeAccuracy = location.AltitudeAccuracy,
                  IsValid = 1,
                  InsertInPosiciones = report.insertInPosiciones
                });
                json["Location"]["Position"] = JObject.FromObject(new {
                  Altitude = location.position.Altitude,
                  Longitude = location.position.Longitude,
                  Latitude = location.position.Latitude,
                  Cuadrante = location.position.Cuadrante,
                  Rumbo = location.position.Head
                });

                //DataBlock_Location fromJson = new JavaScriptSerializer().Deserialize<DataBlock_Location>(json);
                //var loc = new JavaScriptSerializer().DeserializeObject(json);
                //JObject jobject = JObject.Parse(json);//magic

                //var name = new{ Datablock = new []{ new {type = location.BlockType.ToString()}}};
                //JObject namejson = JObject.FromObject(name);
                //string json2 = string.Format("Datablock: {0} {3} : {4}{1} {5}{2}", "{", location.BlockType.ToString(), "}", "'type'", "'", "'");
                //JObject namejson = JObject.Parse(json2);
                //string a = @"{'type':"+"'"+location.BlockType.ToString()+"'"+"}";
                break;
              case ICDBlockType.FreeText:
                var freetext = (DataBlock_FreeText)d;
                json["FreeText"] = JObject.FromObject(new
                {
                  FreeText = freetext.FreeText.Text.ToString(),
                });
                break;
              case ICDBlockType.Recipient:
                var recipient = (DataBlock_Recipient)d;

                break;
              case ICDBlockType.Synchronisation:
                var synchronisation = (DataBlock_Synchronisation)d;
                break;
              case ICDBlockType.DeviceIdentifier:
                var deviceIdentifier = (DataBlock_DeviceIdentifier)d;
                break;
              case ICDBlockType.Diagnostics:
                var diagnostics = (DataBlock_Diagnostics)d;
                break;
              case ICDBlockType.Sender:
                var sender = (DataBlock_Sender)d;
                break;
              case ICDBlockType.RegionCircle:
                var regionCircle = (DataBlock_Circle)d;
                break;
              case ICDBlockType.RegionPolygon:
                var regionPolygon = (DataBlock_Polygon)d;
                break;
              case ICDBlockType.PortalStatus:
                var portalStatus = (DataBlock_PortalStatus)d;
                break;
              case ICDBlockType.PhoneSettings:
                var phoneSettings = (DataBlock_PhoneSettings)d;
                json["PhoneSettings"] = JObject.FromObject(new
                {
                  Type = phoneSettings.BlockType.ToString(),
                  DateTime = report.ReportDate,
                  ReportFrecuencyRate = phoneSettings.ReportingFrecuencyRate,
                  ReportingFrecuencyRateUnits = phoneSettings.ReportingFrecuencyRateUnits,
                  EmergencyDestination = phoneSettings.EmergencyDestination,
                  EmergencyCallRecipient = phoneSettings.EmergencyCallRecipient,
                });
                //JObject jsonPhoneSettings = JObject.FromObject(phoneSettings);
                //report.Data.Add(jsonPhoneSettings);
                break;
              case ICDBlockType.GeofenceStatus:
                var geofenceStatus = (DataBlock_GeofenceStatus)d;
                break;
              case ICDBlockType.CannedMessagesHash:
                var cannedMessageHash = (DataBlock_CannedMessagesHash)d;
                json["CannedMessageHash"] = JObject.FromObject(new
                {
                  Type = cannedMessageHash.BlockType.ToString(),
                  Hash = cannedMessageHash.Hash,
                });
                //JObject jsonCannedMessageHash = JObject.FromObject(cannedMessageHash);
                //report.Data.Add(jsonCannedMessageHash);
                //JsonConvert.SerializeObject(report.Data);
                break;
              case ICDBlockType.PortalProviderInformation:
                var portalProviderInfo = (DataBlock_PortalProviderInformation)d;
                break;
              case ICDBlockType.ReducedSizeLocation:
                var reducedSizeLocation = (DataBlock_ReducedLocation)d;
                break;
              case ICDBlockType.CannedMessageIdentifier:
                var cannedMessageIdentifier = (DataBlock_CannedMessageIdentifier)d;
                break;
              case ICDBlockType.DistributionListHash:
                var distributionList = (DataBlock_DistributionListHash)d;
                break;
              case ICDBlockType.MessageIdentifier:
                var messageIdentifier = (DataBlock_MessageIdentifier)d;
                break;
              case ICDBlockType.FirmwareHardwareVersion:
                var firmwareHardware = (DataBlock_HandsetFwHwVersion)d;
                break;
            }

              }
              report.Data = json;
            }
            else
            {
              ICDMTPacket MTpacket = new ICDMTPacket();
              ICDMTPacket.TryParse(messageSBD, out MTpacket);
              ICDMTMessageType type = ICDMTMessageType.Unknown;
              if (MTpacket.header != null)
              {
            report.IMEI = imei;//chequear si esta registrado
            report.protocolType = (int)MTpacket.header.protocolType;
            report.protocolVersion = (int)MTpacket.header.ProtocolVersionNumber;
            report.EventCode = (int)MTpacket.header.MessageType;
            type = MTpacket.header.MessageType;
              }
              else
              {
            report.IMEI = imei;
            report.protocolType = (int)MTpacket.header.protocolType;
            report.protocolVersion = (int)MTpacket.header.ProtocolVersionNumber;
            report.EventCode = (int)MTpacket.header.MessageType;
            type = MTpacket.header.MessageType;
              }

              report.sent = true;
            }
            return true;
              }
              catch (Exception ex) { }
              return false;
        }
예제 #2
0
        public void ReceiveProcessMails()
        {
            //inserts.Clear();
              mails.Clear();

              Message m = null;
              byte[] bytes;
              String uid = "";
              DateTime dt = DateTime.Now;
              string sdt = "";
              DatabaseMailRecord mail;
              POPClient popClient = new POPClient();
              listReport = new List<IridiumExtremeBinaryReport>();
              try
              {
            log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "Log Iniciado");

            //string TableName = config.getConfigValue("databasesection", "tablename", "tablename");

            int hours = config.getConfigValue("messagesection", "purgetimehours", 30);
            log.writeToLogFile("purgetimehours {0}", hours);

            string s = config.getConfigValue("popsection", "PopServer", "");
            int ins = config.getConfigValue("popsection", "PopPort", 80);
            popClient.Connect(s, ins);
            log.writeToLogFile("Conectado a {0}:{1}", s, ins);

            s = config.getConfigValue("popsection", "PopUsername", "");
            popClient.Authenticate(s, config.getConfigValue("popsection", "PopPassword", ""));
            log.writeToLogFile("Autenticado {0}", s);

            int Count = popClient.GetMessageCount();
            log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "Hay {0} mensajes", Count);

            IridiumExtremeBinaryReport.NumsWithComma = config.getConfigValue("messagesection", "numswithcomma", true);

            for (int i = Count; i >= 1; i -= 1)
            {
              try
              {
            uid = popClient.GetMessageUID(i);
            m = popClient.GetMessage(i, true);

            try
            {
              dt = DateTime.Parse(m.Date);
              sdt = dt.Ticks.ToString();
            }
            catch (Exception)
            {
              sdt = "0";
            }
            if (md.isMail(uid, sdt))
            {
              if (dt.AddHours(hours) < DateTime.Now)
              {
                string strLog = string.Format("Mail muy antiguo {0}, fecha: '{1}', id {2}", i, dt.ToString("yyyy/MM/dd HH:mm:ss"), uid);
                try
                {
                  //popClient.DeleteMessage(i);
                  log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "{0}, fue borrado exitosamente", strLog);
                }
                catch (Exception ex)
                {
                  log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "{0}, hubo un error al intentar borrarlo: {1}", strLog, ex.Message);
                }
              }
              continue;
            }
            else
            {
              md.addValue(uid, sdt);
              if (m != null)
              {
                if (m.HasAttachment)
                {
                  m = popClient.GetMessage(i, false);
                  if (m.Attachments.Count > 0)
                  {
                    foreach (OpenPOP.MIMEParser.Attachment a in m.Attachments)
                    {
                      string attachName = m.GetAttachmentFileName(a);
                      string extension = Path.GetExtension(attachName);

                      if (extension.Equals(config.getValue("AttachmentType")))
                      {
                        mail = new DatabaseMailRecord();
                        mail.Uid = uid;

                        string imei = "desconocido";
                        imei = getIdFromSubject(m.Subject);
                        //try
                        //{
                        //  mail.Data = a.DecodeAsText();
                        //}
                        // catch (Exception)
                        //{
                        //  bytes = a.DecodedAsBytes();
                        //  mail.Data = HexAscii.ConvertToHexAscii(bytes);
                        //  log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "El archivo no es string, procesando como binario");
                        //}
                        try
                        {
                          bytes = a.DecodedAsBytes();
                          saveToDisck(bytes, attachName, @"\MESSAGES_INBOX");
                          mail.Data = HexAscii.ConvertToHexAscii(bytes);
                          log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "El archivo no es string, procesando como binario");
                        }
                        catch (Exception) { }
                        mail.DataTime = dt;
                        mails.Add(mail);
                        string strlog = string.Format("Mail {0}, fecha: '{1}', id {2}", i, dt.ToString("yyyy/MM/dd HH:mm:ss"), uid);
                        strlog = string.Format("{0}, subject: {1}, atachment: {2}", strlog, m.Subject, attachName);
                        strlog = string.Format("{0}, contenido: '{1}', de {2}", strlog, mail.Data.Replace('\r', ' '), m.From);
                        log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", strlog);
                        IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                        string type = "MO";
                        if (IridiumExtremeBinaryReport.TryParse(HexAscii.ConvertToBytes(mail.Data), imei, out report, type))
                        {
                          if (report.inbox)
                          {
                            string TableName = config.getConfigValue("databasesection", "tableinbox", "tablename");
                            inserts.Add(report.ToInsertSQL(true, TableName));
                          }
                          if (report.posiciones)
                          {
                            string TableName = config.getConfigValue("databasesection", "tableposition", "tablename");
                            inserts.Add(report.ToInsertSQL(true, TableName));
                          }
                          //listReport.Add(report);
                        }
                      }
                      else
                      {
                        if (extension.Equals(".htm"))
                        {
                          if (m.Subject.Contains("SBD Mobile Terminated Message Queued for Unit:"))
                          {
                            //string data = mail.Data.Replace('\r', ' ');
                            string filename = getBetween(m.RawMessage, "Filename: ", "\r");
                            string imei = getBetween(m.RawMessage, "IMEI: ", "\r");
                            DateTime time = DateTime.Parse(m.Date);
                            string gatewayStatus = "";
                            if (m.RawMessage.Contains("The following mobile-terminated message was queued for delivery"))
                            {
                              gatewayStatus = "The mobile-terminated message was queued for delivery";
                            }
                            try
                            {
                              OdbcCommand comm;
                              string sql = "";
                              List<string> updates = new List<string>();
                              if (ConnectToDatabase(out comm))
                              {
                                string TableName = config.getValue("tablesent");
                                sql = string.Format("update {0} set GATEWAY_DATETIME = '{1}' where ATTACHMENT_FILENAME = '{2}' and EQP_ESN = '{3}'", TableName, time.ToString("yyyy/MM/dd HH:mm:ss"), filename, imei);
                                //updates.Add(sql);
                                inserts.Add(sql);
                                sql = string.Format("update {0} set GATEWAY_STATUS = '{1}' where ATTACHMENT_FILENAME = '{2}' and EQP_ESN = '{3}'", TableName, gatewayStatus, filename, imei);
                                //updates.Add(sql);
                                inserts.Add(sql);
                                //foreach (string query in updates)
                                //{
                                //  comm.CommandText = query;
                                //  comm.ExecuteNonQuery();
                                //}
                              }

                            }
                            catch (Exception ex)
                            { }
                          }

                        }
                      }
                    }
                  }
                }
                else
                {
                  log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "El mail {0} esta corrupto o es erroneo", i);
                }
              }
            }
              }
              catch (Exception ex)
              {
            if (m != null)
              log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "Hubo un en un mail {0}, {1}, error: {2}", m.From, m.Date, ex.Message);
            else
              log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "Hubo un en un mail {0}, error: {1}", uid, ex.Message);
              }
            }
              }
              catch (Exception ex)
              {
            log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "Hubo un error: {0} ", ex.Message);
              }
              finally
              {
            popClient.Disconnect();
            log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "Desconectado");
            log.Flush();
              }
        }
예제 #3
0
        //chequea la bandeja de entrada y envia los MT pertinentes
        public bool ProcessMessagesFromDataBase(out List<byte[]> msgs, out List<string> imeis, out List<string> filenames)
        {
            //Por acá tendría que estar un método que traiga registros de la base
              //JObject json = JObject.Parse(str);
              int idMessageLastMessage = 0;
              inserts.Clear();
              int idMessage = 0;
              DateTime inDatetime = new DateTime();
              string imei = "000000000000000";//"300215010568090";
              string type = "";
              ICDMOMessageType MO_MessageType = ICDMOMessageType.Unknown;
              ICDMTMessageType MT_MessageType = ICDMTMessageType.Unknown;
              int protocol = 0;
              int protocolVersion = 0;
              int messageIdentifier = 0;
              string jsonData = "";
              JObject json = new JObject();
              //JArray json = new JArray();
              //JObject obj = new JObject();

              ICDMTMessageType TypeOfMT = ICDMTMessageType.Unknown;//(ICDMTMessageType)10;
              SynchronisationDataType typeSynchro = SynchronisationDataType.EmergencyCallRecipient;//(SynchronisationDataType)6;

              byte[] msgBytes;
              msgs = new List<byte[]>();
              imeis = new List<string>();
              filenames = new List<string>();
              List<ICDDataBlock> datablocks = new List<ICDDataBlock>();
              Encoding unicode = Encoding.Unicode;
              Encoding utf8 = Encoding.UTF8;

              OdbcCommand comm;
              string sql = "";
              try
              {
            if (ConnectToDatabase(out comm))
            #region codigo
            {
              string TableName = config.getValue("tableinbox");
              //var cmd = conn.CreateCommand();
              sql = string.Format("select * from {0}", TableName);
              comm.CommandText = sql;
              OdbcDataReader queryResults = comm.ExecuteReader();

              while (queryResults.Read())
              {
            try { idMessage = queryResults.GetInt16(0); }
            catch (InvalidCastException) { }
            try { inDatetime = queryResults.GetDateTime(1); }
            catch (InvalidCastException) { }
            try { imei = queryResults.GetString(2); }
            catch (InvalidCastException) { }
            try { type = queryResults.GetString(3); }
            catch (InvalidCastException) { }
            if (type == "MO")
            {
              try { MO_MessageType = (ICDMOMessageType)queryResults.GetInt16(4); }
              catch (InvalidCastException) { }
            }
            else
            {
              try { MT_MessageType = (ICDMTMessageType)queryResults.GetInt16(4); }
              catch (InvalidCastException) { }
            }
            try { protocol = queryResults.GetInt16(5); }
            catch (InvalidCastException) { }
            try { protocolVersion = queryResults.GetInt16(6); }
            catch (InvalidCastException) { }
            try { messageIdentifier = queryResults.GetInt16(7); }
            catch (InvalidCastException) { }
            try
            {
              jsonData = queryResults.GetString(8);
              json = JObject.Parse(jsonData);
              //string b = RemoveSpecialCharacters(jsonData);
              //var dict = new JavaScriptSerializer().DeserializeObject(jsonData);
              //var obj = JsonConvert.SerializeObject(dict);
            }
            catch (InvalidCastException) { }
            bool MTFLAG = false;
            string result = "";
            bool registered = false;
            string loginState = GET("http://vdms5.tesacom.net/login.php?user_name=userapi&password=T3s@m321");
            string url = String.Format("http://vdms5.tesacom.net/abm/abm_equipos.php?oper=exists&ESN={0}&contentType=json", imei);
            string jsonExists = GET(url);
            try
            {
              JObject jData = new JObject();
              jData = JObject.Parse(jsonExists);
              foreach (JProperty jsonProperty in jData.Children().ToList())
              {
                if (jsonProperty.Name.ToString() == "success")
                {
                  result = jsonProperty.Value.ToString();
                  if (result == "true")
                  {
                    registered = true;
                  }
                  log.writeToLogFile(LogType.LOG_NOTICE, "Consultando API", "Se consultó si existía el equipo con IMEI{0} y el resultado es success:{1}", imei, jsonProperty.Value.ToString());
                }
              }
            }
            catch (Exception ex) { }

            if (type == "MO")
            {
              TypeOfMT = ICDMTMessageType.Unknown;

              switch (MO_MessageType)
              {
                case ICDMOMessageType.SwitchOn:

                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    TypeOfMT = ICDMTMessageType.PortalStatusMessage;
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.AutomaticPositionReport:
                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.ManualPositionReport:
                  if (registered)
                  {
                    imeis.Add(imei);
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.Emergency:
                  if (registered)
                  {
                    imeis.Add(imei);
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));

                    string insertInPosiciones = "";
                    foreach (JProperty jsonObject in json.Children().ToList())
                    {
                      if (jsonObject.Name == "Location")
                      {
                        foreach (JObject location in jsonObject.Children().ToList())
                        {
                          foreach (JProperty property in location.Children().ToList())
                          {
                            if (property.Name.ToString() == "InsertInPosiciones")
                            {
                              insertInPosiciones = property.Value.ToString();
                            }
                          }
                        }
                      }
                    }

                    if (insertInPosiciones == "Si")
                    {
                      string tname3 = config.getConfigValue("databasesection", "tableposition", "tablename");
                      inserts.Add(report.ToInsertSQL(true, tname3));
                    }

                  }
                  break;
                case ICDMOMessageType.CheckIn:
                  if (registered)
                  {
                    imeis.Add(imei);
                    TypeOfMT = ICDMTMessageType.Unknown;
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.DiagnosticsResponse:
                case ICDMOMessageType.BeginMonitoring:
                case ICDMOMessageType.Deregistration:
                case ICDMOMessageType.CannedMessageSend:
                case ICDMOMessageType.EmergencyCancel:
                case ICDMOMessageType.EndMonitoring:
                case ICDMOMessageType.GeofenceCrossedByDevice:
                case ICDMOMessageType.MessageAcknowledgement:
                case ICDMOMessageType.RequestDeviceIdentifierResponse:
                case ICDMOMessageType.ResponseToLocationPingRequest:
                case ICDMOMessageType.SynchronisingDataOverTheAir:
                case ICDMOMessageType.UserExtensions:
                case ICDMOMessageType.Unknown:
                  break;
              }

            }
            else
            {
              MTFLAG = true;

              switch (MT_MessageType)
              {
                case ICDMTMessageType.FreeText:

                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    TypeOfMT = ICDMTMessageType.FreeText;

                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MT_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.messageIdentifier = messageIdentifier;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMTMessageType.PortalStatusMessage:

                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    TypeOfMT = ICDMTMessageType.PortalStatusMessage;
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MT_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.Data = json;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
              }
            }
            ICDMTPacket MTpacket = new ICDMTPacket();
            MTpacket.header = new ICDMTMessageStandardHeader();
            MTpacket.header.protocolType = 101;
            MTpacket.header.ProtocolVersionNumber = 2;
            switch (TypeOfMT)
            {
              case ICDMTMessageType.PortalStatusMessage:
                //List<JProperty> ps = json["portalstatus"].Children().cast<JProperty>().Tolist();
                //foreach (JProperty p in ps)
                //{
                //  string key = p.Name.ToString();
                //  string value = p.Name.ToString();
                //}
                IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                MTpacket.header.messageType = 10;
                MTpacket.header.MessageType = (ICDMTMessageType)MTpacket.header.messageType;
                MTpacket.header.MessageIdentifier = 221;//0

                DataBlock_PortalStatus statusMessage = new DataBlock_PortalStatus();
                DataBlock_PortalProviderInformation portalProviderInformation = new DataBlock_PortalProviderInformation();
                //string msg;
                statusMessage.Status = 0;
                string msgStatus = "OK";
                string msgProviderInfo = "LBS Portal";
                if (MTFLAG)
                {
                  foreach (JProperty jsonObject in json.Children().ToList())
                  {
                    if (jsonObject.Name == "PortalStatus")
                    {
                      foreach (JObject portalstatus in jsonObject.Children().ToList())
                      {
                        foreach (JProperty property in portalstatus.Children().ToList())
                        {
                          if (property.Name.ToString() == "FreeText")
                          {
                            msgStatus = property.Value.ToString();
                          }
                          if (property.Name.ToString() == "Status")
                          {
                            statusMessage.Status = (uint)property.Value;
                          }
                        }
                      }
                    }
                    if (jsonObject.Name == "PortalProviderInformation")
                    {
                      foreach (JObject portalproviderinf in jsonObject.Children().ToList())
                      {
                        foreach (JProperty property in portalproviderinf.Children().ToList())
                        {
                          if (property.Name.ToString() == "FreeText")
                          {
                            msgProviderInfo = property.Value.ToString();
                          }
                        }
                      }
                    }
                  }
                }
                else
                {
                  //We will do it but like the data came from vdms
                  msgStatus = "OK";
                  statusMessage.Status = 0;
                  msgProviderInfo = "LBS Portal";
                  statusMessage.BlockType = ICDBlockType.PortalStatus;
                  portalProviderInformation.BlockType = ICDBlockType.PortalProviderInformation;

                  JObject jsonTemp = new JObject();

                  jsonTemp["PortalStatus"] = JObject.FromObject(new
                  {
                    Type = statusMessage.BlockType.ToString(),
                    FreeText = msgStatus,
                    Status = statusMessage.Status
                  });

                  jsonTemp["PortalProviderInformation"] = JObject.FromObject(new
                  {
                    Type = portalProviderInformation.BlockType.ToString(),
                    FreeText = msgStatus
                  });

                  json = jsonTemp;

                }
                //Finished to set the Portal status
                statusMessage.blockType = (int)ICDBlockType.PortalStatus;
                statusMessage.BlockType = ICDBlockType.PortalStatus;
                statusMessage.BlockLengthIndicator = 0;
                msgBytes = GetBytes(msgStatus);
                msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                statusMessage.FreeText = msgBytes;
                MTpacket.body.datablocks.Add(statusMessage);
                //Finished to set the Portal provider datablock
                portalProviderInformation.blockType = (int)ICDBlockType.PortalProviderInformation;
                portalProviderInformation.BlockType = ICDBlockType.PortalProviderInformation;
                portalProviderInformation.BlockLengthIndicator = 0;
                msgBytes = GetBytes(msgProviderInfo);
                msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                portalProviderInformation.FreeText = msgBytes;
                MTpacket.body.datablocks.Add(portalProviderInformation);

                msgs.Add(MTpacket.ToBytes());
                string type_Message = "MT";

                if (IridiumExtremeBinaryReport.TryParse(MTpacket.ToBytes(), imei, out report, type_Message))
                {
                  if (report.sent)
                  {
                    report.Data = json;
                    report.idMessage = idMessage;
                    report.messageIdentifier = (int)MTpacket.header.MessageIdentifier;
                    report.ReportDate = DateTime.Now;
                    report.attachmentFilename = string.Format("{0}.SBD", DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"));
                    filenames.Add(report.attachmentFilename);

                    saveToDisck(MTpacket.ToBytes(), report.attachmentFilename, @"\MESSAGES_SENT");

                    string table = config.getConfigValue("databasesection", "tablesent", "tablename");
                    inserts.Add(report.ToInsertSQL(true, table));
                  }
                }
                break;
              case ICDMTMessageType.FreeText:

                MTpacket.header.messageType = 7;
                MTpacket.header.MessageType = (ICDMTMessageType)MTpacket.header.messageType;
                MTpacket.header.MessageIdentifier = 0;

                DataBlock_FreeText freeText = new DataBlock_FreeText();
                freeText.BlockType = ICDBlockType.FreeText;
                freeText.blockType = (int)ICDBlockType.FreeText;
                string msg = "Hola desde el portal";
                //PROBAR
                freeText.FreeText.Text = msg;//VER
                freeText.BlockLengthIndicator = 1;
                freeText.FreeText.DecodeTextIndicator = 0;
                freeText.BlockLengthBytes = (uint)(msg.Length);
                freeText.FreeText.FreeTextLengthIndicator = 0;//VER
                freeText.FreeText.FreeTextLength = (uint)(freeText.FreeText.BytesText.Length);
                freeText.FreeText.DecodeTextIndicator = 0;
                freeText.FreeText.DecodeTextLength = (uint)(msg.Length);

                MTpacket.body.datablocks.Add(freeText);

                DataBlock_Sender sender = new DataBlock_Sender();
                sender.BlockType = ICDBlockType.Sender;
                sender.blockType = (uint)ICDBlockType.Sender;
                sender.BlockLengthIndicator = 0;
                msg = "Portal";
                sender.BlockLengthBytes = (uint)(msg.Length + 2);
                msgBytes = GetBytes(msg);
                msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                sender.Sender = msgBytes;
                MTpacket.body.datablocks.Add(sender);
                msgs.Add(MTpacket.ToBytes());
                break;
              case ICDMTMessageType.GeofenceActivate:

                DataBlock_Polygon polygon = new DataBlock_Polygon();

                DataBlock_Circle circle = new DataBlock_Circle();

                break;
              case ICDMTMessageType.ConfirmedCheckIn:
              case ICDMTMessageType.DiagnosticRequest:
              case ICDMTMessageType.EmergencyAcknowledge:
              case ICDMTMessageType.EmergencyCancelRequest:
              case ICDMTMessageType.GeofenceCancel:
              case ICDMTMessageType.LocationPingRequest:
              case ICDMTMessageType.RequestDeviceIdentifier:
              case ICDMTMessageType.SystemTestResponseEndToEnd:
              case ICDMTMessageType.Reserved:
              case ICDMTMessageType.Unknown:
                break;
              case ICDMTMessageType.UserExtensions:
                break;
              case ICDMTMessageType.SynchroniseDataToDevice:

                MTpacket.header.messageType = (uint)ICDMTMessageType.SynchroniseDataToDevice;
                MTpacket.header.MessageType = (ICDMTMessageType)MTpacket.header.messageType;
                MTpacket.header.MessageIdentifier = 0;

                DataBlock_Synchronisation synchronisation = new DataBlock_Synchronisation();
                switch (typeSynchro)
                {
                  case SynchronisationDataType.DistributionlistClearAll:

                    DataBlock_SynchronisationDistributionList distListClearAll = new DataBlock_SynchronisationDistributionList();
                    distListClearAll.blockType = (int)ICDBlockType.Synchronisation;
                    distListClearAll.BlockType = ICDBlockType.Synchronisation;
                    distListClearAll.BlockLengthBytes = 1;
                    distListClearAll.dataType = (int)SynchronisationDataType.DistributionListClear;
                    distListClearAll.DataType = SynchronisationDataType.DistributionListClear;
                    synchronisation = distListClearAll;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.DistributionListAdd:

                    DataBlock_SynchronisationDistributionList syncDistListAdd = new DataBlock_SynchronisationDistributionList();
                    syncDistListAdd.blockType = (int)ICDBlockType.Synchronisation;
                    syncDistListAdd.BlockType = ICDBlockType.Synchronisation;
                    msg = "Work";
                    syncDistListAdd.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncDistListAdd.dataType = (int)SynchronisationDataType.DistributionListAdd;
                    syncDistListAdd.DataType = SynchronisationDataType.DistributionListAdd;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_DistributionList distList = new DataBlock_DistributionList();
                    distList.DistributionList = msgBytes;
                    syncDistListAdd.data = distList;
                    synchronisation = syncDistListAdd;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.DistributionListClear:

                    DataBlock_SynchronisationDistributionList syncDistListClear = new DataBlock_SynchronisationDistributionList();
                    syncDistListClear.blockType = (int)ICDBlockType.Synchronisation;
                    syncDistListClear.BlockType = ICDBlockType.Synchronisation;
                    msg = "Work";
                    syncDistListClear.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncDistListClear.dataType = (int)SynchronisationDataType.DistributionListClear;
                    syncDistListClear.DataType = SynchronisationDataType.DistributionListClear;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_DistributionList distListClear = new DataBlock_DistributionList();
                    distListClear.DistributionList = msgBytes;
                    syncDistListClear.data = distListClear;
                    synchronisation = syncDistListClear;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.CannedMessage:

                    DataBlock_SynchronisationCannedMessage syncCannedMsg = new DataBlock_SynchronisationCannedMessage();
                    syncCannedMsg.blockType = (int)ICDBlockType.Synchronisation;
                    syncCannedMsg.BlockType = ICDBlockType.Synchronisation;
                    msg = "I have achieved my objective";
                    syncCannedMsg.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncCannedMsg.dataType = (int)SynchronisationDataType.CannedMessage;
                    syncCannedMsg.DataType = SynchronisationDataType.CannedMessage;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);

                    DataBlock_CannedMessageData cmd = new DataBlock_CannedMessageData();
                    cmd.LanguageIdentifier = "en";
                    cmd.LanguageIdentifierFirstLetter = (int)LettersIdentifier.e;
                    cmd.LanguageIdentifierSecondLetter = (int)LettersIdentifier.n;
                    cmd.CannedMessageNumber = 1;
                    cmd.IncludeLocation = 0;
                    cmd.CannedMessage = msgBytes;
                    syncCannedMsg.data = cmd;
                    synchronisation = syncCannedMsg;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.AddressBookEntry:
                    DataBlock_SynchronisationAddressBook syncAddressBook = new DataBlock_SynchronisationAddressBook();
                    syncAddressBook.blockType = (int)ICDBlockType.Synchronisation;
                    syncAddressBook.BlockType = ICDBlockType.Synchronisation;
                    msg = "addressBook";
                    syncAddressBook.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncAddressBook.dataType = (int)SynchronisationDataType.AddressBookEntry;
                    syncAddressBook.DataType = SynchronisationDataType.AddressBookEntry;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_AddressBook addressBook = new DataBlock_AddressBook();
                    addressBook.AddressBookNumber = (uint)100;
                    addressBook.BytesAddressBookItem = msgBytes;
                    syncAddressBook.data = addressBook;
                    synchronisation = syncAddressBook;
                    MTpacket.body.datablocks.Add(synchronisation);
                    //to complete
                    break;
                  case SynchronisationDataType.EmergencyCallRecipient:
                    DataBlock_SynchronisationEmergencyCallRecipient syncEmergCallRec = new DataBlock_SynchronisationEmergencyCallRecipient();
                    syncEmergCallRec.blockType = (int)ICDBlockType.Synchronisation;
                    syncEmergCallRec.BlockType = ICDBlockType.Synchronisation;
                    msg = "emergencycallrecipient";
                    syncEmergCallRec.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncEmergCallRec.dataType = (int)SynchronisationDataType.EmergencyCallRecipient;
                    syncEmergCallRec.DataType = SynchronisationDataType.EmergencyCallRecipient;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_EmergencyCallRecipient emerCallRec = new DataBlock_EmergencyCallRecipient();
                    emerCallRec.EmergencyCallRecipient = msgBytes;
                    syncEmergCallRec.data = emerCallRec;
                    synchronisation = syncEmergCallRec;
                    MTpacket.body.datablocks.Add(synchronisation);
                    //to complete
                    break;
                  case SynchronisationDataType.EmergencyDestination:
                    DataBlock_SynchronisationEmergencyDestination syncEmergDest = new DataBlock_SynchronisationEmergencyDestination();
                    syncEmergDest.blockType = (int)ICDBlockType.Synchronisation;
                    syncEmergDest.BlockType = ICDBlockType.Synchronisation;
                    syncEmergDest.dataType = (int)SynchronisationDataType.EmergencyDestination;
                    syncEmergDest.DataType = SynchronisationDataType.EmergencyDestination;
                    //to complete
                    break;
                  case SynchronisationDataType.GPSFrequencyRate:
                    DataBlock_SynchronisationReportingFrequencyRate repFreqRate = new DataBlock_SynchronisationReportingFrequencyRate();
                    //to complete
                    break;
                  case SynchronisationDataType.ProtocolType:
                    DataBlock_SynchronisationProtocolType protocolType = new DataBlock_SynchronisationProtocolType();
                    //to complete
                    break;
                }
                msgs.Add(MTpacket.ToBytes());
                break;
            }//termina switch principal
              }//termina while
              if (msgs.Count > 0)
              {
            return true;
              }
              else
              {
            return false;
              }
            }//termina if
            else
            {
              return false;
            }
            #endregion
              }
              catch (Exception ex)
              {
            log.writeToLogFile(LogType.LOG_NOTICE, "ConnectToDatabase", "Hubo un error: {0}, en la consulta: {1} ", ex.Message, sql);
            return false;
              }
        }
예제 #4
0
        public void ReceiveEmailData()
        {
            //54b89f4ec0311af3c7c74bd8d5a5089a

              IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
              //byte[] bytes = HexAscii.ConvertToBytes("6504AE00067DDC23EB920016A290CC9D2BEE801036000A1005200C4025BEEE11F46E01808A809BC566517A2C3A875910334C6FCD682E1B6C4683C140A8399D6C07C16032580AC47CBB5BB01ACE35B3D968B8190835A793ED20184C464B81826C3A68158381DA20D49C4EB68360B0D92D053A42A7A079983E07C16820192C366BC5642D180D14ABE968B32A75081286E974102E560255E76539881D769F416537685A76D341F674189494A7C9E97A1B");

              //string path = @"C:\Users\jcorrales\Documents\Visual Studio 2008\Projects\IridiumExtreme\IridiumExtreme\bin\Debug\300215010900550_000007.sbd";
              string path = @"C:\Users\jcorrales\Desktop\300215010900550_000005.sbd";
              byte[] fileBytes = File.ReadAllBytes(path);
              string hex = BitConverter.ToString(fileBytes).Replace("-", string.Empty);
              byte[] bytes = HexAscii.ConvertToBytes(hex);
              //StringBuilder sb = new StringBuilder();
              //foreach (byte b in fileBytes)
              //{
              //  sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
              //}
              //string imei = "309015010008060";

              string imei = "300215010568090";
              Encoding unicode = Encoding.Unicode;
              Encoding utf8 = Encoding.UTF8;
              byte[] imeib = GetBytes(imei);
              imeib = Encoding.Convert(unicode, utf8, imeib);
              crc_32c hash = new crc_32c();
              uint hashvar = hash.toHash2(imeib, imeib.Length);

              if (IridiumExtremeBinaryReport.TryParse(bytes, "300215010568090", out report, "MO"))
              {
            inserts.Add(report.ToInsertSQL(true, "MESSAGE_INBOX"));
              }
        }
예제 #5
0
        //chequea la bandeja de entrada y envia los MT pertinentes
        public bool ProcessMessagesFromDataBase(out List<byte[]> msgs, out List<string> imeis, out List<string> filenames)
        {
            //Por acá tendría que estar un método que traiga registros de la base
              //JObject json = JObject.Parse(str);
              int idMessageLastMessage = 0;
              inserts.Clear();
              int idMessage = 0;
              DateTime inDatetime = new DateTime();
              string imei = "300215010568090";
              string type = "";
              ICDMOMessageType MO_MessageType = ICDMOMessageType.Unknown;
              ICDMTMessageType MT_MessageType = ICDMTMessageType.Unknown;
              int protocol = 0;
              int protocolVersion = 0;
              int messageIdentifier = 0;
              string jsonData = "";

              ICDMTMessageType TypeOfMT = ICDMTMessageType.Unknown;//(ICDMTMessageType)10;
              SynchronisationDataType typeSynchro = SynchronisationDataType.EmergencyCallRecipient;//(SynchronisationDataType)6;

              byte[] msgBytes;
              msgs = new List<byte[]>();
              imeis = new List<string>();
              filenames = new List<string>();
              List<ICDDataBlock> datablocks = new List<ICDDataBlock>();
              Encoding unicode = Encoding.Unicode;
              Encoding utf8 = Encoding.UTF8;

              OdbcCommand comm;
              string sql = "";
              try
              {
            if (ConnectToDatabase(out comm))
            #region codigo
            {
              string TableName = config.getValue("tableinbox");
              //var cmd = conn.CreateCommand();
              sql = string.Format("select * from {0}", TableName);
              comm.CommandText = sql;
              OdbcDataReader queryResults = comm.ExecuteReader();

              while (queryResults.Read())
              {
            try { idMessage = queryResults.GetInt16(0); }
            catch (InvalidCastException) { }
            try { inDatetime = queryResults.GetDateTime(1); }
            catch (InvalidCastException) { }
            try { imei = queryResults.GetString(2); }
            catch (InvalidCastException) { }
            try { type = queryResults.GetString(3); }
            catch (InvalidCastException) { }
            if(type == "MO")
            {
            try { MO_MessageType = (ICDMOMessageType)queryResults.GetInt16(4); }
            catch (InvalidCastException) { }
            }
            else
            {
            try { MT_MessageType = (ICDMTMessageType)queryResults.GetInt16(4); }
            catch (InvalidCastException) { }
            }
            try { protocol = queryResults.GetInt16(5); }
            catch (InvalidCastException) { }
            try { protocolVersion = queryResults.GetInt16(6); }
            catch (InvalidCastException) { }
            try { messageIdentifier = queryResults.GetInt16(7); }
            catch (InvalidCastException) { }
            try { jsonData = queryResults.GetString(8); }
            catch (InvalidCastException) { }

            if (type == "MO")
            {
              bool registered = true;
              TypeOfMT = ICDMTMessageType.Unknown;
              switch (MO_MessageType)
              {
                case ICDMOMessageType.SwitchOn:

                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    TypeOfMT = ICDMTMessageType.PortalStatusMessage;
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.jsonData = jsonData;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));

                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.AutomaticPositionReport:
                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.jsonData = jsonData;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.ManualPositionReport:
                  if (registered)
                  {
                    imeis.Add(imei);
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.jsonData = jsonData;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
                case ICDMOMessageType.Emergency:
                  if (registered)
                  {
                    imeis.Add(imei);
                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MO_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.jsonData = jsonData;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                    string tname2 = config.getConfigValue("databasesection", "tableinbox", "tablename");
                    inserts.Add(report.ToDeleteSQL(tname2, idMessage));
                  }
                  break;
                case ICDMOMessageType.CheckIn:
                  break;
              }

            }
            else
            {
              switch (MT_MessageType)
              {
                case ICDMTMessageType.FreeText:
                  bool registered = true;
                  //chequear si esta registrado
                  if (registered)
                  {
                    imeis.Add(imei);
                    TypeOfMT = ICDMTMessageType.FreeText;

                    IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                    report.ReportDate = DateTime.Now;
                    report.IMEI = imei;
                    report.type_message = type;
                    report.EventCode = (int)MT_MessageType;
                    report.protocolType = protocol;
                    report.protocolVersion = protocolVersion;
                    report.idMessage = idMessage;
                    report.messageIdentifier = messageIdentifier;
                    report.jsonData = jsonData;

                    string tname = config.getConfigValue("databasesection", "tableoutbox", "tablename");
                    inserts.Add(report.ToInsertSQL(true, tname));
                  }
                  else { TypeOfMT = ICDMTMessageType.Unknown; }
                  break;
              }
            }
            ICDMTPacket MTpacket = new ICDMTPacket();
            MTpacket.header = new ICDMTMessageStandardHeader();
            MTpacket.header.protocolType = 101;
            MTpacket.header.ProtocolVersionNumber = 2;
            switch (TypeOfMT)
            {
              case ICDMTMessageType.PortalStatusMessage://complementar

                IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                MTpacket.header.messageType = 10;
                MTpacket.header.MessageType = (ICDMTMessageType)MTpacket.header.messageType;
                MTpacket.header.MessageIdentifier = 221;//0

                DataBlock_PortalStatus statusMessage = new DataBlock_PortalStatus();
                statusMessage.blockType = (int)ICDBlockType.PortalStatus;
                statusMessage.BlockType = ICDBlockType.PortalStatus;
                statusMessage.BlockLengthIndicator = 0;
                statusMessage.Status = 0;
                string msg;
                msg = "OK";
                msgBytes = GetBytes(msg);
                msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                statusMessage.FreeText = msgBytes;
                MTpacket.body.datablocks.Add(statusMessage);
                JObject json1 = JObject.FromObject(statusMessage);
                json1.Add("Type", statusMessage.BlockType.ToString());
                json1.Add("FreeText", statusMessage.FreeTextLengthAndFreeTextString);
                json1.Add("Status", statusMessage.Status);

                DataBlock_PortalProviderInformation portalProviderInformation = new DataBlock_PortalProviderInformation();
                portalProviderInformation.blockType = (int)ICDBlockType.PortalProviderInformation;
                portalProviderInformation.BlockType = ICDBlockType.PortalProviderInformation;
                portalProviderInformation.BlockLengthIndicator = 0;
                msg = "LBS Portal";
                msgBytes = GetBytes(msg);
                msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                portalProviderInformation.FreeText = msgBytes;
                MTpacket.body.datablocks.Add(portalProviderInformation);
                msgs.Add(MTpacket.ToBytes());
                JObject json2 = JObject.FromObject(portalProviderInformation);
                json2.Add("Type", portalProviderInformation.BlockType.ToString());
                json2.Add("FreeText", portalProviderInformation.LengthAndFreeTextString);

                string type_Message = "MT";
                if (IridiumExtremeBinaryReport.TryParse(MTpacket.ToBytes(), imei, out report, type_Message ))
                {
                  if (report.sent)
                  {
                    report.Data.Add(json1);
                    report.Data.Add(json2);
                    //report.idMessage = report.idMessage = idMessage;
                    report.idMessage = idMessage;
                    report.messageIdentifier = (int)MTpacket.header.MessageIdentifier;
                    report.ReportDate = DateTime.Now;
                    report.attachmentFilename = string.Format("{0}.SBD", DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"));
                    filenames.Add(report.attachmentFilename);

                    saveToDisck(MTpacket.ToBytes(), report.attachmentFilename, @"\MESSAGES_SENT");

                    string table = config.getConfigValue("databasesection", "tablesent", "tablename");
                    inserts.Add(report.ToInsertSQL(true, table));
                  }
                }
                break;
              case ICDMTMessageType.FreeText:

                MTpacket.header.messageType = 7;
                MTpacket.header.MessageType = (ICDMTMessageType)MTpacket.header.messageType;
                MTpacket.header.MessageIdentifier = 0;

                DataBlock_FreeText freeText = new DataBlock_FreeText();
                freeText.BlockType = ICDBlockType.FreeText;
                freeText.blockType = (int)ICDBlockType.FreeText;
                msg = "Hola desde el portal";
                //PROBAR
                freeText.FreeText.Text = msg;//VER
                freeText.BlockLengthIndicator = 1;
                freeText.FreeText.DecodeTextIndicator = 0;
                freeText.BlockLengthBytes = (uint)(msg.Length);
                freeText.FreeText.FreeTextLengthIndicator = 0;//VER
                freeText.FreeText.FreeTextLength = (uint)(freeText.FreeText.BytesText.Length);
                freeText.FreeText.DecodeTextIndicator = 0;
                freeText.FreeText.DecodeTextLength = (uint)(msg.Length);

                MTpacket.body.datablocks.Add(freeText);

                DataBlock_Sender sender = new DataBlock_Sender();
                sender.BlockType = ICDBlockType.Sender;
                sender.blockType = (uint)ICDBlockType.Sender;
                sender.BlockLengthIndicator = 0;
                msg = "Portal";
                sender.BlockLengthBytes = (uint)(msg.Length + 2);
                msgBytes = GetBytes(msg);
                msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                sender.Sender = msgBytes;
                MTpacket.body.datablocks.Add(sender);
                msgs.Add(MTpacket.ToBytes());
                break;
              case ICDMTMessageType.GeofenceActivate:

                DataBlock_Polygon polygon = new DataBlock_Polygon();

                DataBlock_Circle circle = new DataBlock_Circle();

                break;
              case ICDMTMessageType.ConfirmedCheckIn:
              case ICDMTMessageType.DiagnosticRequest:
              case ICDMTMessageType.EmergencyAcknowledge:
              case ICDMTMessageType.EmergencyCancelRequest:
              case ICDMTMessageType.GeofenceCancel:
              case ICDMTMessageType.LocationPingRequest:
              case ICDMTMessageType.RequestDeviceIdentifier:
              case ICDMTMessageType.SystemTestResponseEndToEnd:
              case ICDMTMessageType.Reserved:
              case ICDMTMessageType.Unknown:
                break;
              case ICDMTMessageType.UserExtensions:
                break;
              case ICDMTMessageType.SynchroniseDataToDevice:

                MTpacket.header.messageType = (uint)ICDMTMessageType.SynchroniseDataToDevice;
                MTpacket.header.MessageType = (ICDMTMessageType)MTpacket.header.messageType;
                MTpacket.header.MessageIdentifier = 0;

                DataBlock_Synchronisation synchronisation = new DataBlock_Synchronisation();
                switch (typeSynchro)
                {
                  case SynchronisationDataType.DistributionlistClearAll:

                    DataBlock_SynchronisationDistributionList distListClearAll = new DataBlock_SynchronisationDistributionList();
                    distListClearAll.blockType = (int)ICDBlockType.Synchronisation;
                    distListClearAll.BlockType = ICDBlockType.Synchronisation;
                    distListClearAll.BlockLengthBytes = 1;
                    distListClearAll.dataType = (int)SynchronisationDataType.DistributionListClear;
                    distListClearAll.DataType = SynchronisationDataType.DistributionListClear;
                    synchronisation = distListClearAll;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.DistributionListAdd:

                    DataBlock_SynchronisationDistributionList syncDistListAdd = new DataBlock_SynchronisationDistributionList();
                    syncDistListAdd.blockType = (int)ICDBlockType.Synchronisation;
                    syncDistListAdd.BlockType = ICDBlockType.Synchronisation;
                    msg = "Work";
                    syncDistListAdd.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncDistListAdd.dataType = (int)SynchronisationDataType.DistributionListAdd;
                    syncDistListAdd.DataType = SynchronisationDataType.DistributionListAdd;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_DistributionList distList = new DataBlock_DistributionList();
                    distList.DistributionList = msgBytes;
                    syncDistListAdd.data = distList;
                    synchronisation = syncDistListAdd;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.DistributionListClear:

                    DataBlock_SynchronisationDistributionList syncDistListClear = new DataBlock_SynchronisationDistributionList();
                    syncDistListClear.blockType = (int)ICDBlockType.Synchronisation;
                    syncDistListClear.BlockType = ICDBlockType.Synchronisation;
                    msg = "Work";
                    syncDistListClear.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncDistListClear.dataType = (int)SynchronisationDataType.DistributionListClear;
                    syncDistListClear.DataType = SynchronisationDataType.DistributionListClear;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_DistributionList distListClear = new DataBlock_DistributionList();
                    distListClear.DistributionList = msgBytes;
                    syncDistListClear.data = distListClear;
                    synchronisation = syncDistListClear;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.CannedMessage:

                    DataBlock_SynchronisationCannedMessage syncCannedMsg = new DataBlock_SynchronisationCannedMessage();
                    syncCannedMsg.blockType = (int)ICDBlockType.Synchronisation;
                    syncCannedMsg.BlockType = ICDBlockType.Synchronisation;
                    msg = "I have achieved my objective";
                    syncCannedMsg.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncCannedMsg.dataType = (int)SynchronisationDataType.CannedMessage;
                    syncCannedMsg.DataType = SynchronisationDataType.CannedMessage;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_CannedMessageData cmd = new DataBlock_CannedMessageData();

                    cmd.LanguageIdentifier = "en";
                    cmd.LanguageIdentifierFirstLetter = (int)LettersIdentifier.e;
                    cmd.LanguageIdentifierSecondLetter = (int)LettersIdentifier.n;
                    cmd.CannedMessageNumber = 1;
                    cmd.IncludeLocation = 0;
                    cmd.CannedMessage = msgBytes;
                    syncCannedMsg.data = cmd;
                    synchronisation = syncCannedMsg;
                    MTpacket.body.datablocks.Add(synchronisation);
                    break;
                  case SynchronisationDataType.AddressBookEntry:
                    DataBlock_SynchronisationAddressBook syncAddressBook = new DataBlock_SynchronisationAddressBook();
                    syncAddressBook.blockType = (int)ICDBlockType.Synchronisation;
                    syncAddressBook.BlockType = ICDBlockType.Synchronisation;
                    msg = "addressBook";
                    syncAddressBook.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncAddressBook.dataType = (int)SynchronisationDataType.AddressBookEntry;
                    syncAddressBook.DataType = SynchronisationDataType.AddressBookEntry;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_AddressBook addressBook = new DataBlock_AddressBook();
                    addressBook.AddressBookNumber = (uint)100;
                    addressBook.BytesAddressBookItem = msgBytes;
                    syncAddressBook.data = addressBook;
                    synchronisation = syncAddressBook;
                    MTpacket.body.datablocks.Add(synchronisation);
                    //to complete
                    break;
                  case SynchronisationDataType.EmergencyCallRecipient:
                    DataBlock_SynchronisationEmergencyCallRecipient syncEmergCallRec = new DataBlock_SynchronisationEmergencyCallRecipient();
                    syncEmergCallRec.blockType = (int)ICDBlockType.Synchronisation;
                    syncEmergCallRec.BlockType = ICDBlockType.Synchronisation;
                    msg = "emergencycallrecipient";
                    syncEmergCallRec.BlockLengthBytes = (uint)(msg.Length + 2);
                    syncEmergCallRec.dataType = (int)SynchronisationDataType.EmergencyCallRecipient;
                    syncEmergCallRec.DataType = SynchronisationDataType.EmergencyCallRecipient;
                    msgBytes = GetBytes(msg);
                    msgBytes = Encoding.Convert(unicode, utf8, msgBytes);
                    DataBlock_EmergencyCallRecipient emerCallRec = new DataBlock_EmergencyCallRecipient();
                    emerCallRec.EmergencyCallRecipient = msgBytes;
                    syncEmergCallRec.data = emerCallRec;
                    synchronisation = syncEmergCallRec;
                    MTpacket.body.datablocks.Add(synchronisation);
                    //to complete
                    break;
                  case SynchronisationDataType.EmergencyDestination:
                    DataBlock_SynchronisationEmergencyDestination syncEmergDest = new DataBlock_SynchronisationEmergencyDestination();
                    syncEmergDest.blockType = (int)ICDBlockType.Synchronisation;
                    syncEmergDest.BlockType = ICDBlockType.Synchronisation;
                    syncEmergDest.dataType = (int)SynchronisationDataType.EmergencyDestination;
                    syncEmergDest.DataType = SynchronisationDataType.EmergencyDestination;
                    //to complete
                    break;
                  case SynchronisationDataType.GPSFrequencyRate:
                    DataBlock_SynchronisationReportingFrequencyRate repFreqRate = new DataBlock_SynchronisationReportingFrequencyRate();
                    //to complete
                    break;
                  case SynchronisationDataType.ProtocolType:
                    DataBlock_SynchronisationProtocolType protocolType = new DataBlock_SynchronisationProtocolType();
                    //to complete
                    break;
                }
                msgs.Add(MTpacket.ToBytes());
                break;
            }//termina switch principal
              }//termina while
              if (msgs.Count > 0)
              {
            return true;
              }
              else
              {
            return false;
              }
            }//termina if
            else
            {
              return false;
            }
            #endregion
              }
              catch (Exception ex)
              {
            log.writeToLogFile(LogType.LOG_NOTICE, "ConnectToDatabase", "Hubo un error: {0}, en la consulta: {1} ", ex.Message, sql);
            return false;
              }
        }