//Edit settings
 public static void Edit(SettingDTO SettingDTO)
 {
     try
     {
         UnitOfWork uow = new UnitOfWork();
         Setting Setting = Transform.SettingToDomain(SettingDTO);
         uow.SettingRepo.Update(Setting);
         uow.SaveChanges();
     }
     catch
     {
         throw;
     }
 }
 public void EditSetting(SettingDTO SettingDTO)
 {
     try
     {
         SettingService.Edit(SettingDTO);
     }
     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"
         });
     }
 }
        //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;
            }
        }
        //
        // 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;
        }
        //Resend coupon by coupon id and client id
        public static CouponDTO ResendCoupon(int CouponId, int ClientId)
        {
            try
            {
                CouponDTO CouponDTO = new CouponDTO();
                CouponDTO = GetById(CouponId);

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

                SettingDTO SettingDTO = new SettingDTO();
                SettingDTO = SettingService.GetById(1);
                double RequiredCredit = CommonService.GetMessageCount(CouponDTO.Message);
                double ActualRequiredCredits = RequiredCredit * SettingDTO.NationalCouponSMSCount;

                if (ClientDTO.SMSCredit >= ActualRequiredCredits) //RequiredCredit
                {

                    // Send Direct SMS
                    //bool IsSent = CommonService.ResendCoupon(CouponDTO.MobileNumber, CouponDTO.Message, ClientDTO.Id);

                    CouponDTO CouponDTONew = new CouponDTO();
                    CouponDTONew = CommonService.ResendCouponByCouponDTOAndClientId(CouponDTO, ClientDTO.Id);
                    return CouponDTONew;

                    //if (IsSent == true)
                    //{
                        //CouponDTO.SentDateTime = System.DateTime.Now;
                        //CouponDTO.Id = 0;
                        //int NewCouponId = Create(CouponDTO);
                        //CouponDTO CouponDTONew = new CouponDTO();
                        //CouponDTONew = GetById(NewCouponId);

                        //////Expire previous coupon
                        //CouponDTO CouponDTOPrevious = new CouponDTO();
                        //CouponDTOPrevious = GetById(CouponId);
                        //CouponDTOPrevious.IsExpired = true;
                        //Edit(CouponDTOPrevious);

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

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

                        //EcouponCampaignService.EditForEcouponResend(EcouponCampaignDTO);

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

                        //return CouponDTONew;
                    //}
                    //else
                    //{
                    //    CouponDTO = null;
                    //    return CouponDTO;
                    //}
                }
                CouponDTO = null;
                return CouponDTO;
            }
            catch
            {
                throw;
            }
        }
        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
            }
        }
        /// <summary>
        /// This method get recipient number & corresponding message from campaign file & sent it to smsoutbox.in gateway
        /// </summary>
        public void AddToSMSQueue()
        {
            General.WriteInFile("Sending file : " + baseFileName);
            HttpWebRequest oHttpRequest;
            HttpWebResponse oHttpWebResponse;

            //GatewayInfo oGatewayInfo = new GatewayInfo(oClient.campaignId, oClient.IsInternal);

            if (ClientDTO.SenderCode != "" && ClientDTO.SenderCode != null)
            {
                GATEWAY_URL = ConfigurationManager.AppSettings["TransactionalGateWay"].ToString();
                GATEWAY_URL = GATEWAY_URL.Replace("[gateway]", ClientDTO.SenderCode.ToString());
                GatewayID = "RouteSMS";// ClientDTO.SenderCode;

            }
            else
            {
                GATEWAY_URL = ConfigurationManager.AppSettings["PromotionalGateWay"].ToString();
                GatewayID = "RouteSMS";// "022751";
            }

            GATEWAY_URL = GATEWAY_URL.Replace("%26", "&"); ;

            //GatewayID = oGatewayInfo.GatewayId;

            string strURL;
            string sMobileNo = null, mymsg = null, msgtype= null;
            int recipientNumberCount = 0; // count of recipient Mobile number.
            int errorCount = 0; // Error count.
            int creditConsumed = 0; // Credit consumed to sent message.
            int sentMsgCount = 0; // this count indicates how many msg sent successfully
            int creditRequiredForSingleMsg = 0; // Credit required to send message in the case of single message to multiple recipients.
            creditsRequired = 0;
            bool IsMultipleMsg;

            XmlNodeList MessageToSend = baseFileXML.SelectNodes("/packet/numbers/message");
            XmlNodeList RecipientsToSendMessage = baseFileXML.SelectNodes("/packet/numbers/number");
            recipientNumberCount = RecipientsToSendMessage.Count;

            // Check for is it an MsgBlaster Testing user or not
            ////if (oClient.IsInternal)
            ////{
            ////    General.WriteInFile(oClient.campaignId + " is a Graceworks team member.");
            ////}

            // check for packet contains multiple messages or not.
            if (MessageToSend.Count == RecipientsToSendMessage.Count && MessageToSend.Count != 1)
            {
                IsMultipleMsg = true;
            }
            else
            {
                IsMultipleMsg = false;
                // In the case of single msg to all recipents calculate the credit required to send this message
                if (CampaignDTO.IsUnicode == false)
                {
                    creditRequiredForSingleMsg = GetMessageCount(ReformatMsg(baseFileXML.GetElementsByTagName("message").Item(0).InnerText.TrimEnd()));
                }
                else creditRequiredForSingleMsg = GetUnicodeMessageCount(ReformatMsg(baseFileXML.GetElementsByTagName("message").Item(0).InnerText.TrimEnd()));
                mymsg = MsgCorrect(baseFileXML.GetElementsByTagName("message").Item(0).InnerText.TrimEnd(), CampaignDTO.IsUnicode);
            }

            foreach (XmlNode currentnode in baseFileXML.DocumentElement.GetElementsByTagName("number")) // loop through the each recipient number in this file
            {
                if (currentnode.Attributes.Count == 0) // check for this number message is send or not
                {
                    // Remove unwanted characters from number
                    sMobileNo = currentnode.InnerText.Replace(" ", "");
                    sMobileNo = sMobileNo.Replace("-", "");
                    sMobileNo = sMobileNo.Replace("(", "");
                    sMobileNo = sMobileNo.Replace(")", "");
                    sMobileNo = sMobileNo.Replace(",", "");
                    sMobileNo = sMobileNo.Replace("+", "");
                    double number;
                    bool IsNumeric = double.TryParse(sMobileNo, out number); // Check the number is in Numeric form or not
                    if (sMobileNo.Length < MINMOBILELENGTH || sMobileNo.Length > MAXMOBILELENGTH || !IsNumeric)
                    {
                        // Recipient numbers is invalid so skip this number
                        XmlAttribute errorStamp;
                        errorStamp = baseFileXML.CreateAttribute("notSent");
                        errorStamp.Value = "Invalid recipient number.";
                        currentnode.Attributes.Append(errorStamp);
                        sentMsgCount++;
                        continue;
                    }
                    else
                    {
                        sMobileNo = sMobileNo.Substring(sMobileNo.Length - MINMOBILELENGTH); // Get last 10 digits from number
                        sMobileNo = "91" + sMobileNo; // Add country code to Recipient number
                    }

                    if (IsMultipleMsg) // prepared separate message for this number
                    {
                        mymsg = MsgCorrect(currentnode.NextSibling.InnerText.TrimEnd(), CampaignDTO.IsUnicode);
                    }

                    if (mymsg == "")// Check for empty message.
                    {
                        // If message is empty than dont send this message & add resone why not send to that recipient number.
                        XmlAttribute errorStamp;
                        errorStamp = baseFileXML.CreateAttribute("notSent");
                        errorStamp.Value = "Empty message.";
                        currentnode.Attributes.Append(errorStamp);
                        sentMsgCount++;
                        continue;
                    }

                    int creditRequiredToSendMsg = 0;

                    if (IsMultipleMsg)
                        creditRequiredToSendMsg = GetMessageCount(ReformatMsg(currentnode.NextSibling.InnerText.TrimEnd()));
                    else
                        creditRequiredToSendMsg = creditRequiredForSingleMsg;

                    //if ((ClientDTO.SMSCredit - creditConsumed) < creditRequiredToSendMsg)//Check for available Credits
                    //{
                    //    baseFileXML.Save(sourceQFile);
                    //    if (IsMultipleMsg)
                    //    {
                    //        if (sentMsgCount > 0)
                    //        {
                    //            General.WriteInFile(baseFileName + " is skiped due to unsufficient credits.\r\nMessages sent upto recipient : " + currentnode.PreviousSibling.PreviousSibling.InnerText);
                    //        }
                    //        else
                    //        {
                    //            General.WriteInFile(baseFileName + " is skiped due to unsufficient credits.");
                    //        }
                    //    }
                    //    else
                    //    {
                    //        if (sentMsgCount > 0)
                    //        {
                    //            General.WriteInFile(baseFileName + " is skiped due to unsufficient credits.\r\nMessages sent upto recipient : " + currentnode.PreviousSibling.InnerText);
                    //        }
                    //        else
                    //        {
                    //            General.WriteInFile(baseFileName + " is skiped due to unsufficient credits.");
                    //        }
                    //    }
                    //    break;
                    //}

                    #region " Submiting to Gateway "

                    strURL = GATEWAY_URL.Replace("[recipient]", sMobileNo).Replace("[message]", mymsg);

                    if (CampaignDTO.IsUnicode == true)
                    {
                        strURL = strURL.Replace("[msgtype]", "2");
                    }
                    else strURL = strURL.Replace("[msgtype]", "0");

                    sErrlocation = "HTTP web request-Line 387";
                    oHttpRequest = (HttpWebRequest)System.Net.WebRequest.Create(strURL);
                    oHttpRequest.Method = "GET";
                TryAgain:
                    try
                    {
                        string messageID = string.Empty;
                        bool IsSent = false;
                        string statuscode = string.Empty;
                        string result = string.Empty;

                        oHttpWebResponse = (HttpWebResponse)oHttpRequest.GetResponse();
                        StreamReader response = new StreamReader(oHttpWebResponse.GetResponseStream());
                        result = response.ReadToEnd();
                        oHttpWebResponse.Close();

                        switch (GatewayID)
                        {
                            case "RouteSMS":
                                if (result.Contains('|'))
                                    statuscode = result.Substring(0, result.IndexOf('|'));
                                else
                                    statuscode = result;

                                switch (statuscode)
                                {
                                    case "11":
                                        messageID = "Invalid destination";
                                        IsSent = true;
                                        break;
                                    case "1701":
                                        messageID = result.Substring(result.IndexOf(':') + 1, result.Length - result.IndexOf(':') - 1);
                                        IsSent = true;
                                        break;
                                    case "1702":
                                        messageID = "Invalid url error";
                                        break;
                                    case "1703":
                                        messageID = "Invalid value in username or password";
                                        break;
                                    case "1704":
                                        messageID = "Invalid value in type field";
                                        break;
                                    case "1705":
                                        messageID = "Invalid Message";
                                        IsSent = true;
                                        break;
                                    case "1706":
                                        messageID = "Destination does not exist";
                                        IsSent = true;
                                        break;
                                    case "1707":
                                        messageID = "Invalid source (Sender)";
                                        break;
                                    case "1708":
                                        messageID = "Invalid value for dlr field";
                                        break;
                                    case "1709":
                                        messageID = "User validation failed";
                                        break;
                                    case "1710":
                                        messageID = "Internal Error";
                                        break;
                                    case "1025":
                                        messageID = "Insufficient credits";
                                        break;
                                    case "1032":
                                        messageID = "Number is in DND";
                                        IsSent = true;
                                        break;
                                    default:
                                        General.WriteInFile("Response :" + result);
                                        break;
                                }
                                break;
                            case "SMSPro":
                                //MessageSent GUID="gracew-8be9d47f999e569a" SUBMITDATE="08/26/2013 03:16:12 PM"
                                if (result.Contains("MessageSent"))
                                {
                                    messageID = result.Split('"')[1];
                                    IsSent = true;
                                }
                                else
                                {
                                    messageID = result;
                                    General.WriteInFile(result);
                                }
                                break;
                            default:
                                break;
                        }

                        if (IsSent)
                        {
                            if (IsMultipleMsg)
                                creditConsumed += creditRequiredToSendMsg;
                            else
                                creditConsumed += creditRequiredForSingleMsg;

                            XmlAttribute timespan;
                            timespan = baseFileXML.CreateAttribute("sentTime");
                            timespan.Value = System.DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt");
                            currentnode.Attributes.Append(timespan);

                            XmlAttribute gatewayID;
                            gatewayID = baseFileXML.CreateAttribute("gatewayID");
                            gatewayID.Value = GatewayID;
                            currentnode.Attributes.Append(gatewayID);

                            XmlAttribute msgID;
                            msgID = baseFileXML.CreateAttribute("msgID");
                            msgID.Value = messageID;
                            currentnode.Attributes.Append(msgID);

                            XmlAttribute msgCode;
                            msgCode = baseFileXML.CreateAttribute("msgCode");
                            msgCode.Value = statuscode;
                            currentnode.Attributes.Append(msgCode);

                            XmlAttribute msgCount;
                            msgCount = baseFileXML.CreateAttribute("msgCount");
                            if (CampaignDTO.IsUnicode == false)
                            {
                                msgCount.Value = GetMessageCount(mymsg).ToString();
                                currentnode.Attributes.Append(msgCount);
                            }
                            else
                            {
                                msgCount.Value = GetUnicodeMessageCount(mymsg).ToString();
                                currentnode.Attributes.Append(msgCount);
                            }

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

                            msgCredits = baseFileXML.CreateAttribute("msgCredits");
                            if (IsMultipleMsg)
                            {
                                msgCredits.Value = creditRequiredToSendMsg.ToString();
                                double credit = Convert.ToDouble(msgCredits.Value);
                                double reqCredits = credit * SettingDTO.NationalCampaignSMSCount;
                                msgCredits.Value = reqCredits.ToString();
                            }
                            else
                            {
                                msgCredits.Value = creditRequiredForSingleMsg.ToString(); // GetMessageCount(mymsg).ToString();

                                double credit = Convert.ToDouble(msgCredits.Value);
                                double reqCredits = credit * SettingDTO.NationalCampaignSMSCount;
                                msgCredits.Value = reqCredits.ToString();
                            }
                            currentnode.Attributes.Append(msgCredits);

                            sentMsgCount++;
                            errorCount = 0;

                            //oClient.ReduceCredit = creditConsumed;
                            //if (sentMsgCount % UPDATEBALAFTER == 0)
                            //{
                            //    ClientDBOperation.UpdateCredit(oClient, creditConsumed);
                            //    creditsRequired += creditConsumed;
                            //    baseFileXML.Save(sourceQFile);
                            //    creditConsumed = 0;
                            //}

                            creditConsumed = 0;
                        }
                        else
                        {
                            errorCount += 1;
                            if (errorCount > MAXCHECKFORRESPONSE)
                            {
                                General.WriteInFile("Message sending stoped due to BAD response from Gateway (i.e" + messageID + ")");
                                break;
                            }
                            else
                                goto TryAgain;
                        }
                    }
                    catch (Exception ex)
                    {
                        errorCount += 1;
                        baseFileXML.Save(sourceQFile);
                        if (errorCount > MAXCHECKFORCONNECTION)
                        {
                            General.WriteInFile(sErrlocation + "\r\nGateway connection unavailable." + "\r\n" + ex.Message);
                            break;
                        }
                        else
                            goto TryAgain;
                    }
                    #endregion

                }
                else
                {
                    sentMsgCount++;
                    if (IsMultipleMsg)
                    {
                        creditsRequired += GetMessageCount(currentnode.NextSibling.InnerText.TrimEnd());
                    }
                    else
                    {
                        creditsRequired += creditRequiredForSingleMsg;
                    }
                }
            }

            baseFileXML.Save(sourceQFile);
            xmlfiledata =  CommonService.ReadXMLFile(sourceQFile);

               // xmlfiledata= xmlfiledata.Replace("<?xml version="1.0"?>","");

            creditsRequired += creditConsumed;
            //oClient.TotalCreditsConsumed += creditsRequired;

            if (errorCount == 0 && sentMsgCount == recipientNumberCount) // indicates sending completed successfully
            {
                System.IO.File.Copy(sourceQFile, sentQFile, true);
                if (System.IO.File.Exists(sourceQFile))
                    System.IO.File.Delete(sourceQFile);
                //ClientDBOperation.UpdateCredit(oClient, creditConsumed);

                //oClient.TotalNumMessages += sentMsgCount;
                //ClientDBOperation.UpdateCreditMsgConsumed(oClient); // Update the count of total credits consumed by user till tody & Number of messages send.
                UpdateMessageLog(CampaignDTO.Id, xmlfiledata);
                General.WriteInFile(baseFileName + " is sent successfully.");
            }
            else
            {
                if (creditConsumed != 0) // creditconsumed is zero means no any message send, hence dont update credit
                {
                    //ClientDBOperation.UpdateCredit(oClient, creditConsumed);
                }
            }

            //#region "Check for Alert message"
            //// Send credit alert and sms alert
            //if (oClient.AlertOnCredit != 0 && oClient.ActualCredits < oClient.AlertOnCredit && oClient.IsAlertOnCredit)
            //{
            //    if (ClientDBOperation.SMSCredits(oClient) >= 1)
            //    {
            //        // get credit alert msg format from QueueProcessorSettings.xml
            //        sErrlocation = "Sending credit goes below minimum limit alert-Line 438";
            //        string message = queuesettingsXML.DocumentElement["lowcreditalertmsg"].InnerText;
            //        message = message.Replace("[CurrentCredits]", oClient.ActualCredits.ToString());
            //        SendAlertMsg(message, "Credit Alert", oClient);
            //        General.WriteInFile("Credit Alert message generated.");
            //        ClientDBOperation.UpdateIsAlertOnCredits(oClient);
            //    }
            //    else
            //    {
            //        sErrlocation = "Due to unsufficient balance Credit Alert message not generated";
            //    }
            //}

            //// send alert when sms count is greater than
            //if (sentMsgCount > oClient.AlertOnMessage && oClient.AlertOnMessage != 0)
            //{
            //    if (ClientDBOperation.SMSCredits(oClient) >= 1)
            //    {
            //        // get sms alert msg format from QueueProcessorSettings.xml
            //        sErrlocation = "Sending max number of Msg sent alert-Line 448";
            //        string message = queuesettingsXML.DocumentElement["maxnumsmssendalertmsg"].InnerText;
            //        message = message.Replace("[SentMsgCount]", sentMsgCount.ToString()).Replace("[MsgLimit]", oClient.AlertOnMessage.ToString());
            //        SendAlertMsg(message, "SMSCount Alert", oClient);
            //        General.WriteInFile("SMSCount Alert message generated.");
            //    }
            //    else
            //    {
            //        sErrlocation = "Due to unsufficient balance SMSCount Alert message not generated";
            //    }
            //}
            //#endregion

            General.WriteInFile("Closing Balance = " + ClientDTO.SMSCredit + "\r\n"); // ClientDBOperation.ActualCredits(oClient) + "\r\n"
        }
        //Get Consumed Credits for one message
        public static double GetConsumedCreditsForOneMessage(string Message, bool IsCoupon)
        {
            double ConsumedCredits = 0;
            int MessageCount = 0;

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

            MessageCount = GetConsumedMessageCount(Message);
            if (IsCoupon == true)
            {
                ConsumedCredits = MessageCount * SettingDTO.NationalCouponSMSCount;
            }
            else
            {
                ConsumedCredits = MessageCount * SettingDTO.NationalCampaignSMSCount;
            }

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

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

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

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

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

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

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

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

                SMSResult(result);
                myResponse.Close();

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

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

                    CouponDTONew = CouponService.GetById(NewCouponId);

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

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

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

                    EcouponCampaignService.EditForEcouponResend(EcouponCampaignDTO);

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

                }
                else
                {
                    IsSent = false;

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

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

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

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

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

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

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

                                    CouponDTONew = CouponService.GetById(NewCouponId);

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

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

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

                                    EcouponCampaignService.EditForEcouponResend(EcouponCampaignDTO);

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

                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }

                    }
                    else
                    {
                        statuscode = resultWhiz;

                    }

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

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

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

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

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

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

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

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

                }
                else
                {
                    statuscode = result;
                }

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

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

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

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

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

                }

            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                    }

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

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

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

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

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

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

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

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

                                            ////}

                                        }

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

                                            sender = "022751";
                                        }

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

                                }

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

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

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

                    }
                    else
                    {

                    }
                }

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

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

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

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

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

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

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

                   // EcouponCampaignService.EditEcouponCampaignFromBackend(EcouponCampaignDTO);
                }

            nextprocess:
                result = finalstring;
            }

            catch (Exception ex)
            {

                result = "";

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

            }
            return result;
        }
 public static Setting SettingToDomain(SettingDTO SettingDTO)
 {
     if (SettingDTO == null) return null;
      Mapper.CreateMap<SettingDTO, Setting>();
      Setting Setting = Mapper.Map<Setting>(SettingDTO);
      return Setting;
 }
        //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;
            }
        }
        //Get Consumed message count for one message
        public static int GetConsumedMessageCount(string message)
        {
            int specialCharCount = 0;

            specialCharCount += message.Count(f => f == '^');
            specialCharCount += message.Count(f => f == '{');
            specialCharCount += message.Count(f => f == '}');
            specialCharCount += message.Count(f => f == '\\');
            specialCharCount += message.Count(f => f == '[');
            specialCharCount += message.Count(f => f == ']');
            specialCharCount += message.Count(f => f == '|');
            specialCharCount += message.Count(f => f == '~');
            specialCharCount += message.Count(f => f == '€');

            int oldmsglength = message.Length;
            int messagelength = oldmsglength;
            //Check is message contans [FirstName], [LastName], [Code], [BirthDate], [AnniversaryDate], [Email], [MobileNumber], [Gender], [ExpiresOn]

            if (message.Contains("[FirstName]")) //|| Message.Contains("[LastName]") || Message.Contains("[Code]") || Message.Contains("[BirthDate]") || Message.Contains("[AnniversaryDate]") || Message.Contains("[Email]") || Message.Contains("[MobileNumber]") || Message.Contains("[Gender]") || Message.Contains("[ExpiresOn]") )
            {

                messagelength = messagelength + 14;
            }

            if (message.Contains("[LastName]")) //|| Message.Contains("[Code]") || Message.Contains("[BirthDate]") || Message.Contains("[AnniversaryDate]") || Message.Contains("[Email]") || Message.Contains("[MobileNumber]") || Message.Contains("[Gender]") || Message.Contains("[ExpiresOn]") )
            {

                messagelength = messagelength + 15;
            }

            if (message.Contains("[Code]")) // || Message.Contains("[BirthDate]") || Message.Contains("[AnniversaryDate]") || Message.Contains("[Email]") || Message.Contains("[MobileNumber]") || Message.Contains("[Gender]") || Message.Contains("[ExpiresOn]") )
            {

                //  messagelength = messagelength;
            }

            if (message.Contains("[BirthDate]")) //|| Message.Contains("[AnniversaryDate]") || Message.Contains("[Email]") || Message.Contains("[MobileNumber]") || Message.Contains("[Gender]") || Message.Contains("[ExpiresOn]") )
            {
                //  messagelength = messagelength;
            }

            if (message.Contains("[AnniversaryDate]")) // || Message.Contains("[Email]") || Message.Contains("[MobileNumber]") || Message.Contains("[Gender]") || Message.Contains("[ExpiresOn]") )
            {
                messagelength = messagelength - 6;
            }

            if (message.Contains("[Email]")) // || Message.Contains("[MobileNumber]") || Message.Contains("[Gender]") || Message.Contains("[ExpiresOn]") )
            {
                messagelength = messagelength + 143;
            }

            if (message.Contains("[MobileNumber]")) // || Message.Contains("[Gender]") || Message.Contains("[ExpiresOn]") )
            {
                messagelength = messagelength - 4;
            }

            if (message.Contains("[Gender]")) // || Message.Contains("[ExpiresOn]") )
            {
                messagelength = messagelength - 2;
            }

            if (message.Contains("[ExpiresOn]")) // || Message.Contains("[ExpiresOn]") )
            {
                //messagelength = messagelength  ;
            }

            //int msgLength = message.Length + specialCharCount;

            int msgLength = messagelength + specialCharCount;

            //// MaxSMSLength, SMSBlockLength these two valus come from database
            //// Calculate the credits required to send this message.
            //string sErrlocation = "Calculating message count-500";

            SettingDTO SettingDTO = new SettingDTO();
            SettingDTO = SettingService.GetById(1);
            int MAXSMSLENGTH = SettingDTO.MessageLength;
            int SMSBLOCKLENGTH = SettingDTO.SingleMessageLength;

            if (msgLength <= MAXSMSLENGTH)
                return 1;
            else if (msgLength % SMSBLOCKLENGTH != 0)
                return (msgLength / SMSBLOCKLENGTH) + 1;
            else
                return msgLength / SMSBLOCKLENGTH;
        }
        /// <summary>
        /// Method to get unicode message count.
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private static int GetUnicodeMessageCount(string message)
        {
            int specialCharCount = 0;

            specialCharCount += message.Count(f => f == '^');
            specialCharCount += message.Count(f => f == '{');
            specialCharCount += message.Count(f => f == '}');
            specialCharCount += message.Count(f => f == '\\');
            specialCharCount += message.Count(f => f == '[');
            specialCharCount += message.Count(f => f == ']');
            specialCharCount += message.Count(f => f == '|');
            specialCharCount += message.Count(f => f == '~');
            specialCharCount += message.Count(f => f == '€');

            int msgLength = message.Length + specialCharCount;

            // MaxSMSLength, SMSBlockLength these two valus come from database
            // Calculate the credits required to send this message.
            string sErrlocation = "Calculating message count-500";

            SettingDTO SettingDTO = new SettingDTO();
            SettingDTO = SettingService.GetById(1);
            int MAXSMSLENGTH = SettingDTO.UTFFirstMessageLength;
            int SMSBLOCKLENGTH = SettingDTO.UTFSecondMessageLength;

            if (msgLength <= MAXSMSLENGTH)
            {
                msgLength = 1;
                return 1;
            }
            else
            {
                if (msgLength <= 134)
                {
                    msgLength = 2;
                    return 2;
                }
                else
                {
                    if (msgLength % SMSBLOCKLENGTH != 0)
                        return (msgLength / SMSBLOCKLENGTH) + 1;
                    else
                        return msgLength / SMSBLOCKLENGTH;
                }
            }
        }
        /// <summary>
        /// Method to get message count.
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static int GetMessageCount(string message)
        {
            int specialCharCount = 0;

            specialCharCount += message.Count(f => f == '^');
            specialCharCount += message.Count(f => f == '{');
            specialCharCount += message.Count(f => f == '}');
            specialCharCount += message.Count(f => f == '\\');
            specialCharCount += message.Count(f => f == '[');
            specialCharCount += message.Count(f => f == ']');
            specialCharCount += message.Count(f => f == '|');
            specialCharCount += message.Count(f => f == '~');
            specialCharCount += message.Count(f => f == '€');

            int msgLength = message.Length + specialCharCount;

            //// MaxSMSLength, SMSBlockLength these two valus come from database
            //// Calculate the credits required to send this message.
            //string sErrlocation = "Calculating message count-500";

            SettingDTO SettingDTO = new SettingDTO();
            SettingDTO = SettingService.GetById(1);
            MAXSMSLENGTH = SettingDTO.MessageLength;
            SMSBLOCKLENGTH = SettingDTO.SingleMessageLength;

            if (msgLength <= MAXSMSLENGTH)
                return 1;
            else if (msgLength % SMSBLOCKLENGTH != 0)
                return (msgLength / SMSBLOCKLENGTH) + 1;
            else
                return msgLength / SMSBLOCKLENGTH;
        }
        public static void CreatePacket()
        {
            StringBuilder recipientnumberslist = new StringBuilder();

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

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

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

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

                        MsgInformationDTO _oMsginfo = new MsgInformationDTO();

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

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

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

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

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

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

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

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

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

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

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

                            }
                        }

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

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

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

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

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

            }
            catch (WebException ex)
            {
                //oUcButtonControl.showMessage(frmButtonControl.Messageflag.errorMessage, Global.DisplayConnectionError(ex));
                throw;
            }
        }
        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)
        {
            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;
        }
        /// <summary>
        /// This method get recipient number & corresponding message from campaign file & sent it to smsoutbox.in gateway
        /// </summary>
        public void AddToSMSQueue()
        {
            General.WriteInFile("Sending file : " + baseFileName);
            HttpWebRequest oHttpRequest;
            HttpWebResponse oHttpWebResponse;

            //GatewayInfo oGatewayInfo = new GatewayInfo(oClient.campaignId, oClient.IsInternal);

            if (ClientDTO.SenderCode != "" && ClientDTO.SenderCode != null)
            {
                GATEWAY_URL = ConfigurationManager.AppSettings["TransactionalGateWay"].ToString();
                GatewayID = "WizSMS";// ClientDTO.SenderCode;

                GATEWAY_URL = GATEWAY_URL.Replace("[gateway]", ClientDTO.SenderCode.ToString());
            }
            else
            {
                GATEWAY_URL = ConfigurationManager.AppSettings["PromotionalGateWay"].ToString();
                GatewayID = "WizSMS";// "563485";
            }

            GATEWAY_URL = GATEWAY_URL.Replace("%26", "&");

            //GatewayID = oGatewayInfo.GatewayId;

            string strURL;
            string sMobileNo = null, mymsg = null, msgtype = null;
            int recipientNumberCount = 0; // count of recipient Mobile number.
            int errorCount = 0; // Error count.
            int creditConsumed = 0; // Credit consumed to sent message.
            int sentMsgCount = 0; // this count indicates how many msg sent successfully
            int creditRequiredForSingleMsg = 0; // Credit required to send message in the case of single message to multiple recipients.
            creditsRequired = 0;
            bool IsMultipleMsg;

            XmlNodeList MessageToSend = baseFileXML.SelectNodes("/packet/numbers/message");
            XmlNodeList RecipientsToSendMessage = baseFileXML.SelectNodes("/packet/numbers/number");
            recipientNumberCount = RecipientsToSendMessage.Count;

            // Check for is it an MsgBlaster Testing user or not
            ////if (oClient.IsInternal)
            ////{
            ////    General.WriteInFile(oClient.campaignId + " is a Graceworks team member.");
            ////}

            // check for packet contains multiple messages or not.
            if (MessageToSend.Count == RecipientsToSendMessage.Count && MessageToSend.Count != 1)
            {
                IsMultipleMsg = true;
            }
            else
            {
                IsMultipleMsg = false;
                // In the case of single msg to all recipents calculate the credit required to send this message
                if (CampaignDTO.IsUnicode == false)
                {
                    creditRequiredForSingleMsg = GetMessageCount(ReformatMsg(baseFileXML.GetElementsByTagName("message").Item(0).InnerText.TrimEnd()));
                }
                else creditRequiredForSingleMsg = GetUnicodeMessageCount(ReformatMsg(baseFileXML.GetElementsByTagName("message").Item(0).InnerText.TrimEnd()));
                mymsg = MsgCorrect(baseFileXML.GetElementsByTagName("message").Item(0).InnerText.TrimEnd(), CampaignDTO.IsUnicode);
            }

            foreach (XmlNode currentnode in baseFileXML.DocumentElement.GetElementsByTagName("number")) // loop through the each recipient number in this file
            {
                if (currentnode.Attributes.Count == 0) // check for this number message is send or not
                {
                    // Remove unwanted characters from number
                    sMobileNo = currentnode.InnerText.Replace(" ", "");
                    sMobileNo = sMobileNo.Replace("-", "");
                    sMobileNo = sMobileNo.Replace("(", "");
                    sMobileNo = sMobileNo.Replace(")", "");
                    sMobileNo = sMobileNo.Replace(",", "");
                    sMobileNo = sMobileNo.Replace("+", "");
                    double number;
                    bool IsNumeric = double.TryParse(sMobileNo, out number); // Check the number is in Numeric form or not
                    if (sMobileNo.Length < MINMOBILELENGTH || sMobileNo.Length > MAXMOBILELENGTH || !IsNumeric)
                    {
                        // Recipient numbers is invalid so skip this number
                        XmlAttribute errorStamp;
                        errorStamp = baseFileXML.CreateAttribute("notSent");
                        errorStamp.Value = "Invalid recipient number.";
                        currentnode.Attributes.Append(errorStamp);
                        sentMsgCount++;
                        continue;
                    }
                    else
                    {
                        sMobileNo = sMobileNo.Substring(sMobileNo.Length - MINMOBILELENGTH); // Get last 10 digits from number
                        sMobileNo = "91" + sMobileNo; // Add country code to Recipient number
                    }

                    if (IsMultipleMsg) // prepared separate message for this number
                    {
                        mymsg = MsgCorrect(currentnode.NextSibling.InnerText.TrimEnd(), CampaignDTO.IsUnicode);
                    }

                    if (mymsg == "")// Check for empty message.
                    {
                        // If message is empty than dont send this message & add resone why not send to that recipient number.
                        XmlAttribute errorStamp;
                        errorStamp = baseFileXML.CreateAttribute("notSent");
                        errorStamp.Value = "Empty message.";
                        currentnode.Attributes.Append(errorStamp);
                        sentMsgCount++;
                        continue;
                    }

                    int creditRequiredToSendMsg = 0;

                    if (IsMultipleMsg)
                        if (CampaignDTO.IsUnicode == false)
                        {
                            creditRequiredToSendMsg = GetMessageCount(ReformatMsg(currentnode.NextSibling.InnerText.TrimEnd()));
                        }
                        else
                        {
                            creditRequiredToSendMsg = GetUnicodeMessageCount(currentnode.NextSibling.InnerText.TrimEnd());
                        }

                        else
                            creditRequiredToSendMsg = creditRequiredForSingleMsg;

                    ////if (ClientDBOperation.ActualCredits(oClient) - creditConsumed < creditRequiredToSendMsg)//Check for available Credits
                    //if ((ClientDTO.SMSCredit - creditConsumed) < creditRequiredToSendMsg)//Check for available Credits
                    //{
                    //    baseFileXML.Save(sourceQFile);
                    //    if (IsMultipleMsg)
                    //    {
                    //        if (sentMsgCount > 0)
                    //        {
                    //            General.WriteInFile(baseFileName + " is skiped due to unsufficient credits.\r\nMessages sent upto recipient : " + currentnode.PreviousSibling.PreviousSibling.InnerText);
                    //        }
                    //        else
                    //        {
                    //            General.WriteInFile(baseFileName + " is skiped due to unsufficient credits.");
                    //        }
                    //    }
                    //    else
                    //    {
                    //        if (sentMsgCount > 0)
                    //        {
                    //            General.WriteInFile(baseFileName + " is skiped due to unsufficient credits.\r\nMessages sent upto recipient : " + currentnode.PreviousSibling.InnerText);
                    //        }
                    //        else
                    //        {
                    //            General.WriteInFile(baseFileName + " is skiped due to unsufficient credits.");
                    //        }
                    //    }
                    //    break;
                    //}

                    #region " Submiting to Gateway "

                    strURL = GATEWAY_URL.Replace("[recipient]", sMobileNo).Replace("[message]", mymsg);

                    if (CampaignDTO.IsUnicode == true)
                    {
                        strURL = strURL.Replace("[msgtype]", "1");
                    }
                    else strURL = strURL.Replace("[msgtype]", "0");

                    sErrlocation = "HTTP web request-Line 387";
                    oHttpRequest = (HttpWebRequest)System.Net.WebRequest.Create(strURL);
                    oHttpRequest.Method = "GET";
                TryAgain:
                    try
                    {
                        string messageID = string.Empty;
                        bool IsSent = false;
                        string statuscode = string.Empty;
                        string result = string.Empty;

                        oHttpWebResponse = (HttpWebResponse)oHttpRequest.GetResponse();
                        StreamReader response = new StreamReader(oHttpWebResponse.GetResponseStream());
                        result = response.ReadToEnd();
                        oHttpWebResponse.Close();

                        switch (GatewayID)
                        {
                            case "WizSMS":
                                //if (result.Contains('|'))
                                //    statuscode = result.Substring(0, result.IndexOf('|'));
                                //else
                                //    statuscode = result;

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

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

                                }
                                else
                                {
                                    statuscode = result;
                                }

                                switch (statuscode)
                                {
                                    case "0":
                                        messageID = "Successfully delivered";
                                        IsSent = true;
                                        messageID = result.Substring(result.IndexOf(':') + 1, result.Length - result.IndexOf(':') - 1);
                                        break;
                                    case "10001":
                                        //messageID = result.Substring(result.IndexOf(':') + 1, result.Length - result.IndexOf(':') - 1);.
                                        messageID = "Username / Password incorrect";
                                        IsSent = false;
                                        break;
                                    case "10002":
                                        messageID = "Contract expired";
                                        IsSent = false;
                                        break;
                                    case "10003":
                                        messageID = "User Credit expired";
                                        IsSent = false;
                                        break;
                                    case "10004":
                                        messageID = "User disabled";
                                        IsSent = false;
                                        break;
                                    case "10005":
                                        messageID = "Service is temporarily unavailable";
                                        IsSent = false;
                                        break;
                                    case "10006":
                                        messageID = "The specified message does not conform to DTD";
                                        IsSent = false;
                                        break;
                                    case "10007":
                                        messageID = "unknown request";
                                        IsSent = false;
                                        break;
                                    case "10008":
                                        messageID = "Invalid URL Error, This means that one of the parameters was not provided or left blank";
                                        IsSent = false;
                                        break;
                                    case "20001":
                                        messageID = "Unknown number, Number not activated, Invalid destination number length. Destination number not numeric";
                                        IsSent = true;
                                        break;
                                    case "20002":
                                        messageID = "Switched OFF or Out of Range";
                                        IsSent = false;
                                        break;
                                    case "20003":
                                        messageID = "Message waiting list full, Handset memory full";
                                        IsSent = true;
                                        break;
                                    case "20004":
                                        messageID = "Unknown equipment, Illegal equipment, Equipment not Short message equipped";
                                        IsSent = true;
                                        break;
                                    case "20005":
                                        messageID = "System failure, Far end network error, No Paging response, Temporary network not available";
                                        IsSent = false;
                                        break;
                                    case "20006":
                                        messageID = "Teleservice not provisioned, Call barred, Operator barring";
                                        IsSent = true;
                                        break;
                                    case "20007":
                                        messageID = "Sender-ID mismatch";
                                        IsSent = false;
                                        break;
                                    case "20008":
                                        messageID = "Dropped Messages";
                                        IsSent = false;
                                        break;
                                    case "20009":
                                        messageID = "Number registered in NDNC";
                                        IsSent = true;
                                        break;
                                    case "20010":
                                        messageID = "Destination number empty";
                                        IsSent = false;
                                        break;
                                    case "20011":
                                        messageID = "Sender address empty";
                                        IsSent = false;
                                        break;
                                    case "20012":
                                        messageID = "SMS over 160 character, Non-compliant message";
                                        IsSent = true;
                                        break;
                                    case "20013":
                                        messageID = "UDH is invalid";
                                        IsSent = false;
                                        break;
                                    case "20014":
                                        messageID = "Coding is invalid";
                                        IsSent = false;
                                        break;
                                    case "20015":
                                        messageID = "SMS text is empty";
                                        IsSent = true;
                                        break;
                                    case "20016":
                                        messageID = "Invalid Sender Id";
                                        IsSent = false;
                                        break;
                                    case "20017":
                                        messageID = "Invalid message, Duplicate message ,Submit failed";
                                        IsSent = false;
                                        break;
                                    case "20018":
                                        messageID = "Invalid Receiver ID (will validate Indian mobile numbers only.)";
                                        IsSent = true;
                                        break;
                                    case "20019":
                                        messageID = "Invalid Date time for message Schedule (If the date specified in message post for schedule delivery is less than current date or more than expiry date or more than 1 year)";
                                        IsSent = false;
                                        break;
                                    case "20020":
                                        messageID = "Message text is invalid";
                                        IsSent = false;
                                        break;
                                    case "20021":
                                        messageID = "Aggregator Id mismatch for template and sender-ID";
                                        IsSent = false;
                                        break;
                                    case "20022":
                                        messageID = "Noise Word Found in Promotional Message";
                                        IsSent = false;
                                        break;
                                    case "20023":
                                        messageID = "Invalid Campaign";
                                        IsSent = false;
                                        break;
                                    case "40001":
                                        messageID = "Message delivered successfully";
                                        IsSent = true;
                                        break;
                                    case "40002":
                                        messageID = "Message failed";
                                        IsSent = false;
                                        break;
                                    case "40003":
                                        messageID = "Message ID is invalid";
                                        IsSent = false;
                                        break;
                                    case "40004":
                                        messageID = "Command Completed Successfully";
                                        IsSent = false;
                                        break;
                                    case "40005":
                                        messageID = "HTTP disabled";
                                        IsSent = false;
                                        break;
                                    case "40006":
                                        messageID = "Invalid Port";
                                        IsSent = false;
                                        break;
                                    case "40007":
                                        messageID = "Invalid Expiry minutes";
                                        IsSent = false;
                                        break;
                                    case "40008":
                                        messageID = "Invalid Customer Reference Id";
                                        IsSent = false;
                                        break;
                                    case "40009":
                                        messageID = "Invalid Bill Reference Id";
                                        IsSent = false;
                                        break;
                                    case "40010":
                                        messageID = "Email Delivery Disabled";
                                        IsSent = false;
                                        break;
                                    case "40011":
                                        messageID = "HTTPS disabled";
                                        IsSent = false;
                                        break;
                                    case "40012":
                                        messageID = "Invalid operator id";
                                        IsSent = false;
                                        break;
                                    case "50001":
                                        messageID = "Cannot update/delete schedule since it has already been processed";
                                        IsSent = false;
                                        break;
                                    case "50002":
                                        messageID = "Cannot update schedule since the new date-time parameter is incorrect";
                                        IsSent = false;
                                        break;
                                    case "50003":
                                        messageID = "Invalid SMS ID/GUID";
                                        IsSent = false;
                                        break;
                                    case "50004":
                                        messageID = "Invalid Status type for schedule search query. The status strings can be PROCESSED, PENDING and ERROR";
                                        IsSent = false;
                                        break;
                                    case "50005":
                                        messageID = "Invalid date time parameter for schedule search query";
                                        IsSent = false;
                                        break;
                                    case "50006":
                                        messageID = "Invalid GUID for GUID search query";
                                        IsSent = false;
                                        break;
                                    case "50007":
                                        messageID = "Invalid command action";
                                        IsSent = false;
                                        break;
                                    case "60001":
                                        messageID = "The number is in DND list";
                                        IsSent = true;
                                        break;
                                    case "60002":
                                        messageID = "Insufficient Fund";
                                        IsSent = false;
                                        break;
                                    case "60003":
                                        messageID = "Validity Expired";
                                        IsSent = false;
                                        break;
                                    case "60004":
                                        messageID = "Credit back not required";
                                        IsSent = false;
                                        break;
                                    case "60005":
                                        messageID = "Record is not there in accounts table";
                                        IsSent = false;
                                        break;
                                    case "60007":
                                        messageID = "Message is accepted";
                                        IsSent = false;
                                        break;
                                    case "60008":
                                        messageID = "Message validity period has expired";
                                        IsSent = false;
                                        break;
                                    case "99999":
                                        messageID = "Unknown Error";
                                        IsSent = false;
                                        break;
                                    default:
                                        General.WriteInFile("Response :" + result);
                                        break;
                                }
                                break;
                            case "SMSPro":
                                //MessageSent GUID="gracew-8be9d47f999e569a" SUBMITDATE="08/26/2013 03:16:12 PM"
                                if (result.Contains("MessageSent"))
                                {
                                    messageID = result.Split('"')[1];
                                    IsSent = true;
                                }
                                else
                                {
                                    messageID = result;
                                    General.WriteInFile(result);
                                }
                                break;
                            default:
                                break;
                        }

                        if (IsSent)
                        {
                            if (IsMultipleMsg)
                                creditConsumed += creditRequiredToSendMsg;
                            else
                                creditConsumed += creditRequiredForSingleMsg;

                            XmlAttribute timespan;
                            timespan = baseFileXML.CreateAttribute("sentTime");
                            timespan.Value = System.DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt");
                            currentnode.Attributes.Append(timespan);

                            XmlAttribute gatewayID;
                            gatewayID = baseFileXML.CreateAttribute("gatewayID");
                            gatewayID.Value = GatewayID;
                            currentnode.Attributes.Append(gatewayID);

                            XmlAttribute msgID;
                            msgID = baseFileXML.CreateAttribute("msgID");
                            msgID.Value = messageID;
                            currentnode.Attributes.Append(msgID);

                            XmlAttribute msgCode;
                            msgCode = baseFileXML.CreateAttribute("msgCode");
                            msgCode.Value = statuscode;
                            currentnode.Attributes.Append(msgCode);

                            XmlAttribute msgCount;
                            msgCount = baseFileXML.CreateAttribute("msgCount");
                            if (CampaignDTO.IsUnicode == false)
                            {
                                msgCount.Value = GetMessageCount(mymsg).ToString();
                                currentnode.Attributes.Append(msgCount);
                            }
                            else
                            {
                                msgCount.Value = GetUnicodeMessageCount(mymsg).ToString();
                                currentnode.Attributes.Append(msgCount);
                            }

                            XmlAttribute msgCredits;
                            SettingDTO SettingDTO = new SettingDTO();
                            SettingDTO = SettingService.GetById(1);
                            msgCredits = baseFileXML.CreateAttribute("msgCredits");
                            if (IsMultipleMsg)
                            {
                                msgCredits.Value = creditRequiredToSendMsg.ToString();
                                double credit = Convert.ToDouble(msgCredits.Value);
                                double reqCredits = credit * SettingDTO.NationalCampaignSMSCount;
                                msgCredits.Value = reqCredits.ToString();
                            }
                            else
                            {
                                msgCredits.Value = creditRequiredForSingleMsg.ToString();
                                double credit = Convert.ToDouble(msgCredits.Value);
                                double reqCredits = credit * SettingDTO.NationalCampaignSMSCount;
                                msgCredits.Value = reqCredits.ToString();
                            } // GetMessageCount(mymsg).ToString();
                            currentnode.Attributes.Append(msgCredits);

                            sentMsgCount++;
                            errorCount = 0;

                            //oClient.ReduceCredit = creditConsumed;
                            //if (sentMsgCount % UPDATEBALAFTER == 0)
                            //{
                            //    ClientDBOperation.UpdateCredit(oClient, creditConsumed);
                            //    creditsRequired += creditConsumed;
                            //    baseFileXML.Save(sourceQFile);
                            //    creditConsumed = 0;
                            //}

                            creditConsumed = 0;
                        }
                        else
                        {
                            errorCount += 1;
                            if (errorCount > MAXCHECKFORRESPONSE)
                            {
                                General.WriteInFile("Message sending stoped due to BAD response from Gateway (i.e" + messageID + ")");
                                break;
                            }
                            else
                                goto TryAgain;
                        }
                    }
                    catch (Exception ex)
                    {
                        errorCount += 1;
                        baseFileXML.Save(sourceQFile);
                        if (errorCount > MAXCHECKFORCONNECTION)
                        {
                            General.WriteInFile(sErrlocation + "\r\nGateway connection unavailable." + "\r\n" + ex.Message);
                            break;
                        }
                        else
                            goto TryAgain;
                    }
                    #endregion

                }
                else
                {
                    sentMsgCount++;
                    if (IsMultipleMsg)
                    {
                        creditsRequired += GetMessageCount(currentnode.NextSibling.InnerText.TrimEnd());
                    }
                    else
                    {
                        creditsRequired += creditRequiredForSingleMsg;
                    }
                }
            }

            baseFileXML.Save(sourceQFile);
            xmlfiledata = CommonService.ReadXMLFile(sourceQFile);

            // xmlfiledata= xmlfiledata.Replace("<?xml version="1.0"?>","");

            creditsRequired += creditConsumed;
            //oClient.TotalCreditsConsumed += creditsRequired;

            if (errorCount == 0 && sentMsgCount == recipientNumberCount) // indicates sending completed successfully
            {
                System.IO.File.Copy(sourceQFile, sentQFile, true);
                if (System.IO.File.Exists(sourceQFile))
                    System.IO.File.Delete(sourceQFile);
                //ClientDBOperation.UpdateCredit(oClient, creditConsumed);

                //oClient.TotalNumMessages += sentMsgCount;
                //ClientDBOperation.UpdateCreditMsgConsumed(oClient); // Update the count of total credits consumed by user till tody & Number of messages send.
                UpdateMessageLog(CampaignDTO.Id, xmlfiledata);
                General.WriteInFile(baseFileName + " is sent successfully.");
            }
            else
            {
                if (creditConsumed != 0) // creditconsumed is zero means no any message send, hence dont update credit
                {
                    //ClientDBOperation.UpdateCredit(oClient, creditConsumed);
                }
            }

            //#region "Check for Alert message"
            //// Send credit alert and sms alert
            //if (oClient.AlertOnCredit != 0 && oClient.ActualCredits < oClient.AlertOnCredit && oClient.IsAlertOnCredit)
            //{
            //    if (ClientDBOperation.SMSCredits(oClient) >= 1)
            //    {
            //        // get credit alert msg format from QueueProcessorSettings.xml
            //        sErrlocation = "Sending credit goes below minimum limit alert-Line 438";
            //        string message = queuesettingsXML.DocumentElement["lowcreditalertmsg"].InnerText;
            //        message = message.Replace("[CurrentCredits]", oClient.ActualCredits.ToString());
            //        SendAlertMsg(message, "Credit Alert", oClient);
            //        General.WriteInFile("Credit Alert message generated.");
            //        ClientDBOperation.UpdateIsAlertOnCredits(oClient);
            //    }
            //    else
            //    {
            //        sErrlocation = "Due to unsufficient balance Credit Alert message not generated";
            //    }
            //}

            //// send alert when sms count is greater than
            //if (sentMsgCount > oClient.AlertOnMessage && oClient.AlertOnMessage != 0)
            //{
            //    if (ClientDBOperation.SMSCredits(oClient) >= 1)
            //    {
            //        // get sms alert msg format from QueueProcessorSettings.xml
            //        sErrlocation = "Sending max number of Msg sent alert-Line 448";
            //        string message = queuesettingsXML.DocumentElement["maxnumsmssendalertmsg"].InnerText;
            //        message = message.Replace("[SentMsgCount]", sentMsgCount.ToString()).Replace("[MsgLimit]", oClient.AlertOnMessage.ToString());
            //        SendAlertMsg(message, "SMSCount Alert", oClient);
            //        General.WriteInFile("SMSCount Alert message generated.");
            //    }
            //    else
            //    {
            //        sErrlocation = "Due to unsufficient balance SMSCount Alert message not generated";
            //    }
            //}
            //#endregion

            General.WriteInFile("Closing Balance = " + ClientDTO.SMSCredit + "\r\n"); // ClientDBOperation.ActualCredits(oClient) + "\r\n"
        }