//Edit Campaign
        public static void CancelCampaign(CampaignDTO campaignDTO)
        {
            try
            {
                UnitOfWork uow = new UnitOfWork();

                //Add Consumed Credits to clients
                ClientDTO ClientDTO = new ClientDTO();
                ClientDTO = ClientService.GetById(campaignDTO.ClientId);
                ClientDTO.SMSCredit = ClientDTO.SMSCredit + campaignDTO.ConsumedCredits;
                ClientService.Edit(ClientDTO);

                campaignDTO.ConsumedCredits = 0;
                campaignDTO.Status = "Cancelled";
                CampaignService.Edit(campaignDTO);

                Campaign Campaign = Transform.CampaignToDomain(campaignDTO);
                uow.CampaignRepo.Update(Campaign);
                uow.SaveChanges();
            }
            catch
            {
                throw;
            }
        }
 public static Client ClientToDomain(ClientDTO ClientDTO)
 {
     if (ClientDTO == null) return null;
      Mapper.CreateMap<ClientDTO, Client>();
      Client Client = Mapper.Map<Client>(ClientDTO);
      return Client;
 }
        //Get client is active or inactive
        public static bool ActiveInactiveClient(int ClientId)
        {
            try
            {
                if (ClientId <= 0) return false;

                ClientDTO ClientDTO = new ClientDTO();
                ClientDTO = GetById(ClientId);

                GlobalSettings.LoggedInClientId = ClientDTO.Id;
                int PartnerId = ClientService.GetById(ClientDTO.Id).PartnerId;
                GlobalSettings.LoggedInPartnerId = PartnerId;

                if (ClientDTO == null) return false;

                if (ClientDTO.IsActive == true)
                {
                    ClientDTO.IsActive = false;
                    Edit(ClientDTO);
                    return true;
                }
                else
                {
                    ClientDTO.IsActive = true;
                    Edit(ClientDTO);
                    return true;
                }

            }
            catch
            {
                throw;
            }
        }
        //Create Client
        public static ClientDTO Create(ClientDTO ClientDTO)
        {
            try
            {
                ClientDTO.RegisteredDate = System.DateTime.Now;
                ClientDTO.IsActive = true;
                ClientDTO.AlertOnCredit = false;
                ClientDTO.SMSCredit = 20;
                ClientDTO.SMSGatewayId = 1;
                //ClientDTO.AllowChequePayment = true;
                //ClientDTO.Email = ClientDTO.Email.ToLower();
                ClientDTO.PartnerId = 1;
                ClientDTO.IsDatabaseUploaded = false;
                var Client = new Client();
                using (var uow = new UnitOfWork())
                {
                    Client = Transform.ClientToDomain(ClientDTO);

                    uow.ClientRepo.Insert(Client);
                    uow.SaveChanges();
                    //HttpContext.Current.Session["LoggedClient"] = Client;
                    //HttpContext.Current.Session["LoggedClientId"] = Client.Id;

                    if (Client.Id > 0)
                    {
                        ClientDTO.Id = Client.Id;
                        return ClientDTO;
                    }
                    else throw new OperationCanceledException("Insert operation terminated");
                }

            }
            catch (msgBlasterValidationException)
            {
                throw new System.TimeoutException();
            }
            catch (Exception)
            {
                //HttpContext.Current.Session["LoggedClient"] = null;
                //HttpContext.Current.Session["LoggedClientId"] = "0";
                throw;
            }
        }
 public void EditClient(ClientDTO ClientDTO)
 {
     try
     {
         ClientService.Edit(ClientDTO);
     }
     catch (TimeoutException)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.RequestTimeout)
         {
             Content = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
     catch (Exception)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
         {
             Content = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
 }
        //Create Camoaign
        public static int Create(CampaignDTO campaignDTO)
        {
            try
            {
                GlobalSettings.LoggedInClientId = campaignDTO.ClientId;
                GlobalSettings.LoggedInUserId = campaignDTO.CreatedBy;
                ClientDTO ClientDTO = new ClientDTO();
                ClientDTO = ClientService.GetById(campaignDTO.ClientId);
                int PartnerId = ClientDTO.PartnerId;// ClientService.GetById(campaignDTO.ClientId).PartnerId;
                GlobalSettings.LoggedInPartnerId = PartnerId;

                //If SMS Credit balance is low then should not create campaign
                if (ClientDTO.SMSCredit < campaignDTO.ConsumedCredits)
                {
                    return 0;
                }
                var campaign = new Campaign();
                SettingDTO SettingDTO = new SettingDTO();
                SettingDTO = SettingService.GetById(1);
                UnitOfWork uow = new UnitOfWork();
                if (campaignDTO.RecipientsNumber != null && campaignDTO.RecipientsNumber != "")
                {
                    campaignDTO.RecipientsNumber = CommonService.RemoveDuplicateMobile(campaignDTO.RecipientsNumber);
                }

                //Get Message Count
                if (campaignDTO.IsUnicode != true)
                {
                    campaignDTO.MessageCount = CommonService.GetMessageCount(campaignDTO.Message);
                }
                else
                {
                    campaignDTO.MessageCount = CommonService.GetUnicodeMessageCount(campaignDTO.Message);
                }
                campaignDTO.IPAddress = CommonService.GetIP();
                if (campaignDTO.GroupId == null)
                {
                    campaignDTO.RecipientsCount = CommonService.GetRecipientsCount(campaignDTO.RecipientsNumber);
                    campaignDTO.RequiredCredits = (campaignDTO.RecipientsCount * campaignDTO.MessageCount) * SettingDTO.NationalCampaignSMSCount;
                    campaignDTO.CreditsDiffrence = campaignDTO.ConsumedCredits - campaignDTO.RequiredCredits;
                }

                if (campaignDTO.ForAllContact == true)
                {
                    campaignDTO.RecipientsNumber = ContactService.GetAllReceipentNumberByClientId(campaignDTO.ClientId);
                    campaignDTO.RecipientsCount = CommonService.GetRecipientsCount(campaignDTO.RecipientsNumber);
                    campaignDTO.RequiredCredits = (campaignDTO.RecipientsCount * campaignDTO.MessageCount) * SettingDTO.NationalCampaignSMSCount;
                    campaignDTO.GroupId = null;
                    campaignDTO.RecipientsNumber = "";
                    campaignDTO.CreditsDiffrence = campaignDTO.ConsumedCredits - campaignDTO.RequiredCredits;
                }

                if (campaignDTO.GroupId > 0)
                {
                    campaignDTO.RequiredCredits = (campaignDTO.RecipientsCount * campaignDTO.MessageCount) * SettingDTO.NationalCampaignSMSCount;
                }

                campaignDTO.IsReconcile = false;
                campaignDTO.ReconcileDate = System.DateTime.Now.Date;
                campaign = Transform.CampaignToDomain(campaignDTO);
                uow.CampaignRepo.Insert(campaign);
                uow.SaveChanges();

                // Deduct SMS credit balance
                campaignDTO.Id = campaign.Id;

                ClientDTO.SMSCredit = ClientDTO.SMSCredit - campaignDTO.ConsumedCredits;
                ClientService.Edit(ClientDTO);

                return campaignDTO.Id;

            }

            catch (Exception)
            {
                throw;
            }
        }
        //Delete campaign
        public static void Delete(int id)
        {
            try
            {
                CampaignDTO CampaignDTO = new CampaignDTO();
                CampaignDTO = CampaignService.GetById(id);
                //Add Consumed Credits to clients
                ClientDTO ClientDTO = new ClientDTO();
                ClientDTO = ClientService.GetById(CampaignDTO.ClientId);
                ClientDTO.SMSCredit = ClientDTO.SMSCredit + CampaignDTO.ConsumedCredits;
                ClientService.Edit(ClientDTO);

                UnitOfWork uow = new UnitOfWork();
                uow.CampaignRepo.Delete(id);
                uow.SaveChanges();

            }
            catch
            {
                throw;
            }
        }
        //Edit Campaign
        public static void Edit(CampaignDTO campaignDTO)
        {
            try
            {

                //Get previous consumed count and restore clients credits
                ClientDTO ClientDTO = new ClientDTO();
                ClientDTO = ClientService.GetById(campaignDTO.ClientId);
                CampaignDTO CampaignDTORestore = new CampaignDTO();
                CampaignDTORestore = GetById(campaignDTO.Id);
                ClientDTO.SMSCredit = ClientDTO.SMSCredit + CampaignDTORestore.ConsumedCredits;
                ClientService.Edit(ClientDTO);

                //If SMS Credit balance is greater or equal to ConsumededCredits then create campaign
                if (ClientDTO.SMSCredit >= campaignDTO.ConsumedCredits)
                {
                GlobalSettings.LoggedInClientId = campaignDTO.ClientId;
                GlobalSettings.LoggedInUserId = campaignDTO.CreatedBy;
                int PartnerId = ClientService.GetById(campaignDTO.ClientId).PartnerId;
                GlobalSettings.LoggedInPartnerId = PartnerId;

                SettingDTO SettingDTO = new SettingDTO();
                SettingDTO = SettingService.GetById(1);

                UnitOfWork uow = new UnitOfWork();

                if (campaignDTO.RecipientsNumber != null && campaignDTO.RecipientsNumber != "")
                {
                    campaignDTO.RecipientsNumber = CommonService.RemoveDuplicateMobile(campaignDTO.RecipientsNumber);
                }

                campaignDTO.MessageCount = CommonService.GetMessageCount(campaignDTO.Message);
                if (campaignDTO.GroupId == null)
                {
                    campaignDTO.RecipientsCount = CommonService.GetRecipientsCount(campaignDTO.RecipientsNumber);
                    campaignDTO.RequiredCredits = (campaignDTO.RecipientsCount * campaignDTO.MessageCount) * SettingDTO.NationalCampaignSMSCount;
                    campaignDTO.CreditsDiffrence = campaignDTO.ConsumedCredits - campaignDTO.RequiredCredits;
                }
                campaignDTO.IPAddress = CommonService.GetIP();

                if (campaignDTO.ForAllContact == true)
                {
                    campaignDTO.RecipientsNumber = ContactService.GetAllReceipentNumberByClientId(campaignDTO.ClientId);
                    campaignDTO.RecipientsCount = CommonService.GetRecipientsCount(campaignDTO.RecipientsNumber);
                    campaignDTO.RequiredCredits = (campaignDTO.RecipientsCount * campaignDTO.MessageCount) * SettingDTO.NationalCampaignSMSCount;
                    campaignDTO.GroupId = null;
                    campaignDTO.GroupName = null;
                    campaignDTO.RecipientsNumber = "";
                    campaignDTO.CreditsDiffrence = campaignDTO.ConsumedCredits - campaignDTO.RequiredCredits;
                }

                if (campaignDTO.GroupId > 0)
                {
                    campaignDTO.RequiredCredits = (campaignDTO.RecipientsCount * campaignDTO.MessageCount) * SettingDTO.NationalCampaignSMSCount;
                }

                campaignDTO.IsReconcile = false;
                campaignDTO.ReconcileDate = System.DateTime.Now.Date;
                Campaign Campaign = Transform.CampaignToDomain(campaignDTO);
                uow.CampaignRepo.Update(Campaign);
                uow.SaveChanges();

                //Deduct clients Credit
                ClientDTO.SMSCredit = ClientDTO.SMSCredit - campaignDTO.ConsumedCredits;
                ClientService.Edit(ClientDTO);

                }
            }
            catch
            {
                throw;
            }
        }
        //Create Campaign for Backend process
        public static int CreateCampaignFromBackend(CampaignDTO campaignDTO)
        {
            try
            {

                GlobalSettings.LoggedInClientId = campaignDTO.ClientId;
                GlobalSettings.LoggedInUserId = campaignDTO.CreatedBy;

                ClientDTO ClientDTO = new ClientDTO();
                ClientDTO = ClientService.GetById(campaignDTO.ClientId);

                int PartnerId = ClientDTO.PartnerId;// ClientService.GetById(campaignDTO.ClientId).PartnerId;
                GlobalSettings.LoggedInPartnerId = PartnerId;

                //If SMS Credit balance is low then should not create campaign
                if (ClientDTO.SMSCredit < campaignDTO.ConsumedCredits)
                {
                    return 0;
                }

                var campaign = new Campaign();
                SettingDTO SettingDTO = new SettingDTO();
                SettingDTO = SettingService.GetById(1);
                UnitOfWork uow = new UnitOfWork();
                if (campaignDTO.RecipientsNumber != null)
                {
                    campaignDTO.RecipientsNumber = CommonService.RemoveDuplicateMobile(campaignDTO.RecipientsNumber);
                }
                //Get Message Count
                if (campaignDTO.IsUnicode != true)
                {
                    campaignDTO.MessageCount = CommonService.GetMessageCount(campaignDTO.Message);
                }
                else
                {
                    campaignDTO.MessageCount = CommonService.GetUnicodeMessageCount(campaignDTO.Message);
                }

                if (campaignDTO.GroupId == null)
                {
                    campaignDTO.RecipientsCount = CommonService.GetRecipientsCount(campaignDTO.RecipientsNumber);
                    campaignDTO.RequiredCredits = (campaignDTO.RecipientsCount * campaignDTO.MessageCount) * SettingDTO.NationalCampaignSMSCount;
                }

                campaignDTO.IsReconcile = false;
                campaignDTO.ReconcileDate = System.DateTime.Now.Date;

                //Calculate consumed credits
                double ConsumedCreditPerOneMsg = CommonService.GetConsumedCreditsForOneMessage(campaignDTO.Message, false);
                int RecepientsCount = CommonService.GetRecipientsCount(campaignDTO.RecipientsNumber);
                campaignDTO.ConsumedCredits = RecepientsCount * ConsumedCreditPerOneMsg;

                campaign = Transform.CampaignToDomain(campaignDTO);
                uow.CampaignRepo.Insert(campaign);
                uow.SaveChanges();
                campaignDTO.Id = campaign.Id;

                //Deduct clients balance

                ClientDTO.SMSCredit = ClientDTO.SMSCredit - campaignDTO.ConsumedCredits;
                ClientService.Edit(ClientDTO);

                return campaignDTO.Id;
            }

            catch (Exception)
            {
                throw;
            }
        }
        //Create credit request
        public static CreditRequestDTO Create(CreditRequestDTO CreditRequestDTO)
        {
            try
            {
                CreditRequestDTO CreditRequestDTONew = new CreditRequestDTO();

                PartnerDTO PartnerDTO = new PartnerDTO();
                ClientDTO ClientDTO = new ClientDTO();
                UserDTO UserDTO = new UserDTO();

                PartnerDTO = PartnerService.GetById(CreditRequestDTO.PartnerId);
                ClientDTO = ClientService.GetById(CreditRequestDTO.ClientId);
                UserDTO = UserService.GetById(CreditRequestDTO.RequestedBy);

                GlobalSettings.LoggedInClientId = ClientDTO.Id;
                GlobalSettings.LoggedInUserId = UserDTO.Id;
                int PartnerId = PartnerDTO.Id;
                GlobalSettings.LoggedInPartnerId = PartnerId;

                if (CreditRequestDTO.RequestedCredit <= 0)
                {
                    return null; //0
                }
                var CreditRequest = new CreditRequest();
                using (var uow = new UnitOfWork())
                {
                    CreditRequest = Transform.CreditRequestToDomain(CreditRequestDTO);
                    CreditRequest.Date = System.DateTime.Now;
                    CreditRequest.OldBalance = ClientDTO.SMSCredit;
                    CreditRequest.IsProvided = false;
                    //CreditRequest.ProvidedCredit = CreditRequest.RequestedCredit;
                    CreditRequest.Amount = CreditRequest.RequestedCredit * CreditRequest.RatePerSMS;
                    double tax = (CreditRequest.Amount * Convert.ToDouble(CreditRequest.Tax)) / 100;
                    CreditRequest.TaxAmount = tax;
                    CreditRequest.GrandTotal = CreditRequest.Amount + tax;

                    bool IsOnlinepaymentSuccess = Onlinepayment(CreditRequest.GrandTotal);

                    if (IsOnlinepaymentSuccess == true)
                    {
                        //CreditRequest.IsPaymentSuccessful = true;
                        //CreditRequest.PaymentDate = System.DateTime.Now;
                        CreditRequest.ProvidedDate = System.DateTime.Now;
                        CreditRequest.IsProvided = true;
                        CreditRequest.IsBillGenerated = true;
                        CreditRequest.PaymentMode = PaymentMode.Card;
                        CreditRequest.PaymentDate = System.DateTime.Now;
                        CreditRequest.IsPaid = true;
                        CreditRequest.ProvidedCredit = CreditRequest.RequestedCredit;

                        uow.CreditRequestRepo.Insert(CreditRequest);
                        uow.SaveChanges();

                        ClientDTO.SMSCredit = ClientDTO.SMSCredit + CreditRequest.RequestedCredit;
                        ClientService.Edit(ClientDTO);

                    }
                    else
                    {
                        //CreditRequest.IsPaymentSuccessful = false;
                        CreditRequest.IsPaid = false;
                        uow.CreditRequestRepo.Insert(CreditRequest);
                        uow.SaveChanges();
                    }

                    //Update TotalAppliedCredit
                    ClientDTO.TotalAppliedCredit = ClientDTO.TotalAppliedCredit + CreditRequest.RequestedCredit;
                    ClientService.Edit(ClientDTO);

                    //Generate Link to provide mail trhough mail
                    string APILink = ConfigurationManager.AppSettings["APILink"].ToString() + "api/CreditRequest/ProvideCreditByMailLink?CreditRequestId=" + CreditRequest.Id;

                    // Send Email To Partner
                    bool IsMailSent = CommonService.SendEmail("SMS Credit Request", "Hello " + PartnerDTO.Name + ", <br/><br/> The New request of " + CreditRequest.RequestedCredit + " credits applied by " + ClientDTO.Company + "<br/><br/> <a href=" + APILink + ">Approve</a>", PartnerDTO.Email, "", false);

                    CreditRequestDTONew = GetById(CreditRequest.Id);
                    if (CreditRequest.PaymentMode == PaymentMode.Card)
                    {
                        CreditRequestDTONew.OnlinePaymentURL = OnlinePaymentLinkWithTemperproofData(UserDTO.Email, CreditRequest.GrandTotal, UserDTO.Mobile, UserDTO.Name, CreditRequest.Id);
                    }
                    return (CreditRequestDTONew); //.Id);

                }

            }
            //catch (LoggedInUserException)
            //{
            //    throw new System.TimeoutException();
            //}
            catch (Exception)
            {
                throw;
            }
        }
 public string UploadSQLiteDatabase(string documentPath, int ClientId, string FileName)
 {
     try
     {
         ClientDTO ClientDTO = new ClientDTO();
         ClientDTO = ClientService.GetById(ClientId);
         if (ClientDTO.IsDatabaseUploaded != true)
         {
             HttpPostedFile file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
             return ClientService.UploadSQLiteDatabase(file, documentPath, ClientId, FileName);
         }
         else
         {
             return "Database already uploaded";
         }
     }
     catch (TimeoutException)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.RequestTimeout)
         {
             Content = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
     catch (Exception e)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
         {
             Content = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
 }
        //Get reedeemed count by clinet id and campaign id
        public static List<RedeemedCountDTO> GetByClientId(int ClientId, int CampaignId)
        {
            List<RedeemedCountDTO> RedeemedCountDTOList = new List<RedeemedCountDTO>();
            try
            {
                UnitOfWork uow = new UnitOfWork();
                IEnumerable<RedeemedCount> RedeemedCount = uow.RedeemedCountRepo.GetAll().Where(e => e.ClientId == ClientId && e.EcouponCampaignId == CampaignId);
                if (RedeemedCount != null)
                {
                    foreach (var item in RedeemedCount)
                    {
                        EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                        EcouponCampaignDTO = EcouponCampaignService.GetById(item.EcouponCampaignId);
                        if (EcouponCampaignDTO.ExpiresOn > System.DateTime.Now)
                        {

                            RedeemedCountDTO RedeemedCountDTO = new RedeemedCountDTO();
                            RedeemedCountDTO = Transform.RedeemedCountToDTO(item);

                            UserDTO UserDTO = new UserDTO();
                            UserDTO = UserService.GetById(item.UserId);
                            RedeemedCountDTO.UserName = UserDTO.Name;
                            RedeemedCountDTO.Location = LocationService.GetById(UserDTO.LocationId).Name;
                            ClientDTO ClientDTO = new ClientDTO();
                            ClientDTO = ClientService.GetById(ClientId);
                            RedeemedCountDTO.ClientName = ClientDTO.Company;
                            RedeemedCountDTO.CampaignName = EcouponCampaignDTO.Title;
                            RedeemedCountDTOList.Add(RedeemedCountDTO);
                        }
                    }
                }

                return RedeemedCountDTOList;
            }
            catch
            {
                //  throw;
                return RedeemedCountDTOList;
            }
        }
 public static bool AllowToProcessClient(CampaignDTO CampaignDTO)
 {
     if (CampaignDTO == null)
     {
         return false;
     }
     else
     {
         ClientDTO ClientDTO = new ClientDTO();
         ClientDTO = ClientService.GetById(CampaignDTO.ClientId);
         if (ClientDTO.SMSCredit > 0)
         {
             return true;
         }
         else
             return false;
     }
 }
        public static string SendMessage(Byte[] array, Byte[] checksum)
        {
            try
            {
                //Checking for Data Accuracy
                Byte[] newchecksum = new MD5CryptoServiceProvider().ComputeHash(array);
                if (checksum.Length == newchecksum.Length)
                {
                    int arraylength = 0;
                    while ((arraylength < checksum.Length) && (newchecksum[arraylength] == checksum[arraylength]))
                    {
                        arraylength++;
                    }
                    if (arraylength != newchecksum.Length)
                    {
                        return ErrorFlag.DataCorrupted.ToString();
                    }
                }

                // Checking User's Validation that is CDKey & MachineID
                XmlSerializer xs = new XmlSerializer(typeof(MsgInformationDTO));
                MemoryStream msgStream = new MemoryStream(array);
                MsgInformationDTO oMsgInformationDTO = (MsgInformationDTO)xs.Deserialize(msgStream);

                CampaignDTO CampaignDTO = new CampaignDTO();
                CampaignDTO = CampaignService.GetById(oMsgInformationDTO.CampaignId);
                //CampaignDTO.ClientId = oMsgInformationDTO.ClientId;
                //CampaignDTO.Id = oMsgInformationDTO.CampaignId;
                ClientDTO ClientDTO = new ClientDTO();
                ClientDTO = ClientService.GetById(CampaignDTO.ClientId);

                string packet = oMsgInformationDTO.xmlpacket;
                string fname = null;
                if (ValidatePacketAgainstSchema(packet)) // Check xml file validation.
                {
                    if (AllowToProcessClient(CampaignDTO))
                    {
                        DateTime DateAndTime = System.DateTime.Now;
                        SettingDTO SettingDTO = new SettingDTO(); // Get limit on msg size
                        SettingDTO = SettingService.GetById(1);

                        int requiredCredit = 0;
                        XmlDocument x = new XmlDocument();
                        x.LoadXml(packet);
                        XmlNodeList messages = x.SelectNodes("/packet/numbers/message/text()"); // Get all messages from xmlpacket
                        XmlNodeList numbers = x.SelectNodes("/packet/numbers/number");
                        for (int i = 0; i < messages.Count; i++) // Get required credits to send this packet;
                        {
                            requiredCredit += MessageCount(MsgCorrect(messages[i].InnerText.TrimEnd()));
                        }
                        if (messages.Count == 1) // Means one message to all numbers
                        {
                            requiredCredit = requiredCredit * numbers.Count;
                        }

                        if (ClientDTO.SMSCredit >= requiredCredit)
                        {
                            XmlNode root = x.DocumentElement;
                            XmlElement requiredcredits = x.CreateElement("requiredcredits");
                            requiredcredits.InnerText = requiredCredit.ToString();
                            root.InsertBefore(requiredcredits, root.LastChild);
                            //_oClsClients.SMSCredits -= requiredCredit;
                            try
                            {
                                fname = DateAndTime.Year.ToString() + DateAndTime.Month + DateAndTime.Day + "-" + DateAndTime.Hour + DateAndTime.Minute + DateAndTime.Second + "-" + oMsgInformationDTO.CampaignId + "-Q.xml";
                                x.Save(ConfigurationManager.AppSettings["SMSFolderPath"].ToString() + fname);
                                x = null;
                                //dbClients.ReduceSMSCredits(oClient, requiredCredit);

                                CampaignDTO CampaignDTONew = new CampaignDTO();
                                CampaignDTONew = CampaignDTO;
                                //CampaignDTONew.IsSent = true;
                                CampaignDTONew.Status = "Sent";
                                CampaignService.Edit(CampaignDTONew);

                                ClientDTO ClientDTOUpdate = new ClientDTO();
                                ClientDTOUpdate = ClientDTO;
                                ClientDTOUpdate.SMSCredit = ClientDTOUpdate.SMSCredit - requiredCredit;
                                ClientService.Edit(ClientDTOUpdate);

                            }
                            catch (Exception ex)
                            {
                                return ErrorFlag.FailedToWriteData.ToString();      // Returns "FailedToWriteData" enum name if message file not created

                            }
                            //return ErrorFlag.Success.ToString();                // Return "Success" enum name if Message file created in the SMSQueue folder successfully
                            return fname;
                        }
                        else
                            return ErrorFlag.InsufficientCredits.ToString();  // Returns "InsufficientCredits" enum name if SMSCredits are insufficient for sending message
                    }
                    else
                        return ErrorFlag.InvalidUser.ToString();        // Returns "InvalidUser" enum name if the CDKey or MachineID not matching
                }
                else
                    return ErrorFlag.BadXml.ToString(); // Return BAD XmlPacke Error
            }
            catch
            {
                throw;             // Returns error flag name if there are any web exception
            }
        }
        //public static string CreatePacket(int ClientId, int CampaignId, bool IsCampaign)
        //{
        //    string TemplatePacket = ReadXMLTemplate();
        //    string NewPacket = null;
        //    if (IsCampaign == true)
        //    {
        //        // Create Campaign Packet
        //        ClientDTO ClientDTO = ClientService.GetById(ClientId);
        //        CampaignDTO CampaignDTO = CampaignService.GetById(CampaignId);
        //        TemplatePacket = TemplatePacket.Replace("[clientId]", CampaignDTO.ClientId.ToString());
        //        NewPacket = TemplatePacket.Replace("[campaignId]", CampaignId.ToString());
        //        //SMSGatewayDTO SMSGatewayDTO = SMSGatewayService.GetById(ClientDTO.SMSGatewayId);
        //        string sender = "";
        //        if (ClientDTO.SenderCode != null && ClientDTO.SenderCode != "")
        //        {
        //            sender = ClientDTO.SenderCode;
        //        }
        //        else
        //        {
        //            sender = "022751";
        //        }
        //        NewPacket = NewPacket.Replace("[sender]", sender);
        //        NewPacket = NewPacket.Replace("[campaignname]", CampaignDTO.Name);
        //        string numbers = CampaignDTO.RecipientsNumber;
        //        string value1 = numbers;
        //        char[] delimiter1 = new char[] { ',' };   // <-- Split on these
        //        // ... Use StringSplitOptions.RemoveEmptyEntries.
        //        string[] array2 = value1.Split(delimiter1,
        //            StringSplitOptions.RemoveEmptyEntries);
        //        string MobileNumber = null;
        //        //Console.WriteLine();
        //        foreach (string item in array2)
        //        {
        //            MobileNumber = MobileNumber + "<number>" + item + "</number>";
        //        }
        //        NewPacket = NewPacket.Replace("[number]", MobileNumber);
        //        NewPacket = NewPacket.Replace("[message]", CampaignDTO.Message);
        //        if (CampaignDTO.IsScheduled == true)
        //        {
        //            DateTime ScheduledDate = CampaignDTO.ScheduledDate.Date;
        //            DateTime Time;
        //            if (CampaignDTO.ScheduledTime != "")
        //            {
        //                Time = Convert.ToDateTime(CampaignDTO.ScheduledTime);
        //            }
        //            else Time = Convert.ToDateTime("12:00 AM");
        //            ScheduledDate = Convert.ToDateTime(ScheduledDate.Date.ToString("MM/dd/yyyy") + " " + Time.TimeOfDay);
        //            NewPacket = NewPacket.Replace("[scheduleddate]", ScheduledDate.ToString());
        //        }
        //        else
        //        {
        //            NewPacket = NewPacket.Replace("[scheduleddate]", System.DateTime.Now.ToString());
        //        }
        //    }
        //    else
        //    {
        //        // Create Ecoupon Campaign Packet
        //        ClientDTO ClientDTO = ClientService.GetById(ClientId);
        //        EcouponCampaignDTO EcouponCampaignDTO = EcouponCampaignService.GetById(CampaignId);
        //        TemplatePacket = TemplatePacket.Replace("[clientId]", EcouponCampaignDTO.ClientId.ToString());
        //        NewPacket = TemplatePacket.Replace("[campaignId]", CampaignId.ToString());
        //        string sender = "";
        //        if (ClientDTO.SenderCode != null && ClientDTO.SenderCode != "")
        //        {
        //            sender = ClientDTO.SenderCode;
        //        }
        //        else
        //        {
        //            sender = "022751";
        //        }
        //        //SMSGatewayDTO SMSGatewayDTO = SMSGatewayService.GetById(ClientDTO.SMSGatewayId);
        //        NewPacket = NewPacket.Replace("[sender]", sender);
        //        NewPacket = NewPacket.Replace("[campaignname]", EcouponCampaignDTO.Title);
        //        string numbers = EcouponCampaignDTO.ReceipentNumber;
        //        string value1 = numbers;
        //        char[] delimiter1 = new char[] { ',' };   // <-- Split on these
        //        // ... Use StringSplitOptions.RemoveEmptyEntries.
        //        string[] array2 = value1.Split(delimiter1,
        //            StringSplitOptions.RemoveEmptyEntries);
        //        string MobileNumber = null;
        //        //Console.WriteLine();
        //        foreach (string item in array2)
        //        {
        //            MobileNumber = MobileNumber + "<number>" + item + "</number>";
        //        }
        //        NewPacket = NewPacket.Replace("[number]", MobileNumber);
        //        NewPacket = NewPacket.Replace("[message]", EcouponCampaignDTO.Message);
        //        if (EcouponCampaignDTO.IsScheduled == true)
        //        {
        //            DateTime ScheduledDate = EcouponCampaignDTO.SendOn.Date;
        //            DateTime Time;
        //            if (EcouponCampaignDTO.ScheduleTime != "")
        //            {
        //                Time = Convert.ToDateTime(EcouponCampaignDTO.ScheduleTime);
        //            }
        //            else Time = Convert.ToDateTime("12:00 AM");
        //            ScheduledDate = Convert.ToDateTime(ScheduledDate.Date.ToString("MM/dd/yyyy") + " " + Time.TimeOfDay);
        //            NewPacket = NewPacket.Replace("[scheduleddate]", ScheduledDate.ToString());
        //        }
        //        else
        //        {
        //            NewPacket = NewPacket.Replace("[scheduleddate]", System.DateTime.Now.ToString());
        //        }
        //    }
        //    string xmlFileUploadPath = ConfigurationManager.AppSettings["XMLFileUploadPath"].ToString() + Guid.NewGuid() + "_" + System.DateTime.Now.ToString("MM-dd-yyyy_hh_mm_tt") + "_" + ClientId + ".xml";
        //    if (!File.Exists(xmlFileUploadPath))
        //    {
        //        using (StreamWriter sw = File.CreateText(xmlFileUploadPath))
        //        {
        //            sw.WriteLine(NewPacket);
        //        }
        //    }
        //    return NewPacket;
        //}
        //Resend Coupon
        public static bool ResendCoupon(string mobilenumber, string message, int ClientId)
        {
            string result = "";
               bool IsSent = false;
               if (message != "" && mobilenumber != "")// Check for empty message.
               {
               ClientDTO ClientDTO = new ClientDTO();
               ClientDTO = ClientService.GetById(ClientId);
               string Url = null;
               //SMSGatewayDTO SMSGatewayDTO = new SMSGatewayDTO();
               //SMSGatewayDTO = SMSGatewayService.GetById(ClientDTO.SMSGatewayId);
               //if (SMSGatewayDTO.Name == "Default")
               //{
               //    Url = ConfigurationManager.AppSettings["PromotionalGateWay"].ToString();
               //}
               //else
               //{
               //    Url = ConfigurationManager.AppSettings["TransactionalGateWay"].ToString();
               //}
               if (ClientDTO.SenderCode != null && ClientDTO.SenderCode != "")
               {
                   Url = ConfigurationManager.AppSettings["TransactionalGateWay"].ToString();
               }
               else
               {

                   Url = ConfigurationManager.AppSettings["PromotionalGateWay"].ToString();
               }

               Url = Url.Replace("%26", "&");
               Url = Url.Replace("[recipient]", mobilenumber);
               Url = Url.Replace("[message]", message);
               Url = Url.Replace("[gateway]", ClientDTO.SenderCode);   //SMSGatewayDTO.Name

               HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
               myRequest.Method = "GET";
               WebResponse myResponse = myRequest.GetResponse();
               StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
               result = sr.ReadToEnd();
               sr.Close();

               string statuscode = "";
               if (result.Contains('|'))
                   statuscode = result.Substring(0, result.IndexOf('|'));
               else
                   statuscode = result;

               SMSResult(result);
               myResponse.Close();

               if (statuscode == "1701" || statuscode == "1705" || statuscode == "1706" || statuscode == "1032")
               {
                   IsSent = true;
               }
               else
               {
                   IsSent = false;

                   string UrlWhiz = "";
                   string resultWhiz = "";
                   if (ClientDTO.SenderCode != null && ClientDTO.SenderCode != "")
                   {
                       UrlWhiz = ConfigurationManager.AppSettings["TransactionalGateWayWhiz"].ToString();
                   }
                   else
                   {

                       UrlWhiz = ConfigurationManager.AppSettings["PromotionalGateWayWhiz"].ToString();
                   }

                   UrlWhiz = UrlWhiz.Replace("%26", "&");
                   UrlWhiz = UrlWhiz.Replace("[recipient]", mobilenumber);
                   UrlWhiz = UrlWhiz.Replace("[message]", message);
                   UrlWhiz = UrlWhiz.Replace("[gateway]", ClientDTO.SenderCode);   //SMSGatewayDTO.Name

                   HttpWebRequest myRequesWhiz = (HttpWebRequest)WebRequest.Create(UrlWhiz);
                   myRequesWhiz.Method = "GET";
                   WebResponse myResponseWhiz = myRequesWhiz.GetResponse();
                   StreamReader srWhiz = new StreamReader(myResponseWhiz.GetResponseStream(), System.Text.Encoding.UTF8);
                   resultWhiz = srWhiz.ReadToEnd();
                   srWhiz.Close();

                   if (resultWhiz.Contains('|'))
                   {
                       //statuscode = result.Substring(0, result.IndexOf('|'));
                       statuscode = "";
                       string[] words = resultWhiz.Split('|');
                       foreach (string word in words)
                       {
                           Console.WriteLine(word);
                           try
                           {
                               int code = Convert.ToInt32(word);

                               statuscode = code.ToString();
                           }
                           catch (Exception)
                           {
                               string code = word.Replace(" ", "");
                               if (code == "Success")
                               {
                                   code = "0";
                                   statuscode = code.ToString();
                                   IsSent = true;
                               }
                               else
                               {
                                   continue;
                               }
                           }
                       }

                   }
                   else
                   {
                       statuscode = resultWhiz;
                   }

               }
               }
               return IsSent;
        }
        public static CouponDTO ResendCouponByCouponDTOAndClientId(CouponDTO CouponDTO, int ClientId)
        {
            SettingDTO SettingDTO = new SettingDTO();
            SettingDTO = SettingService.GetById(1);
            double RequiredCredit = CommonService.GetMessageCount(CouponDTO.Message);
            double ActualRequiredCredits = RequiredCredit * SettingDTO.NationalCouponSMSCount;
            int OldId = 0;

            OldId = CouponDTO.Id;
            CouponDTO CouponDTONew = new CouponDTO();
            CouponDTONew = null;

            string result = "";
            bool IsSent = false;
            if (CouponDTO.Message != "" && CouponDTO.MobileNumber != "")// Check for empty message.
            {
                ClientDTO ClientDTO = new ClientDTO();
                ClientDTO = ClientService.GetById(ClientId);
                string Url = null;

                if (ClientDTO.SenderCode != null && ClientDTO.SenderCode != "")
                {
                    Url = ConfigurationManager.AppSettings["TransactionalGateWay"].ToString();
                }
                else
                {

                    Url = ConfigurationManager.AppSettings["PromotionalGateWay"].ToString();
                }

                Url = Url.Replace("%26", "&");
                Url = Url.Replace("[recipient]", CouponDTO.MobileNumber);
                Url = Url.Replace("[message]", CouponDTO.Message);
                Url = Url.Replace("[gateway]", ClientDTO.SenderCode);   //SMSGatewayDTO.Name

                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
                myRequest.Method = "GET";
                WebResponse myResponse = myRequest.GetResponse();
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
                result = sr.ReadToEnd();
                sr.Close();

                string statuscode = "";
                if (result.Contains('|'))
                    statuscode = result.Substring(0, result.IndexOf('|'));
                else
                    statuscode = result;

                SMSResult(result);
                myResponse.Close();

                if (statuscode == "1701" || statuscode == "1705" || statuscode == "1706" || statuscode == "1032")
                {
                    IsSent = true;

                    CouponDTO.SentDateTime = System.DateTime.Now;
                    CouponDTO.Id = 0;
                    CouponDTO.IsExpired = false;
                    int NewCouponId = CouponService.Create(CouponDTO);

                    CouponDTONew = CouponService.GetById(NewCouponId);

                    //Expire previous coupon
                    CouponDTO CouponDTOPrevious = new CouponDTO();
                    CouponDTOPrevious = CouponService.GetById(OldId);
                    CouponDTOPrevious.IsExpired = true;
                    CouponDTOPrevious.MessageId = result;
                    CouponService.Edit(CouponDTOPrevious);

                    // Modify EcouponCampaign message count
                    EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                    EcouponCampaignDTO = EcouponCampaignService.GetById(CouponDTONew.EcouponCampaignId);
                    EcouponCampaignDTO.ReceipentNumber = EcouponCampaignDTO.ReceipentNumber + "," + CouponDTO.MobileNumber;
                    EcouponCampaignDTO.RecipientsCount = EcouponCampaignDTO.RecipientsCount + 1;
                    if (EcouponCampaignDTO.GroupId == 0)
                    {
                        EcouponCampaignDTO.GroupId = null;
                        EcouponCampaignDTO.Group = null;
                    }

                    EcouponCampaignDTO.RequiredCredits = CouponService.GetECouponCampaignRequiredCreditsByEcouponCampaignId(EcouponCampaignDTO.Id);

                    EcouponCampaignService.EditForEcouponResend(EcouponCampaignDTO);

                    //Modify client SMS credits
                    ClientDTO.SMSCredit = ClientDTO.SMSCredit - ActualRequiredCredits;// RequiredCredit;
                    ClientService.Edit(ClientDTO);

                }
                else
                {
                    IsSent = false;

                    string UrlWhiz = "";
                    string resultWhiz = "";
                    if (ClientDTO.SenderCode != null && ClientDTO.SenderCode != "")
                    {
                        UrlWhiz = ConfigurationManager.AppSettings["TransactionalGateWayWhiz"].ToString();
                    }
                    else
                    {

                        UrlWhiz = ConfigurationManager.AppSettings["PromotionalGateWayWhiz"].ToString();
                    }

                    UrlWhiz = UrlWhiz.Replace("%26", "&");
                    UrlWhiz = UrlWhiz.Replace("[recipient]", CouponDTO.MobileNumber);
                    UrlWhiz = UrlWhiz.Replace("[message]", CouponDTO.Message);
                    UrlWhiz = UrlWhiz.Replace("[gateway]", ClientDTO.SenderCode);   //SMSGatewayDTO.Name

                    HttpWebRequest myRequesWhiz = (HttpWebRequest)WebRequest.Create(UrlWhiz);
                    myRequesWhiz.Method = "GET";
                    WebResponse myResponseWhiz = myRequesWhiz.GetResponse();
                    StreamReader srWhiz = new StreamReader(myResponseWhiz.GetResponseStream(), System.Text.Encoding.UTF8);
                    resultWhiz = srWhiz.ReadToEnd();
                    srWhiz.Close();

                    if (resultWhiz.Contains('|'))
                    {
                        //statuscode = result.Substring(0, result.IndexOf('|'));
                        statuscode = "";
                        string[] words = resultWhiz.Split('|');
                        foreach (string word in words)
                        {
                            Console.WriteLine(word);
                            try
                            {
                                int code = Convert.ToInt32(word);

                                statuscode = code.ToString();
                            }
                            catch (Exception)
                            {
                                string code = word.Replace(" ", "");
                                if (code == "Success")
                                {
                                    code = "0";
                                    statuscode = code.ToString();
                                    IsSent = true;

                                    CouponDTO.SentDateTime = System.DateTime.Now;
                                    CouponDTO.Id = 0;
                                    CouponDTO.IsExpired = false;
                                    int NewCouponId = CouponService.Create(CouponDTO);

                                    CouponDTONew = CouponService.GetById(NewCouponId);

                                    //Expire previous coupon
                                    CouponDTO CouponDTOPrevious = new CouponDTO();
                                    CouponDTOPrevious = CouponService.GetById(OldId);
                                    CouponDTOPrevious.IsExpired = true;
                                    CouponDTOPrevious.MessageId = resultWhiz;
                                    CouponService.Edit(CouponDTOPrevious);

                                    // Modify EcouponCampaign message count
                                    EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                                    EcouponCampaignDTO = EcouponCampaignService.GetById(CouponDTONew.EcouponCampaignId);
                                    EcouponCampaignDTO.ReceipentNumber = EcouponCampaignDTO.ReceipentNumber + "," + CouponDTO.MobileNumber;
                                    EcouponCampaignDTO.RecipientsCount = EcouponCampaignDTO.RecipientsCount + 1;
                                    if (EcouponCampaignDTO.GroupId == 0)
                                    {
                                        EcouponCampaignDTO.GroupId = null;
                                        EcouponCampaignDTO.Group = null;
                                    }

                                    EcouponCampaignDTO.RequiredCredits = CouponService.GetECouponCampaignRequiredCreditsByEcouponCampaignId(EcouponCampaignDTO.Id);

                                    EcouponCampaignService.EditForEcouponResend(EcouponCampaignDTO);

                                    //Modify client SMS credits
                                    ClientDTO.SMSCredit = ClientDTO.SMSCredit - ActualRequiredCredits;// RequiredCredit;
                                    ClientService.Edit(ClientDTO);

                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }

                    }
                    else
                    {
                        statuscode = resultWhiz;

                    }

                }
            }
            return CouponDTONew;
        }
        //Return  list of contacts
        public static List<ContactDTO> ReadExcelFile(int ClientId, string FilePath, bool IsValid)
        {
            List<ContactDTO> ContactDTOList = new List<ContactDTO>();
            ClientDTO ClientDTO = new ClientDTO();
            ClientDTO = ClientService.GetById(ClientId);
            if (ClientDTO.IsActive != true)
            {
                return ContactDTOList;
            }

            try
            {

                if (File.Exists(FilePath))
                {
                    ContactDTOList = Import(FilePath, IsValid);
                    return ContactDTOList;
                }

                return ContactDTOList;
            }
            catch (Exception)
            {
                throw;
            }
        }
        private static bool ActualSmsSend(string mobilenumber, string message, string Gateway, EcouponCampaignDTO EcouponCampaignDTO, ClientDTO ClientDTO, string CouponCode)
        {
            string result = "";
            bool IsSent = false;
            int SMSMsgCount = GetMessageCount(message);
            message = MsgCorrect(message);

            if (message != "" && mobilenumber != "")// Check for empty message.
            {

                string Url = ConfigurationManager.AppSettings["TransactionalGateWay"].ToString();
                Url = Url.Replace("%26", "&");
                Url = Url.Replace("[recipient]", mobilenumber);
                Url = Url.Replace("[message]", message);
                if (Gateway != "022751") //if (Gateway.ToLower() != "default")
                {
                    Url = Url.Replace("[gateway]", Gateway); //Gateway = "MSGBLS"
                }
                else
                {
                    Url = "";
                    Url = ConfigurationManager.AppSettings["PromotionalGateWay"].ToString();
                    Url = Url.Replace("%26", "&");
                    Url = Url.Replace("[recipient]", mobilenumber);
                    Url = Url.Replace("[message]", message);
                }

                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
                myRequest.Method = "GET";
                WebResponse myResponse = myRequest.GetResponse();
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
                result = sr.ReadToEnd();
                sr.Close();

                string statuscode = "";
                //if (result.Contains('|'))
                //    statuscode = result.Substring(0, result.IndexOf('|'));
                //else
                //    statuscode = result;

                //string SMSReplyMessage = SMSResult(statuscode) + "-" + result; //result

                if (result.Contains('|'))
                {
                    //statuscode = result.Substring(0, result.IndexOf('|'));
                    statuscode = "";
                    string[] words = result.Split('|');
                    foreach (string word in words)
                    {
                        Console.WriteLine(word);
                        try
                        {
                            int code = Convert.ToInt32(word);

                            statuscode = code.ToString();
                        }
                        catch (Exception)
                        {
                            string code = word.Replace(" ", "");
                            if (code == "Success")
                            {
                                code = "0";
                                statuscode = code.ToString();
                                IsSent = true;
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }

                }
                else
                {
                    statuscode = result;
                }

                myResponse.Close();
                if (IsSent == true)
                {
                CouponDTO CouponDTO = new CouponDTO();
                //CouponDTO.IsSuccess = true;
                CouponDTO.EcouponCampaignId = EcouponCampaignDTO.Id;
                CouponDTO.MobileNumber = mobilenumber;
                CouponDTO.Code = CouponCode;
                CouponDTO.IsRedeem = false;

                CouponDTO.MessageId = result;
                SettingDTO SettingDTO = new SettingDTO();
                SettingDTO = SettingService.GetById(1);
                double ActualSMSMsgCount = SettingDTO.NationalCouponSMSCount * SMSMsgCount;
                CouponDTO.MessageCount = SMSMsgCount;
                CouponDTO.RequiredCredits = ActualSMSMsgCount;

                CouponDTO.Message = message;
                //CouponDTO.MessageStatus = SMSReplyMessage;
                //CouponDTO.GatewayID = Gateway;
                CouponDTO.SentDateTime = System.DateTime.Now;
                CouponDTO.IsCouponSent = true;
                //CouponDTO.MessageID = statuscode;

                //if (statuscode == "1701")
                //{
                //    CampaignLogDTO.IsSuccess = true;
                //}
                //else if (statuscode != "1701")
                //{
                //    CampaignLogDTO.IsSuccess = false;
                //}
                CouponService.Create(CouponDTO);

                //// Reduce SMS Credits From Client
                //ClientDTO.SMSCredit = ClientDTO.SMSCredit - ActualSMSMsgCount;  //SMSMsgCount;
                //ClientService.Edit(ClientDTO);

                }

            }

            return IsSent; // result;
        }
        public static String SplitMobile(string Mobile, EcouponCampaignDTO EcouponCampaignDTO)
        {
            string result = "";
            bool IsSent = false;
            int FalseCount = 0;
            try
            {
                string finalstring = "";

                // Input string contain separators.
                string value1 = Mobile;

                char[] delimiter1 = new char[] { ',', ';' };   // <-- Split on these
                // ... Use StringSplitOptions.RemoveEmptyEntries.
                string[] array2 = value1.Split(delimiter1,
                    StringSplitOptions.RemoveEmptyEntries);

                //Console.WriteLine();
                foreach (string mobile in array2)
                {
                    Console.WriteLine(mobile);
                    bool isMessageSent = CheckCampainLogByCampaingIdAndMobile(EcouponCampaignDTO.Id, Mobile);

                    ClientDTO ClientDTO = new ClientDTO();
                    ClientDTO = ClientService.GetById(EcouponCampaignDTO.ClientId);

                    //SMSGatewayDTO SMSGatewayDTO = new SMSGatewayDTO();
                    //SMSGatewayDTO = SMSGatewayService.GetById(ClientDTO.SMSGatewayId);

                    if (isMessageSent == false)
                    {
                        Console.Write("Send SMS");
                        //if (ClientDTO.SMSCredit > 0)
                        //{
                            int ecouponcode = 0;
                        createnew:
                            CommonService CommonService = new CommonService();
                            ecouponcode = CommonService.GetRandomNumber();
                            string ecouponcodelength = ecouponcode.ToString();
                            if (ecouponcodelength.Length < 6 || ecouponcodelength.Length > 6)
                            {
                                goto createnew;
                            }
                            List<CouponDTO> CouponDTOList = new List<CouponDTO>();
                            CouponDTOList = CouponService.GetCouponListByCodeAndMobile(ecouponcode.ToString(), mobile);
                            if (CouponDTOList.Count == 0)
                            {
                                string Message = "";
                                EcouponCampaignDTO.Message = EcouponCampaignService.GetById(EcouponCampaignDTO.Id).Message;

                                //macros
                                List<Macros> MacrosList = Enum.GetValues(typeof(Macros)).Cast<Macros>().ToList();

                                ContactDTO ContactDTO = new ContactDTO();
                                ContactDTO = ContactService.GetContactByMobileNumberAndClientId(mobile, EcouponCampaignDTO.ClientId);

                                if (MacrosList.Count() > 0)
                                {
                                    foreach (var item in MacrosList)
                                    {

                                        if (item.ToString() == "FirstName")
                                        {
                                            string FirstName = "";
                                            FirstName = ContactDTO.FirstName;// CommonService.GetFirstname(ContactDTO.Name);
                                            EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", FirstName);
                                        }

                                        if (item.ToString() == "LastName")
                                        {
                                            string LastName = "";
                                            LastName = ContactDTO.LastName;// CommonService.GetLastname(ContactDTO.Name);
                                            EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", LastName);
                                        }

                                        if (item.ToString() == "BirthDate")
                                        {
                                            if (ContactDTO.BirthDate != null)
                                            {
                                                DateTime BirthDate = Convert.ToDateTime(ContactDTO.BirthDate);
                                                EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", BirthDate.ToString("dd-MMM"));
                                            }
                                            else { EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", ""); }
                                        }

                                        if (item.ToString() == "AnniversaryDate")
                                        {
                                            if (ContactDTO.AnniversaryDate != null)
                                            {
                                                DateTime AnniversaryDate = Convert.ToDateTime(ContactDTO.AnniversaryDate);
                                                EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", AnniversaryDate.ToString("dd-MMM"));
                                            }
                                            else { EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", ""); }
                                        }

                                        if (item.ToString() == "Email")
                                        {
                                            if (ContactDTO.Email != null)
                                            {
                                                string Email = ContactDTO.Email;
                                                EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", Email);
                                            }
                                            else { EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", ""); }
                                        }

                                        if (item.ToString() == "MobileNumber")
                                        {
                                            if (ContactDTO.MobileNumber != null)
                                            {
                                                string MobileNumber = ContactDTO.MobileNumber;
                                                EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", MobileNumber);
                                            }
                                            else { EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", ""); }
                                        }

                                        if (item.ToString() == "Gender")
                                        {
                                            if (ContactDTO.Gender != null)
                                            {
                                                string Gender = ContactDTO.Gender;

                                                //if (Gender == "0")
                                                //{
                                                //    Gender = "Male";
                                                //}
                                                //else
                                                //{
                                                //    Gender = "Female";
                                                //}

                                                EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", Gender);
                                            }
                                            else { EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", ""); }
                                        }

                                        if (item.ToString() == "ExpiresOn")
                                        {
                                            if (EcouponCampaignDTO.ExpiresOn != null)
                                            {
                                                DateTime ExpiresOn = Convert.ToDateTime(EcouponCampaignDTO.ExpiresOn);
                                                EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", ExpiresOn.ToString("dd-MMM-yy"));
                                            }
                                            else { EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", ""); }
                                        }

                                        if (item.ToString() == "Code")
                                        {
                                            string Code = ecouponcode.ToString();
                                            EcouponCampaignDTO.Message = EcouponCampaignDTO.Message.Replace("[" + item.ToString() + "]", Code);
                                        }

                                    }

                                    Message = EcouponCampaignDTO.Message;
                                    // Check the Message required credits and actual client credits
                                    double SMSMsgCount = GetMessageCount(Message);

                                    SettingDTO SettingDTO = new SettingDTO();
                                    SettingDTO = SettingService.GetById(1);
                                    SMSMsgCount = SMSMsgCount * SettingDTO.NationalCouponSMSCount;

                                    ////Check Credits
                                    //if (ClientDTO.SMSCredit >= SMSMsgCount)
                                    //{
                                        string sender = "";

                                        List<CouponDTO> CouponDTOListDuplicate = new List<CouponDTO>();
                                        CouponDTOListDuplicate = CouponService.GetCouponListByEcouponCampaignIdAndMobile(EcouponCampaignDTO.Id, mobile);
                                        if (CouponDTOListDuplicate.Count != 0)
                                        {
                                            ////If already sent then skip
                                            continue;
                                            ////foreach (var item in CouponDTOListDuplicate)
                                            ////{
                                            ////    if (item.IsExpired != true)
                                            ////    {
                                            ////        string MobileDuplicate = null;
                                            ////        CouponDTO CouponDTO = new CouponDTO();
                                            ////        CouponDTO = item;
                                            ////        CouponDTO.IsExpired=true;
                                            ////        CouponService.Edit(CouponDTO);

                                            ////        MobileDuplicate = item.MobileNumber;
                                            ////        Message = item.Message;
                                            ////        ecouponcode = Convert.ToInt32(item.Code);

                                            ////        if (ClientDTO.SenderCode != null && ClientDTO.SenderCode != "")
                                            ////        {
                                            ////            sender = ClientDTO.SenderCode;
                                            ////        }
                                            ////        else
                                            ////        {

                                            ////            sender = "022751";
                                            ////        }

                                            ////        IsSent = ActualSmsSend(mobile, Message, sender, EcouponCampaignDTO, ClientDTO, ecouponcode.ToString());
                                            ////        continue;
                                            ////    }

                                            ////}

                                        }

                                        if (ClientDTO.SenderCode != null && ClientDTO.SenderCode != "")
                                        {
                                            sender = ClientDTO.SenderCode;
                                        }
                                        else
                                        {

                                            sender = "022751";
                                        }

                                        IsSent = ActualSmsSend(mobile, Message, sender, EcouponCampaignDTO, ClientDTO, ecouponcode.ToString());
                                    //}
                                    //else goto nextprocess;

                                }

                                // Message = ReformatMsg(EcouponCampaignDTO.Message + " Your ecoupon code is " + ecouponcode + "");

                            }
                            else if (CouponDTOList.Count >= 1)
                            {
                                goto createnew;
                            }

                        //}
                        //else
                        //{
                        //    goto nextprocess;
                        //}

                    }
                    else
                    {

                    }
                }

                int TotatCouponSent = CouponService.GetCouponCountByEcouponCampaignId(EcouponCampaignDTO.Id);

                //if (EcouponCampaignDTO.RecipientsCount == TotatCouponSent)
                if (EcouponCampaignDTO.RecipientsCount <= TotatCouponSent)
                {
                    // Modify EcouponCampaign IsSent status
                    EcouponCampaignDTO.IsSent = true;
                    EcouponCampaignDTO.Message = EcouponCampaignService.GetById(EcouponCampaignDTO.Id).Message;
                    EcouponCampaignDTO.RequiredCredits = CouponService.GetECouponCampaignRequiredCreditsByEcouponCampaignId(EcouponCampaignDTO.Id);
                    EcouponCampaignDTO.CreditsDiffrence = EcouponCampaignDTO.ConsumedCredits - EcouponCampaignDTO.RequiredCredits;

                    if (EcouponCampaignDTO.ConsumedCredits != EcouponCampaignDTO.RequiredCredits)
                    {
                        if (EcouponCampaignDTO.CreditsDiffrence < 0)
                        {
                            //// deduct clients balance
                            ClientDTO ClientDTOUpdate = new ClientDTO();
                            ClientDTOUpdate = ClientService.GetById(EcouponCampaignDTO.ClientId);
                            ClientDTOUpdate.SMSCredit = ClientDTOUpdate.SMSCredit - (-(EcouponCampaignDTO.CreditsDiffrence));
                            ClientService.Edit(ClientDTOUpdate);

                            ////Reconcile Ecoupon Campaign
                            EcouponCampaignDTO.IsReconcile = true;
                            EcouponCampaignDTO.ReconcileDate = System.DateTime.Now;
                            EcouponCampaignService.EditEcouponCampaignFromBackend(EcouponCampaignDTO);

                        }
                        else if (EcouponCampaignDTO.CreditsDiffrence > 0)
                        {
                            ////Add clients balance
                            ClientDTO ClientDTOUpdate = new ClientDTO();
                            ClientDTOUpdate = ClientService.GetById(EcouponCampaignDTO.ClientId);
                            ClientDTOUpdate.SMSCredit = ClientDTOUpdate.SMSCredit + EcouponCampaignDTO.CreditsDiffrence;
                            ClientService.Edit(ClientDTOUpdate);

                            ////Reconcile Ecoupon Campaign
                            EcouponCampaignDTO.IsReconcile = true;
                            EcouponCampaignDTO.ReconcileDate = System.DateTime.Now;
                            EcouponCampaignService.EditEcouponCampaignFromBackend(EcouponCampaignDTO);

                        }
                    }
                    else if (EcouponCampaignDTO.CreditsDiffrence == 0)
                    {
                        EcouponCampaignDTO.IsReconcile = true;
                        EcouponCampaignDTO.ReconcileDate = System.DateTime.Now;
                        EcouponCampaignService.EditEcouponCampaignFromBackend(EcouponCampaignDTO);
                    }

                   // EcouponCampaignService.EditEcouponCampaignFromBackend(EcouponCampaignDTO);
                }

            nextprocess:
                result = finalstring;
            }

            catch (Exception ex)
            {

                result = "";

                using (FileStream file = new FileStream(Directory.GetCurrentDirectory() + "\\msgBlasterBackendService_Log.txt", FileMode.Append, FileAccess.Write))
                {
                    StreamWriter streamWriter = new StreamWriter(file);
                    streamWriter.WriteLine(System.DateTime.Now + " - " + "  SplitMobile()" + " - " + ex.Message);
                    streamWriter.Close();
                }

            }
            return result;
        }
        public void SendMessages()
        {
            try
            {
                //// Load Queue processor settings
                //sErrlocation = "Loading QueueProcessor Settings From QueueProcessorSettings.xml file-Line 69";
                //Load settings from QueueProcessorSettings.xml file (File present in basedirectory of application.)
                queuesettingsXML = new XmlDocument();
                queuesettingsXML.Load(ConfigurationManager.AppSettings["SETTIGNDIR_PATH"].ToString() + "QueueProcessorSettings.xml");
                MAXCHECKFORCONNECTION = Convert.ToInt32(queuesettingsXML.DocumentElement["maxcheckforgatewqycon"].InnerText);
                MAXCHECKFORRESPONSE = Convert.ToInt32(queuesettingsXML.DocumentElement["maxcheckforgatewayresponse"].InnerText);
                UPDATEBALAFTER = Convert.ToInt32(queuesettingsXML.DocumentElement["updatebalafterevery"].InnerText);
                MAXSMSLENGTH = Convert.ToInt32(queuesettingsXML.DocumentElement["maxsmslength"].InnerText);
                SMSBLOCKLENGTH = Convert.ToInt32(queuesettingsXML.DocumentElement["smsblocklength"].InnerText);
                MAXMOBILELENGTH = Convert.ToInt32(queuesettingsXML.DocumentElement["maxmobilelength"].InnerText);

                sErrlocation = "Select All files from SMSQueue Folder - Line 112";
                string[] files = System.IO.Directory.GetFiles(SMSQDIR, "*.xml"); // Get all *.xml files from SMSQUEUE folder
                if (files.Length > 0)
                {
                    General.WriteInFile("\r\n" + "Total Number of Files = " + files.Length + "");
                    General.WriteInFile("=========================================================================================================");
                    foreach (string file in files)
                    {
                        baseFileName = System.IO.Path.GetFileName(file);
                        // Prepare file path for copying file to BAD or SENT folder depending on situation.
                        sentQFile = SENTQDIR + baseFileName;
                        sourceQFile = SMSQDIR + baseFileName;
                        badQFile = BADQDIR + baseFileName;

                        // Check for Xml File Validation against the Schema
                        if (!System.IO.File.Exists(ConfigurationManager.AppSettings["SETTIGNDIR_PATH"].ToString() + "XmlSchema.xsd"))
                        {
                            General.WriteInFile("SMSQueue processor was terminated because XmlSchema.xsd file is not available in " + APP_PATH + " directory \r\n");
                            break;
                        }

                        sErrlocation = "File Validation against the Schema - Line 133";
                        if (!IsValidFile(sourceQFile))
                        {
                            MoveFileToBadFolder(schemaValidationError); // Invalid file
                            General.WriteInFile(baseFileName + " file moved to BAD folder because, this file is invalid according to Schema Validation.\r\n");
                            continue;
                        }

                        sErrlocation = "Load basefile for sending - Line 140";
                        baseFileXML = new XmlDocument();
                        baseFileXML.Load(sourceQFile); // load xml file from SMSQUEUE folder to process

                        strcampaignId = baseFileXML.DocumentElement["campaignId"].InnerText;
                        strclientId = baseFileXML.DocumentElement["clientId"].InnerText;
                        strSender = baseFileXML.DocumentElement["sender"].InnerText;
                        double number;
                        bool IsNumeric = double.TryParse(strSender, out number); // Check the number is in Numeric form or not
                        if (IsNumeric && strSender.Length == 10)
                            strSender = "91" + strSender;

                        campaignname = ReformatMsg(baseFileXML.DocumentElement["campaignname"].InnerText);

                        // Check for validation of recipient number count and message count
                        // i.e message count > 1 AND != recipient number count than it is invalid file.
                        XmlNodeList MessageToSend = baseFileXML.SelectNodes("/packet/numbers/message");
                        XmlNodeList RecipientsToSendMessage = baseFileXML.SelectNodes("/packet/numbers/number");
                        if (MessageToSend.Count > 1 && MessageToSend.Count != RecipientsToSendMessage.Count)
                        {
                            // This indicates that Msg count & Number count doesnot match
                            MoveFileToBadFolder("Msg count & Number count doesnot match.");
                            General.WriteInFile(baseFileName + " file is moved to BAD folder because Msg count & Number count doesnot match.\r\n");
                            continue;
                        }

                        ClientDTO = new MsgBlaster.DTO.ClientDTO();
                        CampaignDTO = new MsgBlaster.DTO.CampaignDTO();

                        ClientDTO.Id = Convert.ToInt32(strclientId);
                        CampaignDTO.Id =Convert.ToInt32( strcampaignId);

                        ClientDTO = MsgBlaster.Service.ClientService.GetById(ClientDTO.Id);
                        CampaignDTO = MsgBlaster.Service.CampaignService.GetById(CampaignDTO.Id);

                        // Befor AddToSMSQueue() validate user
                        sErrlocation = "Check for Valid User - Line 195";
                        int result = ClientDTO.Id;// oClient.IsValidUser(oClient);
                        if (result == 0)// Invalid User
                        {
                            MoveFileToBadFolder("Invalid user.");
                            General.WriteInFile(baseFileName + " file  moved to BAD folder because of invalid campaignId & clientId.\r\n");
                            continue;
                        }

                        //if (result == 2) // Database Error
                        //{
                        //    General.WriteInFile(baseFileName + " file is skiped due to database error during User validation.\r\n");
                        //    continue;//skip this file and continue
                        //}

                        General.WriteInFile("Opening Balance = " + ClientDTO.SMSCredit);// ClientDBOperation.ActualCredits(oClient));
                        // Check for time restriction over message sending for this user
                        sErrlocation = "Check for Send time restriction - Line 214";
                        //double FROMTIME = Convert.ToDouble(oClient.SendFromTime.Replace(':', '.'));
                        //double UPTOTIME = Convert.ToDouble(oClient.SendUptoTime.Replace(':', '.'));
                        double currentTime = Convert.ToDouble(System.DateTime.Now.Hour + "." + System.DateTime.Now.Minute);
                        //if (currentTime < FROMTIME || currentTime > UPTOTIME)
                        //{
                        //    // skip this file due to time restriction.
                        //    General.WriteInFile(baseFileName + " file is skiped due to send time restriction.\r\n");// +
                        //    continue;
                        //}

                        if (baseFileXML.SelectSingleNode("//scheduleddate") != null)
                        {
                            DateTime ScheduledDate;
                            try
                            {
                                ScheduledDate = Convert.ToDateTime(baseFileXML.DocumentElement["scheduleddate"].InnerText);
                            }
                            catch (Exception ex)
                            {
                                MoveFileToBadFolder("Unrecognized scheduled date.");
                                General.WriteInFile(baseFileName + " file moved to BAD folder because of Unrecognized scheduled date.\r\n");
                                continue;
                            }
                            // 1 = Scheduled datetime is > current datetime
                            // 0 = Scheduled datetime = current datetime
                            // -1 = Scheduled datetime < current datetime
                            if (DateTime.Compare(ScheduledDate, System.DateTime.Now) == 1)
                            {
                                // This file will be send in futuer so skip this file
                                General.WriteInFile(baseFileName + " file is skiped due to scheduled datetime restriction.\r\n");
                                continue;
                            }
                        }
                        // Function for preapearing message to broadcast
                        AddToSMSQueue();
                    }
                    General.WriteInFile("========================================================================================================= ");
                }
            }
            catch (Exception ex)
            {
                General.WriteInFile(sErrlocation + "\r\n" + ex.Message);
                General.WriteInFile("========================================================================================================= ");
            }
        }
        public static void GetFolderList()
        {
            string[] folders = Directory.GetDirectories(ConfigurationManager.AppSettings["SQLiteDatabaseFolder"].ToString(), "*", System.IO.SearchOption.AllDirectories);
            int TotalFolders = folders.Count();

            try
            {
                foreach (var folder in folders)
                {
                    try
                    {
                        string[] files = System.IO.Directory.GetFiles(folder, "*");
                        string folderpath = folder;
                        string[] words = folderpath.Split('\\');
                        int ClientId = 0;
                        foreach (string word in words)
                        {
                            try
                            {
                                ClientId = Convert.ToInt32(word);
                            }
                            catch
                            {
                                continue;
                            }
                        }
                        try
                        {
                            foreach (var file in files)
                            {
                                string filepath = file;

                                // Check ClientPresentOrNot
                                ClientDTO ClientDTO = new ClientDTO();
                                ClientDTO = ClientService.GetById(ClientId);
                                if (ClientDTO != null)
                                {
                                    DataTable dtContacts = GetAllContacts(filepath);
                                   // DataTable dtClients = GetClients(filepath);

                                    ReadSqlite(ClientId, filepath);
                                    SaveOtherContact(ClientId, filepath);

                                    if (File.Exists(filepath))
                                    {
                                        File.Delete(filepath);
                                    }
                                }

                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            catch
            {

            }
        }
 public ClientDTO SendMessagesForTodaysBirthday(string accessId, ClientDTO ClientDTO)
 {
     try
     {
         return ClientService.SendMessagesForTodaysBirthday(ClientDTO);
     }
     catch (TimeoutException)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.RequestTimeout)
         {
             Content = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
     catch (Exception)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
         {
             Content = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
 }
        //Get credit request by id
        public static CreditRequestDTO GetById(int Id)
        {
            try
            {
                UnitOfWork uow = new UnitOfWork();
                CreditRequest CreditRequest = uow.CreditRequestRepo.GetById(Id);
                CreditRequestDTO CreditRequestDTO = Transform.CreditRequestToDTO(CreditRequest);

                ClientDTO ClientDTO = new ClientDTO();
                ClientDTO = ClientService.GetById(CreditRequestDTO.ClientId);
                CreditRequestDTO.ClientName = ClientDTO.Company;

                UserDTO UserDTO = new UserDTO();
                UserDTO = UserService.GetById(CreditRequestDTO.RequestedBy);
                CreditRequestDTO.UserName = UserDTO.Name;

                return CreditRequestDTO;
            }
            catch
            {
                throw;
            }
        }
        //GetClientUserByEmailAndPassword
        /// <summary>
        /// Sign In user
        /// </summary>
        /// <param name="Email">Email Id of active user</param>
        /// <param name="Password">Password of the active user</param>
        /// <returns></returns>             
        public static UserDTO SignIn(string Email, string Password)
        {
            try
            {
                UserDTO UserDTO = new UserDTO();
                List<UserDTO> UserDTOList = new List<UserDTO>();

                UnitOfWork uow = new UnitOfWork();
                IEnumerable<User> User = uow.UserRepo.GetAll().Where(e => e.Email.ToLower() == Email.ToLower() && e.Password == Password && e.IsActive == true);
                if (User != null)
                {
                    foreach (var item in User)
                    {
                        //ClientDTOList.Add(Transform.ClientToDTO(item));
                        UserDTO = Transform.UserToDTO(item);
                        GlobalSettings.LoggedInUserId = UserDTO.Id;
                        UserDTO.UserAccessPrivileges = GetUserAccess(UserDTO.UserType.ToString());
                        // Check Client is Active or not
                        ClientDTO ClientDTO = new ClientDTO();
                        ClientDTO = ClientService.GetById(UserDTO.ClientId);
                        GlobalSettings.LoggedInClientId = ClientDTO.Id;

                        if (ClientDTO.IsActive != true)
                        {
                            UserDTO = null;
                        }
                        //HttpContext.Current.Session["LoggedClient"] = ClientDTO;
                        //HttpContext.Current.Session["LoggedClientId"] = ClientDTO.Id;

                    }
                }
                return UserDTO;
            }
            catch
            {
                throw;
            }
        }
        //Get credit request list by  client id
        public static List<CreditRequestDTO> GetCreditRequestsbyClientId(int ClientId, string search)
        {
            List<CreditRequestDTO> CreditRequestDTOList = new List<CreditRequestDTO>();
            try
            {
                UnitOfWork uow = new UnitOfWork();
                IEnumerable<CreditRequest> CreditRequest = uow.CreditRequestRepo.GetAll().Where(e => e.ClientId == ClientId).OrderByDescending(e => e.Date).ToList();
                if (CreditRequest != null)
                {
                    if (search != "" & search != null)
                    {

                        bool IsDate = CommonService.IsDate(search);
                        if (IsDate != true)
                        {
                            // string search
                            // var CreditRequestsearch = CreditRequest.Where(e => e.Amount.ToString().Contains(search.ToLower()) || e.ClientId.ToString().Contains(search) || e.GrandTotal.ToString().Contains(search) || e.IsProvided.ToString().Contains(search) || e.OldBalance.ToString().Contains(search) || e.PartnerId.ToString().Contains(search) || e.RatePerSMS.ToString().Contains(search) || e.RequestedCredit.ToString().Contains(search) || e.Tax.ToString().Contains(search));
                            var CreditRequestsearch = CreditRequest.Where(e => e.OldBalance.ToString() == (search) || e.RatePerSMS.ToString() == (search) || e.RequestedCredit.ToString() == (search)).OrderByDescending(e => e.Date);

                            if (CreditRequestsearch != null)
                            {
                                foreach (var item in CreditRequestsearch)
                                {
                                    CreditRequestDTO CreditRequestDTO = new CreditRequestDTO();
                                    CreditRequestDTO = Transform.CreditRequestToDTO(item);

                                    ClientDTO ClientDTO = new ClientDTO();
                                    ClientDTO = ClientService.GetById(item.ClientId);
                                    CreditRequestDTO.ClientName = ClientDTO.Company;

                                    UserDTO UserDTO = new UserDTO();
                                    UserDTO = UserService.GetById(item.RequestedBy);
                                    CreditRequestDTO.UserName = UserDTO.Name;

                                    CreditRequestDTOList.Add(CreditRequestDTO);// (Transform.CreditRequestToDTO(item));
                                }
                            }
                            return CreditRequestDTOList;
                        }
                        else
                        {
                            //date wise search
                            DateTime date = Convert.ToDateTime(search);
                            var CreditRequestsearch = CreditRequest.Where(e => e.Date >= date && e.Date < date.AddDays(1) || e.ProvidedDate >= date && e.ProvidedDate < date.AddDays(1)).OrderByDescending(e => e.Date);

                            if (CreditRequestsearch != null)
                            {
                                foreach (var item in CreditRequestsearch)
                                {
                                    CreditRequestDTO CreditRequestDTO = new CreditRequestDTO();
                                    CreditRequestDTO = Transform.CreditRequestToDTO(item);

                                    ClientDTO ClientDTO = new ClientDTO();
                                    ClientDTO = ClientService.GetById(item.ClientId);
                                    CreditRequestDTO.ClientName = ClientDTO.Company;

                                    UserDTO UserDTO = new UserDTO();
                                    UserDTO = UserService.GetById(item.RequestedBy);
                                    CreditRequestDTO.UserName = UserDTO.Name;

                                    CreditRequestDTOList.Add(CreditRequestDTO);// (Transform.CreditRequestToDTO(item));
                                }
                            }
                            return CreditRequestDTOList;
                        }

                    }
                    else
                    {
                        foreach (var item in CreditRequest)
                        {
                            CreditRequestDTO CreditRequestDTO = new CreditRequestDTO();
                            CreditRequestDTO = Transform.CreditRequestToDTO(item);

                            ClientDTO ClientDTO = new ClientDTO();
                            ClientDTO = ClientService.GetById(item.ClientId);
                            CreditRequestDTO.ClientName = ClientDTO.Company;

                            UserDTO UserDTO = new UserDTO();
                            UserDTO = UserService.GetById(item.RequestedBy);
                            CreditRequestDTO.UserName = UserDTO.Name;

                            CreditRequestDTOList.Add(CreditRequestDTO);// (Transform.CreditRequestToDTO(item));
                        }
                    }
                }

                return CreditRequestDTOList;
            }
            catch (Exception)
            {

                throw;
            }
        }
        public static void CreatePacket()
        {
            StringBuilder recipientnumberslist = new StringBuilder();

            try
            {
                bool ismailmarge = false;
                int requiredCreditTosendmsg = 0;
                //DataTable dtContact = new DataTable();
                int MOBILENUMBERLEN = 0;
                string xmlpacket = null;
                List<CampaignDTO> CampaignDTOList = CampaignService.GetCampaignNotSentList();
                if (CampaignDTOList.Count != 0)
                {
                    foreach (var item in CampaignDTOList)
                    {
                        // create xml packet
                        DataTable dtContact = new DataTable();

                        xmlpacket = "<?xml version=" + "\"1.0\"?>";
                        xmlpacket += "<packet>";
                        xmlpacket += "<mbversion>MessageBlaster_Web</mbversion>";
                        xmlpacket += "<messagesource>MSGBLASTER</messagesource>";
                        //DataTable regInfoDT = oCompanyInfo.LoadAll();
                        ClientDTO ClientDTO = new ClientDTO();
                        ClientDTO = ClientService.GetById(item.ClientId);

                        SettingDTO SettingDTO = new SettingDTO();
                        SettingDTO = SettingService.GetById(1);
                        MOBILENUMBERLEN = SettingDTO.MobileNumberLength;

                        ArrayList recipientsnumbers = new ArrayList();
                        MessageLogDTO oMessageLog = new MessageLogDTO();
                        string[] recipients;
                        if (item.GroupId == null) // To check wheather the user sending Group message
                        {
                            recipients = item.RecipientsNumber.ToString().Split(',');
                        }
                        else
                        {
                            recipients = item.RecipientsNumber.ToString().Split(',');
                        }
                        if (recipients.Length == 0)
                        {
                            //oUcButtonControl.showMessage(frmButtonControl.Messageflag.warningMessage, "Select recipients first.");
                            return;
                        }
                        for (int i = 0; i < recipients.Length; i++) // Loop through each recipient number & remove duplicate numbers
                        {
                            if (!string.IsNullOrEmpty(recipients[i].ToString())) // Don`t allow empty number
                            {
                                string mobileNumber = GetValidMobileNumber(recipients[i].ToString().Trim()); // Get only digits from Mobile number
                                if (mobileNumber.Length >= MOBILENUMBERLEN) // Check for valid mobile number
                                {
                                    mobileNumber = mobileNumber.Substring(mobileNumber.Length - MOBILENUMBERLEN);
                                    if (!recipientsnumbers.Contains(mobileNumber)) // Check for number duplication.
                                    {
                                        recipientsnumbers.Add(mobileNumber);
                                        recipientnumberslist.Append(mobileNumber).Append(',');
                                    }
                                }
                            }
                        }
                        if (recipientnumberslist.Length != 0)
                        {
                            oMessageLog.Recipients = recipientnumberslist.ToString().Substring(0, recipientnumberslist.Length - 1);
                        }

                        MsgInformationDTO _oMsginfo = new MsgInformationDTO();

                        _oMsginfo.CampaignId = item.Id;// regInfoDT.Rows[0]["SerialKey"].ToString();
                        //xmlpacket += "<cdkey>" + regInfoDT.Rows[0]["SerialKey"].ToString() + "</cdkey>";
                        xmlpacket += "<campaignId>" + _oMsginfo.CampaignId + "</campaignId>";
                        _oMsginfo.ClientId = item.ClientId;// MachineID.Value();
                        //xmlpacket += "<machineid>" + _oMsginfo.MachineID + "</machineid>";
                        xmlpacket += "<clientId>" + _oMsginfo.ClientId + "</clientId>";

                        if (!string.IsNullOrEmpty(item.Name)) // check for TemplateName
                        {
                            //xmlpacket += "<campaignname>" + MsgCorrect(lkupTemplate.Text) + "</campaignname>";
                            xmlpacket += "<campaignname>" + MsgCorrect(item.Name.ToString()) + "</campaignname>";
                            oMessageLog.MessageTemplateID = _oMsginfo.CampaignId;
                        }
                        else
                        {
                            xmlpacket += "<campaignname>Direct_Message</campaignname>";
                            oMessageLog.MessageTemplateID = _oMsginfo.CampaignId;
                        }

                        if (!string.IsNullOrEmpty(item.GroupId.ToString())) //nameOfGroupForMsgSending
                        {
                            GroupDTO GroupDTO = new GroupDTO();
                            GroupDTO = GroupService.GetById(Convert.ToInt32(item.GroupId));
                            xmlpacket += "<groupname>" + MsgCorrect(GroupDTO.Name) + "</groupname>"; // nameOfGroupForMsgSending
                            oMessageLog.RecipientType = GroupDTO.Name;
                        }
                        else if (!string.IsNullOrEmpty(item.Name))  //nameOfImportedFile // Check for is direct message to imported contact
                        {
                            oMessageLog.RecipientType = item.Name;//  nameOfImportedFile ;
                        }
                        else
                        {
                            oMessageLog.RecipientType = "Direct";
                        }

                        oMessageLog.MessageDateTime = Convert.ToString(System.DateTime.Now);
                        xmlpacket += "<senddate>" + System.DateTime.Now.ToString("d/MMM/yyyy") + "</senddate>";

                        if (!string.IsNullOrEmpty(item.ScheduledDate.ToString())) //scheduledDate.Text // check for sheduled Date
                        {
                            DateTime ScheduledDateTime = DateTime.Parse(item.ScheduledDate.ToString());
                            if (item.ScheduledTime == null || item.ScheduledTime == "")
                            {
                                item.ScheduledTime = "12:00 AM";
                            }
                            DateTime ScheduledTime = Convert.ToDateTime(item.ScheduledTime);
                            ScheduledDateTime = ScheduledDateTime.AddHours(ScheduledTime.TimeOfDay.Hours);
                            ScheduledDateTime = ScheduledDateTime.AddMinutes(ScheduledTime.TimeOfDay.Minutes);
                            DateTime ActualScheduleDatetime = Convert.ToDateTime(item.ScheduledDate.ToString("MM/dd/yyyy") + " " + ScheduledDateTime.TimeOfDay); ;
                            xmlpacket += "<scheduleddate>" + ActualScheduleDatetime.ToString("dd/MMM/yyyy HH:mm tt") + "</scheduleddate>";
                            oMessageLog.MessageScheduledDateTime = Convert.ToString(ScheduledDateTime);
                        }

                        oMessageLog.MessageText = item.Message.ToString().Replace("'", "''"); //memoMessagetxt.Text.Replace("'", "''");

                        if (FormatMessageText(item.Message)) //memoMessagetxt.Text
                        {
                            ismailmarge = true;
                            xmlpacket += "<messagetype>MAILMERGE</messagetype>";
                            oMessageLog.MessageTemplateType = "MAILMERGE";
                            // Get information of numbers which are in Contact list to foramte mail-marge-message
                            string nameOfGroupForMsgSending = null;

                            if (nameOfGroupForMsgSending == null)
                                dtContact = CommonService.SelectContatsInNumber(recipientnumberslist.ToString().Substring(0, recipientnumberslist.Length - 1), item.ClientId);
                            else
                                dtContact = CommonService.SelectContatsInNumber(recipientnumberslist.ToString().Substring(0, recipientnumberslist.Length - 1), item.ClientId);
                        }
                        else
                        {

                            xmlpacket += "<messagetype>NORMAL</messagetype>";
                            oMessageLog.MessageTemplateType = "NORMAL";
                        }

                        oMessageLog.Count = recipientsnumbers.Count;
                        xmlpacket += "<messagecount>" + recipientsnumbers.Count.ToString() + "</messagecount>";

                        //oMessageLog.SenderNumber = lookUpSender.Text;
                        List<UserDTO> UserDTOList = new List<UserDTO>();
                        UserDTOList = UserService.GetUsersbyClientId(ClientDTO.Id, "");
                        if (UserDTOList.Count != 0)
                        {
                            foreach (var itemuser in UserDTOList)
                            {
                                if (itemuser.UserType == "Admin")
                                {
                                    oMessageLog.SenderNumber = itemuser.Mobile;
                                    xmlpacket += "<sender>" + MsgCorrect(oMessageLog.SenderNumber) + "</sender>";
                                }

                            }
                        }

                        xmlpacket += "<numbers>";
                        if (ismailmarge)
                            requiredCreditTosendmsg = AddMsgRecipToXmlpacketMailMerge(item.Message, recipientsnumbers, dtContact.DefaultView, xmlpacket, _oMsginfo, recipientsnumbers.Count);
                        else
                            requiredCreditTosendmsg = AddMsgRecipToXmlpacket(item.Message, recipientsnumbers, xmlpacket, _oMsginfo, recipientsnumbers.Count) * recipientsnumbers.Count;

                        //xmlpacket += "</numbers>";
                        //xmlpacket += "</packet>";
                        //_oMsginfo.xmlpacket = xmlpacket;
                        //_oMsginfo.RequiredCredits = requiredCreditTosendmsg;
                        //Byte[] array = Serializeobject(_oMsginfo);
                        //Byte[] checksum = new MD5CryptoServiceProvider().ComputeHash(array); // calculate checksum for validation

                        //if (requiredCreditTosendmsg > recipientsnumbers.Count)
                        //{
                        //    //DialogResult dlg = XtraMessageBox.Show("You will be charged " + requiredCreditTosendmsg + " credits to send this message." + "\r\n" + "Do you want to send ?", "Conformation", MessageBoxButtons.YesNo);
                        //    //if (dlg == DialogResult.Yes)
                        //    //{

                        //    string responsefromService = SendMessage(array, checksum);
                        //    Response(responsefromService);

                        //    //}
                        //    //else
                        //    //{
                        //    //oUcButtonControl.ShowSend = true;
                        //    //oUcButtonControl.showMessage(frmButtonControl.Messageflag.none, "");
                        //    //oUcButtonControl.ButtonView();
                        //    //this.Update();
                        //    //}
                        //}
                        //else
                        //{
                        //    string responsefromService = SendMessage(array, checksum);
                        //    Response(responsefromService);
                        //}
                    }
                }

            }
            catch (WebException ex)
            {
                //oUcButtonControl.showMessage(frmButtonControl.Messageflag.errorMessage, Global.DisplayConnectionError(ex));
                throw;
            }
        }
        //Get document list by client id
        public static List<DocumentDTO> GetDocumentListByClientId(int ClientId)
        {
            List<DocumentDTO> DocumentDTOList = new List<DocumentDTO>();

            try
            {

                using (var uow = new UnitOfWork())
                {
                    IEnumerable<Document> Document = uow.DocumentRepo.GetAll().Where(e => e.ClientId == ClientId);
                    if (Document != null)
                    {
                        foreach (var item in Document)
                        {
                            DocumentDTO DocumentDTO = new DocumentDTO();
                            DocumentDTO = Transform.DocumentToDTO(item);
                            UserDTO UserDTO = new UserDTO();
                            UserDTO = UserService.GetById(DocumentDTO.UserId);
                            DocumentDTO.User = UserDTO.Name;

                            ClientDTO ClientDTO = new ClientDTO();
                            ClientDTO = ClientService.GetById(DocumentDTO.ClientId);
                            DocumentDTO.Client = ClientDTO.Company;

                            DocumentDTOList.Add(DocumentDTO);
                        }
                    }
                }

                return DocumentDTOList;
            }
            //catch (LoggedInUserException)
            //{
            //    throw new System.TimeoutException();
            //}
            catch (Exception)
            {

                throw;
            }
        }
 private static ArrayList getFieldValueList(ClientDTO ClientDTO)
 {
     throw new NotImplementedException();
 }
        public static String SplitMobile(string Mobile, CampaignDTO CampaignDTO)
        {
            string result = "";

            try
            {
                string finalstring = "";

                // Input string contain separators.
                string value1 = Mobile;

                char[] delimiter1 = new char[] { ',', ';' };   // <-- Split on these
                // ... Use StringSplitOptions.RemoveEmptyEntries.
                string[] array2 = value1.Split(delimiter1,
                    StringSplitOptions.RemoveEmptyEntries);

                //Console.WriteLine();
                foreach (string mobile in array2)
                {
                    Console.WriteLine(mobile);
                    bool isMessageSent = CheckCampainLogByCampaingIdAndMobile(CampaignDTO.Id, Mobile);

                    ClientDTO ClientDTO = new ClientDTO();
                    ClientDTO = ClientService.GetById(CampaignDTO.ClientId);

                    //SMSGatewayDTO SMSGatewayDTO = new SMSGatewayDTO();
                    //SMSGatewayDTO = SMSGatewayService.GetById(ClientDTO.SMSGatewayId);

                    if (isMessageSent == false)
                    {
                        Console.Write("Send SMS");
                        // Check the Message required credits and actual client credits
                        string message = "";
                        CampaignDTO.Message = CampaignService.GetById(CampaignDTO.Id).Message;
                        //// macros

                               List<Macros> MacrosList = Enum.GetValues(typeof(Macros)).Cast<Macros>().ToList();
                               ContactDTO ContactDTO = new ContactDTO();
                               ContactDTO = ContactService.GetContactByMobileNumberAndClientId(mobile, CampaignDTO.ClientId);

                                 if (MacrosList.Count() > 0)
                                    {
                                   foreach (var item in MacrosList)
                                   {

                                       if (item.ToString() == "FirstName")
                                       {
                                           string FirstName = "";
                                           FirstName = CommonService.GetFirstname(ContactDTO.Name);
                                           CampaignDTO.Message = CampaignDTO.Message.Replace("[" + item.ToString() + "]", FirstName);
                                       }

                                       if (item.ToString() == "LastName")
                                       {
                                           string LastName = "";
                                           LastName = CommonService.GetLastname(ContactDTO.Name);

                                           CampaignDTO.Message = CampaignDTO.Message.Replace("[" + item.ToString() + "]", LastName);
                                       }

                                   }

                                   message = CampaignDTO.Message;

                                   CampaignDTO.Message = ReformatMsg(message);
                                   int SMSMsgCount = GetMessageCount(message);

                                   if (ClientDTO.SMSCredit >= SMSMsgCount)
                                   {
                                       if (CampaignLogService.GetCampaignLogListByCampaignIdAndMobile(CampaignDTO.Id, mobile).Count != 0)
                                       {
                                           continue;
                                       }

                                       //CampaignDTO.Message
                                       string sender = "";
                                       if (ClientDTO.SenderCode != null && ClientDTO.SenderCode != "")
                                       {
                                           sender = ClientDTO.SenderCode;
                                       }
                                       else
                                       {

                                           sender = "022751";
                                       }

                                       ActualSmsSend(mobile, CampaignDTO.Message, sender, CampaignDTO, ClientDTO);

                                   }
                                   else
                                   {
                                       goto nextprocess;
                                   }

                               }

                        //CampaignDTO.Message = ReformatMsg(message);
                        //int SMSMsgCount = GetMessageCount(message);

                        //if (ClientDTO.SMSCredit >= SMSMsgCount)
                        //{
                        //     //CampaignDTO.Message
                        //    ActualSmsSend(mobile, CampaignDTO.Message, SMSGatewayDTO.Name, CampaignDTO, ClientDTO);

                        //}
                        //else
                        //{
                        //    goto nextprocess;
                        //}

                    }
                    else
                    {

                    }
                }

                // Modify Campaign IsSent status
                CampaignDTO.IsSent = true;
                CampaignDTO.Message = CampaignService.GetById(CampaignDTO.Id).Message;
                CampaignService.EditCampaignFromBackend(CampaignDTO);

                nextprocess:
                result = finalstring;
            }

            catch (Exception ex)
            {

                result = "";

                using (FileStream file = new FileStream(Directory.GetCurrentDirectory() + "\\msgBlasterBackendService_Log.txt", FileMode.Append, FileAccess.Write))
                {
                    StreamWriter streamWriter = new StreamWriter(file);
                    streamWriter.WriteLine(System.DateTime.Now + " - " + "  SplitMobile()" + " - " + ex.Message);
                    streamWriter.Close();
                }

            }
            return result;
        }
Beispiel #30
0
        public void SendMessages()
        {
            try
            {
                //// Load Queue processor settings
                //sErrlocation = "Loading QueueProcessor Settings From QueueProcessorSettings.xml file-Line 69";
                //Load settings from QueueProcessorSettings.xml file (File present in basedirectory of application.)
                queuesettingsXML = new XmlDocument();
                queuesettingsXML.Load(ConfigurationManager.AppSettings["SETTIGNDIR_PATH"].ToString() + "QueueProcessorSettings.xml");
                MAXCHECKFORCONNECTION = Convert.ToInt32(queuesettingsXML.DocumentElement["maxcheckforgatewqycon"].InnerText);
                MAXCHECKFORRESPONSE   = Convert.ToInt32(queuesettingsXML.DocumentElement["maxcheckforgatewayresponse"].InnerText);
                UPDATEBALAFTER        = Convert.ToInt32(queuesettingsXML.DocumentElement["updatebalafterevery"].InnerText);
                MAXSMSLENGTH          = Convert.ToInt32(queuesettingsXML.DocumentElement["maxsmslength"].InnerText);
                SMSBLOCKLENGTH        = Convert.ToInt32(queuesettingsXML.DocumentElement["smsblocklength"].InnerText);
                MAXMOBILELENGTH       = Convert.ToInt32(queuesettingsXML.DocumentElement["maxmobilelength"].InnerText);

                sErrlocation = "Select All files from SMSQueue Folder - Line 112";
                string[] files = System.IO.Directory.GetFiles(SMSQDIR, "*.xml"); // Get all *.xml files from SMSQUEUE folder
                if (files.Length > 0)
                {
                    General.WriteInFile("\r\n" + "Total Number of Files = " + files.Length + "");
                    General.WriteInFile("=========================================================================================================");
                    foreach (string file in files)
                    {
                        baseFileName = System.IO.Path.GetFileName(file);
                        // Prepare file path for copying file to BAD or SENT folder depending on situation.
                        sentQFile   = SENTQDIR + baseFileName;
                        sourceQFile = SMSQDIR + baseFileName;
                        badQFile    = BADQDIR + baseFileName;

                        // Check for Xml File Validation against the Schema
                        if (!System.IO.File.Exists(ConfigurationManager.AppSettings["SETTIGNDIR_PATH"].ToString() + "XmlSchema.xsd"))
                        {
                            General.WriteInFile("SMSQueue processor was terminated because XmlSchema.xsd file is not available in " + APP_PATH + " directory \r\n");
                            break;
                        }

                        sErrlocation = "File Validation against the Schema - Line 133";
                        if (!IsValidFile(sourceQFile))
                        {
                            MoveFileToBadFolder(schemaValidationError); // Invalid file
                            General.WriteInFile(baseFileName + " file moved to BAD folder because, this file is invalid according to Schema Validation.\r\n");
                            continue;
                        }

                        sErrlocation = "Load basefile for sending - Line 140";
                        baseFileXML  = new XmlDocument();
                        baseFileXML.Load(sourceQFile); // load xml file from SMSQUEUE folder to process

                        strcampaignId = baseFileXML.DocumentElement["campaignId"].InnerText;
                        strclientId   = baseFileXML.DocumentElement["clientId"].InnerText;
                        strSender     = baseFileXML.DocumentElement["sender"].InnerText;
                        double number;
                        bool   IsNumeric = double.TryParse(strSender, out number); // Check the number is in Numeric form or not
                        if (IsNumeric && strSender.Length == 10)
                        {
                            strSender = "91" + strSender;
                        }

                        campaignname = ReformatMsg(baseFileXML.DocumentElement["campaignname"].InnerText);

                        // Check for validation of recipient number count and message count
                        // i.e message count > 1 AND != recipient number count than it is invalid file.
                        XmlNodeList MessageToSend           = baseFileXML.SelectNodes("/packet/numbers/message");
                        XmlNodeList RecipientsToSendMessage = baseFileXML.SelectNodes("/packet/numbers/number");
                        if (MessageToSend.Count > 1 && MessageToSend.Count != RecipientsToSendMessage.Count)
                        {
                            // This indicates that Msg count & Number count doesnot match
                            MoveFileToBadFolder("Msg count & Number count doesnot match.");
                            General.WriteInFile(baseFileName + " file is moved to BAD folder because Msg count & Number count doesnot match.\r\n");
                            continue;
                        }

                        ClientDTO   = new MsgBlaster.DTO.ClientDTO();
                        CampaignDTO = new MsgBlaster.DTO.CampaignDTO();

                        ClientDTO.Id   = Convert.ToInt32(strclientId);
                        CampaignDTO.Id = Convert.ToInt32(strcampaignId);

                        ClientDTO   = MsgBlaster.Service.ClientService.GetById(ClientDTO.Id);
                        CampaignDTO = MsgBlaster.Service.CampaignService.GetById(CampaignDTO.Id);



                        // Befor AddToSMSQueue() validate user
                        sErrlocation = "Check for Valid User - Line 195";
                        int result = ClientDTO.Id; // oClient.IsValidUser(oClient);
                        if (result == 0)           // Invalid User
                        {
                            MoveFileToBadFolder("Invalid user.");
                            General.WriteInFile(baseFileName + " file  moved to BAD folder because of invalid campaignId & clientId.\r\n");
                            continue;
                        }

                        //if (result == 2) // Database Error
                        //{
                        //    General.WriteInFile(baseFileName + " file is skiped due to database error during User validation.\r\n");
                        //    continue;//skip this file and continue
                        //}

                        General.WriteInFile("Opening Balance = " + ClientDTO.SMSCredit);// ClientDBOperation.ActualCredits(oClient));
                        // Check for time restriction over message sending for this user
                        sErrlocation = "Check for Send time restriction - Line 214";
                        //double FROMTIME = Convert.ToDouble(oClient.SendFromTime.Replace(':', '.'));
                        //double UPTOTIME = Convert.ToDouble(oClient.SendUptoTime.Replace(':', '.'));
                        double currentTime = Convert.ToDouble(System.DateTime.Now.Hour + "." + System.DateTime.Now.Minute);
                        //if (currentTime < FROMTIME || currentTime > UPTOTIME)
                        //{
                        //    // skip this file due to time restriction.
                        //    General.WriteInFile(baseFileName + " file is skiped due to send time restriction.\r\n");// +
                        //    continue;
                        //}

                        if (baseFileXML.SelectSingleNode("//scheduleddate") != null)
                        {
                            DateTime ScheduledDate;
                            try
                            {
                                ScheduledDate = Convert.ToDateTime(baseFileXML.DocumentElement["scheduleddate"].InnerText);
                            }
                            catch (Exception ex)
                            {
                                MoveFileToBadFolder("Unrecognized scheduled date.");
                                General.WriteInFile(baseFileName + " file moved to BAD folder because of Unrecognized scheduled date.\r\n");
                                continue;
                            }
                            // 1 = Scheduled datetime is > current datetime
                            // 0 = Scheduled datetime = current datetime
                            // -1 = Scheduled datetime < current datetime
                            if (DateTime.Compare(ScheduledDate, System.DateTime.Now) == 1)
                            {
                                // This file will be send in futuer so skip this file
                                General.WriteInFile(baseFileName + " file is skiped due to scheduled datetime restriction.\r\n");
                                continue;
                            }
                        }
                        // Function for preapearing message to broadcast
                        AddToSMSQueue();
                    }
                    General.WriteInFile("========================================================================================================= ");
                }
            }
            catch (Exception ex)
            {
                General.WriteInFile(sErrlocation + "\r\n" + ex.Message);
                General.WriteInFile("========================================================================================================= ");
            }
        }
        private static String ActualSmsSend(string mobilenumber, string message, string Gateway, CampaignDTO CampaignDTO, ClientDTO ClientDTO)
        {
            string result = "";

            int SMSMsgCount = GetMessageCount(message);
            message = MsgCorrect(message);

            if (CampaignDTO.MessageCount != SMSMsgCount)
            {
                CampaignDTO.MessageCount = SMSMsgCount;
            }

            if (message != "" && mobilenumber != "")// Check for empty message.
            {

                string Url = ConfigurationManager.AppSettings["TransactionalGateWay"].ToString();
                Url = Url.Replace("%26", "&");
                Url = Url.Replace("[recipient]", mobilenumber);
                Url = Url.Replace("[message]", message);
                if (Gateway != "022751") //if (Gateway.ToLower() != "default")
                {
                    Url = Url.Replace("[gateway]", Gateway); //Gateway = "MSGBLS"
                }
                else
                {
                    Url="";
                    Url = ConfigurationManager.AppSettings["PromotionalGateWay"].ToString();
                    Url = Url.Replace("%26", "&");
                    Url = Url.Replace("[recipient]", mobilenumber);
                    Url = Url.Replace("[message]", message);
                }

                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
                myRequest.Method = "GET";
                WebResponse myResponse = myRequest.GetResponse();
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
                result = sr.ReadToEnd();
                sr.Close();

                string statuscode = "";
                if (result.Contains('|'))
                    statuscode = result.Substring(0, result.IndexOf('|'));
                else
                    statuscode = result;

                string SMSReplyMessage = SMSResult(statuscode) + "-" + result; //result
                myResponse.Close();

                CampaignLogDTO CampaignLogDTO = new CampaignLogDTO();
                CampaignLogDTO.CampaignId = CampaignDTO.Id;
                CampaignLogDTO.RecipientsNumber = mobilenumber;
                CampaignLogDTO.MessageStatus = SMSReplyMessage;
                CampaignLogDTO.Message = message;
                CampaignLogDTO.GatewayID = Gateway;
                CampaignLogDTO.SentDateTime = System.DateTime.Now;

                CampaignLogDTO.MessageID = statuscode;
                CampaignLogDTO.MessageCount = SMSMsgCount;

                if (statuscode == "1701")
                {
                    CampaignLogDTO.IsSuccess = true;
                }
                else if (statuscode != "1701")
                {
                    CampaignLogDTO.IsSuccess = false;
                }

                CampaignLogService.Create(CampaignLogDTO);

                // Reduce SMS Credits From Clients List
                ClientDTO.SMSCredit = ClientDTO.SMSCredit - SMSMsgCount;// CampaignDTO.MessageCount;
                ClientService.Edit(ClientDTO);

            }

            return result;
        }