//Create group
        public static int Create(GroupDTO GroupDTO)
        {
            try
            {

                GlobalSettings.LoggedInClientId = GroupDTO.ClientID;
                int PartnerId = ClientService.GetById(GroupDTO.ClientID).PartnerId;
                GlobalSettings.LoggedInPartnerId = PartnerId;

                var group = new Group();

                UnitOfWork uow = new UnitOfWork();
                GroupDTO.ClientID = GroupDTO.ClientID;
                group = Transform.GroupToDomain(GroupDTO);
                uow.GroupRepo.Insert(group);

                uow.SaveChanges();

                GroupDTO.Id = group.Id;
                return GroupDTO.Id;

            }

            catch (Exception)
            {
                throw;
            }
        }
 public void EditGroup(GroupDTO GroupDTO)
 {
     try
     {
         GroupService.Edit(GroupDTO);
     }
     catch (TimeoutException)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.RequestTimeout)
         {
             Content = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
     catch (Exception e)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
         {
             Content = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
 }
        //Edit group
        public static void Edit(GroupDTO GroupDTO)
        {
            try
            {
                GlobalSettings.LoggedInClientId = GroupDTO.ClientID;
                int PartnerId = ClientService.GetById(GroupDTO.ClientID).PartnerId;
                GlobalSettings.LoggedInPartnerId = PartnerId;

                UnitOfWork uow = new UnitOfWork();
                Group Group = Transform.GroupToDomain(GroupDTO);
                uow.GroupRepo.Update(Group);
                uow.SaveChanges();
            }
            catch
            {
                throw;
            }
        }
        // Returns group list which have clients
        public static List<GroupContactDTO> GetGroupListWithContactPresentByClientId(int ClientId)
        {
            List<GroupContactDTO> GroupDTOList = new List<GroupContactDTO>();

            try
            {

                using (var uow = new UnitOfWork())
                {
                    IEnumerable<Group> Group = uow.GroupRepo.GetAll().Where(e => e.ClientID == ClientId).OrderBy(e => e.Name).ToList();
                    if (Group != null)
                    {
                        foreach (var item in Group)
                        {
                            GroupDTO GroupDTO = new GroupDTO();
                            GroupDTO = GetById(item.Id);
                            GroupContactDTO GroupContactDTO = new GroupContactDTO();
                            //GroupContactDTO = GetGroupContactById(GroupDTO.Id);
                            List<ContactDTO> ContactDTOList = new List<ContactDTO>();
                            ContactDTOList = GroupContactService.GetGroupIdWiseContacts(GroupDTO.Id);// GroupDTOTemp.Id

                            GroupContactDTO.ContactCount = ContactDTOList.Count();// GroupContactDTO.Contacts.Count();
                            if (ContactDTOList.Count() > 0) // GroupContactDTO.Contacts.Count
                            {
                                GroupDTOList.Add(GroupContactDTO);// (Transform.GroupContactToDTO(item));
                            }
                        }
                    }
                }

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

                throw;
            }
        }
        //get group list by client id
        public static List<GroupDTO> GetGroupListByClientIdForCampaign(int ClientId)
        {
            List<GroupDTO> GroupDTOList = new List<GroupDTO>();

            try
            {

                using (var uow = new UnitOfWork())
                {
                    IEnumerable<Group> Group = uow.GroupRepo.GetAll().Where(e => e.ClientID == ClientId).OrderBy(e => e.Name).ToList();
                    if (Group != null)
                    {
                        GroupDTO GroupDTOAllContact = new GroupDTO();
                        GroupDTOAllContact.Id = 0;
                        GroupDTOAllContact.Name = "All Contacts";
                        string ReceipentsNumber = ContactService.GetAllReceipentNumberByClientId(ClientId);
                        int TotalContactCount = CommonService.GetRecipientsCount(ReceipentsNumber);
                        GroupDTOAllContact.ContactCount = TotalContactCount;
                        GroupDTOList.Add(GroupDTOAllContact);

                        foreach (var item in Group)
                        {
                            GroupDTO GroupDTO = new GroupDTO();
                            GroupDTO = Transform.GroupToDTO(item);
                            Group objGroup = uow.GroupRepo.GetById(item.Id);//, true
                            //GroupContactDTO GroupContactDTO = new GroupContactDTO();
                            //GroupContactDTO = GetGroupContactById(GroupDTO.Id);
                            List<ContactDTO> ContactDTO = new List<ContactDTO>();
                            int ContactCount = GroupContactService.GetGroupIdWiseContactsCount(objGroup.Id, "");

                            GroupDTO.ContactCount = ContactCount;// objGroup.Contacts.Count();//GroupContactDTO.Contacts.Count(); //
                            GroupDTOList.Add(GroupDTO);
                        }
                    }
                }

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

                throw;
            }
        }
        //Get group details by group name and client id
        public static GroupDTO GetGroupByNameAndClientId(string Name, int ClientId)
        {
            try
            {
                GroupDTO GroupDTO = new GroupDTO();
                UnitOfWork uow = new UnitOfWork();
                IEnumerable<Group> Group = uow.GroupRepo.GetAll().Where(e => e.Name.ToLower() == Name.ToLower() && e.ClientID == ClientId);
                //ClientDTO ClientDTO = Transform.ClientToDTO(Client);
                if (Group.ToList().Count > 0)
                {
                    foreach (var item in Group)
                    {

                        GroupDTO = Transform.GroupToDTO(item);
                        return GroupDTO;
                    }
                    return GroupDTO;
                }
                else return GroupDTO;
            }
            catch
            {
                throw;
            }
        }
        public static void ReadSqlite(int ClientId, string sqlitefile)
        {
            int NewGroupId = 0;
            int GrpId = 0;
            try
            {

                DataTable dtGroupContacts = GetGroupContacts(sqlitefile);
                int GroupId = 0;
                for (int i = 0; (i <= (dtGroupContacts.Rows.Count - 1)); i++)
                {
                    try
                    {
                        int ContactId = 0;

                        if (!Convert.IsDBNull(dtGroupContacts.Rows[i]["GroupID"].ToString()))
                        {
                            GroupId = Convert.ToInt32( dtGroupContacts.Rows[i]["GroupID"].ToString());
                        }
                        else
                        {
                            GroupId = 0;
                        }

                        if (!Convert.IsDBNull(dtGroupContacts.Rows[i]["ContactID"].ToString()))
                        {
                            ContactId = Convert.ToInt32(dtGroupContacts.Rows[i]["ContactID"].ToString());
                        }
                        else
                        {
                            ContactId = 0;
                        }

                        DataTable dtGroups = GetGroups(sqlitefile, GroupId);
                        for (int j = 0; (j <= (dtGroups.Rows.Count - 1)); j++)
                        {
                            try
                            {
                                //int chkGroupid = 0;
                                    string Groupname = "";
                                    if (!Convert.IsDBNull(dtGroups.Rows[j]["GroupName"].ToString()))
                                    {
                                        Groupname = dtGroups.Rows[j]["GroupName"].ToString();
                                    }
                                    else
                                    {
                                        Groupname = "";
                                    }

                                    //if (!Convert.IsDBNull(dtGroups.Rows[j]["GroupID"].ToString()))
                                    //{
                                    //    GrpId = Convert.ToInt32(dtGroups.Rows[j]["GroupID"].ToString());
                                    //}
                                    //else
                                    //{
                                    //    GrpId = 0;
                                    //}

                                    if (GroupId != GrpId)
                                    {
                                        // Check group name already present or not
                                        GroupDTO GroupDTOPresent = new GroupDTO();
                                        GroupDTOPresent = GroupService.GetGroupByNameAndClientId(Groupname, ClientId);
                                        if (GroupDTOPresent.Id == 0)
                                        {
                                            ////CreateGroup
                                            GroupDTO GroupDTO = new GroupDTO();
                                            GroupDTO.Name = Groupname;
                                            GroupDTO.ClientID = ClientId;
                                            NewGroupId = GroupService.Create(GroupDTO);
                                        }
                                        else
                                        {
                                            NewGroupId = GroupDTOPresent.Id;
                                        }

                                    }

                                    DataTable dtContacts = GetContactsById(sqlitefile, ContactId);

                                for (int k = 0; (k <= (dtContacts.Rows.Count - 1)); k++)
                                {
                                    try
                                    {
                                         string FirstName;
                                         if (!Convert.IsDBNull(dtContacts.Rows[k]["FirstName"].ToString()))
                                         {
                                             FirstName = dtContacts.Rows[k]["FirstName"].ToString();
                                         }
                                         else
                                         {
                                             FirstName = "";
                                         }

                                         string LastName;
                                         if (!Convert.IsDBNull(dtContacts.Rows[k]["LastName"].ToString()))
                                         {
                                             LastName = dtContacts.Rows[k]["LastName"].ToString();
                                         }
                                         else
                                         {
                                             LastName = "";
                                         }

                                         string FullName = FirstName + " " + LastName;

                                         string Mobile;
                                         if (!Convert.IsDBNull(dtContacts.Rows[k]["MobileNumber"].ToString()))
                                         {
                                             Mobile = dtContacts.Rows[k]["MobileNumber"].ToString();
                                             if (Mobile == "") { continue; }
                                         }
                                         else
                                         {
                                             Mobile = "";
                                         }

                                         string Gender;
                                         if (!Convert.IsDBNull(dtContacts.Rows[k]["Gender"].ToString()))
                                         {
                                             Gender = dtContacts.Rows[k]["Gender"].ToString();
                                             if (Gender == "")
                                             {
                                                 Gender = "Male";
                                             }
                                         }
                                         else
                                         {
                                             Gender = "Male";
                                         }

                                         string BirthDate;
                                         if (!Convert.IsDBNull(dtContacts.Rows[k]["BirthDate"].ToString()))
                                         {
                                             BirthDate = dtContacts.Rows[k]["BirthDate"].ToString();
                                         }
                                         else
                                         {
                                             BirthDate =  null;
                                         }

                                         string Anniversary;
                                         if (!Convert.IsDBNull(dtContacts.Rows[k]["Anniversary"].ToString()))
                                         {
                                             Anniversary = dtContacts.Rows[k]["Anniversary"].ToString();
                                         }
                                         else
                                         {
                                             Anniversary =  null;
                                         }

                                         string Email;
                                         if (!Convert.IsDBNull(dtContacts.Rows[k]["EmailID"].ToString()))
                                         {
                                             Email = dtContacts.Rows[k]["EmailID"].ToString();
                                         }
                                         else
                                         {
                                             Email = null;
                                         }

                                         //Check Contact Present or not
                                         ContactDTO ContactDTO = new ContactDTO();
                                         ContactDTO = ContactService.GetContactByMobileNumberAndClientId(Mobile, ClientId);
                                         if (ContactDTO.Id == 0)
                                         {
                                             ////Create Contact
                                             ContactDTO ContactDTONew = new ContactDTO();
                                             ContactDTONew.Name = FullName;
                                             if (CommonService.IsDate(BirthDate))
                                             {
                                                DateTime? bdate = Convert.ToDateTime( BirthDate);
                                                 ContactDTONew.BirthDate = bdate;
                                             }

                                             if (CommonService.IsDate(Anniversary))
                                             {
                                                 DateTime? anniversarydate = Convert.ToDateTime(Anniversary);
                                                 ContactDTONew.BirthDate = anniversarydate;
                                             }
                                             ContactDTONew.Email = Email;
                                             ContactDTONew.ClientId = ClientId;

                                             ContactDTONew.Gender = Gender;
                                             ContactDTONew.MobileNumber = Mobile;

                                             ContactDTONew.FirstName = FirstName;
                                             ContactDTONew.LastName = LastName;
                                             GroupDTO GroupDTO = GroupService.GetById(NewGroupId);
                                             List<GroupDTO> Groups = new List<GroupDTO>();
                                             Groups.Add(GroupDTO);
                                             ContactDTONew.Groups = Groups;

                                             if (ContactDTONew.FirstName.Length > 50)
                                             {
                                                 continue;
                                             }

                                             if (ContactDTONew.LastName.Length > 50)
                                             {
                                                 continue;
                                             }
                                             ContactService.Create(ContactDTONew);

                                         }
                                    }
                                    catch
                                    {
                                        continue;
                                    }

                                }

                                GrpId = GroupId;
                            }
                            catch
                            {
                                continue;
                            }
                        }

                    }
                    catch
                    {
                        continue;
                    }
                }

            }
            catch(Exception ex)
            {
                using (FileStream file = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\" + System.DateTime.Now.Date.ToString("dd-MMM-yyyy") + "_Log.txt", FileMode.Append, FileAccess.Write))
                {
                    StreamWriter streamWriter = new StreamWriter(file);
                    streamWriter.WriteLine(System.DateTime.Now + " - " + "ReadSqlite" + " - " + ex.Message.ToString());
                    streamWriter.Close();
                }
            }
        }
        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 List<ContactDTO> GetContactsbyClientId(int ClientId, string search, PagingInfo pagingInfo)
        {
            List<ContactDTO> contactDTO = new List<ContactDTO>();
            GroupDTO GroupDTO = new GroupDTO();
            try
            {
                UnitOfWork uow = new UnitOfWork();
                int skip = (pagingInfo.Page - 1) * pagingInfo.ItemsPerPage;
                int take = pagingInfo.ItemsPerPage;
                IQueryable<Contact> Contact = uow.ContactRepo.GetAll().Where(e => e.ClientId == ClientId).AsQueryable();// ToList().Skip(skip).Take(take); //.OrderBy(e => e.Name)

                Contact = PagingService.Sorting<Contact>(Contact, pagingInfo.SortBy, pagingInfo.Reverse);
                Contact = Contact.Skip(skip).Take(take);
                if (Contact != null)
                {
                    if (search != "" && search != null)
                    {

                        bool IsDate = CommonService.IsDate(search);
                        if (IsDate != true)
                        {
                            // string search

                            IQueryable<Contact> Contactsearch = uow.ContactRepo.GetAll().Where(e => (e.ClientId == ClientId) && ((e.Email != null ? (e.Email.ToLower().Contains(search.ToLower())) : false) || e.MobileNumber.Contains(search) || (e.Name != null ? (e.Name.ToLower().Contains(search.ToLower())) : false) || (e.FirstName != null ? (e.FirstName.ToLower().Contains(pagingInfo.Search.ToLower())) : false) || (e.LastName != null ? (e.LastName.ToLower().Contains(pagingInfo.Search.ToLower())) : false) || (e.AnniversaryDate.ToString() != null ? (Convert.ToDateTime(e.AnniversaryDate).ToString("dd-MMM-yyyy").ToLower().Contains(pagingInfo.Search.ToLower())) : false) || (e.BirthDate.ToString() != null ? (Convert.ToDateTime(e.BirthDate).ToString("dd-MMM-yyyy").ToLower().Contains(pagingInfo.Search.ToLower())) : false))).AsQueryable();// .ToList().Skip(skip).Take(take); //.OrderBy(e => e.Name)
                            Contactsearch = PagingService.Sorting<Contact>(Contactsearch, pagingInfo.SortBy, pagingInfo.Reverse);
                            Contactsearch = Contactsearch.Skip(skip).Take(take);

                            if (Contactsearch != null)
                            {
                                foreach (var item in Contactsearch)
                                {
                                    ContactDTO ContactDTOObj = new ContactDTO();
                                    ContactDTOObj = GetById(item.Id);
                                    contactDTO.Add(ContactDTOObj);

                                    //ContactDTOObj =Transform.ContactToDTO(item);
                                    // contactDTO.Add(Transform.ContactToDTO(item));

                                }

                            }

                        }
                        else
                        {
                            //date wise search
                            DateTime date = Convert.ToDateTime(search);
                            IQueryable<Contact> Contactsearch = uow.ContactRepo.GetAll().Where(e => (e.ClientId == ClientId) && e.AnniversaryDate >= date && e.AnniversaryDate < date.AddDays(1) || e.BirthDate >= date && e.BirthDate < date.AddDays(1)).AsQueryable();//.OrderBy(e => e.Name);

                            Contactsearch = PagingService.Sorting<Contact>(Contactsearch, pagingInfo.SortBy, pagingInfo.Reverse);
                            Contactsearch = Contactsearch.Skip(skip).Take(take);

                            if (Contactsearch != null)
                            {
                                foreach (var item in Contactsearch)
                                {
                                    ContactDTO ContactDTOObj = new ContactDTO();
                                    ContactDTOObj = GetById(item.Id);
                                    contactDTO.Add(ContactDTOObj);
                                    // contactDTO.Add(Transform.ContactToDTO(item));

                                }
                            }
                            return contactDTO;

                        }

                    }
                    else
                    {
                        foreach (var item in Contact)
                        {
                            ContactDTO ContactDTOObj = new ContactDTO();
                            ContactDTOObj = GetById(item.Id);
                            contactDTO.Add(ContactDTOObj);
                            //contactDTO.Add(Transform.ContactToDTO(item));

                        }
                    }
                }

                return contactDTO;
            }
            catch (Exception)
            {

                throw;
            }
        }
        //int GroupId,
        public static bool ImportContactsFromExcelFile(int ClientId, List<ContactDTO> ContactDTOList)
        {
            //List<ContactDTO> ContactDTOListNew = new List<ContactDTO>();
            //ContactDTOListNew = ContactDTOList;

            bool IsImported = false;
            try
            {
                ContactDTO ContactDTO = new ContactDTO();
                GroupDTO GroupDTO = new GroupDTO();
                // Create Group
                GroupDTO.Name = "MyGroup " + string.Format("{0:G}", System.DateTime.Now);
                GroupDTO.ClientID = ClientId;
                int GroupId = GroupService.Create(GroupDTO);

                if (GroupId != 0)
                {
                    GroupDTO = GroupService.GetById(GroupId);
                }
                else
                {
                    GroupDTO = null;
                }

                foreach (var item in ContactDTOList)
                {

                    ContactDTO = item;
                    ContactDTO.ClientId = ClientId;
                    if (ContactDTO.Groups == null && GroupDTO != null)
                    {
                        ContactDTO.Groups = new List<GroupDTO>();
                        ContactDTO.Groups.Add(GroupDTO);
                    }

                    bool IsMobileExist = SearchMobileNumber(ContactDTO.MobileNumber, ClientId, ContactDTO.Id);
                    if (IsMobileExist != true)
                    {
                        //Insert Contact information to Contact.
                        try
                        {
                            if (ContactDTO.IsValid == true)
                            {
                                ////Check Contact Present or not
                                //ContactDTO ContactDTOpresent = new ContactDTO();
                                //ContactDTOpresent = ContactService.GetContactByMobileNumberAndClientId(ContactDTO.MobileNumber, ClientId);
                                if (ContactDTO.Id == 0)
                                {
                                    int ContactId = Create(ContactDTO);
                                }
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }

                    IsImported = true;
                }

                GroupDTO GroupDTOTemp = new GroupDTO();
                GroupDTOTemp.ContactCount = GroupContactService.GetGroupIdWiseContactsCount(GroupId, "");
                if (GroupDTOTemp.ContactCount == 0)
                {
                    GroupService.Delete(GroupId);
                }

                return IsImported;
            }
            catch (Exception e)
            {
                throw;
            }
        }
        //Returns Campaign paged list as per client and search with pagingInfo obect
        public static PageData<CampaignDTO> GetCampaignPagedListbyClientId(PagingInfo pagingInfo, int ClientId)
        {
            List<CampaignDTO> CampaignDTOList = new List<CampaignDTO>();
            PageData<CampaignDTO> pageList = new PageData<CampaignDTO>();

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

                pagingInfo = PagingInfoCreated;
            }
            if (pagingInfo.SortBy == "")
            {
                pagingInfo.SortBy = "CreatedDate";
            }

            CampaignDTOList = GetCampaignsbyClientId(ClientId, pagingInfo.Search, pagingInfo);
            IQueryable<CampaignDTO> CampaignDTOPagedList = CampaignDTOList.AsQueryable();
            UnitOfWork uow = new UnitOfWork();
            int count = 0;

            if (pagingInfo.Search != "" && pagingInfo.Search != null)
            {
                bool IsDate = CommonService.IsDate(pagingInfo.Search);
                if (IsDate != true)
                {
                    count = 0;
                    count = uow.CampaignRepo.GetAll().Where(e => e.Name.ToLower().Contains(pagingInfo.Search.ToLower()) || e.RecipientsNumber.Contains(pagingInfo.Search) || e.RequiredCredits.ToString() == (pagingInfo.Search) || (e.ScheduledDate.ToString() != null ? (Convert.ToDateTime(e.ScheduledDate).ToString("dd-MMM-yyyy").ToLower().Contains(pagingInfo.Search.ToLower())) : false)).OrderByDescending(e => e.CreatedDate).Count();
                }
                else
                {
                    DateTime date = Convert.ToDateTime(pagingInfo.Search);
                    count = 0;
                    count = uow.CampaignRepo.GetAll().Where(e => e.CreatedDate >= date && e.CreatedDate < date.AddDays(1) || e.ScheduledDate >= date && e.ScheduledDate < date.AddDays(1)).OrderByDescending(e => e.CreatedDate).Count();

                }

            }
            else
            {
                count = uow.CampaignRepo.GetAll().Where(e => e.ClientId == ClientId).Count();
            }

            ////Sorting
            //CampaignDTOPagedList = PagingService.Sorting<CampaignDTO>(CampaignDTOPagedList, pagingInfo.SortBy, pagingInfo.Reverse);

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

                List<CampaignDTO> pagedCampaignDTOList = new List<CampaignDTO>();
                foreach (var item in CampaignDTOPagedList)
                {
                    if (item.Status == "Unsend" && item.GroupId != null)//item.IsSent == false
                    {
                        GroupContactDTO GroupDTO = new GroupContactDTO();
                        GroupDTO GroupDTOTemp = new GroupDTO();
                        GroupDTOTemp = GroupService.GetById(Convert.ToInt32(item.GroupId));
                        //GroupDTO = GroupService.GetGroupContactById(GroupDTOTemp.Id);

                        //List<ContactDTO> ContactDTOList = new List<ContactDTO>();
                        //ContactDTOList = GroupContactService.GetGroupIdWiseContacts(GroupDTOTemp.Id);

                        int CotactCount = GroupContactService.GetGroupIdWiseContactsCount(GroupDTOTemp.Id, "");

                        item.GroupName = GroupDTOTemp.Name;// GroupDTO.Name;
                        item.GroupContactCount = item.RecipientsCount;

                        if (item.RecipientsCount != CotactCount) // GroupDTO.Contacts.Count()
                        {
                            item.RecipientsCount = CotactCount;// GroupDTO.Contacts.Count();
                            item.GroupContactCount = item.RecipientsCount;
                            item.RequiredCredits = item.RecipientsCount * item.MessageCount;
                            CampaignService.Edit(item);
                        }

                        if (CotactCount == 1) //GroupDTO.Contacts.Count()
                        {
                            item.GroupContactCount = null;
                            List<ContactDTO> ContactDTOList = GroupContactService.GetGroupIdWiseContacts(GroupDTOTemp.Id).ToList();
                            item.RecipientsNumber = ContactDTOList[0].MobileNumber;// GroupDTO.Contacts[0].MobileNumber;
                            item.RecipientsCount = 1;
                        }
                    }
                    else if (item.Status == "Unsend" && item.ForAllContact == true)//item.IsSent == false
                    {
                        int CotactCount = uow.ContactRepo.GetAll().Where(e => e.ClientId == item.ClientId).Count();
                        item.GroupContactCount = CotactCount;
                        if (item.RecipientsCount != CotactCount) // GroupDTO.Contacts.Count()
                        {
                            item.GroupContactCount = CotactCount;
                            item.RecipientsCount = CotactCount;
                            item.RequiredCredits = item.RecipientsCount * item.MessageCount;
                            CampaignService.Edit(item);
                        }

                        if (CotactCount == 1) //GroupDTO.Contacts.Count()
                        {
                            item.GroupContactCount = null;
                            List<ContactDTO> ContactDTOList = ContactService.GetListByClientId(item.ClientId).ToList();
                            item.RecipientsNumber = ContactDTOList[0].MobileNumber;// GroupDTO.Contacts[0].MobileNumber;
                            item.RecipientsCount = 1;
                        }

                    }

                    pagedCampaignDTOList.Add(item);
                }
                pageList.Data = pagedCampaignDTOList;
            }
            else
            {
                pageList.Data = null;
            }

            return pageList;
        }
        public static CampaignDTO GetById(int Id)
        {
            try
            {
                UnitOfWork uow = new UnitOfWork();
                Campaign Campaign = uow.CampaignRepo.GetById(Id);
                CampaignDTO CampaignDTO = Transform.CampaignToDTO(Campaign);

                //TemplateDTO TemplateDTO = new TemplateDTO();
                CampaignDTO.TemplateDTO = TemplateService.GetTemplateByMessage(CampaignDTO.Message);

                //List<GroupDTO> GroupDTOList = new List<GroupDTO>();
                //GroupDTOList = CommonService.GetGroupList(CampaignDTO.Groups);
                //CampaignDTO.GroupDTOList = GroupDTOList;
                if(CampaignDTO.Status == "Unsend")// (CampaignDTO.IsSent == false)
                {
                    if (CampaignDTO.GroupId != null || CampaignDTO.GroupId > 0)
                    {
                        //List<GroupDTO> GroupDTOList = new List<GroupDTO>();
                        GroupDTO GroupDTO = new GroupDTO();
                        //GroupDTOList = CommonService.Get(EcouponCampaignDTO.Groups);
                        GroupDTO = GroupService.GetByIdWithContactCount(Convert.ToInt32(CampaignDTO.GroupId));
                        CampaignDTO.GroupName = GroupDTO.Name;
                        CampaignDTO.GroupContactCount = GroupDTO.ContactCount;
                    }

                    if (CampaignDTO.ForAllContact == true)
                    {
                        CampaignDTO.GroupId = 0;
                        CampaignDTO.GroupContactCount = uow.ContactRepo.GetAll().Where(e => e.ClientId == CampaignDTO.ClientId).Count();
                        CampaignDTO.GroupName = "All Contacts";
                    }
                }

                if (CampaignDTO.ForAllContact == true && CampaignDTO.Status == "Sent")// CampaignDTO.IsSent == true)
                {
                    CampaignDTO.GroupId = 0;
                    CampaignDTO.GroupContactCount = CampaignDTO.RecipientsCount;
                    CampaignDTO.GroupName = "All Contacts";
                }

                if (CampaignDTO.Status == "Sent" && CampaignDTO.GroupId != null || CampaignDTO.GroupId > 0) // CampaignDTO.IsSent == true
                {
                    //List<GroupDTO> GroupDTOList = new List<GroupDTO>();
                    GroupDTO GroupDTO = new GroupDTO();
                    //GroupDTOList = CommonService.Get(EcouponCampaignDTO.Groups);
                    if (CampaignDTO.GroupId > 0)
                    {
                        GroupDTO = GroupService.GetByIdWithContactCount(Convert.ToInt32(CampaignDTO.GroupId));
                        CampaignDTO.GroupName = GroupDTO.Name;
                    }

                }

                return CampaignDTO;
            }
            catch
            {
                throw;
            }
        }
        public static List<GroupDTO> GetGroupList(string GroupIdList)
        {
            int GroupCount = 0;
            List<GroupDTO> GroupDTOList = new List<GroupDTO>();

            try
            {

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

                char[] delimiter1 = new char[] { ',', ';' };   // <-- Split on these
                // ... Use StringSplitOptions.RemoveEmptyEntries.
                string[] array2 = value1.Split(delimiter1,
                    StringSplitOptions.RemoveEmptyEntries);
                GroupCount = array2.Count();
                if (GroupCount > 0)
                {
                    foreach (string GrpId in array2)
                    {
                        int GroupId = Convert.ToInt32(GrpId);
                        GroupDTO GroupDTO = new GroupDTO();
                        GroupDTO = GroupService.GetById(GroupId);
                        GroupDTOList.Add(GroupDTO);

                    }
                }

                return GroupDTOList;

            }
            catch (Exception)
            {
                return GroupDTOList;
            }
        }
        public static void ReadEcouponEcouponCampaign()
        {
            List<EcouponCampaignDTO> EcouponCampaignDTOList = new List<EcouponCampaignDTO>();
            EcouponCampaignDTOList = EcouponCampaignService.GetEcouponCampaignNotSentList();
            if (EcouponCampaignDTOList != null)
            {
                foreach (var item in EcouponCampaignDTOList)
                {
                    try
                    {
                        EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                        EcouponCampaignDTO = item;
                        DateTime ScheduledDate = EcouponCampaignDTO.SendOn.Date;
                        DateTime Time;
                        if (EcouponCampaignDTO.ScheduleTime != "")
                        {
                            Time = Convert.ToDateTime(EcouponCampaignDTO.ScheduleTime);
                        }
                        else Time = Convert.ToDateTime("12:00 AM");

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

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

                        if (ScheduledDate <= System.DateTime.Now)
                        {
                            //SplitMobile(item.ReceipentNumber, EcouponCampaignDTO);
                            if (item.GroupId == null && item.ForAllContact == false)
                            {
                                SplitMobile(item.ReceipentNumber, EcouponCampaignDTO);
                            }
                            else
                            {

                                string RecipientsNumberList = null;
                                if (item.GroupId > 0)
                                {
                                    GroupContactDTO GroupContactDTO = new GroupContactDTO();
                                    GroupDTO GroupDTO = new GroupDTO();
                                    GroupDTO = GroupService.GetById(Convert.ToInt32(item.GroupId));
                                    //GroupContactDTO = GroupService.GetGroupContactById(Convert.ToInt32(GroupDTO.Id));

                                    List<ContactDTO> ContactDTO = new List<ContactDTO>();
                                    ContactDTO = GroupContactService.GetGroupIdWiseContacts(GroupDTO.Id);

                                    foreach (var Contactitem in ContactDTO) //GroupContactDTO.Contacts
                                    {
                                        RecipientsNumberList = Contactitem.MobileNumber + "," + RecipientsNumberList;
                                    }
                                }
                                else if(item.ForAllContact == true)
                                {
                                    RecipientsNumberList = null;
                                    RecipientsNumberList = ContactService.GetAllReceipentNumberByClientId(item.ClientId);
                                    RecipientsNumberList = RecipientsNumberList + ",";
                                }

                                item.ReceipentNumber = RecipientsNumberList.Remove(RecipientsNumberList.LastIndexOf(','));
                                item.RecipientsCount = CommonService.GetRecipientsCount(item.ReceipentNumber);
                                EcouponCampaignService.EditEcouponCampaignFromBackend(item);

                                EcouponCampaignDTO EcouponCampaignGrpDTO = new EcouponCampaignDTO();
                                EcouponCampaignGrpDTO = item;
                                SplitMobile(item.ReceipentNumber, EcouponCampaignGrpDTO);
                            }

                        }
                        else { }

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

                        continue;
                    }

                }
            }

            //Check Client Balance

            //Modify Client Balance
        }
예제 #15
0
 public static Group GroupToDomain(GroupDTO GroupDTO)
 {
     if (GroupDTO == null) return null;
      Mapper.CreateMap<GroupDTO, Group>();
      Mapper.CreateMap<ContactDTO, Contact>();
      Group Group = Mapper.Map<Group>(GroupDTO);
      return Group;
 }
        //Get ecoupon campaign by id
        public static EcouponCampaignDTO GetById(int Id)
        {
            try
            {
                UnitOfWork uow = new UnitOfWork();
                EcouponCampaign EcouponCampaign = uow.EcouponCampaignRepo.GetById(Id);
                EcouponCampaignDTO EcouponCampaignDTO = Transform.EcouponCampaignToDTO(EcouponCampaign);

                EcouponCampaignDTO.TemplateDTO = TemplateService.GetTemplateByMessage(EcouponCampaignDTO.Message);
                if (EcouponCampaignDTO.IsSent == false)
                {
                    if (EcouponCampaignDTO.GroupId != null || EcouponCampaignDTO.GroupId > 0)
                    {
                        //List<GroupDTO> GroupDTOList = new List<GroupDTO>();
                        GroupDTO GroupDTO = new GroupDTO();
                        //GroupDTOList = CommonService.Get(EcouponCampaignDTO.Groups);
                        GroupDTO = GroupService.GetByIdWithContactCount(Convert.ToInt32(EcouponCampaignDTO.GroupId));
                        EcouponCampaignDTO.Group = GroupDTO.Name;
                        EcouponCampaignDTO.GroupContactCount = GroupDTO.ContactCount;
                    }

                    if (EcouponCampaignDTO.ForAllContact == true)
                    {
                        EcouponCampaignDTO.GroupId = 0;
                        EcouponCampaignDTO.GroupContactCount = uow.ContactRepo.GetAll().Where(e => e.ClientId == EcouponCampaignDTO.ClientId).Count();
                        EcouponCampaignDTO.Group = "All Contacts";
                    }
                }
                else if (EcouponCampaignDTO.IsSent == true)
                {
                    if (EcouponCampaignDTO.ForAllContact == true)
                    {
                        EcouponCampaignDTO.GroupId = 0;
                        EcouponCampaignDTO.GroupContactCount = EcouponCampaignDTO.RecipientsCount;
                        EcouponCampaignDTO.Group = "All Contacts";
                    }

                    if (EcouponCampaignDTO.GroupId != null && EcouponCampaignDTO.GroupId > 0)
                    {
                        EcouponCampaignDTO.Group = GroupService.GetById(Convert.ToInt32(EcouponCampaignDTO.GroupId)).Name;
                    }
                }

                return EcouponCampaignDTO;
            }
            catch
            {
                throw;
            }
        }