public JsonResult DestroyCampaign([DataSourceRequest] DataSourceRequest request, CampaignViewModel campaign)
        {
            var deletedCampaign = this.campaigns.DestroyCampaign(campaign);

            var loggedUserId = this.User.Identity.GetUserId();
            Base.CreateActivity(ActivityType.Delete, deletedCampaign.Id.ToString(), ActivityTargetType.Campaign, loggedUserId);

            return Json(new[] { campaign }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult CreateCampaign([DataSourceRequest]  DataSourceRequest request, CampaignViewModel campaign)
        {
            if (!ModelState.IsValid)
            {
                return Json(new[] { campaign }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
            }

            var model = this.campaigns.CreateCampaign(campaign);

            var loggedUserId = this.User.Identity.GetUserId();
            Base.CreateActivity(ActivityType.Create, model.Id.ToString(), ActivityTargetType.Campaign, loggedUserId);

            return Json(new[] { campaign }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
        }
Esempio n. 3
0
        public ActionResult CampaignList()
        {
            CustomerInfoViewModel custInfoVM = new CustomerInfoViewModel();

            if (TempData["CustomerInfo"] != null)
            {
                custInfoVM = (CustomerInfoViewModel)TempData["CustomerInfo"];
                TempData["CustomerInfo"] = custInfoVM; // Keep for change Tab
            }
            else
            {
                return(RedirectToAction("Search", "Customer"));
            }

            Logger.Info(_logMsg.Clear().SetPrefixMsg("Search Campaign").Add("CardNo", custInfoVM.CardNo.MaskCardNo()).ToInputLogString());

            _auditLog              = new AuditLogEntity();
            _auditLog.Module       = Constants.Module.Customer;
            _auditLog.Action       = Constants.AuditAction.RecommendedCampaign;
            _auditLog.IpAddress    = ApplicationHelpers.GetClientIP();
            _auditLog.Status       = LogStatus.Success;
            _auditLog.CreateUserId = this.UserInfo.UserId;

            try
            {
                if (ModelState.IsValid)
                {
                    _campaignFacade = new CampaignFacade();
                    CampaignViewModel campaignVM = new CampaignViewModel();

                    if (!string.IsNullOrWhiteSpace(custInfoVM.CardNo))
                    {
                        campaignVM.CampaignList = _campaignFacade.GetCampaignListByCustomer(_auditLog, custInfoVM.CardNo,
                                                                                            Constants.CMTParamConfig.NoOffered, Constants.CMTParamConfig.NoInterested,
                                                                                            Constants.CMTParamConfig.RecommendCampaign, Constants.CMTParamConfig.NumRecommendCampaign);
                    }

                    Logger.Info(_logMsg.Clear().SetPrefixMsg("Search Campaign").ToSuccessLogString());
                    return(PartialView("~/Views/Campaign/_CampaignList.cshtml", campaignVM));
                }

                return(Json(new
                {
                    Valid = false,
                    Error = string.Empty,
                    Errors = GetModelValidationErrors()
                }));
            }
            catch (CustomException cex)
            {
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Search Campaign").Add("Error Message", cex.Message).ToFailLogString());
                return(Json(new
                {
                    Valid = false,
                    Error = cex.Message
                }));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Search Campaign").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
Esempio n. 4
0
 public ActionResult CreateCampaign(CampaignViewModel model)
 {
     return(View());
 }
Esempio n. 5
0
 /// <summary>
 /// Update Campaign
 /// </summary>
 /// <param name="record"></param>
 /// <returns></returns>
 public async Task UpdateCampaign(CampaignViewModel record)
 {
     await campaignRepository.Update(Mapper.Map <Campaign>(record));
 }
Esempio n. 6
0
 public IActionResult New(CampaignViewModel model)
 {
     return(View());
 }
Esempio n. 7
0
        public ActionResult Id(int id)
        {
            CampaignViewModel viewModel = GetCampaignViewModel(id);

            return(View(viewModel));
        }
        public ActionResult Create(CandidateDTO paramCandidateDTO, HttpPostedFileBase CandidateImage)
        {
            if (paramCandidateDTO == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            // get the campaign ID by camparing the name from the list which was selected
            var               CampId       = "";
            CandidateDTO      candidateDTO = new CandidateDTO();
            CampaignViewModel camVM        = new CampaignViewModel();
            // get all the campaigns in the list with thier ids
            var camp = candidateDTO.Campaigns;

            camp = camVM.GetAllCampaignNamesAndID();

            foreach (var item in camp)
            {
                if (item.Description == paramCandidateDTO.CampaignID)
                {
                    CampId = item.CampaignID;
                }
            }
            //var Name = paramCandidateDTO.UserPic;
            var UserName   = paramCandidateDTO.FirstName.Trim();
            var Surname    = paramCandidateDTO.Surname.Trim();
            var Gender     = paramCandidateDTO.Gender;
            var Country    = paramCandidateDTO.Country.Trim();
            var City       = paramCandidateDTO.City.Trim();
            var DOB        = paramCandidateDTO.DOB.Trim();
            var CampaignID = CampId;

            // get the country of the from Campaign table,  check the country matches the candidate country
            // enter the details to the database else redirect the user to an message Page.
            var CampCountry         = "";
            CampaignViewModel cmVM  = new CampaignViewModel();
            CampaignDTO       cmDTO = new CampaignDTO();

            cmDTO       = cmVM.GetCampaignById(CampaignID);
            CampCountry = cmDTO.Country;
            CampCountry = CampCountry.Trim();

            if (Country != CampCountry)
            {
                return(View("Error"));
            }
            else
            {
                // no check if the same candidate is already registerd in the same campaing twice
                try
                {
                    //byte CandidatePic = paramCandidateDTO.CandidatePic;
                    if (CandidateImage != null)
                    {
                        // To convert the user uploaded Photo as Byte Array before save to DB
                        paramCandidateDTO.CandidatePic = new byte[CandidateImage.ContentLength];
                        CandidateImage.InputStream.Read(paramCandidateDTO.CandidatePic, 0, CandidateImage.ContentLength);
                    }

                    using (sqlconn)
                    {
                        using (SqlCommand cmd = new SqlCommand("InsertIntoCandidatesTable", sqlconn))
                        {
                            cmd.CommandType = System.Data.CommandType.StoredProcedure;


                            cmd.Parameters.AddWithValue("@UserName", UserName);
                            cmd.Parameters.AddWithValue("@Surname", Surname);
                            cmd.Parameters.AddWithValue("@Gender", Gender);
                            cmd.Parameters.AddWithValue("@Country", Country);
                            cmd.Parameters.AddWithValue("@City", City);
                            cmd.Parameters.AddWithValue("@DOB", DOB);
                            cmd.Parameters.AddWithValue("@CandidatePic", paramCandidateDTO.CandidatePic);
                            cmd.Parameters.AddWithValue("@CampaignID", CampaignID);

                            sqlconn.Open();
                            cmd.ExecuteNonQuery();
                            sqlconn.Close();
                        }
                    }
                    //roleManager.Create(new IdentityRole(UserName));
                    //return Redirect("~/Candidate/AddCandidate");


                    return(Redirect("~/Candidate/Create"));
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, "Error: " + ex);
                    return(View("Create"));
                }
            }
        }
Esempio n. 9
0
        // GET: Campaign/Create
        public ActionResult Create()
        {
            var model = new CampaignViewModel();

            return(View(model));
        }
Esempio n. 10
0
 private void SendTestEmail(CampaignViewModel model, string apiKey)
 {
     EmailHelper.SendViaSmtpWithRetry(model.Campaign, model.SendTestEmail.Split(',', ';'), _smtpUser, _smtpPass);
 }
Esempio n. 11
0
        // GET: Vote
        public ActionResult Index()
        {

            CandidatesViewModel candidateVM = new CandidatesViewModel();
            List<CandidateDTO> candidates = candidateVM.GetAllCandidates(); // all the candidate list that in the system 

            List<CandidateDTO> getCandidateListToView = new List<CandidateDTO>();

            CampaignViewModel cVM = new CampaignViewModel();
            List<CampaignDTO> campaign = cVM.GetAllCampaigns();
            bool empty = !campaign.Any(); // check if the campaign list is not empty 

            string currentData = "";

            string date = DateTime.Now.ToString("dd/MM/yyyy ");
            string time = DateTime.Now.ToString("hh:mm:ss");

            currentData = Convert.ToDateTime(date + time).ToString("dd/MM/yyyy HH:mm:ss");

            List<string> uniqueCampID = new List<string>(); // get the unique ID fro each campaign
            string getID = "";


            bool found = false;
            bool timeOK = false;
            if (empty != true)
            {
                foreach (var camp in campaign)
                {
                    if (DateTime.Parse(currentData) <= camp.EndDate)
                    {
                        timeOK = true;
                    }
                    else
                    {
                        timeOK = false;
                    }
                    if (timeOK == true)
                    {
                        foreach (var can in candidates)
                        {
                            if (can.CampaignID == camp.CampaignID)
                            {
                                found = true;
                            }
                            if (found == true)
                            {
                                if (!getID.Contains(can.CandidateId))
                                    getID += can.CandidateId + ",";
                            }
                            found = false;
                        }
                    }

                }
                getID = getID.TrimEnd(',', ' '); 
                var canIdsArray = getID.Split(','); // unique candidate Ids are extracted from the campaigns that are runing currently 
                
                bool isInList = false;
                for (int i = 0; i < canIdsArray.Length; i++)
                {
                    foreach (var can in candidates)
                    {
                        if (canIdsArray[i] == can.CandidateId)
                        {
                            CandidateDTO candidate = new CandidateDTO
                            {
                                CandidateId = can.CandidateId,
                                FirstName = can.FirstName,
                                Surname = can.Surname,
                                Gender = can.Gender,
                                Country = can.Country,
                                City = can.City,
                                DOB = can.DOB,
                                CandidatePic = can.CandidatePic,
                                CampaignID = can.CampaignID
                            };
                            getCandidateListToView.Add(candidate);
                            isInList = true; 
                        }
                    }
                }
                if (isInList == true) // if even one campaign found in the system return list/a candidate to the view 
                {
                    return View(getCandidateListToView);
                }
                else // if no campaigns are found in the system means there are no campaigns in the system yet
                {
                    return View("NoCampaigns"); 
                }
            }
            else
            {
                return View("NoCandidatesInSystem"); // if there are no campaigns in the system redirect the user to this page 
            }

            // this is just for the DEMO day 
            //return View(candidates);
        }
 public async Task Update([FromBody] CampaignViewModel model)
 {
     await campaignService.UpdateCampaign(model);
 }
        public async Task <IActionResult> Edit(CampaignViewModel model)
        {
            ViewBag.AsteriskActions = await _context.AsteriskExtensions.Where(x => !x.Disabled).Select(x => new AsteriskExtensionViewModel
            {
                Extension = x.Extension,
                Title     = x.Title
            }).ToArrayAsync();

            if (!model.Id.HasValue)
            {
                if (model.AbonentsFile == null)
                {
                    ModelState.AddModelError(nameof(model.AbonentsFile), "Для запуска обзвона необходим файл списка абонентов");
                }

                if (model.VoiceFile == null)
                {
                    ModelState.AddModelError(nameof(model.VoiceFile), "Для запуска обзвона необходима запись голосового сообщения");
                }

                if (model.Schedules == null || model.Schedules.Count() == 0)
                {
                    ModelState.AddModelError(nameof(model.Schedules), "Для запуска обзвона необходимо добавить расписание");
                }

                if (model.Retries < 1)
                {
                    ModelState.AddModelError(nameof(model.Retries), "Не указано количество попыток дозвона");
                }
            }

            if (!ModelState.IsValid)
            {
                ViewBag.Error = "Не удалось сохранить форму, проверьте, заполнены ли все поля";
                _logger.LogWarning($"Campaign form validation error. Total errors: {ModelState.ErrorCount}, errors: [{string.Join(",", ModelState.Select(x => $"{x.Key}:{x.Value.ValidationState}"))}], model: [{JsonConvert.SerializeObject(model)}]");
                return(View(model));
            }

            try
            {
                var entity = await GetOrCreateEntity(model.Id);

                entity.Name       = model.Name;
                entity.Modified   = DateTime.Now;
                entity.ModifierId = _currentUserId ?? 0;
                entity.Extension  = model.Action;
                entity.Retries    = model.Retries;

                if (model.LineLimit > 500)
                {
                    model.LineLimit = 500;
                }
                if (model.LineLimit < 1)
                {
                    var lineLimit = _configuration.GetValue <int>("Asterisk:LinesLimit");
                    if (lineLimit < 1)
                    {
                        lineLimit = 6;
                    }
                    model.LineLimit = lineLimit;
                }

                entity.LineLimit = model.LineLimit;

                if (!model.Id.HasValue)
                {
                    await _context.SaveChangesAsync();

                    model.Id = entity.Id;
                }

                var schedules = await _context.CampaignSchedules.Where(x => x.CampaignId == entity.Id).ToArrayAsync();

                var toRemove = schedules.Where(x => !model.Schedules.Any(s => s.Id == x.Id));
                if (toRemove.Any())
                {
                    foreach (var schedule in toRemove)
                    {
                        _context.RemoveRange(toRemove);
                    }
                }

                foreach (var schedule in model.Schedules)
                {
                    var scEntity = schedules.FirstOrDefault(x => x.Id == schedule.Id);
                    if (scEntity == null)
                    {
                        scEntity = new CampaignSchedule
                        {
                            CampaignId = entity.Id
                        };
                        _context.CampaignSchedules.Add(scEntity);
                    }

                    scEntity.ModifierId = _currentUserId.Value;
                    scEntity.DateStart  = schedule.DateStart;
                    scEntity.DateEnd    = schedule.DateEnd;
                    scEntity.DaysOfWeek = schedule.DaysOfWeek;
                    scEntity.TimeStart  = TimeFromString(schedule.TimeStart);
                    scEntity.TimeEnd    = TimeFromString(schedule.TimeEnd);
                }

                if (model.AbonentsFile != null)
                {
                    await SaveFile(model.AbonentsFile, FileType.Abonents.ToFileName(entity.Id));

                    entity.AbonentsCount = await _abonentsFileService.ProcessFileAsync(Path.Combine(_uploadsDir, $"{entity.Id}_abonents"), entity.Id);

                    entity.AbonentsFileName = model.AbonentsFile.FileName;
                }

                if (model.VoiceFile != null)
                {
                    var voiceFileName = FileType.Voice.ToFileName(entity.Id);
                    await SaveFile(model.VoiceFile, voiceFileName);

                    entity.VoiceFileName = model.VoiceFile.FileName;
                    if (_configuration.GetValue <bool>("Asterisk:UseSox"))
                    {
                        Convert(voiceFileName);
                    }
                    else
                    {
                        System.IO.File.Copy(Path.Combine(_uploadsDir, voiceFileName), Path.Combine(_configuration.GetValue <string>("Asterisk:Sounds"), voiceFileName) + Path.GetExtension(model.VoiceFile.FileName));
                    }
                }

                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Could not save Campaign");
                ViewBag.Error = ex.Message;
                return(View(model));
            }

            return(RedirectToAction(nameof(Index)));
        }
Esempio n. 14
0
 public async void AddCampaign(CampaignViewModel campaignViewModel)
 {
     await _dataAccess.AddCampaign(campaignViewModel);
 }
Esempio n. 15
0
 public Campaigns()
 {
     NavigationPage.SetBackButtonTitle(this, "");
     InitializeComponent();
     BindingContext = _campaignViewModel = new CampaignViewModel(Navigation);
 }
Esempio n. 16
0
        public CampaignViewModel GetCampaign(int campaignId)
        {
            CampaignViewModel campaign = Campaign_repo.SelectCampaign(campaignId);

            return(campaign);
        }
Esempio n. 17
0
        public void SetEventsToEmptyListOfEventViewModel_WhenCampaignsEventsIsNull()
        {
            var sut = new CampaignViewModel(new Campaign());

            Assert.Empty(sut.Events);
        }
Esempio n. 18
0
        public ActionResult Index()
        {
            CampaignViewModel viewModel = GetCampaignViewModel();

            return(View(viewModel));
        }
Esempio n. 19
0
        public void ReturnImmediately_WhenConstructingWithNullCampaign()
        {
            var sut = new CampaignViewModel((Campaign)null);

            Assert.Equal(0, sut.Id);
        }
        public JsonResult UpdateCampaign([DataSourceRequest] DataSourceRequest request, CampaignViewModel campaign)
        {
            var updatedCompaign = this.campaigns.UpdateCampaign(campaign);

            var loggedUserId = this.User.Identity.GetUserId();
            Base.CreateActivity(ActivityType.Edit, updatedCompaign.Id.ToString(), ActivityTargetType.Campaign, loggedUserId);

            return Json((new[] { campaign }.ToDataSourceResult(request, ModelState)), JsonRequestBehavior.AllowGet);
        }
Esempio n. 21
0
        public void SetHasPrivacyPolicyToFalse_WhenCampaignsManagingOrganizationIsNull()
        {
            var sut = new CampaignViewModel(new Campaign());

            Assert.False(sut.HasPrivacyPolicy);
        }
Esempio n. 22
0
        public void SetPrivacyPolicyUrlToNull_WhenCampaignsManagingOrganizationIsNull()
        {
            var sut = new CampaignViewModel(new Campaign());

            Assert.Null(sut.PrivacyPolicyUrl);
        }
Esempio n. 23
0
        public void InitializeEventsPropertyToEmptyList_WhenCallingDefaultConstructor()
        {
            var sut = new CampaignViewModel();

            Assert.NotNull(sut.Events);
        }
Esempio n. 24
0
        public IActionResult Index()
        {
            CampaignViewModel model = _campaignService.GetCampaigns();

            return(View(model));
        }
Esempio n. 25
0
        public void SetHasPrivacyPolicyUrlToFalse_WhenPrivacyPolicyUrlIsNullOrEmpty()
        {
            var sut = new CampaignViewModel();

            Assert.False(sut.HasPrivacyPolicyUrl);
        }
Esempio n. 26
0
 public CampaignViewModel Put(CampaignViewModel campaign)
 {
     CampaignService.SetUser(User);
     return(CampaignService.UpdateCampaign(campaign));
 }
Esempio n. 27
0
        public void SetHasHeadlineToFalse_WhenHeadlineIsNullOrEmpty()
        {
            var sut = new CampaignViewModel();

            Assert.False(sut.HasHeadline);
        }
Esempio n. 28
0
        public ActionResult Edit(CampaignViewModel campaignVM)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Save Recommended Campaign").Add("CardNo", campaignVM.CardNo.MaskCardNo())
                        .Add("HasInterested", campaignVM.Interested).Add("FirstName", campaignVM.FirstName).Add("LastName", campaignVM.LastName)
                        .Add("PhoneNo", campaignVM.PhoneNo).ToInputLogString());

            _auditLog              = new AuditLogEntity();
            _auditLog.Module       = Constants.Module.Customer;
            _auditLog.Action       = Constants.AuditAction.RecommendedCampaign;
            _auditLog.IpAddress    = ApplicationHelpers.GetClientIP();
            _auditLog.Status       = LogStatus.Success;
            _auditLog.CreateUserId = this.UserInfo.UserId;

            try
            {
                if (ModelState.IsValid)
                {
                    _userFacade   = new UserFacade();
                    _commonFacade = new CommonFacade();

                    var searchFilter = new CampaignSearchFilter
                    {
                        CampaignId      = campaignVM.CampaignId,
                        HasOffered      = Constants.CMTParamConfig.Offered,
                        IsInterested    = campaignVM.Interested,
                        Comments        = campaignVM.Comments,
                        UpdatedBy       = this.UserInfo.Username,
                        FirstName       = campaignVM.FirstName,
                        LastName        = campaignVM.LastName,
                        PhoneNo         = campaignVM.PhoneNo,
                        Email           = campaignVM.Email,
                        CardNo          = campaignVM.CardNo,
                        ChannelName     = campaignVM.ChannelName,
                        AvailableTime   = campaignVM.AvailableTime,
                        ContractNoRefer = campaignVM.ContractNoRefer
                    };

                    int?ownerLeadId = campaignVM.OwnerLead.ToNullable <int>();
                    if (ownerLeadId != null)
                    {
                        UserEntity ownerLead = _userFacade.GetUserById(ownerLeadId.Value);
                        searchFilter.OwnerLeadCode = ownerLead.EmployeeCode;
                    }

                    _campaignFacade = new CampaignFacade();

                    if (Constants.CMTParamConfig.Interested.Equals(campaignVM.Interested))
                    {
                        Ticket resLead = _campaignFacade.CreateLead(_auditLog, searchFilter);
                        Logger.Info(_logMsg.Clear().SetPrefixMsg("Create Lead").Add("ResponseCode", resLead.ResponseCode)
                                    .Add("ResponseMessage", resLead.ResponseMessage).ToSuccessLogString());
                    }

                    UpdateCampaignFlagsResponse resCamp = _campaignFacade.SaveCampaignFlags(_auditLog, campaignVM.CardNo, searchFilter);
                    Logger.Info(_logMsg.Clear().SetPrefixMsg("Save Recommended Campaign").Add("UpdateStatus", resCamp.UpdateStatus).ToSuccessLogString());

                    // Call CMT and SLM Services
                    return(Json(new
                    {
                        Valid = true,
                        Error = string.Empty,
                    }));
                }

                return(Json(new
                {
                    Valid = false,
                    Error = string.Empty,
                    Errors = GetModelValidationErrors()
                }));
            }
            catch (CustomException cex)
            {
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Search Campaign").Add("Error Message", cex.Message).ToFailLogString());
                return(Json(new
                {
                    Valid = false,
                    Error = cex.Message
                }));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Search Campaign").Add("Error Message", ex.Message).ToFailLogString());
                return(Json(new
                {
                    Valid = false,
                    Error = ex.Message
                }));
            }
        }
Esempio n. 29
0
        public void SetManagingOrganizationIdToZero_WhenCampaignsManagingOrganizationIsNull()
        {
            var sut = new CampaignViewModel(new Campaign());

            Assert.Equal(0, sut.ManagingOrganizationId);
        }
Esempio n. 30
0
        public async Task LoadPage()
        {
            var viewModel = new CampaignViewModel(Navigation);

            BindingContext = viewModel;

            var stack = new StackLayout();

            try
            {
                viewModel.Model = await App.ApiClient.GetCampaignAsync(_campaignId);

                viewModel.DonationModel =
                    await App.ApiClient.GetOrganizationCampaignDonationsAsync(_organizationId, _campaignId);

                viewModel.CamapignUser = viewModel.Model.Organization.OrganizationAdmins.First().User;
            }
            catch (Exception ex)
            {
                var page = new ContentPage();
                page.DisplayAlert("Error", ex.Message, "OK", "Cancel");
            }

            this.Title = viewModel.Model.Title;

            var campaignView = await _createCampaignLayout(viewModel);

            stack.Children.Add(campaignView);

            var cell = new DataTemplate(typeof(UserActionCell));

            cell.SetBinding(TextCell.TextProperty, new Binding("User.FirstName")
            {
                StringFormat = "{0} Donated:"
            });
            cell.SetBinding(TextCell.DetailProperty, new Binding("Amount")
            {
                Converter = new CurrencyDisplayConverter()
            });
            cell.SetBinding(ImageCell.ImageSourceProperty, new Binding("User.Avatar")
            {
                Converter = new UserAvatarConverter()
            });

            var list = new ListView {
                ItemsSource = viewModel.DonationModel, ItemTemplate = cell
            };

            stack.Children.Add(list);

            var donateButton = new DefaultButton
            {
                Text = "DONATE"
            };

            donateButton.Clicked += async(sender, e) =>
            {
                try
                {
                    var bankAccounts = await App.ApiClient.GetBankAccountsAsync();

                    var enumerable = bankAccounts as IList <BankAccount> ?? bankAccounts.ToList();
                    if (!enumerable.Any())
                    {
                        var page = new ContentPage();
                        page.DisplayAlert("Error", "Must Link a Bank Account First", "OK", "Cancel");
                    }
                    else
                    {
                        var donateModal = new DonatePage(_organizationId, _campaignId, enumerable);
                        await Navigation.PushAsync(donateModal);
                    }
                }
                catch (Exception ex)
                {
                    var page = new ContentPage();
                    page.DisplayAlert("Error", ex.Message, "OK", "Cancel");
                }
            };
            stack.Children.Add(donateButton);

            Content = stack;
        }
Esempio n. 31
0
        public void SetManagingOrganizationLogoToEmptyString_WhenCampaignsManagingOrganizationIsNull()
        {
            var sut = new CampaignViewModel(new Campaign());

            Assert.Equal(sut.ManagingOrganizationLogo, string.Empty);
        }
        // GET: Results/ResultsChart
        public ActionResult ResultsChart()
        {
            String uId = User.Identity.GetUserId();        // get logged in users Id

            ResultsViewModel rVM = new ResultsViewModel(); // get all the user roles


            ResultsDTO results = new ResultsDTO(); //


            List <ResultsDTO> resultsDTO = rVM.GetUsersRole();

            bool found = false;

            foreach (var result in resultsDTO)
            {
                if (uId != result.UserId)
                {
                    found = true;
                }
            }
            CampaignViewModel  camVM    = new CampaignViewModel(); // get all the campaign
            List <CampaignDTO> campaign = new List <CampaignDTO>();

            campaign = camVM.GetAllCampaigns();

            ChartsViewModel   cVM         = new ChartsViewModel();
            RegisterViewModel userDetails = cVM.GetUserDetailsById(uId);  // get signed in users details

            List <string> usersCountryCampainglist = new List <string>(); // get the campaigns name from the list campaings model and add them to string list

            if (found == true)                                            // if the user exist
            {
                foreach (var cam in campaign)
                {
                    if (userDetails.Country == cam.Country)
                    {
                        if (!usersCountryCampainglist.Contains(cam.Description.ToString()))
                        {
                            usersCountryCampainglist.Add(cam.Description);
                        }
                    }
                }
            }
            //bool isEmpty = !results.Any();
            bool isEmpty = !usersCountryCampainglist.Any();

            if (!isEmpty) // check if the list is not null than add the values to the object , else redirect the user that there are no campaigns in the country
            {
                results.Campagin  = usersCountryCampainglist.First();
                results.Campaigns = usersCountryCampainglist;
                ViewBag.Campaign  = usersCountryCampainglist.First();         // get the first country for the Campaigns
                var collectedCampaign = usersCountryCampainglist.First();     // get the first country for the Campaigns
                CampaignDashBoardList(collectedCampaign);                     // default draw of the data
                return(View("~/Views/Results/ResultsChart.cshtml", results)); // return with the values to view.
            }
            else
            {
                return(View("~/Views/Results/NotFound.cshtml")); // no ca
            }
        }
        public List <string> GetAllTheDeTailsRelatedToEachCountry(string selectedCountry, string selectedCampaign)
        {
            DynamicChartsModel dM = new DynamicChartsModel();
            // get the data from the DB
            ChartsViewModel          cVM   = new ChartsViewModel();
            List <RegisterViewModel> users = cVM.GetAllUsres(); // get the users

            // get all the Campaign to count the number of Campaigns in each country
            CampaignViewModel  campVM    = new CampaignViewModel();
            List <CampaignDTO> campaigns = campVM.GetAllCampaigns();

            // get all the candidates of the system and count the total number of candidates of each country
            CandidatesViewModel candidateVM = new CandidatesViewModel();
            List <CandidateDTO> candidates  = candidateVM.GetAllCandidates();

            // get alll the Votes for each candidates of each country.
            VoteViewModel   vVM   = new VoteViewModel();
            List <VotesDTO> votes = vVM.GetAllTheVotes();

            string cand = "";

            selectedCountry  = selectedCountry.Trim();
            selectedCampaign = selectedCampaign.Trim();

            List <string> countryCampainglist = new List <string>();

            foreach (var item in campaigns)
            {
                if (!countryCampainglist.Contains(item.Country.ToString()))
                {
                    countryCampainglist.Add(item.Country);
                }
            }
            int  total_votes                    = 0;
            int  total_users                    = 0;
            bool canFound                       = false;
            var  votesForEachCandidate          = "";
            var  totalUsresForEachCampaignVoted = "";

            foreach (var country in countryCampainglist) // get the candidates related to the selected country and campaigns
            {
                if (selectedCountry == country)
                {
                    foreach (var cam in campaigns)
                    {
                        if (selectedCampaign == cam.Description)
                        {
                            foreach (var can in candidates)
                            {
                                if (can.CampaignID == cam.CampaignID)
                                {
                                    cand    += can.FirstName + ",";
                                    canFound = true;
                                    foreach (var vot in votes)
                                    {
                                        if (can.CandidateId == vot.CandidateId) // total votes for the each candidate
                                        {
                                            total_votes++;
                                        }
                                    }
                                    if (canFound == true)
                                    {
                                        votesForEachCandidate += total_votes + ",";
                                        total_votes            = 0;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            foreach (var user in users) // count total number of users related to that country
            {
                if (selectedCountry == user.Country)
                {
                    total_users++;
                }
            }

            var totalVoters = total_users.ToString();

            cand = cand.TrimEnd(',', ' ');                                   // removing the last comma from the string
            votesForEachCandidate = votesForEachCandidate.TrimEnd(',', ' '); // removing the last comma from the string
            //totalUsresForEachCampaignVoted = totalUsresForEachCampaignVoted.TrimEnd(',', ' '); // removing the last comma from the string

            var arrayCand = votesForEachCandidate.Split(',');

            for (int i = 0; i < arrayCand.Length; i++)
            {
                total_users = (total_users - Int32.Parse(arrayCand[i]));// get the possiable votes left
            }
            totalUsresForEachCampaignVoted = total_users.ToString();
            dM.Candidates = cand;
            dM.Votes      = votesForEachCandidate;


            // this is just for the testing////////////////////////////DEMO/////////////////DEMO////////////////////////DEMO/////////////
            cand = "Hamid Karzai,Abdullah Abdullah,Ashraf Ghani,Abdul Rashid Dostum,Mohammad Hanif Atmar";
            votesForEachCandidate          = "350000,2100000,2800000,840000,910000";
            totalUsresForEachCampaignVoted = "3000000";
            totalVoters = "10000000";
            //////////////////////////////////////////////DEMO/////////////////////DEMO////////////////////DEMO/////////////////////////


            List <string> data = new List <string>// return this list to the view and extract the values in the script to chart.
            {
                selectedCountry,
                selectedCampaign,
                cand,
                votesForEachCandidate,
                totalUsresForEachCampaignVoted,
                totalVoters
            };

            return(data);  // return the data to the view
        }