public void UpdateSMSForSubscription_2ContextsChangePriceTwiceNoRemainingSMS_PriceHasCorrectValueAtTheEnd()
        {
            var wpID = "19802294808";//Wallmart only sms
             var price = "0.1";

             var wp = context.WorkingPoints.Find(wpID);
             var sd1 = wp.Users.FirstOrDefault().Company.SubscriptionDetail;
             //make sure that remaining sms is 0 so that we nibble through our spent amount
             sd1.RemainingSMS = 0;
             context.SaveChanges();
             context.Entry(sd1).Reload();
             smsfeedbackEntities altContext = new smsfeedbackEntities();
             var wp2 = altContext.WorkingPoints.Find(wpID);
             var sd2 = wp2.Users.FirstOrDefault().Company.SubscriptionDetail;
             //make sure that we are starting from the same point
             var sd1BeforeTimestamp = sd1.TimeStamp;
             var sd2BeforeTimestamp = sd2.TimeStamp;
             Assert.AreEqual(sd1BeforeTimestamp, sd2BeforeTimestamp, "The initial timestamp should be the same as we start from the same starting point");
             var initialSA = sd1.SpentThisMonth;
             mEFinter.UpdateSMSForSubscription(price, sd1, context);
             context.Entry(sd1).Reload();
             var sd1Timestamp = sd1.TimeStamp;
             mEFinter.UpdateSMSForSubscription(price, sd2, altContext);
             var sd2Timestamp = sd2.TimeStamp;

             Assert.AreNotEqual(sd2Timestamp, sd1Timestamp,"The subscription should have been modified twice (timestamp wise" );

             var finalSA = sd2.SpentThisMonth;
             var expectedPrice = initialSA + 2 * Decimal.Parse(price, CultureInfo.InvariantCulture);
             Assert.AreEqual(expectedPrice, finalSA, "The price should have been modified twice");
             altContext.Dispose();
        }
        public ActionResult GetEmailMessageForm(string emailText, string convID)
        {
            ViewResult result = null;
               try
               {

              ViewData["emailText"] = emailText;
              string[] fromTo = ConversationUtilities.GetFromAndToFromConversationID(convID);
              smsfeedbackEntities lContextPerRequest = new smsfeedbackEntities();
              var lWpTelNoOrShortID = fromTo[1];
              var lEfInteraction = new EFInteraction();
              var wpName = lEfInteraction.GetNameForWorkingPoint(lWpTelNoOrShortID, lContextPerRequest);
              if (String.IsNullOrEmpty(wpName))
              {
                 wpName = lWpTelNoOrShortID;
              }
              ViewData["emailSubject"] = Resources.Global.sendEmailPrefixSubject + fromTo[0] + Resources.Global.sendEmailConjuctionSubject + wpName + "]";
              result = View();
               }
               catch (Exception ex)
               {
              loggerEmailForm.Error("GetEmailMessageForm", ex);
               }
               return result;
        }
        public IEnumerable<SmsMessage> GetConversationsForNumbers(
                                                                  bool onlyFavorites, 
                                                                  string[] tags,
                                                                  string[] workingPointsNumbers,
                                                                  DateTime? startDate,
                                                                  DateTime? endDate,
                                                                  bool onlyUnread,
                                                                  int skip,
                                                                  int top,
                                                                  DateTime? lastUpdate,
                                                                  String userName,
                                                                  bool performUpdateFromExternalSources,
                                                                  smsfeedbackEntities dbContext)
        {
            //the convention is that if workingPoints number is empty then we retrieve all the conversations
             if (workingPointsNumbers == null)
             {//we have to get all the working points
            //workingPointsNumbers = (from wp in mEFRep.GetWorkingPointsPerUser(userName, dbContext) select wp).SelectMany(w=> new []{ w.TelNumber, w.ShortID }).ToArray();
            workingPointsNumbers = (from wp in mEFRep.GetWorkingPointsPerUser(userName, dbContext) select wp.TelNumber).ToArray();
             }

             try
             {
            //in our db we have the conversations
            //we could have additional conversations (which have not been yet read) in Twilio
            //A possible optimization would be that for favourites we don't update with the twilio conversations (as the favourites is our own concept)
            //for Unread we have to retrieve data from Twilio as new twilio conversations are by default unread

               //we may have the following scenario - we get ask for first 10 records, skip 0
               //in our db we have only "old" conversations, so the twilio db returns 40 records
               //we then ask for "more conversations"- next 10, skip 10 - this will end up being applied on the twilio data
               //it is inefficient to retrieve all records from our db, and to merge them afterwards (not to mention very slow)

               //TODO check if we have access to the given numbers to avoid a security breach
               //first update our db with the latest from twilio (nexmo) then do our conditional select
               IEnumerable<SmsMessage> efConversationsForNumbers = mEFRep.GetConversationsForNumbers(onlyFavorites, tags, workingPointsNumbers,startDate,endDate,onlyUnread, skip, top, lastUpdate, userName,dbContext);
               return efConversationsForNumbers;
             }
             catch (Exception ex)
             {
            logger.Error("Error occurred", ex);
             }
             return null;
        }
 public ActionResult Index()
 {
     //based on store ID we should retrieve the "long description"
      smsfeedbackEntities ent = new smsfeedbackEntities();
      var wps = from w in ent.WorkingPoints where w.ShortID == mStore select w;
      if (wps.Count() == 1)
      {
     var wp = wps.First();
     String language = wp.Language;
     Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);
     var desc = wp.Name;
     ViewBag.Store = desc;
     ViewBag.Message = wp.WelcomeMessage;
     //the format of the db language should be en-US or ro-RO (general-LOCAL)
     ViewBag.Language = language.Split('-')[0];
     ViewBag.ComponentLocation = mStore;
     return View();
      }
      //else we should return an error page
      return RedirectToAction("StoreNotFound");
 }
 public IEnumerable<ConvTag> GetTagsForConversation(string convID, smsfeedbackEntities dbContext)
 {
     return mEFRep.GetTagsForConversation(convID,dbContext);
 }
 public IEnumerable<SmsMessage> GetSupportConversationsForWorkingPoints(
                                                           string userName,
                                                           string[] workingPointsNumbers,
                                                           int skip,
                                                           int top,
                                                           smsfeedbackEntities dbContext)
 {
     return mEFRep.GetSupportConversationsForWorkingPoints(userName, workingPointsNumbers, skip, top, dbContext);
 }
        public IEnumerable<SmsMessage> GetConversationsForNumbers(
                                                                bool onlyFavorites,
                                                                string[] tags,
                                                                string[] workingPointsNumbers,
                                                                DateTime? startDate,
                                                                DateTime? endDate,
                                                                bool onlyUnread,
                                                                int skip,
                                                                int top,
                                                                DateTime? lastUpdate,
                                                                String userName,
                                                                smsfeedbackEntities dbContext)
        {
            //TODO we could have a performance penalty for not applying top and skip
             logger.Info("Call made");
             IEnumerable<SmsMessage> results = null;
             foreach (var wp in workingPointsNumbers)
             {
            var conversations = GetConversationsForNumber(onlyFavorites, tags, wp, startDate, endDate,onlyUnread, skip, top, lastUpdate, userName,dbContext);
            if (conversations != null)
            {
               if (results == null) results = conversations;
               //merge all the results
               results = results.Union(conversations);
            }

             }
             //order then descending by TimeReceived
             if (results != null)
             {
            results = results.OrderByDescending(record => record.TimeReceived);
            logger.InfoFormat("Records returned from EF db: {0}", results != null ? results.Count() : 0);
            return results.Skip(skip).Take(top);
             }
             else
             {
            logger.Info("No records for numbers returned from db");
            return null;
             }
        }
 private void UpdateConversationsFromTwilio(string[] workingPointsNumbers, DateTime? lastUpdate, String userName, smsfeedbackEntities dbContext)
 {
     Dictionary<string, SmsMessage> lastConversations = mEFRep.GetLatestConversationForNumbers(workingPointsNumbers, userName, dbContext);
      foreach (var item in lastConversations)
      {
     if (item.Value != null)
     {
        //unfortunatelly twilio is rather imprecisse (YYYY-MM-DD) -> we could/will get the same messages twice
        //we'll tackle this in the addupdate logic
        var lastConversationTime = item.Value.TimeReceived;
        IEnumerable<SmsMessage> twilioConversationsForNumbers = mTwilioRep.GetConversationsForNumber( item.Key, lastConversationTime, userName);
        //we need to add the twilio conversations to our conversations list
        AddTwilioConversationsToDb(twilioConversationsForNumbers, dbContext);
        //TODO - remove the break
        break; //temporary - until we have real data
        //now we can select from our db the latest conversations
     }
     else
     {
        IEnumerable<SmsMessage> twilioConversationsForNumbers = mTwilioRep.GetConversationsForNumber(item.Key, lastUpdate, userName);
        AddTwilioConversationsToDb(twilioConversationsForNumbers, dbContext);
     }
      }
 }
 internal System.Collections.Generic.IEnumerable<ConvTag> GetSpecialTags(string userId, smsfeedbackEntities dbContext)
 {
     return mEFRep.GetSpecialTags(userId,dbContext);
 }
 public MessageStatus SendMessage(string fromWp, string to, string message, smsfeedbackEntities dbContext)
 {
     //get the provider and send the message using the correct network
      var wp = dbContext.WorkingPoints.Find(fromWp);
      if (wp != null)
      {
     //DA first check if we have enough credit
     var usr = wp.Users.FirstOrDefault();//we assume all the users belong to the same company - so any user would do
     if (usr != null)
     {
        var company = usr.Company;
        /**
         * We can send an SMS if we either:
         * 1. have remaining SMS is our subscription
         * 2. have credit for sending 1 more SMS
        */
        var canSend = company.SubscriptionDetail.CanSendSMS;
        if (canSend)
        {
           MessageStatus response;
           switch (wp.Provider)
           {
              case TWILIO_PROVIDER:
                 logger.Info("Sending message via twilio");
                 return mTwilioRep.SendMessage(fromWp, to, message);
                 break;
              case NEXMO_PROVIDER:
                 logger.Info("Sending message via nexmo");
                 return mNexmoRep.SendMessage(fromWp, to, message);
              default:
                 logger.ErrorFormat("Invalid provider for number: {0}", fromWp);
                 break;
           }
           return null;
        }
        else
        {
           //we either have no remaining sms, no extra credit and has reached his spending limit
           return null;
        }
     }
     else
     {
        //something went wrong with finding the user
        return null;
     }
      }
      else
      {
     logger.ErrorFormat("Number: {0} is not a valid working point", fromWp);
     return null;
      }
 }
 internal System.Collections.Generic.IEnumerable<ConvTag> GetSpecialTags(String userId,smsfeedbackEntities dbContext)
 {
     logger.Info("Call made");
     var companies = from user in dbContext.Users where user.UserName == userId select user.Company;
     if (companies.Count() == 1)
     {
        SmsFeedback_EFModels.Company company = companies.First();
        var tagsList = from tag in company.Tags select
                       (from tagType in tag.TagTagTypes select
                            new ConvTag() {
                                CompanyName = company.Name,
                                Name = tag.Name,
                                Description = tag.Description,
                                TagType = tagType.TagType.Type,
                                IsDefault = tagType.IsDefault
                            });
        IEnumerable<ConvTag> result = tagsList.SelectMany(l => l);
        return result;
     }
     else
     {
        return null;
     }
 }
 public int NrOfUnreadConversations(string userName, smsfeedbackEntities dbContext)
 {
     var unreadConvs = from u in dbContext.Users where u.UserName == userName select (from wp in u.WorkingPoints select (from c in wp.Conversations where c.Read == false  select c.Read));
      var nrUnread = 0;
      foreach (var unreads in unreadConvs.First())
      {
     nrUnread += unreads.Count();
      }
      return nrUnread;
 }
 public IEnumerable<WorkingPoint> GetWorkingPointsPerUser(string userName, smsfeedbackEntities dbContext)
 {
     //get logged in user
      //var userID = new Guid("fca4bd52-b855-440d-9611-312708b14c2f");
      var workingPoints = from u in dbContext.Users where u.UserName == userName select (from wp in u.WorkingPoints select new WorkingPoint() {
     TelNumber = wp.TelNumber,
     Name = wp.Name,
     Description = wp.Description,
     NrOfSentSmsThisMonth = wp.SentSms,
     MaxNrOfSmsToSendPerMonth =wp.MaxNrOfSmsToSend,
     ShortID = wp.ShortID,
     XMPPsuffix= wp.XMPPsuffix,
     WelcomeMessage = wp.WelcomeMessage
      });
      if (workingPoints.Count() >= 0)
     return workingPoints.First();
      else return null;
 }
 public System.Collections.Generic.IEnumerable<ConvTag> GetTagsForConversation(string convID, smsfeedbackEntities dbContext)
 {
     logger.Info("Call made");
      var conv = dbContext.Conversations.Find(convID);
      if (conv != null)
      {
     return from convTag in conv.ConversationTags select new ConvTag() { CompanyName = convTag.Tag.CompanyName, Name = convTag.Tag.Name, Description = convTag.Tag.Description };
      }
      else
      {
     return null;
      }
 }
 public IEnumerable<SmsMessage> GetConversationsForNumber(
                                                        bool onlyFavorites,
                                                        string[] tags,
                                                        string workingPointsNumber,
                                                        DateTime? startDate,
                                                        DateTime? endDate,
                                                        bool onlyUnread,
                                                        int skip,
                                                        int top,
                                                        DateTime? lastUpdate,
                                                        String userName, 
                                                        smsfeedbackEntities dbContext)
 {
     //here we don't aplly skip or load, as they will be applied on the merged list
      logger.Info("Call made");
      //the strongest filter first
      //1.favourites
      //2.startDate
      //3.endDate
      //4.tags
      //since we only give as input the dd/mm/yy we make sure that the comparison date is the lowest/highest possible
      DateTime? earliestStartDate = null;
      DateTime? latestEndDate = null;
      if (startDate.HasValue)
      {
     var oldVal = startDate.Value;
     earliestStartDate = new DateTime(oldVal.Year, oldVal.Month, oldVal.Day, 0, 0, 0);
      }
      if (endDate.HasValue)
      {
     var oldVal = endDate.Value;
     latestEndDate = new DateTime(oldVal.Year, oldVal.Month, oldVal.Day, 23, 59, 59);
      }
      IQueryable<IEnumerable<SmsMessage>> convs = null;
      string consistentWP = ConversationUtilities.CleanUpPhoneNumber(workingPointsNumber);
      if (tags != null && tags.Count() != 0)
      {
     //TODO DA could optimize to use FIND for working points
     convs = from wp in dbContext.WorkingPoints
             where (wp.TelNumber == consistentWP)
             select (from c in wp.Conversations
                     where (onlyFavorites ? c.Starred == true : true) &&
                     (onlyUnread ? c.Read == false : true) &&
                     (earliestStartDate.HasValue ? c.StartTime >= earliestStartDate.Value : true) &&
                     (latestEndDate.HasValue ? c.TimeUpdated <= latestEndDate.Value : true) &&
                     !tags.Except(c.ConversationTags.Select(tag => tag.TagName)).Any()
                     orderby c.TimeUpdated descending
                     select (new SmsMessage()
                     {
                        From = c.From,
                        To = c.From,
                        Text = c.Text,
                        TimeReceived = c.TimeUpdated,
                        Read = c.Read,
                        ConvID = c.ConvId,
                        Starred = c.Starred,
                        ClientDisplayName = c.Client.DisplayName,
                        ClientIsSupportBot = c.Client.isSupportClient,
                        IsSmsBased = c.IsSmsBased
                     }));
      }
      else
      {
     //TODO DA could optimize to use FIND for working points
     convs = from wp in dbContext.WorkingPoints
             where (wp.TelNumber == consistentWP )
             select (from c in wp.Conversations
                     where (onlyFavorites ? c.Starred == true : true) &&
                     (onlyUnread ? c.Read == false : true) &&
                     (earliestStartDate.HasValue ? c.StartTime >= earliestStartDate.Value : true) &&
                     (latestEndDate.HasValue ? c.TimeUpdated <= latestEndDate.Value : true)
                     orderby c.TimeUpdated descending
                     select (new SmsMessage()
                     {
                        From = c.From,
                        To = wp.Name,
                        Text = c.Text,
                        TimeReceived = c.TimeUpdated,
                        Read = c.Read,
                        ConvID = c.ConvId,
                        Starred = c.Starred,
                        ClientDisplayName = c.Client.DisplayName,
                        ClientIsSupportBot = c.Client.isSupportClient,
                        IsSmsBased = c.IsSmsBased
                     }));
      }
      if (convs != null && convs.Count() > 0)
      {
     var conversations = convs.First().AsQueryable();
     logger.InfoFormat("Records returned from EF db: {0}", conversations.Count());
     return conversations;
      }
      else
      {
     logger.InfoFormat("No records returned from db for nr: {0}", workingPointsNumber);
     return null;
      }
 }
        public IEnumerable<SmsMessage> GetSupportConversationsForWorkingPoints(
         string userName,
         string[] workingPointsNumbers,
         int skip,
         int top,
         smsfeedbackEntities dbContext)
        {
            // the convention is that if workingPoints number is empty then we retrieve all the conversations
              List<SmsFeedback_EFModels.WorkingPoint> wps = new List<SmsFeedback_EFModels.WorkingPoint>();
              if (workingPointsNumbers == null)
              {
              // we have to get all the working points
              var workingPoints = from u in dbContext.Users where u.UserName == userName select (from wp in u.WorkingPoints select wp);
              if (workingPoints.Count() > 0)
              {
                  wps = workingPoints.First().ToList();
              }
              }
              else
              {
              // get just specific working points
              foreach (var wpNumber in workingPointsNumbers)
              {
                  var currentWorkingPoint = from u in dbContext.Users where u.UserName == userName select (from wp in u.WorkingPoints where wp.TelNumber == wpNumber select wp);
                  if (currentWorkingPoint.Count() > 0)
                  {
                      wps.Add(currentWorkingPoint.First().First());
                  }
              }
              }

              List<SmsMessage> supportConversations = new List<SmsMessage>();
              foreach (var wp in wps)
              {
              var supportConversation = wp.ConversationForSupport;
              if (supportConversation != null)
              {
                 var packedSupportConversation = new SmsMessage()
                 {
                    From = supportConversation.From,
                    To = supportConversation.From,
                    Text = supportConversation.Text,
                    TimeReceived = supportConversation.TimeUpdated,
                    Read = supportConversation.Read,
                    ConvID = supportConversation.ConvId,
                    Starred = supportConversation.Starred,
                    ClientDisplayName = supportConversation.Client.DisplayName,
                    ClientIsSupportBot = supportConversation.Client.isSupportClient,
                    IsSmsBased = supportConversation.IsSmsBased
                 };
                 supportConversations.Add(packedSupportConversation);
              }
              }
              return supportConversations.Skip(skip).Take(top);
        }
 public Dictionary<string, SmsMessage> GetLatestConversationForNumbers(string[] workingPointNumbers, string userName, smsfeedbackEntities dbContext)
 {
     logger.Info("Call made");
      Dictionary<string, SmsMessage> res = new Dictionary<string, SmsMessage>();
      foreach (string wp in workingPointNumbers)
      {
     var conversations = GetConversationsForNumber(false, null, wp, null, null,false, 0, 1, null, userName,dbContext);
     if (conversations != null && conversations.Count() > 0)
     {
        res.Add(wp, conversations.First());
     }
     else
     {
        res.Add(wp, null);
     }
      }
      return res;
 }
 public System.Collections.Generic.IEnumerable<WorkingPoint> GetWorkingPointsPerUser(String userName, smsfeedbackEntities dbContext)
 {
     return mEFRep.GetWorkingPointsPerUser(userName,dbContext);
 }
 public int NrOfUnreadConversations(string userName, smsfeedbackEntities dbContext)
 {
     return mEFRep.NrOfUnreadConversations(userName, dbContext);
 }
        public void UpdateSMSForSubscription_2ContextsChangeWithMoreThan2RemainingSMS_RemainingSMSHasCorrectValueAtTheEnd()
        {
            var wpID = "19802294808";//Wallmart only sms
             var price = "0.1";
             var initialRS = 200;
             var wp = context.WorkingPoints.Find(wpID);
             var sd1 = wp.Users.FirstOrDefault().Company.SubscriptionDetail;
             //make sure that RemainingSMS is not 0 so that we have where to subtract from
             bool saved = false;
             do
             {
            saved = true;
            try
            {
               sd1.RemainingSMS = initialRS;
               context.SaveChanges();
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException ex)
            {
               saved = false;
               ex.Entries.Single().Reload();
            }
             } while (!saved);

             context.Entry(sd1).Reload();
             //initialize second context
             smsfeedbackEntities altContext = new smsfeedbackEntities();
             var wp2 = altContext.WorkingPoints.Find(wpID);
             var sd2 = wp2.Users.FirstOrDefault().Company.SubscriptionDetail;
             //update the subscriptions details twice
             mEFinter.UpdateSMSForSubscription(price, sd1, context);
             mEFinter.UpdateSMSForSubscription(price, sd2, altContext);
             //get final RemainingSMS (RS)
             var finalRS = sd2.RemainingSMS;
             var expectedRS = initialRS - 2;
             Assert.AreEqual(expectedRS, finalRS, "After the dust has settled the RemainingSMS should be decreased by 2");
             altContext.Dispose();
        }
 public void UpdateConversationsFromExternalSources(string[] workingPointsNumbers, DateTime? lastUpdate, String userName, smsfeedbackEntities dbContext)
 {
     if (workingPointsNumbers == null || workingPointsNumbers.Length == 0 )
      {//we have to get all the working points
     workingPointsNumbers = (from wp in mEFRep.GetWorkingPointsPerUser(userName, dbContext) select wp.TelNumber).ToArray();
      }
      //UpdateConversationsFromTwilio(workingPointsNumbers, lastUpdate, userName, dbContext);
 }
 public void Initialise()
 {
     mEFinter = new EFInteraction();
      context =  new smsfeedbackEntities();
 }
 private void AddTwilioConversationsToDb(IEnumerable<SmsMessage> twilioConversationsForNumbers, smsfeedbackEntities dbContext)
 {
     foreach (SmsMessage sms in twilioConversationsForNumbers)
      {
     mEFInterface.UpdateOrAddConversation(sms.From, sms.To, sms.ConvID, sms.Text, sms.Read, sms.TimeReceived, true, dbContext);
      }
 }
 public JsonResult UpdateMessageClientAcknowledgeField(int msgID, bool clientAcknowledge)
 {
     try
        {
       smsfeedbackEntities dbContext = new smsfeedbackEntities();
       mEFInterface.updateMsgClientAckField(msgID, clientAcknowledge, dbContext);
       return Json(JsonReturnMessages.OP_SUCCESSFUL, JsonRequestBehavior.AllowGet);
        }
        catch (Exception e)
        {
       return Json(JsonReturnMessages.OP_FAILED, JsonRequestBehavior.AllowGet);
        }
 }
 private JsonResult SaveIncommingMessage(
    String from, String to, String convId, String text, smsfeedbackEntities lContextPerRequest)
 {
     SubscriptionSmsStatus messageStatus = mEFInterface.MarkMessageActivityInDB(from, to, convId, text, false, DateTime.UtcNow, null, DateTime.UtcNow, true, Constants.DONT_ADD_XMPP_USER, null, null, Constants.DIRECTION_IN, lContextPerRequest);
        return Json(messageStatus, JsonRequestBehavior.AllowGet);
 }
Пример #26
0
        private string UpdateExistingConversation(
           String sender,
           String text,
           Boolean readStatus,
           DateTime? updateTime,
           smsfeedbackEntities dbContext,
           Conversation currentConversation,
           string updateDateToInsert)
        {
            logger.InfoFormat("Updating conversation: [{0}] with read: {1}, updateTime: {2},  text: {3}, from {4}", currentConversation.ConvId, readStatus.ToString(), updateDateToInsert, text, sender);
               /*
            * since twilio returns (messages >= the latest message) it could be that the latest message is returned again - the only difference is that now "read" is false
            * so make sure that something changed, besides "read"
            */
               bool differentMsgBody = currentConversation.Text != text;
               bool differentMsgDate = (updateTime.HasValue && updateTime.Value != currentConversation.TimeUpdated);
               bool newMessage = differentMsgBody && differentMsgDate;

               if (newMessage)
               {
              //updateTime for when marking a conversation as read will be "null"
              if (updateTime.HasValue) currentConversation.TimeUpdated = updateTime.Value;
              if (!string.IsNullOrEmpty(text)) currentConversation.Text = text;
              currentConversation.From = sender;
              currentConversation.Read = readStatus;
              try
              {
                 dbContext.SaveChanges();
              }
              catch (Exception e)
              {
                 logger.Error(e.Message);
                 return JsonReturnMessages.EXCEPTION;
              }
              return JsonReturnMessages.OP_SUCCESSFUL;
               }
               else
               {
              return JsonReturnMessages.DUPLICATE_MESSAGE;
               }
        }
 /* returns the id of the new inserted message */
 private JsonResult SaveImMessageInDb(
    String from, String to, String convId, String text, String xmppUser, smsfeedbackEntities lContextPerRequest,
    String prevConvFrom, DateTime prevConvUpdateTime, string direction)
 {
     // save xmppUser in db just when the message direction is from staff to client
     string xmppUserToBeSaved = xmppUser;
     bool readStatus = true;
     if (direction.Equals(Constants.DIRECTION_IN))
     {
         xmppUserToBeSaved = Constants.DONT_ADD_XMPP_USER;
         readStatus = false;
     }
     //maybe delegate the result to the UpdateDB function
     //or interpret the result and return an appropriate message
     SubscriptionSmsStatus messageStatus = mEFInterface.MarkMessageActivityInDB(from,
        to,
        convId,
        text,
        readStatus,
        DateTime.UtcNow,
        prevConvFrom,
        prevConvUpdateTime,
        false,
        xmppUserToBeSaved,
        null,
        null,
        direction,
        lContextPerRequest);
     return Json(messageStatus, JsonRequestBehavior.AllowGet);
 }
        public void UpdateSMSForSubscription_2ContextsChangeRemainingSMSisJust1_RemainingSMSAndSpentAmountAreCorrectlyUpdated()
        {
            var wpID = "19802294808";//Wallmart only sms
             var price = "0.1";
             var initialRS = 1;
             var wp = context.WorkingPoints.Find(wpID);
             var sd1 = wp.Users.FirstOrDefault().Company.SubscriptionDetail;
             //make sure that RemainingSMS is exactly 1 and that the spent amount has a known value

             var initialSA = 1.34m;
             bool saved = false;
             do
             {
            saved = true;
            try
            {
               sd1.RemainingSMS = initialRS;
               sd1.SpentThisMonth = initialSA;
               context.SaveChanges();
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException ex)
            {
               saved = false;
               ex.Entries.Single().Reload();
            }
             } while (!saved);
             context.Entry(sd1).Reload();

             //initialize second context
             smsfeedbackEntities altContext = new smsfeedbackEntities();
             var wp2 = altContext.WorkingPoints.Find(wpID);
             var sd2 = wp2.Users.FirstOrDefault().Company.SubscriptionDetail;
             //update the subscriptions details twice
             mEFinter.UpdateSMSForSubscription(price, sd1, context);
             mEFinter.UpdateSMSForSubscription(price, sd2, altContext);
             //get final RemainingSMS (RS)
             var finalRS = sd2.RemainingSMS;
             var expectedRS = 0;
             Assert.AreEqual(expectedRS, finalRS, "After the dust has settled the RemainingSMS should be 0");
             var finalSA = sd2.SpentThisMonth;
             var expectedSA = initialSA + Decimal.Parse(price,CultureInfo.InvariantCulture );
             Assert.AreEqual(expectedSA, finalSA, "The spent amount should have been increased with the price of 1 SMS");
             altContext.Dispose();
        }
        private JsonResult SendSmsMessageAndUpdateDb(
           String from, String to, String convId, String text, String xmppUser, smsfeedbackEntities lContextPerRequest, 
           String prevConvFrom, DateTime prevConvUpdateTime)
        {
            SubscriptionSmsStatus messageStatus = new SubscriptionSmsStatus(-1, false, false, false);
            //var messageCanBeSent = SMSRepository.SendMessage(from, to, text, lContextPerRequest, (msgResponse) =>
            var status = SMSRepository.SendMessage(from, to, text,lContextPerRequest);
               //status will tell you if message was sent or not

               //the rest should come later....
            if (status != null) // null stands for  - could not sent SMS - no credit
            {
               //the idea is that a message can be sent but somewhere on Nexmo/Twilio there was a problem....
               messageStatus = mEFInterface.MarkMessageActivityInDB(from,
                      to,
                      convId,
                      text,
                      true,
                      status.DateSent,
                      prevConvFrom,
                      prevConvUpdateTime,
                      true,
                      xmppUser,
                      status.Price,
                      status.ExternalID,
                      Constants.DIRECTION_OUT, lContextPerRequest);
               messageStatus.MessageSent = status.MessageSent != null ? true : false;
            }

            //messageStatus = mEFInterface.MarkMessageActivityInDB(from,
            //           to,
            //           convId,
            //           text,
            //           true,
            //           new DateTime(2013,1,1,10,10,10,100),
            //           prevConvFrom,
            //           prevConvUpdateTime,
            //           true,
            //           xmppUser,
            //           "10",
            //           "115",
            //           Constants.DIRECTION_OUT, lContextPerRequest);
            return Json(messageStatus, JsonRequestBehavior.AllowGet);
        }
 public IEnumerable<SmsMessage> GetMessagesForConversation(string convID, smsfeedbackEntities dbContext)
 {
     return mEFInterface.GetMessagesForConversation(convID, dbContext);
      //we get the messages for a certain conversation from Twilio
      //return mTwilioRep.GetMessagesForConversation(convID,isConvFavourite);
 }