protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         if (Request.QueryString["appId"] != null && Request.QueryString["appId"].IsNumeric())
         {
             lblJobApplicationId.Text = Request.QueryString["appId"];
             var jobApplication = new JobApplications().GetJobApplication(Convert.ToInt32(Request.QueryString["appId"]));
             if (jobApplication != null)
             {
                 lblKillerQuestionScore.Text = jobApplication.KqScore.ToString(CultureInfo.InvariantCulture);
             }
             LoadKillerQuestions(Convert.ToInt32(lblJobApplicationId.Text));
         }
     }
 }
    // ReSharper disable once FunctionComplexityOverflow
    void Save()
    {
        var objContact = new Candidate
        {
            CandidateId = int.Parse(lblContactId.Text),
            Title = ddlTitle.SelectedValue,
            Forename = txtForename.Text,
            Surname = txtSurname.Text,
            ClientId = int.Parse(txtSelectedCompanyID.Text),
            Employer = txtCompany.Text,
            JobTitle = txtJobTitle.Text,
            Email = txtEmail.Text,
            HomePhone = txtHomePhone.Text,
            WorkPhone = txtWorkPhone.Text,
            Mobile = txtMobile.Text,
            Website = txtWebsite.Text,
            Source = new Source { SourceId = int.Parse(ddlSource.SelectedValue) },
            SourceOther = txtSourceOther.Text,
            LinkedIn = txtLinkedIn.Text,
            Newsletter = rbtnNewsLetterYes.Checked,
            DoNotEmail = rbtnDonotemailYes.Checked,
            MinSalary = int.Parse(ddlMinSalary.SelectedValue),
            MaxSalary = int.Parse(ddlMaxSalary.SelectedValue),
            VacancyType = ddlVacancyType.SelectedValue,
            Hours = ddlHours.SelectedValue,
            PersonalSummary = txtPersonalSummary.Text,
            Location = new Location { LocationId = Convert.ToInt32(txtSelectedLocationID.Text) },
            SectorIds = String.Join(",", chbListSectors.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value)),
            LastUpdatedBy = LoginUser.GetLoggedInUserId()
        };

        //create job applicaiton object 
        var jobApplication = new JobApplication
        {
            JobApplicationId = -1,
            Candidate = objContact,
            ApplicationStatusId = Convert.ToInt32(ddlApplicationStatus.SelectedValue),
            JobId = Convert.ToInt32(lblJobId.Text),
            UpdatedBy = Convert.ToInt32(lblUserID.Text),
            ApplicationDate = DateTime.Now,
            ContactId = objContact.CandidateId,
            SendConfirmationEmail = rbtnSendEmailYes.Checked,
            UrlReferrer = "http://doris.resonatesearch.co.uk"
        };
        int candidateId;
        int jobApplicationId;
        var response = new JobApplications().AddUpdateJobApplication(jobApplication);
        if (response != null && response.ContactId > 0 && response.JobApplicationId > 0)
        {
            candidateId = response.ContactId;
            jobApplicationId = response.JobApplicationId;
        }
        else
        {
            ulErrors.Controls.Add(new LiteralControl("<li>Error saving the application.</li>"));
            divErrors.Visible = true;
            divSuccess.Visible = false;
            return;
        }

        // upload documents
        var docList = new List<Document>();
        if (FileUploadProfileImage.HasFile)
            docList.Add(new Document { FileName = FileUploadProfileImage.FileName, PostedFile = FileUploadProfileImage.PostedFile, DocumentTypeValue = 3, UploadedBy = Convert.ToInt32(lblUserID.Text) });
        if (FileUploadCv.HasFile)
            docList.Add(new Document { FileName = FileUploadCv.FileName, PostedFile = FileUploadCv.PostedFile, DocumentTypeValue = 4, SubRefId = Convert.ToInt32(lblJobId.Text), UploadedBy = Convert.ToInt32(lblUserID.Text) });
        else
        {
            // get the current cv
            var cvs = Documents.GetDocumentByDocType(new[] { 4 }, candidateId).ToList();
            if (cvs.Count > 0)
            {
                var latestCv = cvs[0];
                docList.Add(new Document { FileName = latestCv.FileName, UploadUrl = latestCv.DownloadUrl, DocumentTypeValue = 4, SubRefId = Convert.ToInt32(lblJobId.Text), UploadedBy = Convert.ToInt32(lblUserID.Text) });
            }
        }
        if (FileUploadCoverLetter.HasFile)
            docList.Add(new Document { FileName = FileUploadCoverLetter.FileName, PostedFile = FileUploadCoverLetter.PostedFile, DocumentTypeValue = 5, SubRefId = Convert.ToInt32(lblJobId.Text), UploadedBy = Convert.ToInt32(lblUserID.Text) });

        if (FileUploadRef.HasFile)
            docList.Add(new Document { FileName = FileUploadRef.FileName, PostedFile = FileUploadRef.PostedFile, DocumentTypeValue = 6, UploadedBy = Convert.ToInt32(lblUserID.Text) });
        //set the ref id and guid
        docList.ForEach(t => { t.DocGuid = Guid.NewGuid().ToString(); t.RefId = candidateId; });
        new Documents().SaveDocuments(docList);
        //save killer questions
        SaveKillerQuestion(jobApplicationId);


        //load
        //  LoadContact(contactId);
    }
 private bool CheckForExistingApplication()
 {
     var isExists = new JobApplications().CheckForExistingApplication(Convert.ToInt32(lblJobId.Text),
                Convert.ToInt32(lblContactId.Text));
     if (isExists)
     {
         ulErrors.Controls.Add(new LiteralControl("<li>Candidate has already applied for this job.</li>"));
         divErrors.Visible = true;
         return true;
     }
     return false;
 }
        /// <summary>
        /// This function calculates the killer question score of all the applcations for the job
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>
        public bool CalculateKillerQuestionScoreForJob(int jobId)
        {
            var context = new dbDataContext();
            // get the applicatios for killerQuestion
            var applications = new JobApplications().GetJobApplications(new JobApplicationFilter { JobId = jobId, NeedCandidateDetails = false, NeedApplicationStatus = false }).ToList();

            // calculate killer question score for each application
            applications.ForEach(t =>
            {
                var jobApp = context.tbl_JobApplications.FirstOrDefault(k => k.JobApplicationId == t.JobApplicationId);
                if (jobApp == null) return;
                var score = new JobApplications().CalculateKillerQuestionScoreForApplication(t.JobApplicationId);
                jobApp.KqScore = score;
            });
            context.SubmitChanges();
            return true;
        }
 private void SaveKillerQuestions(int jobApplicationId)
 {
     var questions = new List<KillerQuestion>();
     foreach (RepeaterItem item in rptKillerQuestions.Items)
     {
         var lblQuestionid = item.FindControl("lblQuestionId") as Label;
         if (lblQuestionid != null)
         {
             var questionId = Convert.ToInt32(lblQuestionid.Text);
             var question = new KillerQuestions().GetKillerQuestion(questionId);
             if (question != null)
             {
                 question.CandidateAnswers = new List<KillerQuestionCandidateAnswer>();
                 if (question.Answers == null || question.Answers.Count == 0)
                 {
                     //open question  - show text box 
                     var txtOpenQuestion = item.FindControl("txtOpenQuestion") as TextBox;
                     if (txtOpenQuestion != null)
                     {
                         var answer = new KillerQuestionCandidateAnswer
                         {
                             OpenQuestionAnswer = txtOpenQuestion.Text,
                             JobApplicationId = jobApplicationId
                         };
                         var txtScore = item.FindControl("txtScore") as TextBox;
                         int score;
                         if (txtScore != null && !question.ExcludeFromScoring && int.TryParse(txtScore.Text, out score))
                         {
                             answer.AdditionalScore = score;
                         }
                         question.CandidateAnswers.Add(answer);
                     }
                 }
                 else
                 {
                     if (question.SingleChoice)
                     {
                         // single choice - radio buttons 
                         var rbtLstKillerQuestion = item.FindControl("rbtLstKillerQuestion") as RadioButtonList;
                         if (rbtLstKillerQuestion != null)
                         {
                             var ans = rbtLstKillerQuestion.SelectedItem.Value;
                             question.CandidateAnswers.Add(new KillerQuestionCandidateAnswer
                             {
                                 AnswerId = Convert.ToInt32(ans),
                                 JobApplicationId = jobApplicationId
                             });
                         }
                     }
                     else
                     {
                         //multiple choice - check boxes 
                         var chkMultichoice = item.FindControl("chkMultichoice") as CheckBoxList;
                         if (chkMultichoice != null)
                         {
                             var answers = chkMultichoice.Items.Cast<ListItem>()
                                 .Where(li => li.Selected)
                                 .Select(t => new KillerQuestionCandidateAnswer
                                 {
                                     AnswerId = Convert.ToInt32(t.Value),
                                     JobApplicationId = jobApplicationId
                                 });
                             question.CandidateAnswers.AddRange(answers);
                         }
                     }
                 }
             }
             questions.Add(question);
         }
     }
     //save the answers and calculate the score
     var kqFinalScore = new JobApplications().SaveKillerQuestionAnswersForJob(jobApplicationId, questions);
     lblKillerQuestionScore.Text = kqFinalScore.ToString(CultureInfo.InvariantCulture);
 }