public async Task<ActionResult> Create([Bind(Include = "Id,Name,Sex,PassportNumber,MyanmarICNumber,ContactNumber,Email,CountryOfVote,SubmitDate,VotingState,VotingTownship,VotingWard,VotingOtherLocation,NameMissing,BallotMissingPyithu,BallotMissingAmyotha,BallotMissingState,BallotMissingRace,CountryIssue,OtherIssue,OtherIssueReason")] ComplainForm complainForm)
        {
            if (ModelState.IsValid)
            {
                complainForm.SourceIp = Request.UserHostAddress;
                complainForm.SaveDate = DateTimeOffset.Now;

                if (string.IsNullOrWhiteSpace(complainForm.VotingOtherLocation))
                    complainForm.VotingOtherLocation = string.Empty;
                else
                    complainForm.VotingOtherLocation = complainForm.VotingOtherLocation.Trim();
                if (string.IsNullOrWhiteSpace(complainForm.OtherIssueReason))
                    complainForm.OtherIssueReason = string.Empty;
                else
                    complainForm.OtherIssueReason = complainForm.OtherIssueReason.Trim();

                _db.ComplainForms.Add(complainForm);
                _db.SaveChanges();

                try
                {
                    var cfd = new ComplainFormDetail(complainForm);
                    cfd.FillDataforKeys(_db);
                    HostingEnvironment.QueueBackgroundWorkItem(ct => SendMailAsync(cfd));                    
                }
                catch
                {
                    //Ignore
                }

                return RedirectToAction("Details", new { id = complainForm.Id });
            }
            await StoreStateInviewBag();
            return View(complainForm);
        }
        // GET: ComplainForms/Details/5
        public async Task<ActionResult> Details(int id)
        {
            if (id <= 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ComplainForm complainForm = await _db.ComplainForms.FirstOrDefaultAsync(e => e.Id == id);
            if (complainForm == null)
            {
                return HttpNotFound();
            }

            var cfd = new ComplainFormDetail(complainForm);
            cfd.FillDataforKeys(_db);            

            return View(cfd);
        }
        private async Task SendMailAsync(ComplainFormDetail cfd)
        {
            try {
                var mail = new Mail {
                    From = "*****@*****.**",
                    To = cfd.Email,
                    Subject = "ႀကိဳတင္​မဲ​ေပးခြင့္ နစ္​နာမႈမ်ားအား သက္​​ေသခံျခင္​း",
                    Body = GetBody(cfd)
                };

                var mailMsg = new MailMessage();
                mailMsg.To.Add(mail.To);
                mailMsg.From = new MailAddress(mail.From);
                mailMsg.Subject = mail.Subject;
                string Body = mail.Body;
                mailMsg.Body = Body;
                mailMsg.IsBodyHtml = false;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential
                    ("*****@*****.**", "election2015@sg");// Enter seders User name and password
                smtp.EnableSsl = true;
                await smtp.SendMailAsync(mailMsg);
            }
            catch {
                //Ignore
            }
        }
        // GET: ComplainForms/Edit/5
        //public ActionResult Edit(int id)
        //{
        //    if (id <= 0)
        //    {
        //        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        //    }
        //    ComplainForm complainForm = db.ComplainForms.Find(id);
        //    if (complainForm == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    return View(complainForm);
        //}

        //// POST: ComplainForms/Edit/5
        //// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        //// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public async Task<ActionResult> Edit([Bind(Include = "Id,Name,Sex,PassportNumber,MyanmarICNumber,ContactNumber,Email,CountryOfVote,SubmitDate,VotingState,VotingTownship,VotingWard,NameMissing,BallotMissingPyithu,BallotMissingAmyotha,BallotMissingState,BallotMissingRace,CountryIssue,OtherIssue,OtherIssueReason")] ComplainForm complainForm)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        complainForm.SourceIp = Request.UserHostAddress;
        //        complainForm.SaveDate = DateTimeOffset.Now;
        //        db.Entry(complainForm).State = EntityState.Modified;
        //        db.SaveChanges();
        //        return RedirectToAction("Index");
        //    }
        //    await StoreStateInviewBag();
        //    return View(complainForm);
        //}

        //// GET: ComplainForms/Delete/5
        //public async Task<ActionResult> Delete(int id)
        //{
        //    if (id <= 0)
        //    {
        //        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        //    }
        //    ComplainForm complainForm = db.ComplainForms.Find(id);
        //    if (complainForm == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    await StoreStateInviewBag();
        //    return View(complainForm);
        //}

        //// POST: ComplainForms/Delete/5
        //[HttpPost, ActionName("Delete")]
        //[ValidateAntiForgeryToken]
        //public ActionResult DeleteConfirmed(int id)
        //{
        //    ComplainForm complainForm = db.ComplainForms.Find(id);
        //    db.ComplainForms.Remove(complainForm);
        //    db.SaveChanges();
        //    return RedirectToAction("Index");
        //}

        public async Task<FileResult> GeneratePdf(int id)
        {
            Warning[] warnings;
            string[] streamIds;
            string mimeType;
            string encoding;
            string extension;
            string fileName = "complainform.pdf";
            var localReport = new LocalReport
            {
                DisplayName = "Complain Form",
                ReportPath = Server.MapPath("~/Reports/ComplainForm.rdlc")
            };

            // Data Source of Report Object
            ComplainForm complainForm = await _db.ComplainForms.FirstOrDefaultAsync(e => e.Id == id);
            if (complainForm == null)
            {
                //return HttpNotFound();
            }

            var cfd = new ComplainFormDetail(complainForm);
            cfd.CountryOfVotingName = GlobalData.Countries.FirstOrDefault(e => e.code == cfd.CountryOfVote).name;
            cfd.VotingStateName = _db.States.FirstOrDefault(e => e.SR_Pcode == cfd.VotingState).State_Region_Mya_ZawGyi;
            cfd.VotingTownshipName = _db.Townships.FirstOrDefault(e => e.TS_Pcode == cfd.VotingTownship).Township_Mya_ZawGyi;

            var word = _db.Wards.FirstOrDefault(e => e.Ward_Pcode == cfd.VotingWard);
            cfd.VotingWardName = word == null ? "....." : word.Word_Mya_Zawgyi;

            List<ComplainFormDetail> complainFormDetails = new List<ComplainFormDetail>();
            complainFormDetails.Add(cfd);
            var reportDataSource = new ReportDataSource("ComplainFormDS", complainFormDetails);
            localReport.DataSources.Add(reportDataSource);

            var bytes = localReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
            //Response.Buffer = true;
            //Response.Clear();
            //Response.ContentType = mimeType;
            //Response.AddHeader("content-disposition", "attachment; filename=" + fileName + "." + extension);
            //Response.BinaryWrite(bytes); // create the file
            //Response.Flush(); // send it to the client to download

            return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
        }
        private string GetBody(ComplainFormDetail cfd)
        {
            using (StreamReader sr = new StreamReader(Server.MapPath("~/Reports/emailtemplate.txt")))
            {
                string body = sr.ReadToEnd();
                sr.Close();
                body = body.Replace("{name}", cfd.FullName);
                body = body.Replace("{passport}", cfd.PassportNumber);
                body = body.Replace("{nric}", cfd.MyanmarICNumber);
                body = body.Replace("{country}", cfd.CountryOfVotingName);
                body = body.Replace("{state}", cfd.VotingStateName);
                body = body.Replace("{township}", cfd.VotingTownshipName);
                body = body.Replace("{ward}", cfd.VotingPlace);

                body = body.Replace("{NameMissing}", GetCheckMark(cfd.NameMissing));
                body = body.Replace("{BallotMissingPyithu}", GetCheckMark(cfd.BallotMissingPyithu));
                body = body.Replace("{BallotMissingAmyotha}", GetCheckMark(cfd.BallotMissingAmyotha));
                body = body.Replace("{BallotMissingState}", GetCheckMark(cfd.BallotMissingState));
                body = body.Replace("{BallotMissingRace}", GetCheckMark(cfd.BallotMissingRace));
                body = body.Replace("{CountryIssue}", GetCheckMark(cfd.CountryIssue));
                body = body.Replace("{OtherIssue}", GetCheckMark(cfd.OtherIssue));

                body = body.Replace("{reason}", cfd.OtherIssueReason);
                body = body.Replace("{phone}", cfd.ContactNumber);

                var submitDate = ".....";
                if (cfd.SubmitDate != null)
                    submitDate = cfd.SubmitDate.Value.ToString("dd/MMM/yyyy");
                body = body.Replace("{date}", submitDate);

                return body;
            }
        }