//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 Campaign CampaignToDomain(CampaignDTO CampaignDTO)
 {
     if (CampaignDTO == null) return null;
      Mapper.CreateMap<CampaignDTO, Campaign>();
      Campaign Campaign = Mapper.Map<Campaign>(CampaignDTO);
      return Campaign;
 }
        //
        // Method for adding recipient number and mail-marge-message
        //
        public static int AddMsgRecipToXmlpacketMailMerge(string message, ArrayList recipients, DataView DVrecipientInfo, string xmlpacket, MsgInformationDTO _oMsginfo, int recipientsnumberscount, CampaignDTO CampaignDTO)
        {
            //string xmlpacket = null;
            int messagecount = 0;
            string formatedmessage;
            for (int i = 0; i < recipients.Count; i++)
            {
                DVrecipientInfo.RowFilter = "MobileNumber = '" + recipients[i].ToString().Trim() + "'";
                xmlpacket += "<number>" + recipients[i].ToString().Trim() + "</number>";
                xmlpacket += "<message>";
                formatedmessage = FormatMessageTextMicrows(message, DVrecipientInfo);
                xmlpacket += MsgCorrect(FormatMessageText(formatedmessage, DVrecipientInfo));
                messagecount += MessageCount(formatedmessage, CampaignDTO);
                xmlpacket += "</message>";
                DVrecipientInfo.RowFilter = "";
            }

            //////////////////////////////////////////////////////////////////////

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

            if (messagecount > recipientsnumberscount)
            {
                //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);
            }
            //////////////////////////////////////////////////////////////////////
            return messagecount;
        }
 public void CancelCampaign(string accessId, CampaignDTO campaignDTO)
 {
     try
     {
         CampaignService.CancelCampaign(campaignDTO);
     }
     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"
         });
     }
 }
 public int CreateCampaignFromExternalApplication(CampaignDTO campaignDTO)
 {
     try
     {
         return CampaignService.CreateCampaignFromBackend(campaignDTO);
     }
     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"
         });
     }
 }
 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;
     }
 }
        //Returns Contact paged list as per campaign and client with search criteria
        public static PageData<ContactDTO> GetContactsByCampaignId(PagingInfo pagingInfo, int CampaignId, int ClientId)
        {
            UnitOfWork uow = new UnitOfWork();
            CampaignDTO CampaignDTO = new CampaignDTO();
            PageData<ContactDTO> pageList = new PageData<ContactDTO>();

            CampaignDTO = GetById(CampaignId);

            if (CampaignDTO != null)
            {
                string[] array;
                if (CampaignDTO.RecipientsNumber != "")
                {
                    string value = CampaignDTO.RecipientsNumber;
                    array = value.Replace(" ", "").Split(',');

                    List<ContactDTO> ContactDTOList = new List<ContactDTO>();
                    Contact Contact = new Contact();
                    ContactDTO ContactDTO = new ContactDTO();

                    int skip = (pagingInfo.Page - 1) * pagingInfo.ItemsPerPage;
                    int take = pagingInfo.ItemsPerPage;

                    var newlist = array.Skip(skip).Take(take).ToArray();

                    if (pagingInfo.Search != "")
                    {
                        ContactDTOList = SearchContacts(pagingInfo.Search, array, CampaignId, ClientId);
                        pageList.Data = ContactDTOList;
                        pageList.Count = ContactDTOList.Count;
                    }
                    else
                    {
                        for (int i = 0; i < newlist.Length; i++)
                        {
                            Contact = uow.ContactRepo.GetAll().Where(e => e.MobileNumber == newlist[i] && e.ClientId == ClientId).FirstOrDefault();
                            if (Contact == null)
                            {
                                Contact = new Contact();
                                Contact.MobileNumber = newlist.ToList()[i];
                                Contact.Gender = null;
                                Contact.Id = 0;
                                Contact.ClientId = 0;
                                //Contact.Name = null;
                            }

                            ContactDTO = Transform.ContactToDTO(Contact);

                            ContactDTOList.Add(ContactDTO);
                        }
                        pageList.Data = ContactDTOList;
                        pageList.Count = array.Length;
                    }
                }
                else if (CampaignDTO.GroupId != null)
                {
                    // GroupContactDTO GroupContactDTO =  GroupService.GetGroupContactById((int)CampaignDTO.GroupId);
                    pagingInfo.GroupId = (int)CampaignDTO.GroupId;
                    pageList = ContactService.GetGroupIdWisePresentContactsPagedListByClientId(pagingInfo, ClientId);
                }

            }
            else
            {
                pageList.Data = null;
            }

            return pageList;
        }
        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("========================================================================================================= ");
            }
        }
        //Edit Campaign from backend process
        public static void EditCampaignFromBackend(CampaignDTO campaignDTO)
        {
            try
            {
                GlobalSettings.LoggedInClientId = campaignDTO.ClientId;
                GlobalSettings.LoggedInUserId = campaignDTO.CreatedBy;
                int PartnerId = ClientService.GetById(campaignDTO.ClientId).PartnerId;
                GlobalSettings.LoggedInPartnerId = PartnerId;

                UnitOfWork uow = new UnitOfWork();
                Campaign Campaign = Transform.CampaignToDomain(campaignDTO);
                uow.CampaignRepo.Update(Campaign);
                uow.SaveChanges();
            }
            catch
            {
                throw;
            }
        }
        //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;
            }
        }
        public static void ReadCampaign()
        {
            List<CampaignDTO> CampaignDTOList = new List<CampaignDTO>();
            CampaignDTOList = CampaignService.GetCampaignNotSentList();
            if (CampaignDTOList != null)
            {
                foreach (var item in CampaignDTOList)
                {
                    try
                    {
                        CampaignDTO CampaignDTO = new CampaignDTO();
                        CampaignDTO = item;
                        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);

                        Console.WriteLine("Scheduled Time = " + ScheduledDate);

                        if (ScheduledDate <= System.DateTime.Now)
                        {
                            SplitMobile(item.RecipientsNumber, CampaignDTO);
                        }
                        else { }

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

                        continue;
                    }

                }
            }

            //Check Client Balance

            //Modify Client Balance
        }
        //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;
            }
        }
        /// <summary>
        /// Campaign Log Paged List by CampaignId
        /// </summary>
        /// <param name="CampaignId">Campaign Id</param>
        /// <param name="pagingInfo">pagingInfo object</param>
        /// <returns>Returns paged data list of Campaign log</returns>
        public static PageData<CampaignLogDTO> GetCampaignLogPagedListbyCampaignId(int CampaignId, PagingInfo pagingInfo)
        {
            List<CampaignLogDTO> CampaignLogDTOList = new List<CampaignLogDTO>();
            PageData<CampaignLogDTO> pageList = new PageData<CampaignLogDTO>();

            if (pagingInfo == null)
            {
                PagingInfo PagingInfoCreated = new PagingInfo();
                PagingInfoCreated.Page = 1;
                PagingInfoCreated.Reverse = false;
                PagingInfoCreated.ItemsPerPage = 1;
                PagingInfoCreated.Search = "";
                PagingInfoCreated.TotalItem = 0;

                pagingInfo = PagingInfoCreated;
            }
            if (pagingInfo.SortBy == "")
            {
                pagingInfo.SortBy = "SentDateTime";
            }
            CampaignLogDTOList = GetCampaignLogXMLByCampaignId(CampaignId, pagingInfo);
            IQueryable<CampaignLogDTO> CampaignLogDTOPagedList = CampaignLogDTOList.AsQueryable();

            UnitOfWork uow = new UnitOfWork();
            int count = 0;

            if (pagingInfo.Search != "" && pagingInfo.Search != null)
            {
                bool IsDate = CommonService.IsDate(pagingInfo.Search);
                if (IsDate != true)
                {
                    count = 0;
                    count = GetCampaignLogXMLPagedCountByCampaignId(CampaignId, pagingInfo);
                }
                else
                {
                    DateTime date = Convert.ToDateTime(pagingInfo.Search);
                    count = 0;
                    count = GetCampaignLogXMLPagedCountByCampaignId(CampaignId, pagingInfo);

                }

            }
            else
            {
                count = GetCampaignLogXMLPagedCountByCampaignId(CampaignId, pagingInfo);
            }

            ////Sorting
            // CampaignLogDTOPagedList = PagingService.Sorting<CampaignLogDTO>(CampaignLogDTOPagedList, pagingInfo.SortBy, pagingInfo.Reverse);

            // paging
            if (CampaignLogDTOPagedList.Count() > 0)
            {
                //var ContacDTOPerPage = PagingService.Paging<CampaignLogDTO>(CampaignLogDTOPagedList, pagingInfo.ItemsPerPage, pagingInfo.Page);
                pageList.Count = count;// CampaignLogDTOPagedList.Count();

                List<CampaignLogDTO> pagedCampaignLogDTOList = new List<CampaignLogDTO>();
                foreach (var item in CampaignLogDTOPagedList)
                {
                    CampaignDTO CampaignDTO = new CampaignDTO();
                    CampaignDTO = CampaignService.GetById(item.CampaignId);
                    item.CampaignName = CampaignDTO.Name;
                    item.CreatedBy = UserService.GetById(CampaignDTO.CreatedBy).Name;
                    pagedCampaignLogDTOList.Add(item);
                }
                pageList.Data = pagedCampaignLogDTOList;
                pageList.SuccessCount = GetCampaignLogXMLCountByCampaignId(CampaignId, true);
                pageList.FailureCount = GetCampaignLogXMLCountByCampaignId(CampaignId, false);
            }
            else
            {
                pageList.Data = null;
                pageList.SuccessCount = GetCampaignLogXMLCountByCampaignId(CampaignId, true);
                pageList.FailureCount = GetCampaignLogXMLCountByCampaignId(CampaignId, false);
            }

            return pageList;
        }
        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)
                    {
                        DateTime Time;
                        if (item.ScheduledTime != "")
                        {
                            Time = Convert.ToDateTime(item.ScheduledTime);
                        }
                        else Time = Convert.ToDateTime("12:00 AM");

                        item.ScheduledDate = Convert.ToDateTime(item.ScheduledDate.Date.Date.ToString("MM/dd/yyyy") + " " + Time.TimeOfDay);
                        //CampaignService.EditCampaignFromBackend(item);

                        ismailmarge = false;
                        // 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 && item.ForAllContact == false) // To check wheather the user sending Group message
                        {
                            recipients = item.RecipientsNumber.ToString().Split(',');
                        }
                        else
                        {
                            string RecipientsNumberList = null;
                            if (item.GroupId > 0)
                            {

                                GroupContactDTO GroupContactDTO = new GroupContactDTO();
                                GroupDTO GroupDTO = new GroupDTO();
                                GroupDTO = GroupService.GetById(Convert.ToInt32(item.GroupId));
                                List<ContactDTO> ContactDTOList = new List<ContactDTO>();
                                ContactDTOList = GroupContactService.GetGroupIdWiseContacts(Convert.ToInt32(item.GroupId));
                                //GroupContactDTO = GroupService.GetGroupContactById(Convert.ToInt32(GroupDTO.Id));
                                foreach (var Contactitem in ContactDTOList) //GroupContactDTO.Contacts
                                {
                                    RecipientsNumberList = Contactitem.MobileNumber + "," + RecipientsNumberList;
                                }

                            }
                            else if(item.ForAllContact == true)
                            {
                                RecipientsNumberList = null;
                                RecipientsNumberList = ContactService.GetAllReceipentNumberByClientId(item.ClientId);
                                RecipientsNumberList = RecipientsNumberList + ",";

                            }
                                item.RecipientsNumber = RecipientsNumberList.Remove(RecipientsNumberList.LastIndexOf(','));
                                item.RecipientsCount = CommonService.GetRecipientsCount(item.RecipientsNumber);
                                CampaignService.EditCampaignFromBackend(item);
                                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("MM/dd/yyyy") + "</senddate>";

                        if (!string.IsNullOrEmpty(item.ScheduledDate.ToString())) //scheduledDate.Text // check for sheduled Date
                        {

                            if (item.ScheduledDate >= System.DateTime.Now)
                            {

                                continue;
                            }

                            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);
                            DateTime ActualScheduleDatetime = Convert.ToDateTime(item.ScheduledDate);
                            xmlpacket += "<scheduleddate>" + ActualScheduleDatetime.ToString("MM/dd/yyyy HH:mm tt") + "</scheduleddate>";
                            //oMessageLog.MessageScheduledDateTime = Convert.ToString(ScheduledDateTime);
                            oMessageLog.MessageScheduledDateTime = Convert.ToString(ActualScheduleDatetime);
                        }

                        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>";

                        CampaignDTO CampaignDTO = new CampaignDTO();
                        CampaignDTO = item;

                        if (ismailmarge)
                            requiredCreditTosendmsg = AddMsgRecipToXmlpacketMailMerge(item.Message, recipientsnumbers, dtContact.DefaultView, xmlpacket, _oMsginfo, recipientsnumbers.Count, CampaignDTO);
                        else

                            requiredCreditTosendmsg = AddMsgRecipToXmlpacket(item.Message, recipientsnumbers, xmlpacket, _oMsginfo, recipientsnumbers.Count, CampaignDTO) * 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 (Exception ex)
            {
                //oUcButtonControl.showMessage(frmButtonControl.Messageflag.errorMessage, Global.DisplayConnectionError(ex));
                throw;
            }
        }
        public static void CreateCampaigns()
        {
            List<ClientDTO> ClientDTOList = new List<ClientDTO>();
            ClientDTOList = ClientService.GetAllActiveClients();

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

            if (ClientDTOList != null)
            {
                foreach (var item in ClientDTOList)
                {
                    if (item.IsSendBirthdayMessages || item.IsSendBirthdayCoupons)
                    {
                        string RecipientsNumberList = null;
                        int userId = UserService.GetAdminUserByClientId(item.Id);
                        List<ContactDTO> ContactDTOList = new List<ContactDTO>();
                        ContactDTOList = ContactService.GetContactsForTodaysBirthday();
                        if (ContactDTOList.Count > 0)
                        {
                            if (ContactDTOList.Count == 1)
                            {
                                foreach (var Contactitem in ContactDTOList)
                                {
                                    RecipientsNumberList = Contactitem.MobileNumber;
                                }
                            }
                            else {
                                    foreach (var Contactitem in ContactDTOList)
                                    {
                                        RecipientsNumberList = Contactitem.MobileNumber + "," + RecipientsNumberList;
                                    }

                                    RecipientsNumberList = RecipientsNumberList.Remove(RecipientsNumberList.Length - 1);
                            }

                            if (item.IsSendBirthdayMessages)
                            {
                                CampaignDTO CampaignDTO = new CampaignDTO();
                                CampaignDTO.Message = item.BirthdayMessage;
                                CampaignDTO.RecipientsNumber = RecipientsNumberList;
                                CampaignDTO.Name = "Birthday Message_" + string.Format("{0:G}", System.DateTime.Now); ;
                                CampaignDTO.ClientId = item.Id;
                                CampaignDTO.CreatedDate = System.DateTime.Now.Date;
                                CampaignDTO.IsScheduled = false;
                                CampaignDTO.GroupId = null;
                                CampaignDTO.ScheduledDate = System.DateTime.Now.Date;
                                CampaignDTO.CreatedBy = userId;

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

                                CampaignService.CreateCampaignFromBackend(CampaignDTO);
                            }

                            if (item.IsSendBirthdayCoupons)
                            {
                                EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                                EcouponCampaignDTO.Message = item.BirthdayMessage;
                                EcouponCampaignDTO.ReceipentNumber = RecipientsNumberList;
                                EcouponCampaignDTO.Title = "Birthday Coupon_" + string.Format("{0:G}", System.DateTime.Now); ;
                                EcouponCampaignDTO.ClientId = item.Id;
                                EcouponCampaignDTO.CreatedDate = System.DateTime.Now.Date;
                                EcouponCampaignDTO.SendOn = System.DateTime.Now.Date;
                                EcouponCampaignDTO.IsScheduled = false;
                                EcouponCampaignDTO.GroupId = null;
                                EcouponCampaignDTO.MinPurchaseAmount = Convert.ToDouble(item.MinPurchaseAmountForBirthdayCoupon);
                                EcouponCampaignDTO.CreatedBy = userId;

                                int value = Convert.ToInt32(item.BirthdayCouponExpire);

                                string expire_format = item.BirthdayCouponExpireType;
                                if (expire_format == "Day")
                                {
                                    EcouponCampaignDTO.ExpiresOn = System.DateTime.Now.Date.AddDays(value);
                                }
                                else if (expire_format == "Month")
                                {
                                    EcouponCampaignDTO.ExpiresOn = System.DateTime.Now.Date.AddMonths(value);
                                }
                                else if (expire_format == "Week")
                                {
                                    value = value * 7;
                                    EcouponCampaignDTO.ExpiresOn = System.DateTime.Now.Date.AddDays(value);
                                }
                                ////Calculate consumed credits
                                //double ConsumedCreditPerOneMsg = CommonService.GetConsumedCreditsForOneMessage(EcouponCampaignDTO.Message, true);
                                //int RecepientsCount = CommonService.GetRecipientsCount(EcouponCampaignDTO.ReceipentNumber);
                                //EcouponCampaignDTO.ConsumededCredits = RecepientsCount * ConsumedCreditPerOneMsg;

                                EcouponCampaignService.CreateEcouponCampaignBackend(EcouponCampaignDTO);
                            }
                        }
                    }

                    if (item.IsSendAnniversaryMessages || item.IsSendAnniversaryCoupons)
                    {

                        string RecipientsNumberList = null;
                        int userId = UserService.GetAdminUserByClientId(item.Id);
                        List<ContactDTO> ContactDTOList = new List<ContactDTO>();
                        ContactDTOList = ContactService.GetContactsForTodaysAnniversary();
                        if (ContactDTOList.Count > 0)
                        {
                            if (ContactDTOList.Count == 1)
                            {
                                foreach (var Contactitem in ContactDTOList)
                                {
                                    RecipientsNumberList = Contactitem.MobileNumber;
                                }
                            }
                            else
                            {
                                foreach (var Contactitem in ContactDTOList)
                                {
                                    RecipientsNumberList = Contactitem.MobileNumber + "," + RecipientsNumberList;
                                }

                                RecipientsNumberList = RecipientsNumberList.Remove(RecipientsNumberList.Length - 1);
                            }

                            if (item.IsSendAnniversaryMessages)
                            {
                                CampaignDTO CampaignDTO = new CampaignDTO();
                                CampaignDTO.Message = item.AnniversaryMessage;
                                CampaignDTO.RecipientsNumber = RecipientsNumberList;
                                CampaignDTO.Name = "Anniversary Message_" + string.Format("{0:G}", System.DateTime.Now); ;
                                CampaignDTO.ClientId = item.Id;
                                CampaignDTO.CreatedDate = System.DateTime.Now.Date;
                                CampaignDTO.IsScheduled = false;
                                CampaignDTO.GroupId = null;
                                CampaignDTO.ScheduledDate = System.DateTime.Now.Date;
                                CampaignDTO.CreatedBy = userId;

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

                                CampaignService.CreateCampaignFromBackend(CampaignDTO);
                            }

                            if (item.IsSendAnniversaryCoupons)
                            {
                                EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                                EcouponCampaignDTO.Message = item.AnniversaryMessage;
                                EcouponCampaignDTO.ReceipentNumber = RecipientsNumberList;
                                EcouponCampaignDTO.Title = "Anniversary Coupon_" + string.Format("{0:G}", System.DateTime.Now); ;
                                EcouponCampaignDTO.ClientId = item.Id;
                                EcouponCampaignDTO.CreatedDate = System.DateTime.Now.Date;
                                EcouponCampaignDTO.SendOn = System.DateTime.Now.Date;
                                EcouponCampaignDTO.IsScheduled = false;
                                EcouponCampaignDTO.GroupId = null;
                                EcouponCampaignDTO.MinPurchaseAmount = Convert.ToDouble(item.MinPurchaseAmountForAnniversaryCoupon);
                                EcouponCampaignDTO.CreatedBy = userId;

                                int value = Convert.ToInt32(item.AnniversaryCouponExpire);

                                string expire_format = item.AnniversaryCouponExpireType;
                                if (expire_format == "Day")
                                {
                                    EcouponCampaignDTO.ExpiresOn = System.DateTime.Now.Date.AddDays(value);
                                }
                                else if (expire_format == "Month")
                                {
                                    EcouponCampaignDTO.ExpiresOn = System.DateTime.Now.Date.AddMonths(value);
                                }
                                else if (expire_format == "Week")
                                {
                                    value = value * 7;
                                    EcouponCampaignDTO.ExpiresOn = System.DateTime.Now.Date.AddDays(value);
                                }

                                ////Calculate consumed credits
                                //double ConsumedCreditPerOneMsg = CommonService.GetConsumedCreditsForOneMessage(EcouponCampaignDTO.Message, true);
                                //int RecepientsCount = CommonService.GetRecipientsCount(EcouponCampaignDTO.ReceipentNumber);
                                //EcouponCampaignDTO.ConsumededCredits = RecepientsCount * ConsumedCreditPerOneMsg;

                                EcouponCampaignService.CreateEcouponCampaignBackend(EcouponCampaignDTO);
                            }
                        }
                    }
                }
            }
        }
        //
        // Calculate the messagecount
        //
        private static int MessageCount(string message, CampaignDTO CampaignDTO)
        {
            if (CampaignDTO.IsUnicode == true)
            {
               return GetUnicodeMessageCount(message);
            }
            SettingDTO SettingDTO = new SettingDTO();
            SettingDTO = SettingService.GetById(1);

            int MsgLength = SettingDTO.MessageLength;
            int MsgLenPerSingleMessage = SettingDTO.SingleMessageLength;

            if (message.Length <= MsgLength)
                return 1;
            else if (message.Length % MsgLenPerSingleMessage != 0)
                return (message.Length / MsgLenPerSingleMessage) + 1;
            else
                return message.Length / MsgLenPerSingleMessage;
        }
        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;
        }
        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;
        }
        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
            }
        }
        //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;
            }
        }
示例#22
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("========================================================================================================= ");
            }
        }
        /// <summary>
        ///  Campaign Log By CampaignId
        /// </summary>
        /// <param name="CampaignId">Campaign Id</param>
        /// <param name="pagingInfo">pagingInfo object</param>
        /// <returns>Returns list of campaign Log </returns>
        public static List<CampaignLogDTO> GetCampaignLogXMLByCampaignId(int CampaignId, PagingInfo pagingInfo)
        {
            List<CampaignLogXMLDTO> CampaignLogXMLDTOList = new List<CampaignLogXMLDTO>();

            List<CampaignLogDTO> CampaignLogDTOList = new List<CampaignLogDTO>();
            CampaignDTO CampaignDTO = new CampaignDTO();
            CampaignDTO = CampaignService.GetById(CampaignId);
            try
            {
                UnitOfWork uow = new UnitOfWork();
                int skip = (pagingInfo.Page - 1) * pagingInfo.ItemsPerPage;
                int take = pagingInfo.ItemsPerPage;

                IEnumerable<CampaignLogXML> CampaignLogXML = uow.CampaignLogXMLRepo.GetAll().Where(e => e.CampaignId == CampaignId).ToList();

                if (CampaignLogXML != null)
                {
                    foreach (var item in CampaignLogXML)
                    {
                        CampaignLogXMLDTOList.Add(Transform.CampaignLogXMLToDTO(item));
                    }

                    if (CampaignLogXMLDTOList != null)
                    {
                        foreach (var item in CampaignLogXMLDTOList)
                        {
                            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["msgBlasterWebContext"].ToString());
                            con.Open();
                            SqlCommand command = new SqlCommand("Select XMLLog From CampaignLogXMLs WHERE Id=" + item.Id, con);

                            XmlDocument xdoc = new XmlDocument();
                            XmlReader reader = command.ExecuteXmlReader();

                            if (reader.Read())
                            {
                                xdoc.Load(reader);

                                //XmlNodeList msgList = xdoc.SelectNodes("/packet/numbers/message");
                                //XmlNodeList numList = xdoc.SelectNodes("/packet/numbers/number");

                                foreach (XmlNode currentnode in xdoc.DocumentElement.GetElementsByTagName("numbers"))
                                {

                                    //

                                    XmlNodeList numList = xdoc.SelectNodes("/packet/numbers/number");
                                    foreach (XmlNode node in numList)
                                    {
                                        CampaignLogDTO CampaignLogDTO = new CampaignLogDTO();

                                        CampaignLogDTO.RecipientsNumber = node.InnerText;// node.SelectNodes("number").Item(0).InnerText;// node.SelectSingleNode("number").InnerText;
                                        string MsgStatus = null;
                                        string code = null;

                                        if (node.Attributes != null)
                                        {
                                            code = node.Attributes["msgCode"].Value;
                                            CampaignLogDTO.SentDateTime = Convert.ToDateTime(node.Attributes["sentTime"].Value);
                                            CampaignLogDTO.MessageCount = Convert.ToInt32(node.Attributes["msgCount"].Value);
                                            CampaignLogDTO.RequiredCredits = Convert.ToDouble(node.Attributes["msgCredits"].Value);
                                            CampaignLogDTO.CampaignId = CampaignId;
                                            CampaignLogDTO.CampaignName = CampaignDTO.Name;
                                            CampaignLogDTO.CreatedOn = CampaignDTO.CreatedDate;
                                            CampaignLogDTO.CreatedBy = UserService.GetById(CampaignDTO.CreatedBy).Name;

                                        }

                                        MsgStatus = CodeDescription(code);
                                        CampaignLogDTO.MessageStatus = MsgStatus;
                                        //if (IsSuccessful == true)
                                        //{
                                        if (code == "1701" || code == "0")
                                        {
                                            CampaignLogDTOList.Add(CampaignLogDTO);
                                        }
                                        else
                                            //}
                                            //else if (code != "1701" && code != "0")
                                            //{
                                            CampaignLogDTOList.Add(CampaignLogDTO);
                                        // }

                                    }
                                }
                            }
                            con.Close();

                            if (pagingInfo.Search != "" && pagingInfo.Search != null)
                            {
                                bool Isdate = CommonService.IsDate(pagingInfo.Search);
                                if (Isdate != true)
                                {
                                    List<CampaignLogDTO> CampaignLogDTOSearchList = new List<CampaignLogDTO>();
                                    var CampaignLogSearch = CampaignLogDTOList.Where(e => e.MessageStatus.ToLower().Contains(pagingInfo.Search.ToLower()) || e.RecipientsNumber.Contains(pagingInfo.Search) || (e.SentDateTime.ToString() != null ? (Convert.ToDateTime(e.SentDateTime).ToString("dd-MMM-yyyy").ToLower().Contains(pagingInfo.Search.ToLower())) : false)).OrderByDescending(e => e.SentDateTime);//.Skip(skip).Take(take); //|| (e.GatewayID != null ? (e.GatewayID.ToLower().Contains(pagingInfo.Search.ToLower())) : false)|| e.Message.ToLower().Contains(pagingInfo.Search.ToLower())|| (e.MessageID != null ? (e.MessageID.ToLower().Contains(pagingInfo.Search.ToLower())) : false)|| (e.CampaignName != null ? (e.CampaignName.ToLower().Contains(search.ToLower())) : false)
                                    if (CampaignLogSearch != null)
                                    {
                                        foreach (var itemsearch in CampaignLogSearch)
                                        {
                                            itemsearch.CampaignName = CampaignDTO.Name;
                                            itemsearch.CreatedOn = CampaignDTO.CreatedDate;
                                            itemsearch.CreatedBy = UserService.GetById(CampaignDTO.CreatedBy).Name;

                                            CampaignLogDTOSearchList.Add(itemsearch);
                                        }
                                    }

                                    IQueryable<CampaignLogDTO> CampaignLogDTOQuarableSearch = CampaignLogDTOSearchList.AsQueryable();
                                    return CampaignLogDTOQuarableSearch.Skip(skip).Take(take).ToList();

                                }
                                else
                                {
                                    List<CampaignLogDTO> CampaignLogDTOSearchList = new List<CampaignLogDTO>();
                                    DateTime date = Convert.ToDateTime(pagingInfo.Search);
                                    var CampaignLogSearch = CampaignLogDTOList.Where(e => e.SentDateTime >= date && e.SentDateTime < date.AddDays(1)).OrderByDescending(e => e.SentDateTime);//.Skip(skip).Take(take);
                                    if (CampaignLogSearch != null)
                                    {
                                        foreach (var itemsearch in CampaignLogSearch)
                                        {
                                            itemsearch.CampaignName = CampaignDTO.Name;
                                            itemsearch.CreatedOn = CampaignDTO.CreatedDate;
                                            itemsearch.CreatedBy = UserService.GetById(CampaignDTO.CreatedBy).Name;
                                            CampaignLogDTOSearchList.Add(itemsearch);
                                        }
                                    }
                                    IQueryable<CampaignLogDTO> CampaignLogDTOQuarableDate = CampaignLogDTOSearchList.AsQueryable();
                                    return CampaignLogDTOQuarableDate.Skip(skip).Take(take).ToList();

                                }
                            }

                        }

                    }

                }
                //List<CampaignLogXMLDTO> CampaignLogXMLDTOSearchList = new List<CampaignLogXMLDTO>();

                IQueryable<CampaignLogDTO> CampaignLogDTOQuarableall = CampaignLogDTOList.AsQueryable();
                CampaignLogDTOQuarableall = PagingService.Sorting<CampaignLogDTO>(CampaignLogDTOQuarableall, pagingInfo.SortBy, pagingInfo.Reverse);
                return CampaignLogDTOQuarableall.Skip(skip).Take(take).ToList();

            }

            catch (Exception)
            {
                throw;
            }
        }