예제 #1
0
        public static async void SendResetedPasswordEmail(seekios_dbEntities seekiosEntities
                                                          , string userEmail
                                                          , string firstName
                                                          , string lastName
                                                          , string newPassword
                                                          , int idcountryResources)
        {
            dynamic sendGridClient  = new SendGridClient(_API_KEY);
            var     contentEmailBdd = (from cr in seekiosEntities.countryResources
                                       where cr.idcountryResources == idcountryResources
                                       select cr).Take(1).First();

            var emailSendFrom = new EmailAddress(_EMAIL_HELLO);
            var emailSendTo   = new EmailAddress(userEmail);

            // add the text body
            string finalAlertContent = contentEmailBdd.resetPassordEmailContent
                                       .Replace("{0}", firstName)
                                       .Replace("{1}", lastName)
                                       .Replace("{2}", newPassword)
                                       .Replace("{3}", userEmail);

            var content  = new Content(_ACCOUNT_VERIFICATION_EMAIL_CONTENT_TYPE, finalAlertContent);
            var mail     = MailHelper.CreateSingleEmail(emailSendFrom, emailSendTo, contentEmailBdd.resetPassordEmailTitle, null, content.Value);
            var response = await sendGridClient.SendEmailAsync(mail);
        }
예제 #2
0
        /// <summary>
        /// Custom behavior when an exception is raised
        /// </summary>
        /// <param name="error">exception error</param>
        /// <param name="version">MessageVersion version (not used)</param>
        /// <param name="fault">Message fault (not used)</param>
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            // get the json if it's a DefaultCustomError
            var defaultCustomError = string.Empty;

            if (error is WebFaultException <DefaultCustomError> )
            {
                var detail = ((WebFaultException <DefaultCustomError>)error).Detail;
                defaultCustomError = string.Format("{0} - {1} - {2}", detail.ErrorCode, detail.ErrorInfo, detail.ErrorDetails);
                // bypass those errors, it's indicate a new update for android or ios is available
                if (detail.ErrorCode == "0x0102" || detail.ErrorCode == "0x0103")
                {
                    return;
                }
            }
            // log the exception in the database
            using (var seekiosEntities = new seekios_dbEntities())
            {
                var log = new logExceptionSeekios()
                {
                    data               = OperationContext.Current?.RequestContext.RequestMessage == null ? string.Empty : OperationContext.Current.RequestContext.RequestMessage.ToString(),
                    exceptionDate      = DateTime.UtcNow,
                    exceptionMessage   = error.Message,
                    defaultCustomError = defaultCustomError,
                    headers            = WebOperationContext.Current?.IncomingRequest.Headers.ToString(),
                    innerException     = error.InnerException == null ? string.Empty : GetInnersExceptionsRecursive(error.InnerException),
                    method             = WebOperationContext.Current?.IncomingRequest.Method,
                    url = OperationContext.Current?.IncomingMessageProperties.Via.PathAndQuery
                };
                seekiosEntities.logExceptionSeekios.Add(log);
                seekiosEntities.SaveChanges();
            }
        }
예제 #3
0
        public static void SendNotifications(seekios_dbEntities seekiosEntities
                                             , int idUser
                                             , string seekiosName
                                             , object parameters
                                             , string messageSent
                                             , string language
                                             , bool isNotificationWithBadge = false)
        {
            // get the platform list that the user id targets
            bool containAndroid = false;
            bool containiOS     = false;
            bool containWeb     = false;

            SeekiosService.GetPlatformsByUser(seekiosEntities, idUser, out containAndroid, out containiOS, out containWeb);

            string tag = GetTagToAdd(idUser.ToString());

            if (containAndroid)
            {
                SendNotificationWithDataToAndroid(seekiosEntities, tag, seekiosName, messageSent, parameters, language);
            }
            if (containiOS)
            {
                SendNotificationWithDataToiOS(seekiosEntities, tag, seekiosName, messageSent, parameters, isNotificationWithBadge);
            }
            if (containWeb)
            {
                SendNotificationWithDataToWeb(seekiosEntities, tag, seekiosName, messageSent, parameters);
            }
        }
예제 #4
0
        public static async void SendZoneAlertEmail(seekios_dbEntities seekiosEntities
                                                    , string emailTo
                                                    , string firstName
                                                    , string lastName
                                                    , string seekiosName
                                                    , string title
                                                    , string alertContent
                                                    , double?lat
                                                    , double?longi
                                                    , int idcountryResources)
        {
            var latitude = lat != null?lat.ToString().Replace(",", ".") : string.Empty;

            var longitude = longi != null?longi.ToString().Replace(",", ".") : string.Empty;

            dynamic sendGridClient  = new SendGridClient(_API_KEY);
            var     contentEmailBdd = (from cr in seekiosEntities.countryResources
                                       where cr.idcountryResources == idcountryResources
                                       select cr).Take(1).First();

            var emailSendFrom = new EmailAddress(_EMAIL_SENDER);
            var emailSendTo   = new EmailAddress(emailTo);

            // add the text body
            var finalAlertContent = contentEmailBdd.alertZoneEmailContent.Replace("{0}", firstName)
                                    .Replace("{1}", lastName)
                                    .Replace("{2}", seekiosName)
                                    .Replace("{3}", string.IsNullOrEmpty(title) ? string.Empty : title)
                                    .Replace("{4}", string.IsNullOrEmpty(alertContent) ? string.Empty : alertContent)
                                    .Replace("{5}", latitude).Replace("{6}", longitude);

            var content  = new Content(_ACCOUNT_VERIFICATION_EMAIL_CONTENT_TYPE, finalAlertContent);
            var mail     = MailHelper.CreateSingleEmail(emailSendFrom, emailSendTo, contentEmailBdd.alertZoneEmailTitle, null, content.Value);
            var response = await sendGridClient.SendEmailAsync(mail);
        }
예제 #5
0
        /// <summary>
        /// Custom behavior when an exception is raised
        /// </summary>
        /// <param name="error">exception error</param>
        /// <param name="version">MessageVersion version (not used)</param>
        /// <param name="fault">Message fault (not used)</param>
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            // get the json if it's a DefaultCustomError
            var defaultCustomError = string.Empty;

            if (error is WebFaultException <int> )
            {
                defaultCustomError = ((WebFaultException <int>)error).Detail.ToString();
            }
            // log the exception in the database
            using (var seekiosEntities = new seekios_dbEntities())
            {
                var log = new logExceptionSES()
                {
                    data               = OperationContext.Current?.RequestContext.RequestMessage == null ? string.Empty : OperationContext.Current.RequestContext.RequestMessage.ToString(),
                    exceptionDate      = DateTime.UtcNow,
                    exceptionMessage   = error.Message,
                    defaultCustomError = defaultCustomError,
                    headers            = WebOperationContext.Current?.IncomingRequest.Headers.ToString(),
                    innerException     = error.InnerException == null ? string.Empty : GetInnersExceptionsRecursive(error.InnerException),
                    method             = WebOperationContext.Current?.IncomingRequest.Method,
                    url = OperationContext.Current?.IncomingMessageProperties.Via.PathAndQuery
                };
                seekiosEntities.logExceptionSES.Add(log);
                seekiosEntities.SaveChanges();
            }
        }
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            HttpRequestMessageProperty httpRequest = request.Properties["httpRequest"] as HttpRequestMessageProperty;

            if (httpRequest != null)
            {
                // check if the client sent an "OPTIONS" request (necessary for the webapp)
                if (httpRequest.Method == "OPTIONS")
                {
                    // store the requested headers
                    OperationContext.Current.Extensions.Add(new PreflightDetected(httpRequest.Headers["Access-Control-Request-Headers"]));
                }
                else
                {
                    var methodName = OperationContext.Current.IncomingMessageProperties["HttpOperationName"].ToString();
                    var requestUrl = OperationContext.Current.IncomingMessageProperties.Via.PathAndQuery;

                    // methods allow to pass (without authentification)
                    if (_lsNotRestrictedMethods.Contains(methodName))
                    {
                        return(0x00);
                    }

                    // the user must have a valid token to access to the resource
                    var token = httpRequest.Headers["token"];
                    if (!string.IsNullOrEmpty(token) && token.Length == 36)
                    {
                        using (seekios_dbEntities seekiosEntities = new seekios_dbEntities())
                        {
                            var tokenFromBdd = seekiosEntities.token.FirstOrDefault(t => t.authToken == token);
                            if (tokenFromBdd == null)
                            {
                                SeekiosService.Telemetry.TrackEvent("Unauthorized access : No Token");
                                throw new WebFaultException <DefaultCustomError>(new DefaultCustomError("0x0000"
                                                                                                        , "unauthorized access", "no token"), HttpStatusCode.Unauthorized);
                            }
                            if (tokenFromBdd.dateExpiresToken < DateTime.UtcNow)
                            {
                                SeekiosService.Telemetry.TrackEvent("Unauthorized access : Token Expired");
                                throw new WebFaultException <DefaultCustomError>(new DefaultCustomError("0x0001"
                                                                                                        , "unauthorized access", "token has expired"), HttpStatusCode.Unauthorized);
                            }
                        }
                    }
                    else
                    {
                        SeekiosService.Telemetry.TrackEvent("Unauthorized access : Invalid Format Token");
                        throw new WebFaultException <DefaultCustomError>(new DefaultCustomError("0x0002"
                                                                                                , "unauthorized access", "no token in the HTTP header"), HttpStatusCode.Unauthorized);
                    }
                }
            }
            return(null);
        }
예제 #7
0
        public static async void SendAlertSOSEmail(seekios_dbEntities seekiosEntities
                                                   , IEnumerable <string> emailsTo
                                                   , string firstName
                                                   , string lastName
                                                   , string seekiosName
                                                   , double?lat
                                                   , double?longi
                                                   , string alertContent
                                                   , int idcountryResources
                                                   , bool isGPS = true)
        {
            var latitude = lat != null?lat.ToString().Replace(",", ".") : string.Empty;

            var longitude = longi != null?longi.ToString().Replace(",", ".") : string.Empty;

            dynamic sendGridClient  = new SendGridClient(_API_KEY);
            var     contentEmailBdd = (from cr in seekiosEntities.countryResources
                                       where cr.idcountryResources == idcountryResources
                                       select cr).Take(1).First();

            var emailContent  = string.IsNullOrEmpty(alertContent) ? contentEmailBdd.alertSOSEmailContent : contentEmailBdd.alertSOSEmailWithMsgContent;
            var emailSendFrom = new EmailAddress(_EMAIL_SENDER);
            var emailSendTo   = new List <EmailAddress>();

            foreach (var email in emailsTo)
            {
                emailSendTo.Add(new EmailAddress()
                {
                    Email = email
                });
            }

            // add the text body
            string finalAlertContent = string.IsNullOrEmpty(alertContent) ?
                                       emailContent.Replace("{0}", firstName)
                                       .Replace("{1}", lastName)
                                       .Replace("{2}", seekiosName)
                                       .Replace("{3}", isGPS ? ResourcesHelper.GetLocalizedString("GPS", idcountryResources) : ResourcesHelper.GetLocalizedString("ApproxPosition", idcountryResources))
                                       .Replace("{4}", latitude)
                                       .Replace("{5}", longitude)
                : emailContent.Replace("{0}", firstName)
                                       .Replace("{1}", lastName)
                                       .Replace("{2}", seekiosName)
                                       .Replace("{3}", alertContent)
                                       .Replace("{4}", isGPS ? ResourcesHelper.GetLocalizedString("GPS", idcountryResources) : ResourcesHelper.GetLocalizedString("ApproxPosition", idcountryResources))
                                       .Replace("{5}", latitude)
                                       .Replace("{6}", longitude);

            var content  = new Content(_ACCOUNT_VERIFICATION_EMAIL_CONTENT_TYPE, finalAlertContent);
            var mail     = MailHelper.CreateSingleEmailToMultipleRecipients(emailSendFrom, emailSendTo, contentEmailBdd.alertSOSEmailTitle, null, content.Value);
            var response = await sendGridClient.SendEmailAsync(mail);
        }
        /// <summary>
        /// Check if the user remains credits
        /// </summary>
        /// <param name="seekiosEntities">the database context</param>
        /// <param name="user">user object</param>
        /// <param name="minThreshold">the minimum to compare</param>
        /// <returns>true : the user still have credits | false : the user don't have enough credits</returns>
        public static bool UserCanAffordAction(seekios_dbEntities seekiosEntities
                                               , user user
                                               , int minThreshold = 0)
        {
            if (user == null)
            {
                return(false);
            }
            int creditsOfferedLeft = (from s in seekiosEntities.seekios
                                      where s.user_iduser == user.iduser
                                      join sp in seekiosEntities.seekiosProduction on s.idseekios equals sp.idseekiosProduction
                                      select sp.freeCredit).Sum();
            int totalCredits = (user.remainingRequest != null ? user.remainingRequest.Value : 0) + creditsOfferedLeft;

            return(totalCredits > minThreshold);
        }
예제 #9
0
        public static bool SendNotificationWithDataToAndroid(seekios_dbEntities seekiosEntities
                                                             , string tag
                                                             , string seekiosName
                                                             , string methodName
                                                             , object parameters
                                                             , string language)
        {
            var request = CreateHttpRequest(PlatformEnum.Android);
            var obj     = new
            {
                app_id                = ONESIGNAL_PRIVATE_KEY_ANDROID,
                contents              = new { en = methodName },
                headings              = new { en = seekiosName },
                filters               = new object[] { new { field = "tag", key = tag, relation = "exists" } },//filters,
                data                  = parameters,
                android_group         = _isRefreshingCredits ? "2" : "1",
                android_group_message = new { en = ResourcesHelper.GetLocalizedString("NotifCount", language) },
            };
            var param           = new JavaScriptSerializer().Serialize(obj);
            var byteArray       = Encoding.UTF8.GetBytes(param);
            var responseContent = string.Empty;
            var exception       = string.Empty;
            var returnCode      = true;

            try
            {
                using (var writer = request.GetRequestStream())
                {
                    writer.Write(byteArray, 0, byteArray.Length);
                }

                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseContent = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                exception  = ex.Message;
                returnCode = !returnCode;
            }
            LogOneSignalRequest(seekiosEntities, tag, seekiosName, methodName, exception, responseContent, returnCode);
            return(returnCode);
        }
예제 #10
0
        public static bool SendNotificationWithDataToWeb(seekios_dbEntities seekiosEntities
                                                         , string tag
                                                         , string seekiosName
                                                         , string methodName
                                                         , object parameters)
        {
            var request    = CreateHttpRequest(PlatformEnum.Web);
            var serializer = new JavaScriptSerializer();
            var obj        = new
            {
                app_id   = ONESIGNAL_PRIVATE_KEY_WEB,
                contents = new { en = methodName },
                headings = new { en = seekiosName },
                filters  = new object[] { new { field = "tag", key = tag, relation = "exists" } },
                data     = parameters,
            };
            var param           = serializer.Serialize(obj);
            var byteArray       = Encoding.UTF8.GetBytes(param);
            var responseContent = string.Empty;
            var exception       = string.Empty;
            var returnCode      = true;

            try
            {
                using (var writer = request.GetRequestStream())
                {
                    writer.Write(byteArray, 0, byteArray.Length);
                }

                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseContent = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                exception  = ex.Message + " | " + new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                returnCode = !returnCode;
            }
            LogOneSignalRequest(seekiosEntities, tag, seekiosName, methodName, exception, responseContent, returnCode);
            return(returnCode);
        }
예제 #11
0
        /// <summary>
        /// Return the langage of a user depends on the langage device associate
        /// </summary>
        /// <param name="seekiosEntities">the database context</param>
        /// <param name="idUser">id user</param>
        public static string GetPreferredLanguage(seekios_dbEntities seekiosEntities, int idUser)
        {
            var deviceList = (from d in seekiosEntities.device
                              where d.user_iduser == idUser
                              orderby d.lastUseDate descending
                              select d).ToList();

            if (deviceList?.Count > 0)
            {
                foreach (var device in deviceList)
                {
                    if (device.plateform.Contains("iOS") || device.plateform.Contains("Android"))
                    {
                        return(device.countryCode);
                    }
                }
            }
            return("en");
        }
예제 #12
0
 /// <summary>
 /// Trace in the table LogVodafoneAndOnesignal
 /// </summary>
 private static void LogOneSignalRequest(seekios_dbEntities seekiosEntities
                                         , string tag
                                         , string seekiosName
                                         , string methodName
                                         , string exception
                                         , string responseContent
                                         , bool returnCode)
 {
     seekiosEntities.logVodafoneAndOnesignal.Add(new logVodafoneAndOnesignal()
     {
         dateBegin = DateTime.UtcNow,
         apiUser   = "******" + ONESIGNAL_PRIVATE_KEY_ANDROID,
         imsi      = methodName + "/" + seekiosName,
         majorCode = responseContent,
         minorCode = exception.Length < 50 ? exception : exception.Substring(0, 50),
         msgRef    = tag,
         outcome   = returnCode ? "ok" : "bad",
         dateEnd   = DateTime.UtcNow
     });
     seekiosEntities.SaveChanges();
 }
        /// <summary>
        /// Return true if the seekios has enough credit to do the operation
        /// </summary>
        /// <param name="uidSeekios">seekios unique identifier</param>
        /// <param name="minThreshold">the minimum to have</param>
        public static bool SeekiosCanAffordAction(seekios_dbEntities seekiosEntities
                                                  , string uidSeekios
                                                  , int minThreshold = 0)
        {
            var user = (from sp in seekiosEntities.seekiosProduction
                        where sp.uidSeekios == uidSeekios
                        join s in seekiosEntities.seekios on sp.idseekiosProduction equals s.idseekios
                        join u in seekiosEntities.user on s.user_iduser equals u.iduser
                        select u).Take(1).FirstOrDefault();

            if (user == null)
            {
                return(false);
            }
            int creditsOfferedLeft = (from s in seekiosEntities.seekios
                                      where s.user_iduser == user.iduser
                                      join sp in seekiosEntities.seekiosProduction on s.idseekios equals sp.idseekiosProduction
                                      select sp.freeCredit).Sum();
            int totalCredits = (user.remainingRequest != null ? user.remainingRequest.Value : 0) + creditsOfferedLeft;

            return(totalCredits > minThreshold);
        }
        /// <summary>
        /// Add operation to the context database
        /// </summary>
        /// <param name="seekiosEntities">the context database</param>
        /// <param name="now">begining time</param>
        /// <param name="idMode">id mode</param>
        /// <param name="idSeekios">id seekios</param>
        /// <param name="idUser">id user</param>
        /// <param name="operationTypeEnum">the operation type</param>
        /// <param name="amount">the amount to debit</param>
        /// <param name="isOnSeekios">is the transaction concern a seekios</param>
        public static void AddOperationInDatabase(seekios_dbEntities seekiosEntities
                                                  , DateTime now
                                                  , int?idMode
                                                  , int idSeekios
                                                  , int idUser
                                                  , OperationType operationTypeEnum
                                                  , int amount
                                                  , bool isOnSeekios)
        {
            var operationDb = new operation
            {
                dateBeginOperation            = now,
                mode_idmode                   = idMode,
                seekios_idseekios             = idSeekios,
                user_iduser                   = idUser,
                operationType_idoperationType = (int)operationTypeEnum,
                amount           = amount,
                isOnSeekios      = isOnSeekios,
                dateEndOperation = DateTime.UtcNow
            };

            seekiosEntities.operation.Add(operationDb);
        }
예제 #15
0
        public static async void SendMoveAlertEmail(seekios_dbEntities seekiosEntities
                                                    , IEnumerable <string> emailsTo
                                                    , string firstName
                                                    , string lastName
                                                    , string seekiosName
                                                    , string title
                                                    , string alertContent
                                                    , int idcountryResources)
        {
            dynamic sendGridClient  = new SendGridClient(_API_KEY);
            var     contentEmailBdd = (from cr in seekiosEntities.countryResources
                                       where cr.idcountryResources == idcountryResources
                                       select cr).Take(1).First();

            var emailSendFrom = new EmailAddress(_EMAIL_SENDER);
            var emailSendTo   = new List <EmailAddress>();

            foreach (var email in emailsTo)
            {
                emailSendTo.Add(new EmailAddress()
                {
                    Email = email
                });
            }

            // add the text body
            var finalAlertContent = contentEmailBdd.alertMoveEmailContent
                                    .Replace("{0}", firstName)
                                    .Replace("{1}", lastName)
                                    .Replace("{2}", seekiosName)
                                    .Replace("{3}", string.IsNullOrEmpty(title) ? string.Empty : title)
                                    .Replace("{4}", string.IsNullOrEmpty(alertContent) ? string.Empty : alertContent);

            var content  = new Content(_ACCOUNT_VERIFICATION_EMAIL_CONTENT_TYPE, finalAlertContent);
            var mail     = MailHelper.CreateSingleEmailToMultipleRecipients(emailSendFrom, emailSendTo, contentEmailBdd.alertMoveEmailTitle, null, content.Value);
            var response = await sendGridClient.SendEmailAsync(mail);
        }
예제 #16
0
        public static bool SendNotificationWithDataToiOS(seekios_dbEntities seekiosEntities
                                                         , string tag
                                                         , string seekiosName
                                                         , string methodName
                                                         , object parameters
                                                         , bool isNotificationWithBadge = true)
        {
            var request    = CreateHttpRequest(PlatformEnum.iOS);
            var serializer = new JavaScriptSerializer();
            var obj        = new object();

            if (isNotificationWithBadge)
            {
                obj = new
                {
                    app_id         = ONESIGNAL_PRIVATE_KEY_IOS,
                    contents       = new { en = methodName },
                    headings       = new { en = seekiosName },
                    filters        = new object[] { new { field = "tag", key = tag, relation = "exists" } },//filters,
                    data           = parameters,
                    collapse_id    = new Guid().ToString(),
                    ios_badgeType  = "Increase",
                    ios_badgeCount = 1,
                    //ios_sound = "nil",
                    content_available = 1
                };
            }
            else
            {
                obj = new
                {
                    app_id      = ONESIGNAL_PRIVATE_KEY_IOS,
                    contents    = new { en = methodName },
                    headings    = new { en = seekiosName },
                    filters     = new object[] { new { field = "tag", key = tag, relation = "exists" } },
                    data        = parameters,
                    collapse_id = new Guid().ToString(),
                    //ios_sound = "nil",
                    content_available = 1
                };
            }
            var param           = serializer.Serialize(obj);
            var byteArray       = Encoding.UTF8.GetBytes(param);
            var responseContent = string.Empty;
            var exception       = string.Empty;
            var returnCode      = true;

            try
            {
                using (var writer = request.GetRequestStream())
                {
                    writer.Write(byteArray, 0, byteArray.Length);
                }

                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseContent = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                exception  = ex.Message + " | " + new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                returnCode = !returnCode;
            }
            LogOneSignalRequest(seekiosEntities, tag, seekiosName, methodName, exception, responseContent, returnCode);
            return(returnCode);
        }
        /// <summary>
        /// Pay the amount of the operation
        /// Debit seekios free credit or user credit or both
        /// </summary>
        /// <param name="seekiosEntities">the database context</param>
        /// <param name="operationTypeEnum">the operation type</param>
        /// <param name="idUser">id user</param>
        /// <param name="idMode">id mode</param>
        /// <param name="idSeekios">id seekios</param>
        /// <param name="minUserCreditThreshold">the minimum left on the account</param>
        /// <returns>return 1 if it's working</returns>
        public static int PayOperationCost(seekios_dbEntities seekiosEntities
                                           , OperationType operationTypeEnum
                                           , int idUser
                                           , int?idMode
                                           , int idSeekios
                                           , int minUserCreditThreshold = 0)
        {
            //bool alreadyCommit = false;
            //using (DbContextTransaction dbContextTransaction = seekiosEntities.Database.BeginTransaction(System.Data.IsolationLevel.Snapshot))
            //{
            try
            {
                // Get user
                var userDb = (from u in seekiosEntities.user
                              where u.iduser == idUser
                              select u).FirstOrDefault();
                if (userDb == null)
                {
                    return(-1);
                }

                // Retrieves all seekioses for the current user, order by freecredits...
                var seekiosAndSeekiosProductionBdd = (from s in seekiosEntities.seekiosAndSeekiosProduction
                                                      where s.user_iduser == idUser
                                                      orderby s.freeCredit descending
                                                      select s).ToArray();
                int sumOfseekiosFreeCredits = seekiosAndSeekiosProductionBdd.Sum(s => s.freeCredit);
                int amountToPay             = operationTypeEnum.GetAmount();
                int sumOfTotalCredit        = (!userDb.remainingRequest.HasValue ? 0 : userDb.remainingRequest.Value) + sumOfseekiosFreeCredits + amountToPay;
                var uidSeekiosToNotify      = string.Empty;

                // Can not pay the operation, not enough credit
                if (sumOfTotalCredit < minUserCreditThreshold)
                {
                    // Delete the mode
                    if (idMode.HasValue)
                    {
                        // WARNING : Hotfix, the mobile app should display the tracking is not available for the seekios because the seekios will receive M01 (wait state)
                        //var result = new System.Data.Entity.Core.Objects.ObjectParameter("Result", 0);
                        //seekiosEntities.DeleteModeById(idMode, result);
                        SeekiosService.PrepareInstructionForNewMode(seekiosEntities
                                                                    , null
                                                                    , (from s in seekiosEntities.seekios where s.idseekios == idSeekios select s).First());
                    }
                    return(-2);
                }

                // Pay the operation with free credit
                // Take the seekios with the value freeCredit more than the amount requested to pay
                var now             = DateTime.UtcNow;
                var oneSeekiosToPay = seekiosAndSeekiosProductionBdd.FirstOrDefault(f => f.freeCredit > -amountToPay);
                if (oneSeekiosToPay != null)
                {
                    // Pay the operation (decrement the freeCredit value)
                    seekiosEntities.UpdateSeekiosFreeCreditById(oneSeekiosToPay.idseekios, amountToPay);
                    AddOperationInDatabase(seekiosEntities, now, idMode, idSeekios, idUser, operationTypeEnum, amountToPay, true);
                    uidSeekiosToNotify = oneSeekiosToPay.uidSeekios;
                    amountToPay        = 0;
                }
                else
                {
                    // Not enought on one seekios but more than one seekios
                    var moreThanOneSeekiosToPay = seekiosAndSeekiosProductionBdd.Where(w => w.freeCredit > 0);
                    foreach (var seekiosToPay in moreThanOneSeekiosToPay)
                    {
                        if (amountToPay + seekiosToPay.freeCredit >= 0)
                        {
                            seekiosEntities.UpdateSeekiosFreeCreditById(seekiosToPay.idseekios, amountToPay);
                            AddOperationInDatabase(seekiosEntities, now, idMode, idSeekios, idUser, operationTypeEnum, amountToPay, true);
                            uidSeekiosToNotify = seekiosToPay.uidSeekios;
                            amountToPay        = 0;
                            break;
                        }
                        else
                        {
                            seekiosEntities.UpdateSeekiosFreeCreditById(seekiosToPay.idseekios, -seekiosToPay.freeCredit);
                            AddOperationInDatabase(seekiosEntities, now, idMode, idSeekios, idUser, operationTypeEnum, -seekiosToPay.freeCredit, true);
                            amountToPay += seekiosToPay.freeCredit;
                        }
                    }
                }
                int userDebit    = 0;
                int seekiosDebit = operationTypeEnum.GetAmount() - amountToPay;

                // The operation is not finish to pay, we need to use the user credit
                if (amountToPay < 0)
                {
                    userDb.remainingRequest += amountToPay;
                    AddOperationInDatabase(seekiosEntities, now, idMode, idSeekios, idUser, operationTypeEnum, amountToPay, false);
                    userDebit = amountToPay;
                }

                // Save changes and commit
                seekiosEntities.SaveChanges();
                //dbContextTransaction.Commit();
                //alreadyCommit = true;

                // Broadcast user devices
                SignalRHelper.BroadcastUser(HubProxyEnum.CreditsHub
                                            , SignalRHelper.METHOD_REFRESH_CREDIT
                                            , new object[]
                {
                    userDb.iduser,
                    uidSeekiosToNotify,
                    userDebit,
                    seekiosDebit,
                    now
                });
                return(1);
            }
            catch (Exception ex)
            {
                //if (!alreadyCommit) dbContextTransaction.Rollback();
                throw ex;
            }
            //finally
            //{
            //    dbContextTransaction.Dispose();
            //}
            //}
        }
        /// <summary>
        /// Give credits to the user account
        /// </summary>
        /// <param name="seekiosEntities">the database context</param>
        /// <param name="userBdd">user from the database</param>
        /// <param name="boughtPackBdd">the credit pack from the database</param>
        /// <param name="purchase">the purchase bought by the user</param>
        /// <param name="timeOfPayment">datetime of the payment</param>
        /// <returns>return 1 if it's working</returns>
        public static int GiveCreditsToUser(seekios_dbEntities seekiosEntities /*, bool isSubscription*/
                                            , user userBdd
                                            , packCreditAndOperationType boughtPackBdd
                                            , PurchaseDTO purchase
                                            , DateTime?timeOfPayment)
        {
            //using (DbContextTransaction dbContextTransaction = seekiosEntities.Database.BeginTransaction(System.Data.IsolationLevel.Snapshot))
            //{
            try
            {
                // useless : subscription
                //// if subscription, have to seek for the operation type for subscription, we also could do a +x given the id of each pack, but it's more dirty... (+add index for operationName)
                //if (isSubscription)
                //{
                //    string actualPackId = boughtPack.operationName + (isSubscription ? "Subscription" : "");
                //    var opType = (from o in seekiosEntities.operationType where o.operationName == actualPackId select o).Take(1).FirstOrDefault();
                //    if (opType == null) return 7000;//le pack est introuvable...
                //}

                // Create the operation transaction
                var dateTransactionNow = timeOfPayment.HasValue ? timeOfPayment.Value : DateTime.UtcNow;
                var purchaseDb         = new operationFromStore()
                {
                    creditsPurchased = boughtPackBdd.rewarding,//boughtPack.rewarding, //on va enlever ca ?
                    idPack           = boughtPackBdd.idcreditPack,
                    dateTransaction  = dateTransactionNow,
                    idUser           = purchase.IdUser,
                    isPackPremium    = false, //isSubscription,
                    refStore         = purchase.InnerData,
                    status           = "OK",  // TODO : insertPurchase when user clicks on buy, put status Pending and when validated put OK. else put Canceled.
                    versionApp       = purchase.VersionApp,
                };
                // Create an operation
                var operationToAdd = new operation()
                {
                    dateBeginOperation            = dateTransactionNow,
                    dateEndOperation              = dateTransactionNow,
                    mode_idmode                   = null,
                    seekios_idseekios             = null,
                    user_iduser                   = purchase.IdUser,
                    operationType_idoperationType = boughtPackBdd.idoperationType,
                    amount      = boughtPackBdd.amount, // not that uselful
                    isOnSeekios = false,
                };
                // Add credit to user account
                userBdd.remainingRequest += boughtPackBdd.amount;
                // Add operation and and operation transaction
                seekiosEntities.operation.Add(operationToAdd);
                seekiosEntities.operationFromStore.Add(purchaseDb);
                seekiosEntities.SaveChanges();
                //dbContextTransaction.Commit();
            }
            catch (Exception ex)
            {
                //dbContextTransaction.Rollback();
                throw ex;
            }
            finally
            {
                //dbContextTransaction.Dispose();
                //seekiosEntities.Dispose();
            }
            //}
            return(1);
        }