public ActionResult SendToEmail(string kindergartenId, int id, string email)
        {
            Statement statement = StatementManager.GetStatementById(id);

            if (User.Identity.IsAuthenticated &&
                ((User.IsInRole("Administrator") && statement.KindergartenId == User.Identity.GetUserId()) ||
                 (User.IsInRole("Admin"))))
            {
                try
                {
                    Kindergarten Kindergarten        = KindergartenManager.GetKindergartenById(statement.KindergartenId);
                    SiteUser     siteUser            = SiteUserManager.GetSiteUserById(statement.SiteUserId);
                    StatementListItemViewModel model = new StatementListItemViewModel
                    {
                        Statement        = statement,
                        UserPrivileges   = StatementManager.GetUserPrivilegesByStatementId(id),
                        KindergartenName = Kindergarten.Name,
                        UserName         = siteUser.FullName
                    };

                    MailCustom.Mail(email, "Заява в електронну чергу #" + model.Statement.Id, GetAnswer(model));

                    return(RedirectToAction("Statements", "Kindergarten", new { kindergartenId }));
                }
                catch { return(RedirectToAction("Statements", "Kindergarten", new { kindergartenId })); }
            }
            ;
            return(RedirectToAction("Index", "Home"));
        }
 public ActionResult AddKindergarten(AddKindergartenViewModel model)
 {
     if (User.Identity.IsAuthenticated && User.IsInRole("Admin"))
     {
         if (ModelState.IsValid)
         {
             var user = new ApplicationUser {
                 UserName = model.Email, Email = model.Email
             };
             string password = Guid.NewGuid().ToString("N");
             if (ApplicationManager.IsEmailExist(model.Email))
             {
                 ModelState.AddModelError("Email", "Такий емейл вже використовується");
                 return(View(model));
             }
             else
             {
                 var result = UserManager.Create(user, password);
                 if (result.Succeeded)
                 {
                     KindergartenManager.AddKindergarten(model, user.Id, Server);
                     UserManager.AddToRole(user.Id, "Administrator");
                     MailCustom.Mail(model.Email, "IStudy password", GetAnswer(model.Email, password));
                     return(RedirectToAction("Kindergartens", "Admin"));
                 }
                 AddErrors(result);
             }
         }
         return(View(model));
     }
     return(RedirectToAction("Index", "Home"));
 }
        public MailCustom generateMailBody(string type, Database.Database db)
        {
            db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody(type: " + type + ") | Creation d une instance.");

            if (type.Equals("client_error"))
            {
                CustomMailRecap recap_imp = null;
                CustomMailRecap recap_exp = null;
                ConfigurationCustomMailSaveLoad configurationCustomMailSaveLoad = new ConfigurationCustomMailSaveLoad();

                db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | type => client_error");

                bool          sendMailImp  = false;
                string        textImp      = "";
                string        textImp_     = "";
                bool          sendMailExp  = false;
                string        textExp      = "";
                string        textExp_     = "";
                List <string> attachements = new List <string>();

                //check if the file exist
                if (configurationCustomMailSaveLoad.isSettings(configurationCustomMailSaveLoad.fileName_ERR_Imp))
                {
                    configurationCustomMailSaveLoad.Load(configurationCustomMailSaveLoad.fileName_ERR_Imp);
                    recap_imp = configurationCustomMailSaveLoad.customMailRecap;

                    //make the following body message
                    if (recap_imp.Lines.Count == 0)
                    {
                        sendMailImp = false;
                    }
                    else if (recap_imp.Lines.Count == 1)
                    {
                        sendMailImp = true;
                        textImp    += "L'import d'un document commercial a échoué. Voici un résumé du document en erreur :\n";
                    }
                    else if (recap_imp.Lines.Count > 1)
                    {
                        sendMailImp = true;
                        textImp    += "L'import de plusieurs documents commerciaux ont échoué. Voici le résumé de chaque document en erreur :\n";
                    }


                    for (int i = 0; i < recap_imp.Lines.Count; i++)
                    {
                        if (recap_imp.Lines[i].DocumentErrorMessage != null && !recap_imp.Lines[i].DocumentErrorMessage.Equals(""))
                        {
                            textImp_ += (i + 1) + " -\t Le numéro du document \"" + recap_imp.Lines[i].DocumentReference + "\" de la commande \"" + recap_imp.Lines[i].NumCommande + "\",\n" +
                                        " \t a une erreur : " + recap_imp.Lines[i].DocumentErrorMessage + "\n";
                        }
                    }

                    if (textImp_.Equals(""))
                    {
                        sendMailImp = false;
                    }
                    else
                    {
                        textImp += textImp_;
                    }
                }
                else
                {
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Fichier mail => " + configurationCustomMailSaveLoad.fileName_ERR_Imp + " n existe pas.");
                }

                //check if the file exist
                if (configurationCustomMailSaveLoad.isSettings(configurationCustomMailSaveLoad.fileName_ERR_Exp))
                {
                    configurationCustomMailSaveLoad.Load(configurationCustomMailSaveLoad.fileName_ERR_Exp);
                    recap_exp = configurationCustomMailSaveLoad.customMailRecap;


                    //make the following body message
                    if (recap_exp.Lines.Count == 0)
                    {
                        sendMailExp = false;
                    }
                    else if (recap_exp.Lines.Count == 1)
                    {
                        sendMailExp = true;
                        textExp    += "L'import d'un document commercial a échoué. Voici un résumé du document :\n";
                    }
                    else if (recap_exp.Lines.Count > 1)
                    {
                        sendMailExp = true;
                        textExp    += "L'import de plusieurs documents commerciaux a échoué. Voici le résumé détaillé :\n";
                    }

                    for (int i = 0; i < recap_exp.Lines.Count; i++)
                    {
                        if (recap_exp.Lines[i].DocumentErrorMessage != null && !recap_exp.Lines[i].DocumentErrorMessage.Equals(""))
                        {
                            textExp_ += (i + 1) + " -\t Le numéro du document \"" + recap_exp.Lines[i].DocumentReference + "\" du fichier EDI : " + recap_exp.Lines[i].FileName + ", a une erreur : " + recap_exp.Lines[i].DocumentErrorMessage + "\n";
                        }
                    }

                    if (textExp_.Equals(""))
                    {
                        sendMailExp = false;
                    }
                    else
                    {
                        textExp += textExp_;
                    }
                }
                else
                {
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Fichier mail => " + configurationCustomMailSaveLoad.fileName_ERR_Exp + " n existe pas.");
                }

                //send the recap mail
                MailCustom xxx = null;
                if (sendMailImp & !sendMailExp)
                {
                    xxx = new MailCustom("[" + recap_imp.Client + "] " + recap_imp.Subject, "Bonjour, \n\n" + textImp + "\nCordialement,\nConnecteur SAGE [" + recap_imp.Client + "]. Version client.", null);
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Json : " + Newtonsoft.Json.JsonConvert.SerializeObject(xxx, Newtonsoft.Json.Formatting.Indented));
                    return(xxx);
                }
                else if (sendMailExp & !sendMailImp)
                {
                    xxx = new MailCustom("[" + recap_exp.Client + "] " + recap_exp.Subject, "Bonjour, \n\n" + textExp + "\nCordialement,\nConnecteur SAGE [" + recap_exp.Client + "]. Version client.", null);
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Json : " + Newtonsoft.Json.JsonConvert.SerializeObject(xxx, Newtonsoft.Json.Formatting.Indented));
                    return(xxx);
                }
                else if (sendMailImp && sendMailExp)
                {
                    xxx = new MailCustom("[" + getDNS() + "] " + recap_imp.Subject + " et " + recap_exp.Subject, "Bonjour, \n\n" + textImp + "\n\n\n" + textExp + "\nCordialement,\nConnecteur SAGE [" + getDNS() + "]. Version client.", null);
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Json : " + Newtonsoft.Json.JsonConvert.SerializeObject(xxx, Newtonsoft.Json.Formatting.Indented));
                    return(xxx);
                }
                else
                {
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Rien à preparer.");
                    return(xxx);
                }
            }
            else if (type.Equals("log"))
            {
                CustomMailRecap recap_imp = null;
                CustomMailRecap recap_exp = null;
                ConfigurationCustomMailSaveLoad configurationCustomMailSaveLoad = new ConfigurationCustomMailSaveLoad();

                db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | type => log");

                bool          sendMailImp  = false;
                string        textImp      = "";
                bool          sendMailExp  = false;
                string        textExp      = "";
                List <string> attachements = new List <string>();

                //check if the file exist
                if (configurationCustomMailSaveLoad.isSettings(configurationCustomMailSaveLoad.fileName_ERR_Imp))
                {
                    configurationCustomMailSaveLoad.Load(configurationCustomMailSaveLoad.fileName_ERR_Imp);
                    recap_imp = configurationCustomMailSaveLoad.customMailRecap;

                    //make the following body message
                    if (recap_imp.Lines.Count == 0)
                    {
                        sendMailImp = false;
                    }
                    else if (recap_imp.Lines.Count == 1)
                    {
                        sendMailImp = true;
                        textImp    += "L'import d'un document commercial a échoué. Voici un résumé du document en erreur :\n";
                    }
                    else if (recap_imp.Lines.Count > 1)
                    {
                        sendMailImp = true;
                        textImp    += "L'import de plusieurs documents commerciaux a échoué. Voici le résumé de chaque document en erreur :\n";
                    }
                    for (int i = 0; i < recap_imp.Lines.Count; i++)
                    {
                        textImp += (i + 1) + " -\t Le numéro du document \"" + recap_imp.Lines[i].DocumentReference + "\"\nNom du fichier : " + recap_imp.Lines[i].FileName + "\nMessage erreur : " + recap_imp.Lines[i].DocumentErrorMessageDebug + "\nStackTrace: " + recap_imp.Lines[i].DocumentErrorStackTraceDebug + "\nL'erreur peut etre trouvé dans " + recap_imp.Lines[i].FilePath + "\n\n";
                    }
                    if (sendMailImp)
                    {
                        attachements.AddRange(recap_imp.Attachments);
                    }
                }
                else
                {
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Fichier mail => " + configurationCustomMailSaveLoad.fileName_ERR_Imp + " n existe pas.");
                }

                //check if the file exist
                //check if the file exist
                if (configurationCustomMailSaveLoad.isSettings(configurationCustomMailSaveLoad.fileName_ERR_Exp))
                {
                    configurationCustomMailSaveLoad.Load(configurationCustomMailSaveLoad.fileName_ERR_Exp);
                    recap_exp = configurationCustomMailSaveLoad.customMailRecap;


                    //make the following body message
                    if (recap_exp.Lines.Count == 0)
                    {
                        sendMailExp = false;
                    }
                    else if (recap_exp.Lines.Count == 1)
                    {
                        sendMailExp = true;
                        textExp    += "L'import d'un document commercial a échoué. Voici un résumé du document :\n";
                    }
                    else if (recap_exp.Lines.Count > 1)
                    {
                        sendMailExp = true;
                        textExp    += "L'import de plusieurs documents commerciaux a échoué. Voici le résumé de chaque document :\n";
                    }
                    for (int i = 0; i < recap_exp.Lines.Count; i++)
                    {
                        textExp += (i + 1) + " -\t Le numéro du document \"" + recap_exp.Lines[i].DocumentReference + "\"\nNom du fichier : " + recap_exp.Lines[i].FileName + "\nMessage erreur : " + recap_exp.Lines[i].DocumentErrorMessageDebug + "\nStackTrace: " + recap_exp.Lines[i].DocumentErrorStackTraceDebug + "\nL'erreur peut etre trouvé dans " + recap_exp.Lines[i].FilePath + "\n\n";
                    }
                    if (sendMailExp)
                    {
                        attachements.AddRange(recap_exp.Attachments);
                    }
                }
                else
                {
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Fichier mail => " + configurationCustomMailSaveLoad.fileName_ERR_Exp + " n existe pas.");
                }

                //send the recap mail
                MailCustom xxx = null;
                if (sendMailImp & !sendMailExp)
                {
                    xxx = new MailCustom("[" + recap_imp.Client + "] " + recap_imp.Subject, "Bonjour Team BDC, \n\n" + textImp + "\nCordialement,\nConnecteur SAGE [" + recap_imp.Client + "]. Version équipe", recap_imp.Attachments);
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Json : " + Newtonsoft.Json.JsonConvert.SerializeObject(xxx, Newtonsoft.Json.Formatting.Indented));
                    return(xxx);
                }
                else if (sendMailExp & !sendMailImp)
                {
                    xxx = new MailCustom("[" + recap_exp.Client + "] " + recap_exp.Subject, "Bonjour Team BDC, \n\n" + textExp + "\nCordialement,\nConnecteur SAGE [" + recap_exp.Client + "]. Version équipe", recap_exp.Attachments);
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Json : " + Newtonsoft.Json.JsonConvert.SerializeObject(xxx, Newtonsoft.Json.Formatting.Indented));
                    return(xxx);
                }
                else if (sendMailImp && sendMailExp)
                {
                    xxx = new MailCustom("[" + getDNS() + "] " + recap_imp.Subject + " et " + recap_exp.Subject, "Bonjour, \n\n" + textImp + "\n\n\n" + textExp + "\nCordialement,\nConnecteur SAGE [" + getDNS() + "]. Version équipe", attachements);
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Json : " + Newtonsoft.Json.JsonConvert.SerializeObject(xxx, Newtonsoft.Json.Formatting.Indented));
                    return(xxx);
                }
                else
                {
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Rien à preparer.");
                    return(xxx);
                }
            }
            else
            {
                db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: Alert-Mail.dll => generateMailBody() | Aucun type trouvé!");
                return(null);
            }
        }
Пример #4
0
        private static void errorMail(ConfigurationEmail settings, Database.Database db)
        {
            Alert_Mail.EmailManagement emailManagement = new Alert_Mail.EmailManagement();
            try
            {
                db.alertMailLogManager.insert(db.connectionString, "");
                db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | EndSoftwareExe...");
                Console.WriteLine("EndSoftwareExe...");

                if (settings.emailError.active)
                {
                    if (settings.emailLists.emailClientList.Count == 0 && settings.emailLists.emailTeamList.Count == 0)
                    {
                        Console.WriteLine("Aucun address mail enregistré!");
                        db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | EAucun address mail enregistré!");
                        return;
                    }

                    MailCustom mMailCustom_client = null;
                    MailCustom mMailCustom_log    = null;
                    try
                    {
                        mMailCustom_client = emailManagement.generateMailBody("client_error", db);
                        mMailCustom_log    = emailManagement.generateMailBody("log", db);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("");
                        Console.WriteLine(DateTime.Now + " | Main() : *********** Exception generateMailBody() ***********");
                        Console.WriteLine(DateTime.Now + " | Main() : " + ex.Message);
                        Console.WriteLine(DateTime.Now + " | Main() : " + ex.StackTrace);

                        db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " :: ############################### Exception generateMailBody() ###############################");
                        db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | Message : " + ex.Message);
                        //db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | StackTrace : " + ex.StackTrace);
                        db.alertMailLogManager.insert(db.connectionString, "");

                        Console.WriteLine("");
                        mMailCustom_client = null;
                        mMailCustom_log    = null;
                    }

                    //Envoi
                    if (settings.emailError.informClient)
                    {
                        if (mMailCustom_client != null)
                        {
                            try
                            {
                                Console.WriteLine("Envoi de mail client en cours....");
                                db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | Envoi de mail client en cours....");
                                emailManagement.EnvoiMail(settings, "client", mMailCustom_client.subject, mMailCustom_client.body, mMailCustom_client.attachements, db);   //cheminLogFile
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("");
                                Console.WriteLine(DateTime.Now + " | Main() : *********** Exception Envoi Mail Error Client ***********");
                                Console.WriteLine(DateTime.Now + " | Main() : " + ex.Message);
                                Console.WriteLine(DateTime.Now + " | Main() : " + ex.StackTrace);

                                db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " :: ############################### Exception Envoi Mail Error Client ###############################");
                                db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | Message : " + ex.Message);
                                //db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | StackTrace : " + ex.StackTrace);
                                db.alertMailLogManager.insert(db.connectionString, "");
                                Console.WriteLine("");
                            }
                        }
                        else
                        {
                            Console.WriteLine("Nothing to send for the client");
                            db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | Rien à envoie vers le client");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Send mail to client is desable");
                        db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | Envoie mail client est désactivité");
                    }

                    if (settings.emailError.informTeam)
                    {
                        if (mMailCustom_log != null)
                        {
                            try
                            {
                                Console.WriteLine("Envoi de mail log en cours....");
                                db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | Envoi de mail log en cours....");
                                emailManagement.EnvoiMail(settings, "log", mMailCustom_log.subject, mMailCustom_log.body, mMailCustom_log.attachements, db);   //cheminLogFile
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("");
                                Console.WriteLine(DateTime.Now + " | Main() : *********** Exception Envoi Mail Error Team log ***********");
                                Console.WriteLine(DateTime.Now + " | Main() : " + ex.Message);
                                Console.WriteLine(DateTime.Now + " | Main() : " + ex.StackTrace);

                                db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " :: ############################### Exception Envoi Mail Error Team log ###############################");
                                db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | Message : " + ex.Message);
                                //db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | StackTrace : " + ex.StackTrace);
                                db.alertMailLogManager.insert(db.connectionString, "");
                                Console.WriteLine("");
                            }
                        }
                        else
                        {
                            Console.WriteLine("No log to send for the team");
                            db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | Rien à envoyer au team");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Send log mail to team is desable");
                        db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | Envoie mail log au Team");
                    }

                    if (mMailCustom_client != null && mMailCustom_log != null)
                    {
                        ConfigurationCustomMailSaveLoad xxx = new ConfigurationCustomMailSaveLoad();

                        if (File.Exists(xxx.fileName_ERR_Imp))
                        {
                            File.Delete(xxx.fileName_ERR_Imp);
                        }
                        if (File.Exists(xxx.fileName_ERR_Exp))
                        {
                            File.Delete(xxx.fileName_ERR_Exp);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Les mails d'erreur sont désactivé!");
                    db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | Les mails d erreur sont désactivé!");
                }

                db.alertMailLogManager.insert(db.connectionString, "");

                //stop at the end of the program
                //Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + " | Main() : *********** Exception Main EndSoftwareExe ***********");
                Console.WriteLine(DateTime.Now + " | Main() : " + ex.Message);
                Console.WriteLine(DateTime.Now + " | Main() : " + ex.StackTrace);


                db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " :: ############################### Exception Main EndSoftwareExe ###############################");
                db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | Message : " + ex.Message);
                // db.alertMailLogManager.insert(db.connectionString, DateTime.Now + " : AlertMail :: errorMail() | StackTrace : " + ex.StackTrace);
                db.alertMailLogManager.insert(db.connectionString, "");
            }
        }
        public IHttpActionResult CheckPointSendNotic([FromBody] GetRequestDataRequests req)
        {
            int  stage;
            bool debugEmail = Convert.ToBoolean(ConfigurationManager.AppSettings["debugEmail"]);

            if (debugEmail == true)
            {
                MailCustom mailM = new MailCustom("*****@*****.**", "*****@*****.**", "bayernmunichm21");
                mailM.sendMail("DeviceDataChanged", JsonConvert.SerializeObject(req));
            }

            #region Check Token
            var    re          = Request;
            var    headers     = re.Headers;
            string tokenHeader = "";
            if (headers.Contains("Authorization"))
            {
                tokenHeader = headers.Authorization.Parameter;
            }
            DeTokenProperties detoken = new DeTokenProperties();
            detoken.inputIp    = GetUser_IP();
            detoken.inputToken = tokenHeader;
            if (!_authen.CheckToken(ref detoken))
            {
                return(Unauthorized());
            }
            #endregion

            try
            {
                TrackingResponse traksend    = new TrackingResponse();
                LogDatabase      updateLog   = new LogDatabase();
                CallService      callService = new CallService();

                int    countPosition = 0;
                string lastLatPoint, lastLonPoint, areaStatusInOut, lastDifCurrent, inOutSaveZone, a;
                string returnStatus = null;
                string nameTh       = string.Empty;
                string nameEn       = string.Empty;

                bool NoPosition = false;

                DataTable dtResultIden              = new DataTable();
                DataTable dtResultCallInOut         = new DataTable();
                DataTable dtUpdateDeviceCurrent     = new DataTable();
                DataTable dtInsertDataToLocationLog = new DataTable();
                DataTable dtReUpdateDeviceCurrent   = new DataTable();
                DataTable dtInsertActivityLog       = new DataTable();

                dtResultIden            = null;
                dtReUpdateDeviceCurrent = null;
                dtInsertActivityLog     = null;

                //ตรวจสอบข้อมูล เเละทำการส่ง SOS
                if (req.sos == 1)
                {
                    bool checkHaveTicket = callService.sosSend(req);
                }

                stage = 0;

                //ตรวจสอบมีจุดส่งมาหรือไม่ ถ้าไม่มีไม่ต้องไป Iden
                // ** จุดไม่มี , จุดมี
                if (req.position.Count() > 0)
                {
                    countPosition     = req.position.Count() - 1;
                    lastLatPoint      = req.position[countPosition].latitude.ToString();
                    lastLonPoint      = req.position[countPosition].longitude.ToString();
                    dtResultIden      = callService.Identify(lastLatPoint, lastLonPoint);
                    dtResultCallInOut = CheckInOutArea(lastLatPoint, lastLonPoint, req.deviceId);
                }
                else
                {
                    NoPosition   = true;
                    lastLatPoint = string.Empty;
                    lastLonPoint = string.Empty;
                    dtResultCallInOut.Columns.Add("AreaStatus");
                    dtResultCallInOut.Columns.Add("AreaId");
                    DataRow row = dtResultCallInOut.NewRow();
                    row["AreaStatus"] = null;
                    row["AreaId"]     = null;
                    dtResultCallInOut.Rows.Add(row);
                }

                if (dtResultCallInOut.Rows[0]["AreaStatus"].ToString() == "0" || dtResultCallInOut.Rows[0]["AreaStatus"].ToString() == null)
                {
                    dtResultCallInOut.Rows[0]["AreaStatus"] = DBNull.Value;
                }

                if (dtResultCallInOut.Rows[0]["AreaId"].ToString() == "0" || dtResultCallInOut.Rows[0]["AreaId"].ToString() == null)
                {
                    dtResultCallInOut.Rows[0]["AreaId"] = DBNull.Value;
                }


                //Call service :: Push Notification Event by Device
                // Online Offline
                dtInsertActivityLog = updateLog.InsertActivityLog(req, "onlineoffline", dtResultCallInOut.Rows[0]["AreaStatus"].ToString());
                bool dtPushEvent = callService.callMobilServiceEvent(dtInsertActivityLog);
                //battery Level

                dtInsertActivityLog = updateLog.InsertActivityLog(req, "baterryLevel", dtResultCallInOut.Rows[0]["AreaStatus"].ToString());
                dtPushEvent         = callService.callMobilServiceEvent(dtInsertActivityLog);

                // In out Area
                dtInsertActivityLog = updateLog.InsertActivityLog(req, "InoutArea", dtResultCallInOut.Rows[0]["AreaStatus"].ToString());
                dtPushEvent         = callService.callMobilServiceEvent(dtInsertActivityLog);

                stage = 4;

                // req : ตัวที่ได้มาจาก Raw data dtResultIden : ได้มาจาก Identify , NoPosition : ใช้ตรวจสอบว่ามี ตำแหน่งส่งมาหรือไม่ , dtResultCallInOut : ได้มาจากการ Update InoutArea , dtInsertActivityLog ได้มาจากตัว set Activitylog
                dtInsertDataToLocationLog = updateLog.InsertDataToLocationLog(req, dtResultIden, NoPosition, dtResultCallInOut);
                stage = 5;

                dtReUpdateDeviceCurrent = UpdateDeviceCurrent(dtResultIden, req, NoPosition, dtResultCallInOut);
                stage = 6;

                //การ set ค่า input status ที่จะส่งไปที่ signalR
                returnStatus = dtReUpdateDeviceCurrent.Rows[0]["AreaStatus"].ToString();

                if (dtResultIden != null)
                {
                    nameTh                = dtReUpdateDeviceCurrent.Rows[0]["locationNameTh"].ToString();
                    nameEn                = dtReUpdateDeviceCurrent.Rows[0]["locationNameEn"].ToString();
                    traksend.latitude     = Convert.ToDouble(dtReUpdateDeviceCurrent.Rows[0]["Latitude"]);
                    traksend.longitude    = Convert.ToDouble(dtReUpdateDeviceCurrent.Rows[0]["Longitude"]);
                    traksend.inout_status = returnStatus;

                    if (nameTh == "" || nameTh == null)
                    {
                        traksend.thai_address = dtReUpdateDeviceCurrent.Rows[0]["locationProvinceTh"].ToString() + "," + dtReUpdateDeviceCurrent.Rows[0]["locationDistrictTh"].ToString() + "," + dtReUpdateDeviceCurrent.Rows[0]["locationSubDistrictTh"].ToString();
                    }
                    else
                    {
                        traksend.thai_address = dtReUpdateDeviceCurrent.Rows[0]["locationNameTh"].ToString();
                    }

                    if (nameEn == "" || nameEn == null)
                    {
                        traksend.english_address = dtReUpdateDeviceCurrent.Rows[0]["locationProvinceEn"].ToString() + "," + dtReUpdateDeviceCurrent.Rows[0]["locationDistrictEn"].ToString() + "," + dtReUpdateDeviceCurrent.Rows[0]["locationSubDistrictEn"].ToString();
                    }
                    else
                    {
                        traksend.english_address = dtReUpdateDeviceCurrent.Rows[0]["locationNameEn"].ToString();
                    }

                    traksend.battery          = Convert.ToInt32(dtReUpdateDeviceCurrent.Rows[0]["BatteryLevel"]);
                    traksend.current_datetime = dtReUpdateDeviceCurrent.Rows[0]["Timestamp"].ToString();
                    traksend.online_status    = dtReUpdateDeviceCurrent.Rows[0]["OnlineStatus"].ToString();
                }
                else
                {   // ตรงนี้ไม่เข้านะ
                    if (countPosition > 0)
                    {
                        traksend.latitude        = Convert.ToDouble(req.position[countPosition].latitude);
                        traksend.longitude       = Convert.ToDouble(req.position[countPosition].longitude);
                        traksend.thai_address    = traksend.latitude.ToString() + "," + traksend.longitude.ToString();
                        traksend.english_address = traksend.latitude.ToString() + "," + traksend.longitude.ToString();

                        traksend.inout_status     = returnStatus;
                        traksend.battery          = Convert.ToInt32(req.batteryLevel);
                        traksend.current_datetime = req.position[countPosition].gpsDateTime.ToString();
                        traksend.online_status    = dtReUpdateDeviceCurrent.Rows[0]["OnlineStatus"].ToString();
                    }
                    else
                    {
                        traksend.latitude        = Convert.ToDouble(dtReUpdateDeviceCurrent.Rows[0]["Latitude"]);
                        traksend.longitude       = Convert.ToDouble(dtReUpdateDeviceCurrent.Rows[0]["Longitude"]);
                        traksend.thai_address    = dtReUpdateDeviceCurrent.Rows[0]["locationProvinceTh"].ToString() + "," + dtReUpdateDeviceCurrent.Rows[0]["locationDistrictTh"].ToString() + "," + dtReUpdateDeviceCurrent.Rows[0]["locationSubDistrictTh"].ToString();
                        traksend.english_address = dtReUpdateDeviceCurrent.Rows[0]["locationProvinceEn"].ToString() + "," + dtReUpdateDeviceCurrent.Rows[0]["locationDistrictEn"].ToString() + "," + dtReUpdateDeviceCurrent.Rows[0]["locationSubDistrictEn"].ToString();

                        traksend.battery          = Convert.ToInt32(req.batteryLevel);
                        traksend.inout_status     = returnStatus;
                        traksend.current_datetime = dtReUpdateDeviceCurrent.Rows[0]["Timestamp"].ToString();
                        traksend.online_status    = dtReUpdateDeviceCurrent.Rows[0]["OnlineStatus"].ToString();
                    }
                }

                //Call service :: Signal R
                bool Recalltrack = callService.CallTracking(traksend, req.imei);
                stage = 7;

                ReaponseNotic resPonse = new ReaponseNotic();
                resPonse.imei     = req.imei;
                resPonse.deviceId = req.deviceId;
                resPonse.stage    = stage;
                resPonse.userId   = req.userId;
                return(Ok(resPonse));
            }
            catch (Exception ex)
            {
                //MailCustom mailM = new MailCustom("*****@*****.**", "*****@*****.**", "gtpatchaya@005853");
                //mailM.sendMail("tamroi:error", ex.ToString());
                return(InternalServerError(ex));
            }
        }