using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using System.IO;
using System.Configuration;
using Fab2ApprovalSystem.ViewModels;
//using Ionic.Zip;
using System.IO.Compression;
//using ReportManagement;
using Fab2ApprovalSystem.PdfGenerator;
using Dapper;

namespace Fab2ApprovalSystem.Controllers
{
    [Authorize]
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    [SessionExpireFilter]
    public class ECNController : PdfViewController
    {
        private const string ECN_PREFIX = "ECN_";
        private const string TECN_PREFIX = "TECN_";
        private const string ETECN_PREFIX = "ETECN_";

        ECN_DMO ecnDMO = new ECN_DMO();
        WorkflowDMO wfDMO = new WorkflowDMO();
        TrainingDMO trainingDMO = new TrainingDMO();

        
        //
        // GET: /ECN/
        public ActionResult Index()
        {
            return View();
            
        }

        //
        // GET: /ECN/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /ECN/Create
        public ActionResult Create()
        {
            
            
            ECN ecn = new ECN();
            try
            {
                // TODO: Add insert logic here


                ecn.OriginatorID = (int)Session[GlobalVars.SESSION_USERID];
                ecnDMO.InsertECN(ecn);
                return RedirectToAction("Edit", new { issueID = ecn.ECNNumber });
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecn.ECNNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument - ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecn.ECNNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
                throw new Exception(e.Message);

            }
        }

        //
       
        //
        // GET: /ECN/Edit/5
        public ActionResult Edit(int issueID)
        {

            int isITARCompliant = 1;
            ECN ecn = new ECN();
            //GlobalVars.DocumentType docType = GlobalVars.DocumentType.ECN;
            try
            {
                
                //ecn = ecnDMO.GetECN(issueID);
                ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);

                //if (ecn.IsTECN && ecn.IsEmergencyTECN)
                //    docType = GlobalVars.DocumentType.EECN;

                if (isITARCompliant == 0) // not ITAR Compliant
                {
                    return View("UnAuthorizedAccess");
                }
                else
                {                  

                    //if (ecn.CloseDate != null)
                    //{
                    //    return RedirectToAction("ReadOnly", new { issueID = issueID });
                    //}
                    if (ecn.Deleted)
                    {
                        return RedirectToAction("ReadOnly", new { issueID = issueID });
                    }
                    if (ecn.CurrentStep >= 1)
                    {
                        return RedirectToAction("EditApproval", new { issueID = issueID });
                    }
                    else
                    {
                        //ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);

                        if ((ecn.RecordLockIndicator && ecn.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]))
                        {
                            return RedirectToAction("ReadOnly", new { issueID = issueID });
                        }
                        else
                        {
                            ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);
                            ViewBag.Departments = ecnDMO.GetDepartments();
                            ViewBag.AffectedModules = ecnDMO.GetModules();
                            ViewBag.AffectedAreas = ecnDMO.GetECNAreas();
                            ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies();
                            ViewBag.AcknowledgementTrainingByIDs = trainingDMO.GetTrainingGroups();
                            ViewBag.Categories = ecnDMO.GetCategories();
                            ViewBag.ProductFamilies = ecnDMO.GetProductFamilies();
                            return View(ecn);
                        }
                    }
                }



            }
            catch (Exception e)
            {
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(
                    String.Format("{0}\r\nEdit ECN\r\n{1}\r\n{2}", @User?.Identity?.Name, ecn?.ECNNumber, e.InnerException), 
                    System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString });
                return View("Error");
            }
            
        }

        //
        // POST: /ECN/Edit/5
        [HttpPost]
        public void Edit(ECN ecn)
        {
            try
            {
                // TODO: Add update logic here

                ecnDMO.UpdateECN(ecn);;
            }
            catch
            {
                //return View();
            }
        }

        //public JsonResult GetTechnology(int? area)
        //{
        //    List<ECNTechnology> respIssue = ecnDMO.GetECNTechnology(area);

        //    var data = respIssue.Select(s => new SelectListItem { Value = s.TechnologyID.ToString(), Text = s.Technology });
        //    return Json(data, JsonRequestBehavior.AllowGet);
        //}


        /// <summary>
        /// 
        /// </summary>
        /// <param name="ECN"></param>
        /// <returns></returns>
        public ActionResult ReadOnly(int issueID)
        {
            int isITARCompliant = 1;
            ECN ecn = new ECN();
            try
            {
                
                ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);
                bool trainingRequired = ecn.TrainingRequired;
                if (isITARCompliant == 0) // not ITAR Compliant
                {
                    return View("UnAuthorizedAccess");
                }
                else
                {
                    GlobalVars.DocumentType docType =  (ecn.ExpirationInProgress || ecn.ExpirationProcessed || ecn.CancellationInProgress || ecn.CancellationApproved)? GlobalVars.DocumentType.TECNCancelledExpired : GlobalVars.DocumentType.ECN;
                    if (ecn.IsEmergencyTECN)
                        docType = GlobalVars.DocumentType.EECN;

                    List<ApproversListViewModel> userList = MiscDMO.GetPendingApproversListByDocument(issueID, ecn.CurrentStep, (int)docType);
                    ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; });
                    if (approver == null)
                        ViewBag.IsApprover = "false";
                    else
                        ViewBag.IsApprover = "true";


                    if ((int)Session[GlobalVars.SESSION_USERID] == ecn.OriginatorID)
                        ViewBag.IsOriginator = "true";
                    else
                        ViewBag.IsOriginator = "false";
                    int trainingId = trainingDMO.GetTrainingId(ecn.ECNNumber);
                    if(trainingId > 0)
                    {
                        bool? trainingStatus = (trainingDMO.GetTraining(trainingId)).Status;

                        ViewBag.TrainingID = trainingId;
                        ViewBag.TrainingStatus = trainingStatus;
                    }
                    
                    ViewBag.Departments = ecnDMO.GetDepartments();
                    ViewBag.AffectedModules = ecnDMO.GetModules();
                    ViewBag.AffectedAreas = ecnDMO.GetECNAreas();
                    ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies();
                    ViewBag.AcknowledgementTrainingByIDs = trainingDMO.GetTrainingGroups();
                    ViewBag.Categories = ecnDMO.GetCategories();
                    ViewBag.ProductFamilies = ecnDMO.GetProductFamilies();
                    ViewBag.ECNNumber = ecn.ECNNumber;

                    return View(ecn);
                }
            }

            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + "  " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString });
                throw new Exception(e.Message);

            }
        }
        [OutputCache(Duration = 60, VaryByCustom = "host")]
        public ActionResult ECNTrainingView(int issueID)
        {
            int isITARCompliant = 1;
            ECN ecn = new ECN();
            try
            {

                ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);
                //bool trainingRequired = ecn.TrainingRequired;
                if (isITARCompliant == 0) // not ITAR Compliant
                {
                    return PartialView("UnAuthorizedAccess");
                }
                else
                {
                    ViewBag.Departments = ecnDMO.GetDepartments();
                    ViewBag.AffectedModules = ecnDMO.GetModules();
                    ViewBag.AffectedAreas = ecnDMO.GetECNAreas();
                    ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies();
                    ViewBag.AcknowledgementTrainingByIDs = ecnDMO.GetECNAcknowledgementTrainingBy();
                    ViewBag.Categories = ecnDMO.GetCategories();
                    ViewBag.ProductFamilies = ecnDMO.GetProductFamilies();
                    ViewBag.ECNNumber = ecn.ECNNumber;

                    return PartialView(ecn);
                }
            }

            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + "  " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString });
                throw new Exception(e.Message);

            }
        }
        public ActionResult Acknowledge(int issueID)
        {
            int isITARCompliant = 1;
            ECN ecn = new ECN();
            try
            {

                ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);
                if (isITARCompliant == 0) // not ITAR Compliant
                {
                    return View("UnAuthorizedAccess");
                }
                else
                {
                    GlobalVars.DocumentType docType = (ecn.ExpirationInProgress || ecn.ExpirationProcessed || ecn.CancellationInProgress || ecn.CancellationApproved) ? GlobalVars.DocumentType.TECNCancelledExpired : GlobalVars.DocumentType.ECN;
                    if (ecn.IsEmergencyTECN)
                        docType = GlobalVars.DocumentType.EECN;

                    List<ApproversListViewModel> userList = MiscDMO.GetPendingApproversListByDocument(issueID, ecn.CurrentStep, (int)docType);
                    ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; });
                    if (approver == null)
                        ViewBag.IsApprover = "false";
                    else
                        ViewBag.IsApprover = "true";


                    if ((int)Session[GlobalVars.SESSION_USERID] == ecn.OriginatorID)
                        ViewBag.IsOriginator = "true";
                    else
                        ViewBag.IsOriginator = "false";

                    ViewBag.Departments = ecnDMO.GetDepartments();
                    ViewBag.AffectedModules = ecnDMO.GetModules();
                    ViewBag.AffectedAreas = ecnDMO.GetECNAreas();
                    ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies();
                    ViewBag.AcknowledgementTrainingByIDs = ecnDMO.GetECNAcknowledgementTrainingBy();
                    ViewBag.Categories = ecnDMO.GetCategories();
                    ViewBag.ProductFamilies = ecnDMO.GetProductFamilies();

                    return View(ecn);
                }
            }

            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + "  " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString });
                throw new Exception(e.Message);

            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <returns></returns>
        public ActionResult EditApproval(int issueID)
        {
            int isITARCompliant = 1;
            ECN ecn = new ECN();
            try
            {

                ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);
                if (isITARCompliant == 0) // not ITAR Compliant
                {
                    return View("UnAuthorizedAccess");
                }
                else
                {
                    if (ecn.Deleted)
                    {
                        return RedirectToAction("ReadOnly", new { issueID = issueID });
                    }

                    GlobalVars.DocumentType docType = GlobalVars.DocumentType.ECN;
                    if (ecn.IsEmergencyTECN)
                        docType = GlobalVars.DocumentType.EECN;
                    if (ecn.ExpirationInProgress || ecn.ExpirationProcessed || ecn.CancellationInProgress || ecn.CancellationApproved)
                        docType = GlobalVars.DocumentType.TECNCancelledExpired;

                    List<ApproversListViewModel> userList = MiscDMO.GetPendingApproversListByDocument(issueID, ecn.CurrentStep, (int)docType);
                    ApproversListViewModel approver = userList.Find(delegate(ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; });
                    if (approver == null)
                        ViewBag.IsApprover = "false";
                    else
                        ViewBag.IsApprover = "true";


                    if ((int)Session[GlobalVars.SESSION_USERID] == ecn.OriginatorID)
                        ViewBag.IsOriginator = "true";
                    else
                        ViewBag.IsOriginator = "false";



                    //==============

                    //if ((ViewBag.IsApprover == "true" && ecn.CancellationInProgress)
                    //    ||
                    //    (ViewBag.IsApprover == "true" && ecn.ExpirationInProgress)
                    //    ||
                    //    (
                    //    (ViewBag.IsApprover == "true" && ecn.TECNExtensionState && ecn.CurrentStep > 2)
                    //    || (ViewBag.IsApprover == "true" && ecn.CurrentStep == 3 && ecn.ConvertedFromNumber != null)
                    //    )
                    //    ||
                    //    (ViewBag.IsApprover == "true")
                    //    ||
                    //     (ecn.CurrentStep <= 2 && ecn.CloseDate == null && !ecn.ReSubmitted && ecn.ConvertedFromNumber == null && ecn.TECNExtensionState == false)
                    //)
                    int trainingId = trainingDMO.GetTrainingId(ecn.ECNNumber);
                    if (trainingId > 0)
                    {
                        bool? trainingStatus = (trainingDMO.GetTraining(trainingId)).Status;

                        ViewBag.TrainingID = trainingId;
                        ViewBag.TrainingStatus = trainingStatus;
                    }
                    if (ViewBag.IsApprover == "true" || ViewBag.IsOriginator == "true")
                    {
                        ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);
                        if (ecn.RecordLockIndicator && ecn.RecordLockedBy == (int)Session[GlobalVars.SESSION_USERID])
                            
                        {
                            
                            ViewBag.Departments = ecnDMO.GetDepartments();
                            ViewBag.AffectedModules = ecnDMO.GetModules();
                            ViewBag.AffectedAreas = ecnDMO.GetECNAreas();
                            ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies();
                            ViewBag.AcknowledgementTrainingByIDs = trainingDMO.GetTrainingGroups();
                            ViewBag.Categories = ecnDMO.GetCategories();
                            ViewBag.ProductFamilies = ecnDMO.GetProductFamilies();

                            return View(ecn);
                        }
                        else
                        {
                            return RedirectToAction("ReadOnly", new { issueID = issueID });
                        }
                    }
                    else
                    {
                        return RedirectToAction("ReadOnly", new { issueID = issueID });
                    }

                    //if (ecn.CloseDate != null )
                    //{
                    //    return RedirectToAction("ReadOnly", new { issueID = issueID });
                    //}

                    //if (
                    //    (ecn.RecordLockIndicator && ecn.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID])
                    //    || ((ViewBag.IsApprover == "false") && (ViewBag.IsOriginator == "false"))
                    //    )
                    //{
                    //    return RedirectToAction("ReadOnly", new { issueID = issueID });
                    //}
                    //else
                    //{
                    //    ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);
                    //    ViewBag.Departments = ecnDMO.GetDepartments();
                    //    ViewBag.AffectedModules = ecnDMO.GetModules();
                    //    ViewBag.AffectedAreas = ecnDMO.GetECNAreas();
                    //    ViewBag.AffectedTechnologies = ecnDMO.GetECNTechnologies();
                    //    ViewBag.AcknowledgementTrainingByIDs = ecnDMO.GetECNAcknowledgementTrainingBy();


                    //    return View(ecn);
                    //}
                }
            }

            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }

                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + "  " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString });
                throw new Exception(e.Message);

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public ActionResult AttachSave(IEnumerable<HttpPostedFileBase> files, int ecnNumber)
        {
            // The Name of the Upload component is "files"
            if (files != null)
            {
                foreach (var file in files)
                {
                    // Some browsers send file names with full path.
                    // We are only interested in the file name.
                    var fileName = Path.GetFileName(file.FileName);

                    string ecnFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber.ToString();

                    DirectoryInfo di = new DirectoryInfo(ecnFolderPath);
                    if (!di.Exists)
                        di.Create();

                    var physicalPath = Path.Combine(ecnFolderPath, fileName);

                    file.SaveAs(physicalPath);
                    ECNAttachment attach = new ECNAttachment()
                    {
                        ECNNumber = ecnNumber,
                        FileName = fileName,
                        UserID = (int)Session[GlobalVars.SESSION_USERID],
                    };
                    if (System.IO.File.Exists(physicalPath))
                    {
                        
                        ecnDMO.InsertECNAttachment(attach);
                    }
                    else
                    {
                        throw new Exception();
                    }
                    
                }
            }
            return Content("");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="issueID"></param>
        /// <returns></returns>
        public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int ecnNumber)
        {
            return Json(ecnDMO.GetECNAttachments(ecnNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="ecnNumber"></param>
        /// <returns></returns>
         public ActionResult ApprovalLogHistory_Read([DataSourceRequest] DataSourceRequest request, int ecnNumber)
        {
            return Json(ecnDMO.GetECNApprovalLogHistory(ecnNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }


        //[AcceptVerbs(HttpVerbs.Post)]
        /// <summary>
        /// 
        /// </summary>
        /// <param name="attachmentID"></param>
        /// <param name="fileName"></param>
        [HttpPost]
        public void DeleteAttachment(int attachmentID, string fileName, int ecnNumber)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    ecnDMO.DeleteECNAttachment(attachmentID);
                    //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName);                    
                    //var physicalPath = Path.Combine(@"C:\Websites\Fab2ApprovalAttachments\ECN\" + ecnNumber.ToString(), fileName);
                    var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"ECN\" + ecnNumber.ToString(), fileName); 
                    

                    FileInfo f = new FileInfo(physicalPath);

                    if (f.Exists)
                        f.Delete();

                }
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + "  " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n DeleteAttachment ECN\r\n" + ecnNumber.ToString() + detailedException.ToString(), System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Delete Attachment " + exceptionString });
                throw new Exception(e.Message);

            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="attachment"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Attachment_Destroy([DataSourceRequest] DataSourceRequest request, Attachment attachment)
        {
            try
            {
                if (attachment != null && ModelState.IsValid)
                {
                    ecnDMO.DeleteECNAttachment(attachment.AttachmentID);

                }
            }
            catch (Exception e)
            {
                //string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + attachmentID.ToString() + "  " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                //Functions.WriteEvent(@User.Identity.Name + "\r\n AttachmentID ECN\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                //EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString });
                //throw new Exception(e.Message);

            }


            return Json(new[] { attachment }.ToDataSourceResult(request, ModelState));
        }


        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="peRequired"></param>
        public ActionResult SubmitDocument(int ecnNumber, int documentType, string ecnTypeString)
        {
            int isITARCompliant = 1;
            try
            {

                int appoverCount = ecnDMO.SubmitDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], documentType, out isITARCompliant);
                if (isITARCompliant == 0) // not ITAR Compliant
                {
                    // the content gets evaluated on the client side
                    return Content("ITAR");
                }
                else
                {

                    if (appoverCount > 0)
                    {
                        NotifyApprovers(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, documentType, ecnTypeString);
                    }
                    else
                    {
                        // automaically approve current step (Step 1) beacuase there are no approvers in step 1 and move to the next step of approval
                        Approve(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, "", documentType, ecnTypeString); // this is the Submit Level Approval

                    }


                    if (Request.IsAjaxRequest())
                    {
                        // the content gets evaluated on the client side
                        return Content("Redirect");
                    }
                    else
                        return Content("Invalid");
                }
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
                throw new Exception(e.Message);

            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="documentType"></param>
        /// <param name="ecnTypeString"></param>
        /// <param name="extensionDate"></param>
        /// <returns></returns>
        public ActionResult SubmitTECNExtension(int ecnNumber, int documentType, string ecnTypeString, DateTime extensionDate)
        {
            try
            {



                int appoverCount = ecnDMO.SubmitTECNExtensionDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], documentType, extensionDate);

                // Update the TECN Extension History
                try
                {
                    //ecnDMO.TECNExtensionLog(ecnNumber, extensionDate);
                }
                catch (Exception e)
                {
                    string detailedException = "";
                    try
                    {
                        detailedException = e.InnerException.ToString();
                    }
                    catch
                    {
                        detailedException = e.Message;
                    }
                    string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                    Functions.WriteEvent(@User.Identity.Name + "\r\n TECNExtensionLog\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                    EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "TECNExtensionLog - " + exceptionString });

                }

                if (appoverCount > 0)
                    NotifyApprovers(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, documentType, ecnTypeString);
                else
                {
                    // automaically approve current step (Step 1) beacuase there are no approvers in step 1 and move to the next step of approval
                    Approve(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, "", documentType, ecnTypeString); // this is the Submit Level Approval

                }


                if (Request.IsAjaxRequest())
                {
                    return Content("Redirect");
                }
                else
                    return Content("Invalid");
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
                throw new Exception(e.Message);

            }
        }


        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="peRequired"></param>
        public ActionResult SubmitDocument_EmergencyTECN(int ecnNumber, int documentType)
        {
            int isITARCompliant = 0;
            try
            {

                ecnDMO.SubmitDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], documentType, out isITARCompliant);

                if (isITARCompliant == 0) // not ITAR Compliant
                {
                    return View("ITAR");
                }
                else
                {

                    if (Request.IsAjaxRequest())
                    {
                        return Content("Redirect");
                    }
                    else
                        return Content("Invalid");
                }
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument ETECN\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument-ETECN - " + exceptionString });
                throw new Exception(e.Message);

            }
        }


       /// <summary>
       /// 
       /// </summary>
       /// <param name="ecnNumber"></param>
       /// <param name="currentStep"></param>
       /// <param name="comments"></param>
        public void Approve(int ecnNumber, byte currentStep, string comments, int documentType, string ecnTypeString)
        {
            try
            {
                bool lastStep = false;
                ECN ecn = ecnDMO.GetECN(ecnNumber);
                bool lastApprover = wfDMO.Approve(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType, ecn.WorkFlowNumber);

                
                while (lastApprover && !lastStep)
                { 
                    
                   currentStep++;
                    //Changed this next line of code to not pass the currently approving user. This prevents a user from approving multiple steps at once. An undesired function.
                   lastApprover = wfDMO.Approve(ecnNumber, currentStep, comments, out lastStep, 11111111, documentType, ecn.WorkFlowNumber);
                   NotifyApprovers(ecnNumber, currentStep, documentType, ecnTypeString);

                }


                //#if(!DEBUG)
                // only execute at the last step of the Approval loop
                if (lastApprover && lastStep)
                {
                    NotifySubmitter(ecn.ECNNumber, ecnTypeString);
                    NotifyAdmin(ecn.ECNNumber, ecnTypeString);
                    if (ecn.TrainingRequired)
                    {
                        TrainingController NewTraining = new TrainingController();
                        NewTraining.Create(ecnNumber);
                    }
                    
                    if (ecn.IsECN && ecn.ConvertedFromNumber != null)
                    {
                        // Set the cancellation date for the TECN
                        ecnDMO.CancelECN(ecn.ConvertedFromNumber);

                        //copy the TECN to the new ECN folder
                        GenerateECNPdfDifferentLocation((int)ecn.ConvertedFromNumber, ecnNumber);
                        
                        

                    }
                    // Combine the TECN and the ECN in a zipped file for DCC task creation
                    PostApproval(ecnNumber, documentType);
                    

                    if (ecn.IsECN && ecn.ConvertedFromNumber != null)
                    {
                        ApprovalLogDMO.Add(new ApprovalLog
                        {
                            IssueID = (int)ecn.ConvertedFromNumber,
                            DocumentTypeID = documentType,
                            OperationType = "Change to " + ecnTypeString + ecnNumber.ToString() + " Approved",
                            UserID = (int)Session[GlobalVars.SESSION_USERID],
                            OperationLog = "Approval of the Document conversion"
                        });

                        List<string> attachments = new List<string>();
                        attachments.Add(Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber + "\\ECNForm_" + ecnNumber + ".pdf");
                        attachments.Add(Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber + "\\ECNForm_" + ecn.ConvertedFromNumber + ".pdf");

                        NotifyTECNAutoCancellation(ecnNumber, (int)ecn.ConvertedFromNumber, attachments);
                    }
                    
                }
//#endif

            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString });
                throw new Exception(e.Message);
            }

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        void PostApproval(int ecnNumber, int documentType)
        {
            try
            {
                ECNPdf ecn = new ECNPdf();

                // Generate the PDF version of the ECN form and Approval log
                if (GenerateECNPdf(ecnNumber, out ecn))
                {
                    // Zip up all the attached files along with the Pdf version of the ECN form and the Approval Log
                    if (CreateZip(ecn))
                    {
                        //Documentum.Process(Functions.GetAttachmentFolder() + "\\ECNZipped\\" + ecnNumber.ToString() + ".zip");

                    }
                    else
                    {
                        // TODO How to recreate and send the files to documentum
                        throw new Exception("Problems while generating the ZIP file. Please contact the system Administrator");
                    }
                }
                else
                {
                    throw new Exception("Problems while generating the PDF file. Please contact the system Administrator");
                }

                // Notify a list of people when the E-TECN is approved
                if (documentType == (int)GlobalVars.DocumentType.EECN)
                {
                    NotifyEmergencyTECNApproval(ecnNumber, ecn.ExpirationDate);
                }
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n ECN - PostApproval \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "PostApprovalForECNsDerivedFromTECN - " + exceptionString });
                throw e;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="documentType"></param>
        //void PostApprovalForECNsDerivedFromTECN(int ecnNumber, int tecnNumber)
        //{

        //    try
        //    {
        //        // Generate the PDF version of the ECN form and Approval log
        //        string sourceFile = Functions.GetAttachmentFolder() + "ECN\\" + tecnNumber + "\\ECNForm_" + tecnNumber + ".pdf";
        //        string destFile = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber + "\\ECNForm_" + tecnNumber + ".pdf";


        //        GenerateECNPdfDifferentLocation(ecnNumber, tecnNumber);




        //    }

        //    catch(Exception e)
        //    {
        //        string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
        //        Functions.WriteEvent(@User.Identity.Name + "\r\n ECN - PostApprovalForECNsDerivedFromTECN \r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
        //        EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "PostApprovalForECNsDerivedFromTECN - " + exceptionString });
        //        throw e;
        //    }



        //}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="documentType"></param>
        public void NotifySubmitter(int ecnNumber, string ecnTypeString)
        {

            try
            {
                string emailSentList = "";
                ECN ecn = ecnDMO.GetECN(ecnNumber);
                //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
                //List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList();
                int ecnCreatedById = ecn.OriginatorID;
                string ecnCreatedByEmail = MiscDMO.GetEmail(ecnCreatedById);

                string emailTemplate = "ECNApproved.txt";
                string userEmail = string.Empty;
                string subject = string.Empty;
                string senderName = ecnTypeString;

                subject = ecnTypeString + " Approval notice for Number " + ecn.ECNNumber + ", - " + ecn.Title;

                    EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                    string[] emailparams = new string[4];
                    emailparams[0] = ecnNumber.ToString();
                    emailparams[1] = ecnNumber.ToString();
                    emailparams[2] = GlobalVars.hostURL;
                    emailparams[3] = ecnTypeString;
                    userEmail = ecnCreatedByEmail;
                    //#if(DEBUG)
                    //string SenderEmail = "MesaFabApproval@infineon.com";
                    //userEmail = "jonathan.ouellette@infineon.com";
                    //#endif

                    en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
                    //en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams);
                    emailSentList = ecnCreatedByEmail;

                try
                {

                    EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " +  ":" + emailSentList });
                }
                catch { }

                //EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                //string[] emailparams = new string[4];
                //emailparams[0] = issueID.ToString();
                //emailparams[1] = issueID.ToString();
                //emailparams[2] = GlobalVars.hostURL;
                //emailparams[3] =Session[GlobalVars.SESSION_USERNAME].ToString();
                //en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams);
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString });
                throw e;

            }


        }
        public void NotifyAdmin(int ecnNumber, string ecnTypeString)
        {

            try
            {
                string emailSentList = "";
                ECN ecn = ecnDMO.GetECN(ecnNumber);
                //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
                //List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList();
                IEnumerable<int> ecnAdminIDs = MiscDMO.GetUserIDsBySubRoleID(383);
                foreach (int id in ecnAdminIDs)
                {
                    string ecnCreatedByEmail = MiscDMO.GetEmail(id);

                    string emailTemplate = "ECNApproved.txt";
                    string userEmail = string.Empty;
                    string subject = string.Empty;
                    string senderName = ecnTypeString;

                    subject = ecnTypeString + " Approval notice for Number " + ecn.ECNNumber + ", - " + ecn.Title;

                    EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                    string[] emailparams = new string[4];
                    emailparams[0] = ecnNumber.ToString();
                    emailparams[1] = ecnNumber.ToString();
                    emailparams[2] = GlobalVars.hostURL;
                    emailparams[3] = ecnTypeString;
                    userEmail = ecnCreatedByEmail;
                    //#if(DEBUG)
                    //string SenderEmail = "MesaFabApproval@infineon.com";
                    //userEmail = "jonathan.ouellette@infineon.com";
                    //#endif

                    en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
                    //en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams);
                    emailSentList = ecnCreatedByEmail;

                    try
                    {

                        EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + ":" + emailSentList });
                    }
                    catch { }

                    //EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                    //string[] emailparams = new string[4];
                    //emailparams[0] = issueID.ToString();
                    //emailparams[1] = issueID.ToString();
                    //emailparams[2] = GlobalVars.hostURL;
                    //emailparams[3] =Session[GlobalVars.SESSION_USERNAME].ToString();
                    //en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams);
                }


            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString });
                throw e;

            }


        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="currentStep"></param>
        public void NotifyApprovers(int ecnNumber, byte currentStep, int documentType, string ecnTypeString)
        {

            try
            {
                string emailSentList = "";
                ECN ecn = ecnDMO.GetECN(ecnNumber);
                //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
                List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList();

                string emailTemplate = "ECNAssigned.txt";
                string userEmail = string.Empty;
                string subject = string.Empty;
                string senderName = ecnTypeString;

                subject = ecnTypeString + " Assignment notice for Number " + ecn.ECNNumber + ", - " + ecn.Title;
                foreach (string email in emailIst)
                {
                    
                    EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                    string[] emailparams = new string[4];
                    emailparams[0] = ecnNumber.ToString();
                    emailparams[1] = ecnNumber.ToString();
                    emailparams[2] = GlobalVars.hostURL;
                    emailparams[3] = ecnTypeString;
                    userEmail = email;
                    //#if(DEBUG)
                    //string SenderEmail = "MesaFabApproval@infineon.com";
                    //userEmail = "jonathan.ouellette@infineon.com";
                    //#endif

                    en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
                    //en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams);
                    emailSentList += email + ",";
                }

                try
                {

                    EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList });
                }
                catch { }

                //EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                //string[] emailparams = new string[4];
                //emailparams[0] = issueID.ToString();
                //emailparams[1] = issueID.ToString();
                //emailparams[2] = GlobalVars.hostURL;
                //emailparams[3] =Session[GlobalVars.SESSION_USERNAME].ToString();
                //en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams);
            }
            catch ( Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);                
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString });
                throw e;

            }
            

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        //public void NotifyRejectionToOrginator(int ecnNumber, int documentType)
        //{

        //    List<string> emailIst = ecnDMO.GetRejectionOrginatorEmailList(@ecnNumber).Distinct().ToList();

        //    string emailTemplate = "ECNReject.txt";
        //    string userEmail = string.Empty;
        //    string subject = "ECN Rejection";
        //    string senderName = "ECN";

        //    foreach (string email in emailIst)
        //    {
        //        subject = "ECN Rejection";
        //        EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
        //        string[] emailparams = new string[4];
        //        emailparams[0] = ecnNumber.ToString();
        //        emailparams[1] = ecnNumber.ToString();
        //        emailparams[2] = GlobalVars.hostURL;
        //        emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString();
        //        userEmail = email;
        //        //#if(DEBUG)
        //        //    userEmail =  GlobalVars.SENDER_EMAIL;
        //        //#endif

        //        en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
        //    }

        //    try
        //    {

        //        EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Email", Comments = "Rejection: " + userEmail });
        //    }
        //    catch { }

        //}


        /// <summary>
        /// Get a list of Approvers and the status
        /// </summary>
        /// <param name="request"></param>
        /// <param name="issueID"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step, bool isTECN, bool isEmergrncyTECN)
        {
            int isITARCompliant = 0;
            ECN ecn = new ECN();
            ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);

            GlobalVars.DocumentType docType;
            // fix related to ticket #35336
            if (ecn.CancellationInProgress || ecn.CancellationApproved || ecn.ExpirationInProgress || ecn.ExpirationProcessed)
                docType = GlobalVars.DocumentType.TECNCancelledExpired;
            else
                docType = isEmergrncyTECN ? GlobalVars.DocumentType.EECN : GlobalVars.DocumentType.ECN;

            return Json(MiscDMO.GetApproversListByDocument(issueID, step,(int) docType).ToDataSourceResult(request));
        }
       
        
      


        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        public void NotifyRejectionToOrginator(int issueID, string ecnTypeString, string comments)
        {

            List<string> emailIst = ecnDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList();
            ECN ecn = ecnDMO.GetECN(issueID);

            string emailTemplate = "ECNReject.txt";
            string userEmail = string.Empty;
            string subject = ecnTypeString + " Rejection";
            string senderName = ecnTypeString;

            foreach (string email in emailIst)
            {
                subject = ecnTypeString + " Rejection notice for Number " + ecn.ECNNumber + ", - " + ecn.Title;
                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[6];
                emailparams[0] = issueID.ToString();
                emailparams[1] = issueID.ToString();
                emailparams[2] = GlobalVars.hostURL;
                emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString();
                emailparams[4] = ecnTypeString;
                emailparams[5] = comments;
                userEmail = email;
                //#if(DEBUG)
                //    userEmail =  GlobalVars.SENDER_EMAIL;
                //#endif

                en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
            }

            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail });
            }
            catch { }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="ecnTypeString"></param>
        public void NotifyTECNExtensionRejectionToOrginator(int issueID, string ecnTypeString)
        {

            List<string> emailIst = ecnDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList();
            ECN ecn = ecnDMO.GetECN(issueID);

            string emailTemplate = "TECNExtensionReject.txt";
            string userEmail = string.Empty;
            string subject = ecnTypeString + " Rejection";
            string senderName = ecnTypeString;

            foreach (string email in emailIst)
            {
                subject = ecnTypeString + " Extension Rejection notice for Number " + ecn.ECNNumber + ", - " + ecn.Title;
                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[5];
                emailparams[0] = issueID.ToString();
                emailparams[1] = issueID.ToString();
                emailparams[2] = GlobalVars.hostURL;
                emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString();
                emailparams[4] = ecnTypeString;
                userEmail = email;
                //#if(DEBUG)
                //    userEmail =  GlobalVars.SENDER_EMAIL;
                //#endif

                en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
            }

            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail });
            }
            catch { }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="currentStep"></param>
        /// <param name="comments"></param>
        public void Reject(int ecnNumber, byte currentStep, string comments, int docType, string ecnTypeString)
        {
            try
            {
                // TODO 
                // Check Rejection is for the TECN Extension

                int isITARCompliant = 0;
                ECN ecn = new ECN();
                ecn = ecnDMO.GetECNForRead(ecnNumber, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);


                if (Session[GlobalVars.SESSION_USERID] != null)
                {
                    if (ecn.TECNExtensionState)
                    {
                        wfDMO.RejectTECNExtension(ecnNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType);
                        NotifyTECNExtensionRejectionToOrginator(ecnNumber, ecnTypeString);
                    }
                    else
                    {

                        if (ecn.IsECN && ecn.ConvertedFromNumber != null)
                        {

                            ecnDMO.ECNResetTECNAtRejection(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], docType);
                        }

                        wfDMO.Reject(ecnNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType);
                        NotifyRejectionToOrginator(ecnNumber, ecnTypeString, comments);
                    }
                }
                else
                {

                    Response.Redirect("~/Account/Login");
                }
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }

                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n Reject\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Reject - " + exceptionString });
                throw new Exception(e.Message);

            }

        }
        public void RecallDocument(int ecnNumber, byte currentStep, string comments, int docType, string ecnTypeString)
        {
            try
            {
                // TODO 
                // Check Rejection is for the TECN Extension

                int isITARCompliant = 0;
                ECN ecn = new ECN();
                ecn = ecnDMO.GetECNForRead(ecnNumber, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);


                if (Session[GlobalVars.SESSION_USERID] != null)
                {
                    NotifyApproversForRecall(ecnNumber, currentStep, docType, ecnTypeString, comments);
                    wfDMO.Recall(ecnNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType);
                    
                        //NotifyRejectionToOrginator(ecnNumber, ecnTypeString, comments);
                }
                else
                {

                    Response.Redirect("~/Account/Login");
                }
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }

                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n Reject\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Reject - " + exceptionString });
                throw new Exception(e.Message);

            }
        }

        

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="reAssignApproverFrom"></param>
        /// <param name="reAssignApproverTo"></param>
        /// <param name="step"></param>
        public void ReAssignApproverByAdmin(int issueID, int reAssignApproverFrom, int reAssignApproverTo, byte step, int docType, string ecnTypeString)
        {
            var email = "";
            try
            {
                
                email = wfDMO.ReAssignApproval(issueID, reAssignApproverFrom, reAssignApproverTo, step,  docType);

            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString });
                throw new Exception(e.Message);

            }

            ECN ecn = ecnDMO.GetECN(issueID);
            string emailTemplate = "ECNReAssigned.txt";
            string userEmail = string.Empty;
            string subject;
            string senderName = ecnTypeString;

            subject = ecnTypeString + " Re-Assignment" + " - ECN #" + ecn.ECNNumber + ", - " + ecn.Title;;
            EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
            string[] emailparams = new string[4];
            emailparams[0] = issueID.ToString();
            emailparams[1] = issueID.ToString();
            emailparams[2] = GlobalVars.hostURL;
            emailparams[3] = ecnTypeString;

            userEmail = email;
            //#if(DEBUG)
            //            userEmail = "rkotian1@infineon.com";
            //#endif

            en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "ReAssign Approver: " + email });
            }
            catch { }

        }

        [HttpPost]
        public void ReAssignOriginatorByAdmin(int ecnNumber, string comments, int newOriginatorId)
        {
            if (Session[GlobalVars.IS_ADMIN] == null)
                throw new Exception("Permission denied");

            try
            {
                ecnDMO.ReassignOriginatorECN(ecnNumber, newOriginatorId, comments, (int)Session[GlobalVars.SESSION_USERID]);
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim();
                if (exceptionString.Length > 450) exceptionString = exceptionString.Substring(0, 450);
                Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignOriginatorByAdmin\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "ReAssignOriginatorByAdmin - " + exceptionString });
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="userIDs"></param>
        /// <param name="step"></param>
        /// <param name="docType"></param>
        public void ReAssignApproval(int issueID, int userIDs, byte step, int docType, string ecnTypeString)
        {
            var email = "";
            try
            {
                email = wfDMO.ReAssignApproval(issueID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, docType);

            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n ReAssignApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString });
                throw new Exception(e.Message);

            }

            ECN ecn = ecnDMO.GetECN(issueID);
            string emailTemplate = "ECNReAssigned.txt";
            string userEmail = string.Empty;
            string subject = ecnTypeString + " Re-Assignment";
            string senderName = ecnTypeString;

            subject = ecnTypeString + " Re-Assignment" + " - Email would be sent to " + email +  " for Number " + ecn.ECNNumber + ", - " + ecn.Title;;
            EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
            string[] emailparams = new string[4];
            emailparams[0] = issueID.ToString();
            emailparams[1] = issueID.ToString();
            emailparams[2] = GlobalVars.hostURL;
            emailparams[3] = ecnTypeString;
            userEmail = email;
            //#if(DEBUG)
            //            userEmail =  GlobalVars.SENDER_EMAIL;
            //#endif

            en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "ReAssign Approver: " + email });
            }
            catch { }

        }


        #region
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        //public JsonResult GetUserListForAdditionalAppprrovers()
        //{
        //    UserAccountDMO userDMO = new UserAccountDMO();
        //    IEnumerable<LoginModel> userlist = userDMO.GetAllUsers();
        //    return Json(userlist, JsonRequestBehavior.AllowGet);

        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="currentStep"></param>
        /// <returns></returns>
        public JsonResult GetAllUsersList()
        {
            //var userList = ldDMO.GetApprovedApproversList(issueID, currentStep);
            //return Json(userList, JsonRequestBehavior.AllowGet);

            UserAccountDMO userDMO = new UserAccountDMO();
            IEnumerable<LoginModel> userlist = userDMO.GetAllActiveUsers();
            return Json(userlist, JsonRequestBehavior.AllowGet);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="step"></param>
        /// <param name="userIDs"></param>
        /// <param name="docType"></param>
        public void AddAdditionalApproval(int issueID, byte step, string userIDs, int docType, string ecnTypeString)
        {
            string emailSentList = "";
            var emailArray = "";
            try
            {
                emailArray = wfDMO.AddAdditionalApproval(issueID, userIDs, step, docType);
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + issueID.ToString() + "\r\n"  + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
                throw new Exception(e.Message);
            }
            ECN ecn = ecnDMO.GetECN(issueID);

            string emailTemplate = "ECNAssigned.txt";
            string userEmail = string.Empty;
            string subject = ecnTypeString + " Assignment";
            string senderName = ecnTypeString;


            string[] emailIst = emailArray.Split(new char[] { '~' });
            foreach (string email in emailIst)
            {
                if (email.Length > 0)
                {
                    //subject = "Lot Disposition Assignment" + " - Email would be sent to " + email;
                    subject = ecnTypeString + "Assignment notice for Number " + ecn.ECNNumber + ", - " + ecn.Title;
                    EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                    string[] emailparams = new string[4];
                    emailparams[0] = issueID.ToString();
                    emailparams[1] = issueID.ToString();
                    emailparams[2] = GlobalVars.hostURL;
                    emailparams[3] = ecnTypeString;

                    userEmail = email;
                    //#if(DEBUG)
                    //    userEmail = "rkotian1@infineon.com";
                    //#endif

                    en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
                    emailSentList += email + ",";

                }

            }
            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Additonal Approver: " + emailSentList });
            }
            catch { }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        public bool GenerateECNPdf(int ecnNumber,  out ECNPdf ecn)
        {
            //DateTime? expDt;
            try
            {
                
                string outputFileName = "";

                ecn = ecnDMO.GetECNPdf(ecnNumber);
                //expDate = ecn.ExpirationDate;
                //extensionDate = ecn.ExtensionDate;

                outputFileName = ecnNumber.ToString() + ".pdf";


                string ecnFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber.ToString();
                //string ecnFolderPath = @"C:\Users\Ouellette\Desktop";
                DirectoryInfo di = new DirectoryInfo(ecnFolderPath);
                // create the folder for the ECN if it does not exist
                if (!di.Exists)
                    di.Create();

                // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This
                // requires the controller to be inherited from MyController instead of MVC's Controller.
                SavePdf(ecnFolderPath + "\\ECNForm_" + outputFileName, "ECNPdf", ecn);
                SavePdf(ecnFolderPath + "\\ECNApprovalLog_" + outputFileName, "ECNApprovalPdf", ecn);
            }
            catch (Exception ex)
            {
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Generate PDF", Comments = ex.Message });
                ecn = null;
                return false;

            }

            return true;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="?"></param>
        /// <param name="ecn"></param>
        /// <returns></returns>
        public bool GenerateECNPdfDifferentLocation(int ecnNumber, int folderName)
        {
            ECNPdf ecn = new ECNPdf();
            try
            {

                string outputFileName = "";

                ecn = ecnDMO.GetECNPdf(ecnNumber);
                //expDate = ecn.ExpirationDate;
                //extensionDate = ecn.ExtensionDate;

                outputFileName = ecnNumber.ToString() + ".pdf";


                string ecnFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + folderName.ToString();

                DirectoryInfo di = new DirectoryInfo(ecnFolderPath);
                // create the folder for the ECN if it does not exist
                if (!di.Exists)
                    di.Create();

                // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This
                // requires the controller to be inherited from MyController instead of MVC's Controller.
                SavePdf(ecnFolderPath + "\\ECNForm_" + outputFileName, "ECNPdf", ecn);
            }
            catch (Exception ex)
            {
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Generate PDF", Comments = ex.Message });
                ecn = null;
                return false;

            }

            return true;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="ecn"></param>
        /// <returns></returns>
        public ActionResult PrintECNPdf(int ecnNumber)
        {
            ECNPdf ecn;
            try
            {

                //string outputFileName = "";

                ecn = ecnDMO.GetECNPdf(ecnNumber);
                // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This
                // requires the controller to be inherited from MyController instead of MVC's Controller.
                return this.ViewPdf("", "ECNPdf", ecn);
                
            }
            catch (Exception ex)
            {
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Print PDF", Comments = ex.Message });
                ecn = null;
                return Content("");

            }

            //return true;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        public void NotifyEmergencyTECNApproval(int ecnNumber, DateTime? expDate)
        {
            string ecnFolderPath = Functions.GetAttachmentFolder() + "E-TECNZipped\\" + ETECN_PREFIX + ecnNumber.ToString() + ".zip";

            string emailSentList = "";

            List<string> emailIst = MiscDMO.GetEmergencyTECNApprovalNotifyList(ecnNumber).Distinct().ToList();

            string emailTemplate = "ETECNApproved.txt";
            string userEmail = string.Empty;
            string subject = "E-TECN Approved";
            string senderName = "E-TECN";

            ECN ecn = ecnDMO.GetECN(ecnNumber);
            subject = "E-TECN Approved notice for Number " + ecn.ECNNumber + ", - " + ecn.Title;
            EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
            string[] emailparams = new string[5];
            emailparams[0] = ecnNumber.ToString();
            emailparams[1] = ecnNumber.ToString();
            emailparams[2] = GlobalVars.hostURL;
            emailparams[3] = "E-TECN";
            emailparams[4] = expDate.ToString();

//#if(DEBUG)
//                userEmail = "rkotian1@infineon.com";
//#endif

                if (IsITAR(ecn))
                    en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams);
                else
                    en.SendNotificationEmailWithAttachment(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, ecnFolderPath, emailparams);
                
                //emailSentList += email + ",";
                emailSentList = String.Join(", ", emailIst.Distinct().ToArray()) ;
            

            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Step 1:" + emailSentList });
            }
            catch { }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="currentStep"></param>
        /// <param name="documentType"></param>
        /// <param name="ecnTypeString"></param>
        public void NotifyApproversForCancellation(int ecnNumber, byte currentStep, int documentType, string ecnTypeString)
        {
            ECN ecn = ecnDMO.GetECN(ecnNumber);
            string emailSentList = "";

            //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
            List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList();

            string emailTemplate = "TECNCancellationApproval.txt";
            string userEmail = string.Empty;
            string subject = ecnTypeString + " Cancellation Approval Required - " + ecnNumber + " for " + ecn.Title + ", Cancellation initiated on :" + ecn.CancellationDate;
            string senderName = ecnTypeString;

            foreach (string email in emailIst)
            {                
                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[4];
                emailparams[0] = ecnNumber.ToString();
                emailparams[1] = ecnNumber.ToString();
                emailparams[2] = GlobalVars.hostURL;
                emailparams[3] = ecnTypeString;
                userEmail = email;
//#if(DEBUG)
//                userEmail = "rkotian1@infineon.com";
//#endif

                en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
                emailSentList += email + ",";
            }

            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList });
            }
            catch { }

           

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="currentStep"></param>
        /// <param name="documentType"></param>
        /// <param name="ecnTypeString"></param>
        public void NotifyApproversForRecall(int ecnNumber, byte currentStep, int documentType, string ecnTypeString, string recallComments)
        {
            ECN ecn = ecnDMO.GetECN(ecnNumber);
            string emailSentList = "";

            //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
            List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList();
            emailIst.Add("Jeanne.McIntyre@infineon.com");
            emailIst.Add("Jonathan.Ouellette@infineon.com");
            string emailTemplate = "ECNRecallApproval.txt";
            string userEmail = string.Empty;
            string subject = ecnTypeString + " Recalled  - " + ecnNumber + " for " + ecn.Title + ", Recall initiated on :" + DateTime.Now.ToString();
            string senderName = ecnTypeString;

            foreach (string email in emailIst)
            {
                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[5];
                emailparams[0] = ecnNumber.ToString();
                emailparams[1] = ecnNumber.ToString();
                emailparams[2] = GlobalVars.hostURL;
                emailparams[3] = ecnTypeString;
                emailparams[4] = recallComments;
                userEmail = email;
                //#if(DEBUG)
                //                userEmail = "rkotian1@infineon.com";
                //#endif

                en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
                emailSentList += email + ",";
            }

            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList });
            }
            catch { }



        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="currentStep"></param>
        /// <param name="documentType"></param>
        /// <param name="ecnTypeString"></param>
        public void NotifyApproversForExpiration(int ecnNumber, byte currentStep, int documentType, string ecnTypeString)
        {
            ECN ecn = ecnDMO.GetECN(ecnNumber);
            string emailSentList = "";

            //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
            List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList();

            string emailTemplate = "TECNExpirationApproval.txt";
            string userEmail = string.Empty;
            string subject = " TECN Expiration Approval Reqquired - " + ecnTypeString + "# " + ecnNumber + " for " + ecn.Title + ", Expired:" + ecn.ExpirationDate;
            string senderName = ecnTypeString;

            foreach (string email in emailIst)
            {
                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[4];
                emailparams[0] = ecnNumber.ToString();
                emailparams[1] = ecnNumber.ToString();
                emailparams[2] = GlobalVars.hostURL;
                emailparams[3] = ecnTypeString;
                userEmail = email;
#if(DEBUG)
                userEmail =  GlobalVars.SENDER_EMAIL;
#endif

                en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
                emailSentList += email + ",";
            }

            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList });
            }
            catch { }



        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        public void NotifyTECNCancellation(int ecnNumber, string ecnFolderPath)
        {
            //string ecnFolderPath = Functions.GetAttachmentFolder() + "TECNCancelledZipped\\" + TECN_PREFIX + ecnNumber.ToString() + ".zip";
            ECN ecn = ecnDMO.GetECN(ecnNumber);
            string emailSentList = "";

            List<string> emailIst = MiscDMO.GetTECNCancelledApprovalNotifyList(ecnNumber).Distinct().ToList();

            string emailTemplate = "TECNCancelled.txt";
            string userEmail = string.Empty;
            string subject = string.Empty;
            if (ecn.CancellationApprovalDate == null)
            {
                subject = "TECN Cancellation Initiated  Notice - " + ecnNumber + " for " + ecn.Title + ", Cancellation Initiated on:" + DateTime.Now;
            }
            else
            {
                subject = "TECN Cancellation Approved Notice - " + ecnNumber + " for " + ecn.Title + ", Cancelled:" + ecn.CancellationApprovalDate;
            }
            string senderName = "ECN";

            //foreach (string email in emailIst)
            //{
                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[5];
                emailparams[0] = ecnNumber.ToString();
                emailparams[1] = ecnNumber.ToString();
                emailparams[2] = GlobalVars.hostURL;
                emailparams[3] = "TECN";
                emailparams[4] = DateTime.Now.ToString();
                //userEmail = email;

#if(DEBUG)
                userEmail =  GlobalVars.SENDER_EMAIL;
#endif

                //en.SendNotificationEmailWithAttachment(emailTemplate, "rkotian1@irf.com", senderName, userEmail, null, subject, ecnFolderPath, emailparams);
                if (IsITAR(ecn))
                    en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams);
                else
                    en.SendNotificationEmailWithAttachment(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, ecnFolderPath, emailparams);
                //emailSentList += email + ",";
                emailSentList = String.Join(", ", emailIst.Distinct().ToArray());
            
            //}

            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Cancellation :" + emailSentList });
            }
            catch { }

        }

        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="attachments"></param>
        public void NotifyTECNAutoCancellation(int ecnNumber, int tecnNumber, List<string> attachments)
        {
            //string ecnFolderPath = Functions.GetAttachmentFolder() + "TECNCancelledZipped\\" + TECN_PREFIX + ecnNumber.ToString() + ".zip";
            ECN ecn = ecnDMO.GetECN(tecnNumber);
            string emailSentList = "";

            List<string> emailIst = MiscDMO.GetTECNCancelledApprovalNotifyList(ecnNumber).Distinct().ToList();

            string emailTemplate = "TECNAutoCancelled.txt";
            string userEmail = string.Empty;
            string subject = string.Empty;
            subject = "TECN Conversion and Cancellation Notice - " + tecnNumber + " for " + ecn.Title + ", Converted on:" + DateTime.Now;
            string senderName = "ECN";

            //foreach (string email in emailIst)
            //{
            EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
            string[] emailparams = new string[6];
            emailparams[0] = tecnNumber.ToString();
            emailparams[1] = tecnNumber.ToString();
            emailparams[2] = GlobalVars.hostURL;
            emailparams[3] = "TECN";
            emailparams[4] = DateTime.Now.ToString();
            emailparams[5] = ecnNumber.ToString();
            //userEmail = email;

#if(DEBUG)
                userEmail =  GlobalVars.SENDER_EMAIL;
#endif

            //en.SendNotificationEmailWithAttachment(emailTemplate, "rkotian1@irf.com", senderName, userEmail, null, subject, ecnFolderPath, emailparams);
            if (IsITAR(ecn))
                en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams);
            else
                en.SendNotificationEmailWithAttachments(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, attachments, emailparams);
            //emailSentList += email + ",";
            emailSentList = String.Join(", ", emailIst.Distinct().ToArray());

            //}

            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Cancellation :" + emailSentList });
            }
            catch { }

        }


         /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        public void NotifyTECNExpiration(int ecnNumber, string ecnFolderPath)
        {

            ECN ecn = ecnDMO.GetECN(ecnNumber);
            //string ecnFolderPath = Functions.GetAttachmentFolder() + "TECNExpiredZipped\\" + TECN_PREFIX + ecnNumber.ToString() + ".zip";

            string emailSentList = "";

            List<string> emailIst = MiscDMO.GetEmergencyTECNApprovalNotifyList(ecnNumber).Distinct().ToList();

            string emailTemplate = "TECNExpired.txt";
            string userEmail = string.Empty;
            string subject = "TECN Expiration Approved Notice - " + ecnNumber + " for " + ecn.Title + ", Expired:" + ecn.ExpirationDate;
            string senderName = "ECN";

            //foreach (string email in emailIst)
            //{
                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[5];
                emailparams[0] = ecnNumber.ToString();
                emailparams[1] = ecnNumber.ToString();
                emailparams[2] = GlobalVars.hostURL;
                emailparams[3] = "TECN";
                emailparams[4] = ecn.ExpirationDate.Value.ToShortDateString();
            //userEmail = email;

            //#if(DEBUG)
            //                userEmail = "rkotian1@infineon.com";
            //#endif


            //en.SendNotificationEmailWithAttachment(emailTemplate, "rkotian1@infineon.com", senderName, userEmail, null, subject, ecnFolderPath, emailparams);
            if (IsITAR(ecn))
                    en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, emailparams);
                else
                    en.SendNotificationEmailWithAttachment(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, emailIst, null, subject, ecnFolderPath, emailparams);

                


                //emailSentList += email + ",";
                emailSentList = String.Join(", ", emailIst.Distinct().ToArray());
            
            //}

            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Email", Comments = "Approvers for Expiration:" + emailSentList });
            }
            catch { }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        bool CreateZip(ECNPdf ecn)
        {
            try
            {
                string sourceDirectory = Functions.GetAttachmentFolder() + "ECN\\" + ecn.ECNNumber.ToString() + "\\";
                string outputFullFilePath = "";

                string outputFileName;
                if (ecn.IsTECN)
                {
                    if (ecn.ExtensionDate != null)
                        outputFileName = TECN_PREFIX + ecn.ECNNumber.ToString() + "_Extension.zip";
                    else
                        outputFileName = TECN_PREFIX + ecn.ECNNumber.ToString() + ".zip";

                    
                    outputFullFilePath = Functions.GetAttachmentFolder() + "\\ECNZipped\\" + outputFileName;
                }
              
                else if (ecn.IsEmergencyTECN) // Transfer it to different folder , coz documentum does not need to have a Workflow Item created for Emergency TECN
                {
                    outputFileName = ETECN_PREFIX + ecn.ECNNumber.ToString() + ".zip";
                    outputFullFilePath = Functions.GetAttachmentFolder() + "\\E-TECNZipped\\" + outputFileName;
                }
                else 
                {
                    outputFileName = ECN_PREFIX + ecn.ECNNumber.ToString() + ".zip";
                    outputFullFilePath = Functions.GetAttachmentFolder() + "\\ECNZipped\\" + outputFileName;
                }

                
                Zipper zip = new Zipper();
                zip.CreateZip(outputFullFilePath, sourceDirectory);
            }
            catch(Exception ex)
            {
                EventLogDMO.Add(new WinEventLog() { IssueID = ecn.ECNNumber, UserID = @User.Identity.Name, DocumentType = ecn.IsECN? "ECN" : (ecn.IsEmergencyTECN? "E-TECN" : "TECN"), OperationType = "Error", Comments = ex.Message });
                return false;
            }

            return true;

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="step"></param>
        /// <param name="userIDs"></param>
        public void AddEECNApproval(int ecnNumber, byte step, string engUserIDs, string OpUserIDs)
        {
            // it is always going to be the first step
            step = 1;
            string emailSentList = "";
            var emailArray = "";
            try
            {
                emailArray = wfDMO.AddEECNApproval(ecnNumber, step, (int)GlobalVars.DocumentType.EECN, engUserIDs,  OpUserIDs);
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + step + " " + " Userid:" + engUserIDs + " - " + OpUserIDs + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n AddEECNApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN ", OperationType = "Error", Comments = "AddEECNApproval - " + exceptionString });
                throw new Exception(e.Message);
            }
            ECN ecn = ecnDMO.GetECN(ecnNumber);
            string emailTemplate = "ECNAssigned.txt";
            string userEmail = string.Empty;
            string subject = "E-TECN Assignment";
            string senderName = "E-TECN";

            string[] emailIst = emailArray.Split(new char[] { '~' });
            foreach (string email in emailIst)
            {
                if (email.Length > 0)
                {
                    subject = "E-TECN Assignment notice for Number " + ecn.ECNNumber + ", - " + ecn.Title;
                    EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                    string[] emailparams = new string[4];
                    emailparams[0] = ecnNumber.ToString();
                    emailparams[1] = ecnNumber.ToString();
                    emailparams[2] = GlobalVars.hostURL;
                    emailparams[3] = "E-TECN";

                    userEmail = email;
                    //#if(DEBUG)
                    //    userEmail = "rkotian1@infineon.com";
                    //#endif

                    en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
                    emailSentList += email + ",";

                }

            }
            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList });
            }
            catch { }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="implementationDetails"></param>
        public void SaveAfterSubmitByApprover(int ecnNumber, string implementationDetails)
        {
            try
            {
                ecnDMO.SaveAfterSubmitByApprover(ecnNumber, implementationDetails);
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n SaveAfterSubmitByApprover\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN ", OperationType = "Error", Comments = "SaveAfterSubmitByApprover - " + exceptionString });
                throw new Exception(e.Message);
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="ecnTypeString"></param>
        public void DeleteDocument(int ecnNumber, string ecnTypeString)
        {
            try
            {
                ecnDMO.DeleteDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], ecnTypeString);
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n DeleteDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "", OperationType = "Error", Comments = "DeleteDocument - " + exceptionString });
                throw new Exception(e.Message);
            }
        }
        public void DeleteDocumentBySubmitter(int ecnNumber, string ecnTypeString)
        {
            ECN ecn = ecnDMO.GetECN(ecnNumber);
            int submitterId = ecn.OriginatorID;
            if (submitterId == (int)Session[GlobalVars.SESSION_USERID])
            {
                try
                {
                    ecnDMO.DeleteDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], ecnTypeString);
                }
                catch (Exception e)
                {
                    string detailedException = "";
                    try
                    {
                        detailedException = e.InnerException.ToString();
                    }
                    catch
                    {
                        detailedException = e.Message;
                    }
                    string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                    Functions.WriteEvent(@User.Identity.Name + "\r\n DeleteDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                    EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "", OperationType = "Error", Comments = "DeleteDocument - " + exceptionString });
                    throw new Exception(e.Message);
                }
            }
            else
            {

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="documentType"></param>
        /// <param name="ecnTypeString"></param>
        /// <param name="oldECNTypeString"></param>
        /// <returns></returns>
        public ActionResult ReSubmitDocument(int ecnNumber, int documentType, string ecnTypeString, string oldECNTypeString, string descriptionOfChange, string reasonForChange, string categoryId = "")
        {
            // Update ECN Type in the ECN table

            ECN ecn = new ECN();
            
            int isITARCompliant = 1;
            int newECNNumber = 0;
            int catId = 0;
            Int32.TryParse(categoryId, out catId);
            try
            {

                int appoverCount = ecnDMO.ReSubmitDocument(
                    ecnNumber, 
                    (int)Session[GlobalVars.SESSION_USERID], 
                    documentType, 
                    out isITARCompliant, 
                    descriptionOfChange, 
                    reasonForChange, 
                    ecnTypeString, 
                    out newECNNumber,
                    catId);
               
                if (isITARCompliant == 0) // not ITAR Compliant
                {
                    // the content gets evaluated on the client side
                    return Content("ITAR");
                }
                else
                {
                    //TODO - COPY ATTACHMENTS
                    Functions.CopyAttachments(ecnNumber, newECNNumber);

                    // Log into the Approval Log
                    try
                    {
                        ecn = ecnDMO.GetECN(ecnNumber);

                        //ecnDMO.UpdateECNType(ecnNumber, ecnTypeString);

                        ApprovalLogDMO.Add(new ApprovalLog
                        {
                            IssueID = ecnNumber,
                            DocumentTypeID = documentType,
                            OperationType = "Changed From " + oldECNTypeString + " To " + ecnTypeString,
                            UserID = (int)Session[GlobalVars.SESSION_USERID],
                            OperationLog = "Changed the Document Type"
                        });
                    }
                    catch (Exception e)
                    {
                        string detailedException = "";
                        try
                        {
                            detailedException = e.InnerException.ToString();
                        }
                        catch
                        {
                            detailedException = e.Message;
                        }
                        string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                        Functions.WriteEvent(@User.Identity.Name + "\r\n ReSubmitDocument (ApprovalLogDMO)\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                        EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReSubmitDocument (ApprovalLogDMO)" + exceptionString });

                    }

                    // Add to the Document Change Log
                    try
                    {
                        ECNTypeChangeLogDMO.Add(new ECNTypeChangeLog
                        {
                            ECNNumber = ecnNumber,
                            UserID = (int)Session[GlobalVars.SESSION_USERID],
                            ECNTypeFrom = oldECNTypeString,
                            ECNTypeTo = ecnTypeString
                        });
                    }
                    catch (Exception e)
                    {
                        string detailedException = "";
                        try
                        {
                            detailedException = e.InnerException.ToString();
                        }
                        catch
                        {
                            detailedException = e.Message;
                        }
                        string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                        Functions.WriteEvent(@User.Identity.Name + "\r\n ReSubmitDocument (ECNTypeChangeLogDMO)\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                        EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReSubmitDocument (ECNTypeChangeLogDMO)" + exceptionString });

                    }



                    //if (appoverCount > 0)
                    //{
                    //    NotifyApprovers(newECNNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, documentType, ecnTypeString);
                    //}
                    //else
                    //{
                    //    // automaically approve current step (Step 1) beacuase there are no approvers in step 1 and move to the next step of approval
                    //    Approve(newECNNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, "", documentType, ecnTypeString); // this is the Submit Level Approval

                    //}

                    

                    if (Request.IsAjaxRequest())
                    {
                        // the content gets evaluated on the client side
                        return Content("Redirect~" + newECNNumber);
                        
                    }
                    else
                        return Content("Invalid");
                }
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Re-SubmitDocument - " + exceptionString });
                throw new Exception(e.Message);

            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pcrb"></param>
        /// <returns></returns>
        public ActionResult PCRBExists(int pcrb)
        {
            
            return Content(ecnDMO.PCRBExists(pcrb).ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        public ActionResult CancelDocument(int ecnNumber, byte currentStep, int documentType, string ecnTypeString)
        {
            // log the cancelled event
            //EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Cancelled", Comments = "Cancelled the document" });
            // Set the ECN Current step to the last step of the document type, which is the execution step

            bool lastApproverAndLastStep = false;
            int appoverCount = ecnDMO.SubmitForCancellation(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, (int)Session[GlobalVars.SESSION_USERID], documentType, ecnTypeString, (int)GlobalVars.TECNExpirationCancellation.Cancellation);
            if (appoverCount > 0)
            {
                NotifyApproversForCancellation(ecnNumber, currentStep, documentType, ecnTypeString);
            }
            else // TODO Automatically close the
            {
                lastApproverAndLastStep = ApproveCancellation(ecnNumber, currentStep, "", documentType, ecnTypeString);
                // automaically approve current step (Step 1) because there are no approvers in step 1 and move to the next step of approval
                //Approve(ecnNumber, currentStep, "", documentType, ecnTypeString); // this is the Submit Level Approval

            }

            // if there are approvers dont wait for it to finish the approval loop for sending cancel notications.
            if (!lastApproverAndLastStep)
            {
                // send notifications
                try
                {
                    lastApproverAndLastStep = true;

                    ECNPdf ecn = new ECNPdf();
                    GenerateECNPdf(ecnNumber, out ecn);


                    string sourceDirectory = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber.ToString() + "\\";
                    string outputFullFilePath = "";

                    string outputFileName;
                    outputFileName = TECN_PREFIX + ecnNumber.ToString() + ".zip";

                    outputFullFilePath = Functions.GetAttachmentFolder() + "\\TECNCancelledZipped\\" + outputFileName;

                    // Create the zipped package
                    Zipper zip = new Zipper();
                    zip.CreateZip(outputFullFilePath, sourceDirectory);
                    NotifyTECNCancellation(ecnNumber, outputFullFilePath);
                    

                }
                catch (Exception ex)
                {
                    EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Error", Comments = ex.Message });

                }
                
            }
            int trainingId = trainingDMO.GetTrainingId(ecnNumber);
            trainingDMO.DeleteTraining(trainingId);

            if (Request.IsAjaxRequest())
            {
                // the content gets evaluated on the client side
                return Content("Redirect");
            }
            else
                return Content("Invalid");
                        
        }
        public ActionResult CancelDocumentBySubmitter(int ecnNumber, byte currentStep, int documentType, string ecnTypeString)
        {
            return Content("Redirect");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="currentStep"></param>
        /// <param name="comments"></param>
        /// <param name="documentType"></param>
        /// <param name="ecnTypeString"></param>
        public bool ApproveCancellation(int ecnNumber, byte currentStep, string comments, int documentType, string ecnTypeString)
        {
            bool lastApproverAndLastStep = false;
            bool lastStep = false;
            bool lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType);
            while (lastApprover && !lastStep)
            {
                currentStep++;
                lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType);
                NotifyApproversForCancellation(ecnNumber, currentStep, documentType, ecnTypeString);
            }
          
            if (lastApprover && lastStep)
            {
                try
                {
                    lastApproverAndLastStep = true;

                    ECNPdf ecn = new ECNPdf();
                    GenerateECNPdf(ecnNumber, out ecn);

                    
                    string sourceDirectory = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber.ToString() + "\\";
                    string outputFullFilePath = "";

                    string outputFileName;
                    outputFileName = TECN_PREFIX + ecnNumber.ToString() + ".zip";

                    outputFullFilePath = Functions.GetAttachmentFolder() + "\\TECNCancelledZipped\\" + outputFileName;

                    // Create the zipped package
                    Zipper zip = new Zipper();
                    zip.CreateZip(outputFullFilePath, sourceDirectory);
                    NotifyTECNCancellation(ecnNumber, outputFullFilePath);

                   
                }
                catch (Exception ex)
                {
                    EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Error", Comments = ex.Message });
                    
                }
            }

            return lastApproverAndLastStep;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        /// <param name="currentStep"></param>
        /// <param name="comments"></param>
        /// <param name="documentType"></param>
        /// <param name="ecnTypeString"></param>
        public void ApproveExpiration(int ecnNumber, byte currentStep, string comments, int documentType, string ecnTypeString)
        {
            bool lastStep = false;
            bool lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType);
            while (lastApprover && !lastStep)
            {
                currentStep++;
                lastApprover = lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType);
                NotifyApproversForExpiration(ecnNumber, currentStep, documentType, ecnTypeString);
            }
            if (lastApprover && lastStep)
            {
                try
                {
                    ECNPdf ecn = new ECNPdf();
                    GenerateECNPdf(ecnNumber, out ecn);

                    string sourceDirectory = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber.ToString() + "\\";
                    string outputFullFilePath = "";

                    string outputFileName;
                    outputFileName = TECN_PREFIX + ecnNumber.ToString() + ".zip";

                    outputFullFilePath = Functions.GetAttachmentFolder() + "\\TECNExpiredZipped\\" + outputFileName;


                    Zipper zip = new Zipper();
                    zip.CreateZip(outputFullFilePath, sourceDirectory);

                    NotifyTECNExpiration(ecnNumber, outputFullFilePath);
                }
                catch (Exception ex)
                {
                    EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Error", Comments = ex.Message });

                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecnNumber"></param>
        public void CheckCanSubmit(int ecnNumber)
        {
            bool result = ecnDMO.CanSubmitECN(ecnNumber);
            if (result)
            {
                throw new Exception("Cannot Submit");
            }
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="workRequestID"></param>
        public void ReleaseLockOnDocument(int issueID)
        {
            try
            {
                ecnDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID);
            }
            catch(Exception e)
            {
                try
                {
                    Functions.WriteEvent(@User.Identity.Name + "\r\n ReleaseLockOnDocument ECN\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error);
                }
                catch { }
                ecnDMO.ReleaseLockOnDocument(-1, issueID);

            }


        }
        public void ReleaseLockOnDocumentAdmin(int issueID)
        {
            try
            {
                ecnDMO.ReleaseLockOnDocument(-1, issueID);
            }
            catch (Exception e)
            {
                try
                {
                    Functions.WriteEvent(@User.Identity.Name + "\r\n ReleaseLockOnDocument ECN\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error);
                }
                catch { }
                ecnDMO.ReleaseLockOnDocument(-1, issueID);

            }


        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="attachmentID"></param>
        /// <param name="ecnNumber"></param>
        /// <returns></returns>
        public FileResult DownloadFile(string attachmentID, string ecnNumber)
        {
            //fileName = "ECNForm_71132.pdf";           

            string fileName = ecnDMO.GetFileName(attachmentID);

            string ecnFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + ecnNumber.ToString();
            var sDocument = Path.Combine(ecnFolderPath, fileName);

            var FDir_AppData = Functions.GetAttachmentFolder();
            if (!sDocument.StartsWith(FDir_AppData))
            {
                // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder
                // and block requests outside like "../web.config"
                throw new HttpException(403, "Forbidden");
            }

            if (!System.IO.File.Exists(sDocument))
            {
                return null;
                //throw new Exception("File not found");
            }

            return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
        }

        ///// <summary>
        ///// 
        ///// </summary>
        //void CreateZipFile()
        //{

        //    try
        //    {
        //        using (ZipFile zip = new ZipFile())
        //        {
        //            // note: this does not recurse directories! 
        //            String[] filenames = System.IO.Directory.GetFiles(@"C:\Documents\Approval System\ECN-TECN");

        //            // This is just a sample, provided to illustrate the DotNetZip interface.  
        //            // This logic does not recurse through sub-directories.
        //            // If you are zipping up a directory, you may want to see the AddDirectory() method, 
        //            // which operates recursively. 
        //            foreach (String filename in filenames)
        //            {
        //                Console.WriteLine("Adding {0}...", filename);

        //                ZipEntry e = zip.AddFile(filename);
        //                e.Comment = "Added by Cheeso's CreateZip utility.";
        //            }

        //            zip.Comment = String.Format("This zip archive was created by the CreateZip example application on machine '{0}'",
        //               System.Net.Dns.GetHostName());

        //            zip.Save(@"C:\Documents\Approval System\ECN-TECN\New.Zip");
        //        }

        //    }
        //    catch (System.Exception ex1)
        //    {
        //        System.Console.Error.WriteLine("exception: " + ex1);
        //    }


        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ecn"></param>
        /// <returns></returns>
        bool IsITAR(ECN ecn)
        {
            if (ecn.IsRH && !ecn.IsAU && !ecn.IsIndustrial && !ecn.IsMA)
            {
                return true;
            }
            else
                return false;

        }

       
    }
}