using Ionic.Zip;
using MassTransit;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using WK_KLI_LAPS_Service.Controllers.WorkArea;
using WK_KLI_LAPS_Service.Models;

namespace WK_KLI_LAPS_Service.App_Data
{
    public class MergedFile_Service
    {
        WorkAreaService oWorkAreaService = new WorkAreaService();
        private readonly IRequestClient<ISimpleRequest, ISimpleResponse> _requestClient = null;
        public string FileName { get; set; }
        public string TempFolder { get; set; }
        public int MaxFileSizeMB { get; set; }
        public List<String> FileParts { get; set; }
        private object Res_list;
        #region # Final Saved File Path 
        private string _finalFileName { get; set; }

        private string _returnmsg { get; set; }

        private string _Job_Header_Id { get; set; }

        private string _finalFileNameWithoutUserID { get; set; }

        public string FinalFilePath
        {
            get
            {
                return _finalFileName;
            }
        }

        public string ReturnMsg
        {
            get
            {
                return _returnmsg;
            }
        }

        public string Job_Header_Id
        {
            get
            {
                return _Job_Header_Id;
            }
        }

        public string FinalFilePathWithoutUserID
        {
            get
            {
                return _finalFileNameWithoutUserID;
            }
        }


        public IRequestClient<ISimpleRequest, ISimpleResponse> RequestClient => _requestClient;
        #endregion
        public MergedFile_Service()
        {
            FileParts = new List<string>();
        }

        /// <summary>
        /// original name + ".part_N.X" (N = file part number, X = total files)
        /// Objective = enumerate files in folder, look for all matching parts of split file. If found, merge and return true.
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        /// 

        //public bool MergeFile_Book(string FileName, string UserID, string UploadPath_, string trankey, string TOC, string sparams)
        //{
        //    bool rslt = false;
        //    string partToken = ".part_";
        //    string baseFileName = FileName.Substring(0, FileName.IndexOf(partToken));
        //    string trailingTokens = FileName.Substring(FileName.IndexOf(partToken) + partToken.Length);
        //    int FileIndex = 0;
        //    int FileCount = 0;
        //    int.TryParse(trailingTokens.Substring(0, trailingTokens.IndexOf(".")), out FileIndex);
        //    int.TryParse(trailingTokens.Substring(trailingTokens.IndexOf(".") + 1), out FileCount);
        //    string Searchpattern = Path.GetFileName(baseFileName) + partToken + "*";
        //    string[] FilesList = Directory.GetFiles(Path.GetDirectoryName(FileName), Searchpattern);
        //    if (FilesList.Count() == FileCount)
        //    {

        //        if (!MergeFileManager.Instance.InUse(baseFileName))
        //        {
        //            MergeFileManager.Instance.AddFile(baseFileName);
        //            if (File.Exists(baseFileName))
        //                File.Delete(baseFileName);
        //            MergeFileManager.Instance.RemoveFile(baseFileName);

        //            List<SortedFile> MergeList = new List<SortedFile>();
        //            foreach (string File1 in FilesList)
        //            {
        //                SortedFile sFile = new SortedFile();
        //                sFile.FileName = File1;
        //                baseFileName = File1.Substring(0, File1.IndexOf(partToken));
        //                trailingTokens = File1.Substring(File1.IndexOf(partToken) + partToken.Length);
        //                int.TryParse(trailingTokens.Substring(0, trailingTokens.IndexOf(".")), out FileIndex);
        //                sFile.FileOrder = FileIndex;
        //                MergeList.Add(sFile);
        //            }

        //            var MergeOrder = MergeList.OrderBy(s => s.FileOrder).ToList();
        //            var BaseFileName_ = Path.GetFileNameWithoutExtension(baseFileName);


        //            // using (ServerInfo.GrantFolderPermission svr = new ServerInfo.GrantFolderPermission("3330"))
        //            // {
        //            if (!Directory.Exists(UploadPath_)) Directory.CreateDirectory(UploadPath_);
        //            var path = Path.Combine(UploadPath_ + @"\", BaseFileName_ + Path.GetExtension(baseFileName));
        //            _finalFileName = path;
        //            using (FileStream FS = new FileStream(path, FileMode.Create))
        //            {
        //                foreach (var chunk in MergeOrder)
        //                {
        //                    try
        //                    {
        //                        using (FileStream fileChunk = new FileStream(chunk.FileName, FileMode.Open))
        //                        {
        //                            fileChunk.CopyTo(FS);
        //                        }
        //                        File.Delete(chunk.FileName);
        //                    }
        //                    catch (IOException ex)
        //                    {
        //                    }
        //                }
        //            }

        //            if (File.Exists(path))
        //            {
        //                if (Path.GetExtension(path).ToLower() == ".zip" || Path.GetExtension(path).ToLower() == ".docx")
        //                {
        //                    if (Directory.Exists(Path.Combine(UploadPath_ + @"\", BaseFileName_)))
        //                    {
        //                        System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(Path.Combine(UploadPath_ + @"\", BaseFileName_));
        //                        foreach (System.IO.FileInfo fle in dirinfo.GetFiles("*.*"))
        //                        {
        //                            if (!fle.Name.ToString().ToLower().Contains("thumb.db"))
        //                                File.Delete(fle.FullName.ToString());
        //                        }
        //                    }
        //                    using (ZipFile zip = ZipFile.Read(path))
        //                    {
        //                        zip.ExtractAll(Path.Combine(UploadPath_ + @"\", BaseFileName_), ExtractExistingFileAction.OverwriteSilently);
        //                    }
        //                }

        //                var stans = sparams.Split('`');
        //                DBContext _dbContext = new DBContext();
        //                BLDatamanipulation db = new BLDatamanipulation();
        //                var LastTranId = "";
        //                for (int k = 0; k <= stans.Length - 1; k++)
        //                {

        //                    if (stans[k].Length > 1)
        //                    {
        //                        var filename = stans[k].Split(',')[0];
        //                        trankey = stans[k].Split(',')[1];
        //                        string[] files = System.IO.Directory.GetFiles(UploadPath_ + @"/" + BaseFileName_, filename, SearchOption.AllDirectories);
        //                        if (files.Count() > 0)
        //                        {

        //                            Npgsql.NpgsqlParameter[] sParams = { new Npgsql.NpgsqlParameter("@trankey", trankey) };
        //                            var dt = db.GetDataTable(_dbContext, "select a.*,b.lotkey from lot_transaction a left outer join lot_master b on a.lotid = b.lotid where transactionkey = @trankey and a.lotstatus in ('R','P','F')", sParams);
        //                            if (dt.Rows.Count > 0)
        //                            {
        //                                ServerInfo servinfo = new ServerInfo();
        //                                string serverpath = servinfo.GetServerPath(dt.Rows[0]["transactionid"].ToString(), true, "serverinfo");

        //                                var usr_lot_tran_update = _dbContext.Database.SqlQuery<jsonvalue>("select * from  usr_lot_tran_update(@p_userid, @p_tranid,@p_holdreason,@p_option) as json",
        //                                 new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = dt.Rows[0]["pickedby"].ToString() },
        //                                 new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = dt.Rows[0]["transactionid"].ToString() },
        //                                 new Npgsql.NpgsqlParameter { ParameterName = "@p_holdreason", Value = "" },
        //                                 new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "checkout_" }).ToList();
        //                                var obj1 = JsonConvert.DeserializeObject<resultvalue>(usr_lot_tran_update[0].json);

        //                                using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(obj1.p_tranid.ToString()))
        //                                {

        //                                    string serverpath_ = servinfo.GetServerPath(obj1.p_tranid.ToString(), true, "serverinfo");
        //                                    string serverpath_prev_ = servinfo.GetServerPath(dt.Rows[0]["transactionid"].ToString(), false, "serverinfo");

        //                                    System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(System.IO.Path.Combine(serverpath_prev_, "IN"));
        //                                    foreach (System.IO.FileInfo fle in dirinfo.GetFiles("*.*"))
        //                                    {
        //                                        if (File.Exists(System.IO.Path.Combine(serverpath_, "IN", fle.Name)))
        //                                            File.Delete(System.IO.Path.Combine(serverpath_, "IN", fle.Name));

        //                                        if (!fle.Name.ToString().ToLower().Contains("thumb.db"))
        //                                            fle.CopyTo(System.IO.Path.Combine(serverpath_, "IN", fle.Name), true);
        //                                    }

        //                                    var destpath = Path.Combine(serverpath_, "IN");

        //                                    if (!Directory.Exists(destpath))
        //                                        Directory.CreateDirectory(destpath);

        //                                    if (File.Exists(destpath + @"/" + Path.GetFileName(files[0])))
        //                                        File.Delete(destpath + @"/" + Path.GetFileName(files[0]));

        //                                    File.Copy(files[0], destpath + @"/" + Path.GetFileName(files[0]));
        //                                    File.Delete(files[0]);
        //                                }

        //                                DashboardApiController dc = new DashboardApiController();
        //                                dc.Postmail_SignOff(Convert.ToInt32(obj1.p_tranid.ToString()), 0, "2", 0);
        //                                dc.Postmail_Ack(Convert.ToInt32(dt.Rows[0]["transactionid"].ToString()), "2");
        //                                LastTranId = dt.Rows[0]["transactionid"].ToString();
        //                                rslt = true;
        //                                _returnmsg = "Successfully Uploaded";
        //                            }
        //                            else
        //                            {
        //                                _returnmsg = "Already Completed the Job";
        //                            }
        //                        }
        //                        else
        //                        {
        //                            rslt = false;
        //                            _returnmsg = "File Validation failed: Incorrect file selected";
        //                        }
        //                    }
        //                }

        //                //****** Mail To Invalid File

        //                string[] tfiles = System.IO.Directory.GetFiles(UploadPath_ + @"/" + BaseFileName_, "*.docx", SearchOption.AllDirectories);
        //                if (tfiles.Count() > 0)
        //                {
        //                    var sTempFileName = Guid.NewGuid().ToString();

        //                    if (!Directory.Exists(UploadPath_ + @"/" + sTempFileName + @"/Additional"))
        //                        Directory.CreateDirectory(UploadPath_ + @"/" + sTempFileName + @"/Additional");


        //                    System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(UploadPath_ + @"/" + BaseFileName_);
        //                    foreach (System.IO.FileInfo fle in dirinfo.GetFiles("*.docx"))
        //                    {
        //                        if (!fle.Name.ToString().ToLower().Contains("thumb.db"))
        //                            fle.CopyTo(System.IO.Path.Combine(UploadPath_ + @"/" + sTempFileName + @"/Additional", fle.Name), true);
        //                    }


        //                    if (File.Exists(UploadPath_ + @"\" + sTempFileName + @"\" + BaseFileName_ + ".zip"))
        //                        File.Delete(UploadPath_ + @"\" + sTempFileName + @"\" + BaseFileName_ + ".zip");
        //                    try
        //                    {
        //                        if (!Directory.Exists(Path.Combine(UploadPath_ + @"\" + sTempFileName)))
        //                            Directory.CreateDirectory(Path.Combine(UploadPath_ + @"\" + sTempFileName));

        //                        CreateZip(UploadPath_ + @"/" + sTempFileName + @"/Additional", Path.Combine(UploadPath_ + @"\" + sTempFileName + @"\" + BaseFileName_ + ".zip"));
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                    }
        //                    string serverpathdownload = ConfigurationManager.AppSettings["serverroot"] + ConfigurationManager.AppSettings["downloadspath"] + @"/From/" + sTempFileName + @"/" + BaseFileName_ + ".zip".ToString().Trim();
        //                    DashboardApiController dc = new DashboardApiController();
        //                    dc.Postmail_PM(Convert.ToInt32(LastTranId), "1", serverpathdownload);
        //                }
        //            }
        //            else
        //            {
        //                _returnmsg = "Already Completed the Job";
        //                rslt = false;
        //            }

        //            // string hostName = Dns.GetHostName();
        //            // string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
        //            rslt = true;

        //            //}
        //        }
        //    }
        //    return rslt;
        //}

        //public bool MergeFile_Proof(string FileName, string UserID, string UploadPath_, string trankey, string TOC, string sparams, string userid)
        //{
        //    bool rslt = false; string frommailid = "";
        //    string partToken = ".part_";
        //    string baseFileName = FileName.Substring(0, FileName.IndexOf(partToken));
        //    string trailingTokens = FileName.Substring(FileName.IndexOf(partToken) + partToken.Length);
        //    int FileIndex = 0;
        //    int FileCount = 0;
        //    int.TryParse(trailingTokens.Substring(0, trailingTokens.IndexOf(".")), out FileIndex);
        //    int.TryParse(trailingTokens.Substring(trailingTokens.IndexOf(".") + 1), out FileCount);
        //    string Searchpattern = Path.GetFileName(baseFileName) + partToken + "*";
        //    string[] FilesList = Directory.GetFiles(Path.GetDirectoryName(FileName), Searchpattern);
        //    if (FilesList.Count() == FileCount)
        //    {

        //        if (!MergeFileManager.Instance.InUse(baseFileName))
        //        {
        //            MergeFileManager.Instance.AddFile(baseFileName);
        //            if (File.Exists(baseFileName))
        //                File.Delete(baseFileName);
        //            MergeFileManager.Instance.RemoveFile(baseFileName);

        //            List<SortedFile> MergeList = new List<SortedFile>();
        //            foreach (string File1 in FilesList)
        //            {
        //                SortedFile sFile = new SortedFile();
        //                sFile.FileName = File1;
        //                baseFileName = File1.Substring(0, File1.IndexOf(partToken));
        //                trailingTokens = File1.Substring(File1.IndexOf(partToken) + partToken.Length);
        //                int.TryParse(trailingTokens.Substring(0, trailingTokens.IndexOf(".")), out FileIndex);
        //                sFile.FileOrder = FileIndex;
        //                MergeList.Add(sFile);
        //            }

        //            var MergeOrder = MergeList.OrderBy(s => s.FileOrder).ToList();
        //            var BaseFileName_ = Path.GetFileNameWithoutExtension(baseFileName);


        //            // using (ServerInfo.GrantFolderPermission svr = new ServerInfo.GrantFolderPermission("3330"))
        //            // {
        //            UploadPath_ = UploadPath_ + "//" + userid;
        //            if (!Directory.Exists(UploadPath_)) Directory.CreateDirectory(UploadPath_);
        //            var path = Path.Combine(UploadPath_ + @"\", BaseFileName_ + Path.GetExtension(baseFileName));
        //            _finalFileName = path;
        //            using (FileStream FS = new FileStream(path, FileMode.Create))
        //            {
        //                foreach (var chunk in MergeOrder)
        //                {
        //                    try
        //                    {
        //                        using (FileStream fileChunk = new FileStream(chunk.FileName, FileMode.Open))
        //                        {
        //                            fileChunk.CopyTo(FS);
        //                        }
        //                        File.Delete(chunk.FileName);
        //                    }
        //                    catch (IOException ex)
        //                    {
        //                    }
        //                }
        //            }
        //            DBContext _dbContext = new DBContext();
        //            if (File.Exists(path))
        //            {
        //                if (Path.GetExtension(path).ToLower() == ".zip" || Path.GetExtension(path).ToLower() == ".docx")
        //                {
        //                    if (Directory.Exists(Path.Combine(UploadPath_ + @"\", BaseFileName_)))
        //                    {
        //                        System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(Path.Combine(UploadPath_ + @"\", BaseFileName_));
        //                        foreach (System.IO.FileInfo fle in dirinfo.GetFiles("*.*"))
        //                        {
        //                            if (!fle.Name.ToString().ToLower().Contains("thumb.db"))
        //                                File.Delete(fle.FullName.ToString());
        //                        }
        //                    }
        //                    using (ZipFile zip = ZipFile.Read(path))
        //                    {
        //                        zip.ExtractAll(Path.Combine(UploadPath_ + @"\", BaseFileName_), ExtractExistingFileAction.OverwriteSilently);
        //                    }
        //                    BLDatamanipulation db1 = new BLDatamanipulation();
        //                    Npgsql.NpgsqlParameter[] sParams = { new Npgsql.NpgsqlParameter("@p_jobkey", trankey.ToString()), new Npgsql.NpgsqlParameter("@userid", userid.ToString()) };
        //                    var Dt2 = db1.GetDataTable(_dbContext, "select * from book_proof_details a where  a.bookproofkey = @p_jobkey and userid = @userid and active = 1 and status in ('R','P')", sParams);
        //                    if (Dt2.Rows.Count <= 0)
        //                    {
        //                        return false;
        //                    }
        //                    else
        //                    {
        //                        trankey = Dt2.Rows[0]["transid"].ToString();
        //                        frommailid = Dt2.Rows[0]["mailid"].ToString();
        //                        ServerInfo servinfo = new ServerInfo();
        //                        string serverpath = servinfo.GetServerPath(trankey.ToString(), true, "serverinfo");
        //                        using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(trankey.ToString()))
        //                        {
        //                            if (!Directory.Exists(serverpath + "//" + userid))
        //                            {
        //                                Directory.CreateDirectory(serverpath + "//" + userid);
        //                            }
        //                            FileCopyed(Path.Combine(UploadPath_ + @"\", BaseFileName_), serverpath + "//" + userid);
        //                        }
        //                    }
        //                }





        //                var stans = sparams.Split('`');

        //                BLDatamanipulation db = new BLDatamanipulation();
        //                for (int k = 0; k <= stans.Length - 1; k++)
        //                {

        //                    if (stans[k].Length > 1)
        //                    {
        //                        var filename = stans[k].Split(',')[0];
        //                        var t_trankey = stans[k].Split(',')[1];
        //                        string[] files = System.IO.Directory.GetFiles(UploadPath_ + @"/" + BaseFileName_, filename, SearchOption.AllDirectories);
        //                        if (files.Count() > 0)
        //                        {
        //                            var usr_lot_tran_update = _dbContext.Database.SqlQuery<jsonvalue>("select * from  set_book_proof_details_update_status_v1(@p_tranid, @p_status,@p_userid,@p_finalapprove) as json",
        //                                 new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = t_trankey.ToString() },
        //                                 new Npgsql.NpgsqlParameter { ParameterName = "@p_status", Value = "C".ToString() },
        //                                 new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = userid },
        //                                 new Npgsql.NpgsqlParameter { ParameterName = "@p_finalapprove", Value = 'A' }).ToList();

        //                            DashboardApiController dc = new DashboardApiController();
        //                            //dc.Postmail_SignOff(Convert.ToInt32(obj1.p_tranid.ToString()), 0, "2", 0);
        //                            //dc.Postmail_Ack(Convert.ToInt32(dt.Rows[0]["transactionid"].ToString()), "2");
        //                            Npgsql.NpgsqlParameter[] sParams1 = { new Npgsql.NpgsqlParameter("@lotkey", t_trankey.ToString()) };
        //                            var dt1 = db.GetDataTable(_dbContext, "select title,filename,b.transid,b.mailid  from lot_master a left outer join book_proof_details b on a.lotkey = b.transactionkey where a.lotkey = @lotkey and b.active = 1 limit 1", sParams1);
        //                            if (dt1.Rows.Count > 0)
        //                            {
        //                                dc.Postmail_PM_Proof(trankey.ToString(), "4", dt1.Rows[0]["title"].ToString(), frommailid, "Uploaded", userid);
        //                            }

        //                            rslt = true;
        //                            _returnmsg = "Successfully Uploaded";
        //                            //}
        //                            //else
        //                            //{
        //                            //    _returnmsg = "Already Completed the Job";
        //                            //}
        //                        }
        //                        else
        //                        {
        //                            rslt = false;
        //                            _returnmsg = "File Validation failed: Incorrect file selected";
        //                        }
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                _returnmsg = "Already Completed the Job";
        //                rslt = false;
        //            }
        //            rslt = true;
        //        }
        //    }
        //    return rslt;
        //}

        public bool MergeFile(string FileName, string UserID, string UploadPath_, string trankey, string TOC, string tranid, string key = "")
        {
            bool rslt = false;
            string partToken = ".part_";
            string baseFileName = FileName.Substring(0, FileName.IndexOf(partToken));
            string trailingTokens = FileName.Substring(FileName.IndexOf(partToken) + partToken.Length);
            int FileIndex = 0;
            int FileCount = 0;
            int.TryParse(trailingTokens.Substring(0, trailingTokens.IndexOf(".")), out FileIndex);
            int.TryParse(trailingTokens.Substring(trailingTokens.IndexOf(".") + 1), out FileCount);
            string Searchpattern = Path.GetFileName(baseFileName) + partToken + "*";
            string[] FilesList = Directory.GetFiles(Path.GetDirectoryName(FileName), Searchpattern);
            CommonRepository oCommonRepository = new CommonRepository();
            string path = string.Empty;
            string BaseFileName_ = string.Empty;
            //List<string> files = new List<string>();
            string[] files = new string[0];
            if (FilesList.Count() == FileCount)
            {
                //key
                var data1 = new { vendorkey = key, p_option = "getlotstatusbyvendorkey" };
                var jsonstr1 = JsonConvert.SerializeObject(data1);
                var next_ordernores1 = oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", jsonstr1);
                var next_ordernodata1 = JsonConvert.DeserializeObject<object>(next_ordernores1.ToString());
                JArray LotDetails = JArray.Parse(next_ordernodata1.ToString());
                string filename = string.Empty;
                string trans_key = string.Empty;
                string trans_id = string.Empty;
                string lotstatus = string.Empty;
                string movebackstage = string.Empty;
                string jobworkflowid = string.Empty;
                string nextstage = string.Empty;
                string nextnextstage = string.Empty;
                string current_stageid = "";
                if (LotDetails.Count > 0)
                {
                    JObject firstElement = (JObject)LotDetails[0];
                    string jobid = firstElement["jobid"].ToString();
                    lotstatus = firstElement["lotstatus"].ToString();
                    if (lotstatus == "C")
                    {
                        rslt = false; _returnmsg = "Already Completed the Job";
                        return rslt;
                    }
                    string serverpath = oCommonRepository.GetServerPath(jobid, "serverinfo_job", false);
                    serverpath = Path.Combine(serverpath, "VendorAllocation", "Upload", UserID, key);
                    UploadPath_ = "";
                    try
                    {
                        if (!MergeFileManager.Instance.InUse(baseFileName))
                        {
                            MergeFileManager.Instance.AddFile(baseFileName);
                            if (File.Exists(baseFileName))
                                File.Delete(baseFileName);
                            MergeFileManager.Instance.RemoveFile(baseFileName);

                            List<SortedFile> MergeList = new List<SortedFile>();
                            foreach (string File1 in FilesList)
                            {
                                SortedFile sFile = new SortedFile();
                                sFile.FileName = File1;
                                baseFileName = File1.Substring(0, File1.IndexOf(partToken));
                                trailingTokens = File1.Substring(File1.IndexOf(partToken) + partToken.Length);
                                int.TryParse(trailingTokens.Substring(0, trailingTokens.IndexOf(".")), out FileIndex);
                                sFile.FileOrder = FileIndex;
                                MergeList.Add(sFile);
                            }

                            var MergeOrder = MergeList.OrderBy(s => s.FileOrder).ToList();
                            if (Path.GetExtension(baseFileName).ToLower() == ".zip")
                            {
                                BaseFileName_ = Path.GetFileNameWithoutExtension(baseFileName);
                                UploadPath_ = Path.Combine(serverpath, "TEMP");
                                if (Directory.Exists(UploadPath_)) Directory.Delete(UploadPath_, true);
                                if (!Directory.Exists(UploadPath_)) Directory.CreateDirectory(UploadPath_);
                                path = Path.Combine(UploadPath_ + @"\", BaseFileName_ + Path.GetExtension(baseFileName));
                                _finalFileName = path;
                               
                                using (FileStream FS = new FileStream(path, FileMode.Create))
                                {
                                    foreach (var chunk in MergeOrder)
                                    {
                                        try
                                        {
                                            using (FileStream fileChunk = new FileStream(chunk.FileName, FileMode.Open))
                                            {
                                                fileChunk.CopyTo(FS);
                                            }
                                            File.Delete(chunk.FileName);
                                        }
                                        catch (IOException ex)
                                        {
                                            Console.WriteLine(ex.Message.ToString());
                                        }
                                    }
                                }

                                if (File.Exists(path))
                                {
                                    if (Path.GetExtension(path).ToLower() == ".zip")
                                    {
                                        System.IO.Compression.ZipFile.ExtractToDirectory(path, Path.Combine(UploadPath_ + @"\", BaseFileName_), true);
                                    }
                                    files = System.IO.Directory.GetFiles(Path.Combine(UploadPath_, BaseFileName_), "*.*", SearchOption.TopDirectoryOnly)
                                                                                        .Where(x => Path.GetExtension(x.ToString()).ToLower() != ".zip").ToArray();
                                    if (files.Length > 0)
                                    {
                                        if (files.Length == LotDetails.Count)
                                        {
                                            for (int i = 0; i < files.Length; i++)
                                            {
                                                // if (!Path.GetFileName(files[i]).EndsWith(".visf", StringComparison.OrdinalIgnoreCase))
                                                if (!Path.GetFileName(files[i]).EndsWith(".visf", StringComparison.OrdinalIgnoreCase) &&
    !Path.GetFileName(files[i]).EndsWith(".txt", StringComparison.OrdinalIgnoreCase))

                                                {
                                                    rslt = false; _returnmsg = "Required file missing. Kindly upload .visf lot files";
                                                    return rslt;
                                                }
                                                //check vlsf file upload
                                                string fileName = Path.GetFileNameWithoutExtension(files[i]);
                                                var filteredLotDetails = LotDetails
   .Where(obj => obj["filename"] != null && obj["filename"].ToString() == fileName)
   .ToList();
                                                if (filteredLotDetails.Count == 0)
                                                {
                                                    rslt = false; _returnmsg = "Lot file missing. Kindly upload downloaded lot files";
                                                    return rslt;
                                                }
                                            }

                                        }
                                        else
                                        {
                                            rslt = false; _returnmsg = "File count mismatch. Kindly upload downloaded lot files";
                                            return rslt;
                                        }
                                    }
                                    else
                                    {
                                        rslt = false; _returnmsg = "File count mismatch. Kindly upload downloaded lot files";
                                        return rslt;
                                    }
                                }
                                else
                                {
                                    _returnmsg = "Already Completed the Job";
                                    rslt = false;
                                    return rslt;
                                }
                            }
                            else
                            {
                                _returnmsg = "Kindly upload zip file only";
                                rslt = false;
                                return rslt;
                            }
                        }
                        for (var item = 0; item < LotDetails.Count; item++)
                        {
                            filename = LotDetails[item]["filename"].ToString();
                            trans_key = LotDetails[item]["transactionkey"].ToString();
                            trans_id = LotDetails[item]["transactionid"].ToString();
                            lotstatus = LotDetails[item]["lotstatus"].ToString();
                            current_stageid = LotDetails[item]["stageid"].ToString();
                            movebackstage = LotDetails[item]["movebackstage"].ToString();
                            jobworkflowid = LotDetails[item]["jobworkflowid"].ToString();
                            nextstage = LotDetails[item]["nextstage"].ToString();
                            nextnextstage = LotDetails[item]["nextnextstage"].ToString();
                            var data = new { trankey = trans_key, p_option = "getmergedfilelotstatus", transid = trans_id };
                            var jsonstr = JsonConvert.SerializeObject(data);
                            var list = oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", jsonstr);

                            if (lotstatus == "C")
                            {
                                rslt = false; _returnmsg = "Already Completed the Job";
                                return rslt;
                            }

                            try
                            {
                                if (File.Exists(path))
                                {
                                    if (Convert.ToInt64(current_stageid) == Convert.ToInt64(Startup.Configuration.GetValue<string>("AppSettings:vp_stage_id").ToString()))
                                    {
                                        files = System.IO.Directory.GetFiles(Path.Combine(UploadPath_, BaseFileName_), "*.*", SearchOption.TopDirectoryOnly)
        .Where(x => Path.GetExtension(x).ToLower() != ".zip" && Path.GetFileNameWithoutExtension(x).ToLower().Contains(filename.ToLower()))
        .ToArray();
                                        if (files.Count() > 0)
                                        {

                                            string serverpath_prev_ = oCommonRepository.GetServerPath(trans_id, "serverinfo", true);
                                            var destpath = Path.Combine(serverpath_prev_, "OUT");

                                            for (int i = 0; i < files.Length; i++)
                                            {
                                                if (File.Exists(destpath + @"/" + Path.GetFileName(files[i])))
                                                    File.Delete(destpath + @"/" + Path.GetFileName(files[i]));
                                                File.Copy(files[i], destpath + @"/" + Path.GetFileName(files[i]));
                                            }
                                            long next_tranid = 0;
                                            //VISF QC and Review -nextnextstage
                                            oWorkAreaService.getCheckout(trans_id, UserID, "C", "checkout_only", jobworkflowid, "");
                                            Res_list = oWorkAreaService.getCheckout(trans_id, UserID, "R", "checkout_next", nextnextstage, "");

                                            if (Res_list != null)
                                            {
                                                var list_ = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(Res_list.ToString());
                                                next_tranid = Convert.ToInt64(list_[0]["p_tranid"]);
                                            }
                                            //filemovement
                                            string filePath_curr = oCommonRepository.getfilesavelocation(Convert.ToInt32(trans_id));
                                            filePath_curr = oCommonRepository.FormatPath(filePath_curr);
                                            string filePath_server_curr = oCommonRepository.GetServerPath(trans_id, "serverinfo", false);
                                            filePath_server_curr = filePath_server_curr.Replace("/", "\\");
                                            string filePath_cur_IN = Path.Combine(filePath_server_curr, "OUT");

                                            string filePath_next = oCommonRepository.getfilesavelocation(Convert.ToInt32(next_tranid));
                                            filePath_next = oCommonRepository.FormatPath(filePath_next);
                                            string filePath_server_next = oCommonRepository.GetServerPath(next_tranid.ToString(), "serverinfo", false);
                                            filePath_server_next = filePath_server_next.Replace("/", "\\");
                                            var filePath_next_IN = Path.Combine(filePath_server_next, "IN");
                                            oCommonRepository.CopyDirectory(filePath_cur_IN, filePath_next_IN);
                                        }
                                        else
                                        {
                                            rslt = false;
                                            _returnmsg = "File Validation failed: Incorrect file selected";
                                            return rslt;
                                        }
                                    }
                                    else
                                    {
                                        WorkAreaApiController wb = new WorkAreaApiController(RequestClient, null, null);
                                        files = System.IO.Directory.GetFiles(Path.Combine(UploadPath_, BaseFileName_), "*.*", SearchOption.TopDirectoryOnly)
                                                                                      .Where(x => Path.GetExtension(x.ToString()).ToLower() != ".zip").ToArray();

                                        string[] dirs = System.IO.Directory.GetDirectories(Path.Combine(UploadPath_, BaseFileName_), "*.*", SearchOption.TopDirectoryOnly).ToArray();

                                        if (files.Count() > 0)
                                        {

                                            string serverpath_prev_ = oCommonRepository.GetServerPath(trans_id, "serverinfo", true);
                                            var destpath = Path.Combine(serverpath_prev_, "OUT");

                                            for (int i = 0; i < files.Length; i++)
                                            {
                                                if (File.Exists(destpath + @"/" + Path.GetFileName(files[i])))
                                                    File.Delete(destpath + @"/" + Path.GetFileName(files[i]));
                                                File.Copy(files[i], destpath + @"/" + Path.GetFileName(files[i]));
                                            }

                                            foreach (string dir in dirs)
                                            {
                                                CopyDirectory(dir, Path.Combine(destpath, Path.GetFileName(dir)));
                                            }



                                            var cFlag = "A";
                                            if (movebackstage != "0")
                                                cFlag = "F";

                                            var fields = new Fields();
                                            long userId_t = Convert.ToInt64(UserID);

                                            fields.cflag = cFlag;
                                            fields.comment = "";
                                            fields.fields = "";
                                            fields.option = "checkout";
                                            fields.userid = userId_t.ToString();//obj1["pickedby"].ToString();
                                            fields.transid = Convert.ToInt32(trans_id);
                                            wb.PostUpdatelot_transaction(fields);

                                            rslt = true;
                                            _returnmsg = "Successfully Uploaded";

                                        }
                                        else
                                        {
                                            rslt = false;
                                            _returnmsg = "File Validation failed: Incorrect file selected";
                                            return rslt;
                                        }

                                    }
                                }
                                else
                                {
                                    _returnmsg = "Already Completed the Job";
                                    rslt = false;
                                    return rslt;
                                }

                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message.ToString());
                                _returnmsg = ex.Message.ToString();
                                rslt = false;
                                return rslt;
                            }

                        }
                        rslt = true;
                        _returnmsg = "Successfully Uploaded";
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message.ToString());
                        _returnmsg = ex.Message.ToString();
                        rslt = false;
                        return rslt;
                    }
                }
            }
            return rslt;
        }


        private void CreateZip(string directoryPathToZip, string outputZipFileName)
        {
            try
            {
                if (File.Exists(outputZipFileName))
                {
                    File.Delete(outputZipFileName);
                }

                using (ZipFile outputZip = new ZipFile(outputZipFileName))
                {
                    outputZip.AddDirectory(directoryPathToZip);
                    outputZip.Save();
                }
            }
            catch (Exception ex)
            { Console.WriteLine(ex.Message.ToString()); }

        }

        //public bool MergeFile_Query(string FileName, string UserID, string UploadPath_, string trankey, string TOC, string sparams)
        //{
        //    bool rslt = false;
        //    string partToken = ".part_";
        //    string baseFileName = FileName.Substring(0, FileName.IndexOf(partToken));
        //    string trailingTokens = FileName.Substring(FileName.IndexOf(partToken) + partToken.Length);
        //    int FileIndex = 0;
        //    int FileCount = 0;
        //    int.TryParse(trailingTokens.Substring(0, trailingTokens.IndexOf(".")), out FileIndex);
        //    int.TryParse(trailingTokens.Substring(trailingTokens.IndexOf(".") + 1), out FileCount);
        //    string Searchpattern = Path.GetFileName(baseFileName) + partToken + "*";
        //    string[] FilesList = Directory.GetFiles(Path.GetDirectoryName(FileName), Searchpattern);
        //    if (FilesList.Count() == FileCount)
        //    {

        //        if (!MergeFileManager.Instance.InUse(baseFileName))
        //        {
        //            MergeFileManager.Instance.AddFile(baseFileName);
        //            if (File.Exists(baseFileName))
        //                File.Delete(baseFileName);
        //            MergeFileManager.Instance.RemoveFile(baseFileName);

        //            List<SortedFile> MergeList = new List<SortedFile>();
        //            foreach (string File1 in FilesList)
        //            {
        //                SortedFile sFile = new SortedFile();
        //                sFile.FileName = File1;
        //                baseFileName = File1.Substring(0, File1.IndexOf(partToken));
        //                trailingTokens = File1.Substring(File1.IndexOf(partToken) + partToken.Length);
        //                int.TryParse(trailingTokens.Substring(0, trailingTokens.IndexOf(".")), out FileIndex);
        //                sFile.FileOrder = FileIndex;
        //                MergeList.Add(sFile);
        //            }

        //            var MergeOrder = MergeList.OrderBy(s => s.FileOrder).ToList();
        //            var BaseFileName_ = Path.GetFileNameWithoutExtension(baseFileName);


        //            // using (ServerInfo.GrantFolderPermission svr = new ServerInfo.GrantFolderPermission("3330"))
        //            // {
        //            var path = Path.Combine(UploadPath_ + @"\", BaseFileName_ + Path.GetExtension(baseFileName));

        //            if (Path.GetExtension(baseFileName).ToLower() == ".docx")
        //            {
        //                path = Path.Combine(UploadPath_ + @"\", BaseFileName_ + @"\", Path.GetFileName(baseFileName));
        //                if (!Directory.Exists(UploadPath_ + @"\" + BaseFileName_)) Directory.CreateDirectory(UploadPath_ + @"\" + BaseFileName_);
        //            }
        //            else
        //            { if (!Directory.Exists(UploadPath_)) Directory.CreateDirectory(UploadPath_); }
        //            _finalFileName = path;
        //            using (FileStream FS = new FileStream(path, FileMode.Create))
        //            {
        //                foreach (var chunk in MergeOrder)
        //                {
        //                    try
        //                    {
        //                        using (FileStream fileChunk = new FileStream(chunk.FileName, FileMode.Open))
        //                        {
        //                            fileChunk.CopyTo(FS);
        //                        }
        //                        File.Delete(chunk.FileName);
        //                    }
        //                    catch (IOException ex)
        //                    {
        //                    }
        //                }
        //            }

        //            if (File.Exists(path))
        //            {
        //                if (Path.GetExtension(path).ToLower() == ".zip")
        //                {
        //                    using (ZipFile zip = ZipFile.Read(path))
        //                    {
        //                        zip.ExtractAll(Path.Combine(UploadPath_ + @"\", BaseFileName_), ExtractExistingFileAction.OverwriteSilently);
        //                    }
        //                }

        //                var stans = sparams.Split('`');
        //                DBContext _dbContext = new DBContext();
        //                BLDatamanipulation db = new BLDatamanipulation();
        //                for (int k = 0; k <= stans.Length - 1; k++)
        //                {

        //                    if (stans[k].Length > 1)
        //                    {
        //                        var filename = stans[k].Split(',')[0];
        //                        //trankey = stans[k].Split(',')[1];
        //                        string[] files = System.IO.Directory.GetFiles(UploadPath_ + @"/" + BaseFileName_, filename, SearchOption.AllDirectories);
        //                        if (files.Count() > 0)
        //                        {

        //                            Npgsql.NpgsqlParameter[] sParams = { new Npgsql.NpgsqlParameter("@trankey", trankey) };
        //                            //var dt = db.GetDataTable(_dbContext, "select a.*,b.lotkey from lot_transaction a left outer join lot_master b on a.lotid = b.lotid where transactionkey = @trankey and a.lotstatus in ('R','P','F')", sParams);

        //                            var dt = db.GetDataTable(_dbContext, "select lotstatus,lotid,pickedby,transactionid from lot_transaction where transactionkey in (select transactionkey from query_author_details where bookauthorkey = '" + trankey + "' and active = 1) and lotstatus = 'P'", null);

        //                            if (dt.Rows.Count > 0)
        //                            {
        //                                for (int i = 0; i <= dt.Rows.Count - 1; i++)
        //                                {
        //                                    ServerInfo servinfo = new ServerInfo();
        //                                    string serverpath = servinfo.GetServerPath(dt.Rows[i]["transactionid"].ToString(), true, "serverinfo");
        //                                    jobrevertback orderno = new jobrevertback();
        //                                    using (DBContext db1 = new DBContext())
        //                                    {

        //                                        var lotdetails = db1.Database.SqlQuery<jsonvalue>("select json_build_object('stagename_alias', jwm.stagename_alias, 'fromorder', jwm.stageorder, 'nextstage', jwm.nextstage, 'toorder', jwm1.stageorder )as json from lot_transaction lt left outer join job_workflow_master jwm on jwm.jobworkflowid = lt.jobworkflowid left outer join job_workflow_master jwm1 on jwm.nextstage = jwm1.jobworkflowid where lt.transactionid = @tranid", new Npgsql.NpgsqlParameter { ParameterName = "@tranid", Value = dt.Rows[i]["transactionid"].ToString() }).ToList();

        //                                        foreach (var item in lotdetails)
        //                                        {
        //                                            orderno = JsonConvert.DeserializeObject<jobrevertback>(item.json);
        //                                        }


        //                                    }
        //                                    //var usr_lot_tran_update = _dbContext.Database.SqlQuery<Int64>("select * from job_back_forwad(@p_tranid,@p_fromorder,@p_toorder,@p_option) as json",
        //                                    //new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = dt.Rows[i]["transactionid"].ToString() },
        //                                    //new Npgsql.NpgsqlParameter { ParameterName = "@p_fromorder", Value = 9 },
        //                                    //new Npgsql.NpgsqlParameter { ParameterName = "@p_toorder", Value = 5 },
        //                                    //new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "B" }).ToList();


        //                                    var usr_lot_tran_update = _dbContext.Database.SqlQuery<Int64>("select * from job_back_forwad(@p_tranid,@p_fromorder,@p_toorder,@p_option) as json",
        //                                new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = dt.Rows[i]["transactionid"].ToString() },
        //                                new Npgsql.NpgsqlParameter { ParameterName = "@p_fromorder", Value = orderno.fromorder },
        //                                new Npgsql.NpgsqlParameter { ParameterName = "@p_toorder", Value = orderno.toorder },
        //                                new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "W" }).ToList();

        //                                    using (ServerInfo.GrantFolderPermission svr = new ServerInfo.GrantFolderPermission(usr_lot_tran_update[0].ToString()))
        //                                    {
        //                                        string serverpath_ = servinfo.GetServerPath(usr_lot_tran_update[0].ToString(), true, "serverinfo");

        //                                        string vernfile = Directory.GetFiles(serverpath_ + @"\" + "OUT" + @"\", "*.docx", SearchOption.TopDirectoryOnly).FirstOrDefault();
        //                                        string destfile = Directory.GetFiles(serverpath_ + @"\" + "IN" + @"\", "*.docx", SearchOption.TopDirectoryOnly).FirstOrDefault();

        //                                        if (File.Exists(vernfile))
        //                                        {
        //                                            if (File.Exists(destfile))
        //                                            {
        //                                                string versiopath = getfolderName(System.IO.Path.Combine(serverpath_));
        //                                                System.IO.DirectoryInfo dirinfoinfold = new System.IO.DirectoryInfo(System.IO.Path.Combine(serverpath_, "IN"));
        //                                                foreach (System.IO.FileInfo fle in dirinfoinfold.GetFiles("*.*"))
        //                                                {
        //                                                    if (!fle.Name.ToString().ToLower().Contains("thumb.db"))
        //                                                        fle.MoveTo(System.IO.Path.Combine(versiopath, "IN", fle.Name));

        //                                                }
        //                                                System.IO.DirectoryInfo dirinfoout = new System.IO.DirectoryInfo(System.IO.Path.Combine(serverpath_, "OUT"));
        //                                                foreach (System.IO.FileInfo fle in dirinfoout.GetFiles("*.*"))
        //                                                {
        //                                                    if (!fle.Name.ToString().ToLower().Contains("thumb.db"))
        //                                                        fle.MoveTo(System.IO.Path.Combine(serverpath_, "IN", fle.Name));
        //                                                }
        //                                                System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(System.IO.Path.Combine(serverpath, "OUT"));
        //                                                foreach (System.IO.FileInfo fle in dirinfo.GetFiles("*.*"))
        //                                                {
        //                                                    if (!fle.Name.ToString().ToLower().Contains("thumb.db"))
        //                                                    {
        //                                                        fle.CopyTo(System.IO.Path.Combine(serverpath_, "IN", fle.Name), true);
        //                                                        //fle.CopyTo(System.IO.Path.Combine(nxtserverpath, "OUT", fle.Name), true);
        //                                                    }
        //                                                }
        //                                                //string versiopath = getfolderName(System.IO.Path.Combine(serverpath_));
        //                                                //string vpath = Path.Combine(serverpath_, versiopath);
        //                                                //if (!Directory.Exists(vpath))
        //                                                //    Directory.CreateDirectory(vpath);
        //                                                //File.Move(destfile, vpath);
        //                                            }
        //                                            // File.Copy(vernfile, destfile);
        //                                        }
        //                                        //string serverpath_prev_ = servinfo.GetServerPath(dt.Rows[i]["transactionid"].ToString(), false, "serverinfo");
        //                                        var destpath = Path.Combine(serverpath_, "IN");


        //                                        if (!Directory.Exists(destpath))
        //                                            Directory.CreateDirectory(destpath);

        //                                        if (File.Exists(destpath + @"/" + Path.GetFileName(files[0])))
        //                                            File.Delete(destpath + @"/" + Path.GetFileName(files[0]));

        //                                        File.Copy(files[0], destpath + @"/" + Path.GetFileName(files[0]));
        //                                        DashboardApiController dc = new DashboardApiController();
        //                                        dc.Postmail_SignOff(Convert.ToInt32(usr_lot_tran_update[0].ToString()), 0, "2", 0);
        //                                        dc.Postmail_PM(Convert.ToInt32(dt.Rows[i]["transactionid"].ToString()), "1");
        //                                        dc.Postmail_Ack(Convert.ToInt32(dt.Rows[i]["transactionid"].ToString()), "2");
        //                                        rslt = true;
        //                                        _returnmsg = "Successfully Uploaded";
        //                                    }
        //                                }
        //                            }
        //                            else
        //                            {
        //                                _returnmsg = "Already Completed the Job";
        //                            }
        //                        }
        //                        else
        //                        {
        //                            rslt = false;
        //                            _returnmsg = "File Validation failed: Incorrect file selected";
        //                        }
        //                    }
        //                }



        //            }
        //            else
        //            {
        //                _returnmsg = "Already Completed the Job";
        //                rslt = false;
        //            }

        //            // string hostName = Dns.GetHostName();
        //            // string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
        //            rslt = true;

        //            //}
        //        }
        //    }
        //    return rslt;
        //}

        //public bool MergeFile(string FileName, string UserID, string UploadPath_, string trankey, string TOC,string tranid)
        //{
        //    bool rslt = false;
        //    string partToken = ".part_";
        //    string baseFileName = FileName.Substring(0, FileName.IndexOf(partToken));
        //    string trailingTokens = FileName.Substring(FileName.IndexOf(partToken) + partToken.Length);
        //    int FileIndex = 0;
        //    int FileCount = 0;
        //    int.TryParse(trailingTokens.Substring(0, trailingTokens.IndexOf(".")), out FileIndex);
        //    int.TryParse(trailingTokens.Substring(trailingTokens.IndexOf(".") + 1), out FileCount);
        //    string Searchpattern = Path.GetFileName(baseFileName) + partToken + "*";
        //    string[] FilesList = Directory.GetFiles(Path.GetDirectoryName(FileName), Searchpattern);
        //    CommonRepository oCommonRepository = new CommonRepository();

        //    if (FilesList.Count() == FileCount)
        //    {
        //        //DBContext _dbContext = new DBContext();
        //        //BLDatamanipulation db = new BLDatamanipulation();
        //        var data = new { trankey = trankey, p_option = "getmergedfilelotstatus", transid = tranid };
        //        var jsonstr = JsonConvert.SerializeObject(data);
        //        var list = oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", jsonstr);

        //        if (list == null)
        //        {
        //            rslt = false; _returnmsg = "Already Completed the Job";
        //            return rslt;
        //        }
        //        var i1 = JsonConvert.DeserializeObject<object>(list.ToString());
        //        JArray a1 = JArray.Parse(i1.ToString());
        //        JObject obj1 = JObject.Parse(a1[0].ToString());
        //        try
        //        {
        //            if (obj1["lotid"].ToString() != "")
        //            {
        //                var data1 = new { lotid = obj1["lotid"].ToString(), title = Path.GetFileNameWithoutExtension(baseFileName).ToString(), p_option = "getmergedfilename" };
        //                var jsonstr1 = JsonConvert.SerializeObject(data1);
        //                var list1 = oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", jsonstr1);                      
        //                if (list1  == null)
        //                {
        //                    rslt = false; _returnmsg = "Please use the same file that we sent and make amendments and upload the same.";
        //                    return rslt;
        //                }
        //            }
        //            else if (obj1["batchid"].ToString() != "")
        //            {
        //                var data1 = new { jobworkflowid = obj1["jobworkflowid"].ToString() , p_option = "getstagename" };
        //                var jsonstr1 = JsonConvert.SerializeObject(data1);
        //                var list1 = oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", jsonstr1);                       
        //                if (list1 == null)
        //                {
        //                    rslt = false; _returnmsg = "Please use the same file that we sent and make amendments and upload the same.";
        //                    return rslt;
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {

        //        }

        //        UploadPath_ = "";
        //       // ServerInfo servinfo = new ServerInfo();
        //        string serverpath = oCommonRepository.GetServerPath(obj1["transactionid"].ToString(), "serverinfo", true);
        //        try
        //        {


        //            if (!MergeFileManager.Instance.InUse(baseFileName))
        //            {
        //                MergeFileManager.Instance.AddFile(baseFileName);
        //                if (File.Exists(baseFileName))
        //                    File.Delete(baseFileName);
        //                MergeFileManager.Instance.RemoveFile(baseFileName);

        //                List<SortedFile> MergeList = new List<SortedFile>();
        //                foreach (string File1 in FilesList)
        //                {
        //                    SortedFile sFile = new SortedFile();
        //                    sFile.FileName = File1;
        //                    baseFileName = File1.Substring(0, File1.IndexOf(partToken));
        //                    trailingTokens = File1.Substring(File1.IndexOf(partToken) + partToken.Length);
        //                    int.TryParse(trailingTokens.Substring(0, trailingTokens.IndexOf(".")), out FileIndex);
        //                    sFile.FileOrder = FileIndex;
        //                    MergeList.Add(sFile);
        //                }

        //                var MergeOrder = MergeList.OrderBy(s => s.FileOrder).ToList();

        //                if (Path.GetExtension(baseFileName).ToLower() == ".zip")
        //                {

        //                    var BaseFileName_ = Path.GetFileNameWithoutExtension(baseFileName);
        //                    UploadPath_ = Path.Combine(serverpath, "TEMP");

        //                 //   using (ServerInfo.GrantFolderPermission svr = new ServerInfo.GrantFolderPermission("", "", dt.Rows[0]["jobid"].ToString()))
        //                 //   {
        //                        if (!Directory.Exists(UploadPath_)) Directory.CreateDirectory(UploadPath_);
        //                        var path = Path.Combine(UploadPath_ + @"\", BaseFileName_ + Path.GetExtension(baseFileName));
        //                        _finalFileName = path;
        //                        using (FileStream FS = new FileStream(path, FileMode.Create))
        //                        {
        //                            foreach (var chunk in MergeOrder)
        //                            {
        //                                try
        //                                {
        //                                    using (FileStream fileChunk = new FileStream(chunk.FileName, FileMode.Open))
        //                                    {
        //                                        fileChunk.CopyTo(FS);
        //                                    }
        //                                    File.Delete(chunk.FileName);
        //                                }
        //                                catch (IOException ex)
        //                                {
        //                                }
        //                            }
        //                        }

        //                        if (File.Exists(path))
        //                        {
        //                            if (Path.GetExtension(path).ToLower() == ".zip")
        //                            {
        //                            System.IO.Compression.ZipFile.ExtractToDirectory(path, Path.Combine(UploadPath_ + @"\", BaseFileName_), true);
        //                            //using (ZipFile zip = ZipFile.Read(path))
        //                            //{
        //                            //    zip.ExtractAll(Path.Combine(UploadPath_ + @"\", BaseFileName_), ExtractExistingFileAction.OverwriteSilently);
        //                            //}
        //                        }
        //                        string current_stageid = "";
        //                        var data2 = new { jobworkflowid = obj1["jobworkflowid"].ToString(),   p_option = "getmergedservicestageid" };
        //                        var jsonstr2 = JsonConvert.SerializeObject(data2);
        //                        var list2 = oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", jsonstr2);

        //                        var i_stageid = JsonConvert.DeserializeObject<object>(list2.ToString());
        //                        JArray a_stageid = JArray.Parse(i_stageid.ToString());
        //                        JObject obj_stageid = JObject.Parse(a_stageid[0].ToString());
        //                        current_stageid = obj_stageid["stageid"].ToString();                               

        //                            if (Convert.ToInt64(current_stageid) == Convert.ToInt64(Startup.Configuration.GetValue<string>("AppSettings:ce_stage_id").ToString()))
        //                            {
        //                            #region commented
        //                            /* If the file stage is not Copy-Editing stage then copy the IN folder files to OUT and then copy the uploaded files */

        //                            //string art_foldername = ConfigurationManager.AppSettings["art_foldername"].ToString();
        //                            //string artpdf_foldername = ConfigurationManager.AppSettings["artpdf_foldername"].ToString();

        //                            //string serverpath_prev_ = servinfo.GetServerPath(dt.Rows[0]["transactionid"].ToString(), false, "serverinfo");
        //                            //var inpath = Path.Combine(serverpath_prev_, "IN");
        //                            //var destpath = Path.Combine(serverpath_prev_, "OUT");

        //                            ///* Validate the .docx in file and upload file for file size i.e upload docx size must greater than IN docx size */
        //                            //FileInfo fin = new FileInfo(Directory.GetFiles(inpath, "*.docx", SearchOption.TopDirectoryOnly).FirstOrDefault());
        //                            //FileInfo fupl = new FileInfo(Directory.GetFiles(Path.Combine(UploadPath_, BaseFileName_), "*.docx", SearchOption.TopDirectoryOnly).FirstOrDefault());

        //                            //if (fupl.Length != fin.Length)
        //                            //{
        //                            //    /* get the ART folder files and Other folder files and copy to OUT folder */
        //                            //    string[] indirs = Directory.GetDirectories(inpath, "*.*", SearchOption.TopDirectoryOnly).ToArray();

        //                            //    foreach (string ind in indirs)
        //                            //    {
        //                            //        if (!Directory.Exists(Path.Combine(destpath, Path.GetFileName(ind))))
        //                            //        {
        //                            //            Directory.CreateDirectory(Path.Combine(destpath, Path.GetFileName(ind)));
        //                            //        }

        //                            //        foreach (string f in Directory.GetFiles(ind, "*.*", SearchOption.TopDirectoryOnly))
        //                            //        {
        //                            //            File.Copy(f, Path.Combine(destpath, Path.GetFileName(ind), Path.GetFileName(f)), true);
        //                            //        }
        //                            //    }

        //                            //    string files = System.IO.Directory.GetFiles(Path.Combine(UploadPath_, BaseFileName_), "*.docx", SearchOption.TopDirectoryOnly).FirstOrDefault();

        //                            //    string dirs = System.IO.Directory.GetDirectories(Path.Combine(UploadPath_, BaseFileName_), "*.*", SearchOption.TopDirectoryOnly).FirstOrDefault();

        //                            //    if (!string.IsNullOrEmpty(files))
        //                            //    {

        //                            //        if (File.Exists(destpath + @"/" + Path.GetFileName(files)))
        //                            //            File.Delete(destpath + @"/" + Path.GetFileName(files));
        //                            //        File.Copy(files, destpath + @"/" + Path.GetFileName(files));

        //                            //        if (!string.IsNullOrEmpty(dirs) && dirs.ToString().ToLower().Contains(artpdf_foldername.ToLower()))
        //                            //        {
        //                            //            CopyDirectory(dirs, Path.Combine(destpath, art_foldername, Path.GetFileName(dirs)));
        //                            //        }

        //                            //        var cFlag = "A";
        //                            //        if (dt.Rows[0]["movebackstage"].ToString() != "")
        //                            //            cFlag = "F";

        //                            //        var fields = new Fields();
        //                            //        long userId_t = Convert.ToInt64((HttpContext.Current.Session["UserID"] as string));
        //                            //        WorkAreaApiController wb = new WorkAreaApiController();
        //                            //        fields.cflag = cFlag;
        //                            //        fields.comment = "";
        //                            //        fields.fields = "";
        //                            //        fields.option = "checkout";
        //                            //        fields.userid = dt.Rows[0]["pickedby"].ToString();
        //                            //        fields.transid = Convert.ToInt32(dt.Rows[0]["transactionid"].ToString());
        //                            //        wb.PostUpdatelot_transaction(fields);

        //                            //        rslt = true;
        //                            //        _returnmsg = "Successfully Uploaded";
        //                            //    }
        //                            //    else
        //                            //    {
        //                            //        rslt = false;
        //                            //        _returnmsg = "File Validation failed: Incorrect file selected";
        //                            //    }
        //                            //}
        //                            //else
        //                            //{
        //                            //    rslt = false;
        //                            //    foreach (string t in Directory.GetFiles(Path.Combine(UploadPath_ + @"\", BaseFileName_), "*.*", SearchOption.AllDirectories))
        //                            //    {
        //                            //        File.Delete(t);
        //                            //    }
        //                            //    foreach (string t in Directory.GetDirectories(Path.Combine(UploadPath_ + @"\", BaseFileName_), "*.*", SearchOption.AllDirectories))
        //                            //    {
        //                            //        Directory.Delete(t);
        //                            //    }
        //                            //    Directory.Delete(Path.Combine(UploadPath_ + @"\", BaseFileName_));
        //                            //    File.Delete(path);
        //                            //    _returnmsg = "File Validation failed: No updates made in .docx file";
        //                            //}
        //                            #endregion commented

        //                        }
        //                        else
        //                            {
        //                                WorkAreaApiController wb = new WorkAreaApiController(_requestClient);

        //                            #region commented

        //                            //string project_defid = db.GetDataTable(_dbContext, @"select projectdefinitionid from job_master where jobid = '"
        //                            //                                                           + dt.Rows[0]["jobid"].ToString() + "' ", null).Rows[0][0].ToString();

        //                            //string indexmode = db.GetDataTable(_dbContext, @"select indexmode from job_master where jobid = '" + dt.Rows[0]["jobid"].ToString() + "' ", null).Rows[0][0].ToString();


        //                            //if (Convert.ToInt64(project_defid) == Convert.ToInt64(ConfigurationManager.AppSettings["tandf_project_defid"].ToString())
        //                            //    && Convert.ToInt64(current_stageid) == Convert.ToInt64(ConfigurationManager.AppSettings["author_stage_id"].ToString()))
        //                            //{
        //                            //    if (indexmode == ConfigurationManager.AppSettings["indexmode"].ToString())
        //                            //    {
        //                            //        /* If the project is T&F and stage is Author then check for whether Index file(.docx) is uploaded or not. 
        //                            //        First check index mode from job master for whether Index stage in Inhouse/Author processing */

        //                            //        string index_compilation_jobworkflowid = db.GetDataTable(_dbContext, @"select jw.jobworkflowid from job_workflow_master jw
        //                            //                                                                       where jw.jobid = " + dt.Rows[0]["jobid"].ToString()
        //                            //                                                                      + @" and jw.stageid = " + ConfigurationManager.AppSettings["index_compilation_stage_id"].ToString()
        //                            //                                                                      , null).Rows[0][0].ToString();

        //                            //        string checkqry = @"select count(transactionid) from lot_transaction where jobworkflowid in (" + index_compilation_jobworkflowid + ") and lotstatus = 'C' ";

        //                            //        if (Convert.ToInt32(db.GetDataTable(_dbContext, checkqry, null).Rows[0][0]) == 0)
        //                            //        {
        //                            //            string indexfile = string.Empty;

        //                            //            if (Directory.GetFiles(Path.Combine(UploadPath_, BaseFileName_), "*.docx", SearchOption.TopDirectoryOnly).Any())
        //                            //            {
        //                            //                indexfile = Directory.GetFiles(Path.Combine(UploadPath_, BaseFileName_), "*.docx", SearchOption.TopDirectoryOnly).FirstOrDefault();
        //                            //            }
        //                            //            else
        //                            //            {
        //                            //                string serverjobpath = servinfo.GetServerPath(dt.Rows[0]["jobid"].ToString(), false, "serverinfo_job");
        //                            //                string indexfilepath = Path.Combine(serverjobpath, ConfigurationManager.AppSettings["parent_foldername"].ToString(),
        //                            //                                ConfigurationManager.AppSettings["author_index_foldername"].ToString());

        //                            //                if (Directory.Exists(indexfilepath) && Directory.GetFiles(indexfilepath, "*.docx", SearchOption.TopDirectoryOnly).Any())
        //                            //                {
        //                            //                    indexfile = Directory.GetFiles(indexfilepath, "*.docx", SearchOption.TopDirectoryOnly).FirstOrDefault();
        //                            //                }
        //                            //                else
        //                            //                {
        //                            //                    rslt = false;
        //                            //                    _returnmsg = "Index word file is missing, include the index file in the zip file and then upload.";
        //                            //                    return rslt;
        //                            //                }
        //                            //            }

        //                            //            if (!string.IsNullOrEmpty(indexfile) && File.Exists(indexfile))
        //                            //            {



        //                            //                int index_transactionid = wb.InsertBatchTrasaction(dt.Rows[0]["batchid"].ToString(), index_compilation_jobworkflowid, "", "");

        //                            //                using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission("", "", dt.Rows[0]["jobid"].ToString()))
        //                            //                {
        //                            //                    string index_compilation_path = servinfo.GetServerPath(index_transactionid.ToString(), true, "serverinfo");

        //                            //                    if (!Directory.Exists(Path.Combine(index_compilation_path, "IN")))
        //                            //                    {
        //                            //                        Directory.CreateDirectory(Path.Combine(index_compilation_path, "IN", Path.GetFileName(indexfile)));
        //                            //                    }
        //                            //                    File.Copy(indexfile, Path.Combine(index_compilation_path, "IN", Path.GetFileName(indexfile)), true);

        //                            //                }
        //                            //            }
        //                            //            else
        //                            //            {
        //                            //                rslt = false;
        //                            //                _returnmsg = "Index word file is missing, include the index file in the zip file and then upload.";
        //                            //                return rslt;
        //                            //            }
        //                            //        }
        //                            //    }
        //                            //    else if (string.IsNullOrEmpty(indexmode))
        //                            //    {
        //                            //        if (Directory.GetFiles(Path.Combine(UploadPath_, BaseFileName_), "*.docx", SearchOption.TopDirectoryOnly).Any())
        //                            //        {
        //                            //            string indexfile = Directory.GetFiles(Path.Combine(UploadPath_, BaseFileName_), "*.docx", SearchOption.TopDirectoryOnly).FirstOrDefault();

        //                            //            if (File.Exists(indexfile))
        //                            //            {
        //                            //                string serverjobpath = servinfo.GetServerPath(dt.Rows[0]["jobid"].ToString(), false, "serverinfo_job");
        //                            //                string indexfilepath = Path.Combine(serverjobpath, ConfigurationManager.AppSettings["parent_foldername"].ToString(),
        //                            //                                ConfigurationManager.AppSettings["author_index_foldername"].ToString());
        //                            //                if (!Directory.Exists(indexfilepath))
        //                            //                {
        //                            //                    Directory.CreateDirectory(indexfilepath);
        //                            //                }
        //                            //                File.Copy(indexfile, Path.Combine(indexfilepath, Path.GetFileName(indexfile)), true);
        //                            //            }
        //                            //        }
        //                            //    }
        //                            //}

        //                            #endregion commented
        //                            /* If the file stage is not Copy-Editing stage then all files must be loaded into the OUT path */

        //                            string[] files = System.IO.Directory.GetFiles(Path.Combine(UploadPath_, BaseFileName_), "*.*", SearchOption.TopDirectoryOnly)
        //                                               .Where(x => Path.GetExtension(x.ToString()).ToLower() != ".zip").ToArray();

        //                                string[] dirs = System.IO.Directory.GetDirectories(Path.Combine(UploadPath_, BaseFileName_), "*.*", SearchOption.TopDirectoryOnly).ToArray();

        //                                if (files.Count() > 0)
        //                                {

        //                                string serverpath_prev_ = oCommonRepository.GetServerPath(obj1["transactionid"].ToString(), "serverinfo", true);// servinfo.GetServerPath(dt.Rows[0]["transactionid"].ToString(), false, "serverinfo");
        //                                    var destpath = Path.Combine(serverpath_prev_, "OUT");

        //                                    //string[] files_pdf = System.IO.Directory.GetFiles(Path.Combine(serverpath_prev_, "IN"), "*.pdf", SearchOption.AllDirectories);


        //                                    //if (File.Exists(destpath + @"/" + Path.GetFileName(files[0])))
        //                                    //    File.Delete(destpath + @"/" + Path.GetFileName(files[0]));
        //                                    //File.Copy(files[0], destpath + @"/" + Path.GetFileName(files[0]));

        //                                    for (int i = 0; i < files.Length; i++)
        //                                    {
        //                                        if (File.Exists(destpath + @"/" + Path.GetFileName(files[i])))
        //                                            File.Delete(destpath + @"/" + Path.GetFileName(files[i]));
        //                                        File.Copy(files[i], destpath + @"/" + Path.GetFileName(files[i]));
        //                                    }

        //                                    foreach (string dir in dirs)
        //                                    {
        //                                        CopyDirectory(dir, Path.Combine(destpath, Path.GetFileName(dir)));
        //                                    }

        //                                //if (files_pdf.Count() > 0)
        //                                //    {
        //                                //        if (File.Exists(destpath + @"/" + Path.GetFileName(files_pdf[0])))
        //                                //            File.Delete(destpath + @"/" + Path.GetFileName(files_pdf[0]));
        //                                //        File.Copy(files_pdf[0], destpath + @"/" + Path.GetFileName(files_pdf[0]));
        //                                //    }

        //                                //var cFlag = "A";
        //                                //if (obj1["movebackstage"].ToString() != "")
        //                                //    cFlag = "F";

        //                                var cFlag = "A";
        //                                if (obj1["movebackstage"].ToString() != "0")
        //                                    cFlag = "F";

        //                                var fields = new Fields();
        //                                    long userId_t = Convert.ToInt64(UserID);

        //                                    fields.cflag = cFlag;
        //                                    fields.comment = "";
        //                                    fields.fields = "";
        //                                    fields.option = "checkout";
        //                                    fields.userid = obj1["pickedby"].ToString();
        //                                    fields.transid = Convert.ToInt32(obj1["transactionid"].ToString());
        //                                    wb.PostUpdatelot_transaction(fields);

        //                                    rslt = true;
        //                                    _returnmsg = "Successfully Uploaded";

        //                                }
        //                                else
        //                                {
        //                                    rslt = false;
        //                                    _returnmsg = "File Validation failed: Incorrect file selected";
        //                                }
        //                            }
        //                        }
        //                        else
        //                        {
        //                            _returnmsg = "Already Completed the Job";
        //                            rslt = false;
        //                        }

        //                        rslt = true;
        //                  //  }

        //                }
        //                else
        //                {
        //                    _returnmsg = "Kindly upload zip file only";
        //                    rslt = false;
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {

        //        }
        //    }
        //    return rslt;
        //}

        public bool validatefile(string zipfilename, string serverpath, string lotkey)
        {
            bool idflag = false;
            if (System.IO.Path.GetExtension(zipfilename).ToLower() == ".docm" || System.IO.Path.GetExtension(zipfilename).ToLower() == ".docx")
            {
                Directory.CreateDirectory(serverpath + "\\OUT\\TEMP");
                using (Ionic.Zip.ZipFile Zip = new Ionic.Zip.ZipFile(zipfilename))
                {
                    Zip.ExtractExistingFile = Ionic.Zip.ExtractExistingFileAction.OverwriteSilently;
                    Zip.ExtractAll(serverpath + "\\OUT\\TEMP");
                }
                try
                {

                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.Load(serverpath + @"\OUT\TEMP\customUI\customUI.XML");


                    foreach (System.Xml.XmlNode node in doc.SelectNodes("//*"))
                    {
                        if (node.Name == "tab" && node.Attributes["id"] != null)
                        {
                            if (node.Attributes["id"].Value.Contains(lotkey))
                            {
                                idflag = true;
                                break;
                            }
                        }
                    }
                    doc = null;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message.ToString()); //returnobj = new returnojb { ErrorObject = ex.Message.ToString(), isProcessSuccess = false }; goto endproce; 
                }
                finally
                {
                    Directory.Delete(serverpath + "\\OUT\\TEMP", true);
                }
            }
            return idflag;
        }

        public void FileCopyed(string sourcefile, string destFile)
        {
            string[] files = Directory.GetFiles(sourcefile, "*.*", SearchOption.AllDirectories);
            foreach (var item in files)
            {
                if (File.Exists(destFile + @"/" + Path.GetFileName(item)))
                    File.Delete(destFile + @"/" + Path.GetFileName(item));

                File.Copy(item, destFile + @"/" + Path.GetFileName(item), true);
            }
        }

        //public object getInputPDFfile(string tranid, string Extn)
        //{
        //    returnojb tmp = new returnojb();
        //    try
        //    {
        //        // DBContext db = new DBContext();
        //        List<NpgsqlParameter> parametr = new List<NpgsqlParameter>();
        //        parametr.Add(new NpgsqlParameter { ParameterName = "p_userid", NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Varchar, Value = Extn });
        //        parametr.Add(new NpgsqlParameter { ParameterName = "p_tranid", NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Integer, Value = tranid });
        //        parametr.Add(new NpgsqlParameter { ParameterName = "p_option", NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Varchar, Value = "getInputFileName" });

        //        DBContext db = new DBContext();
        //        var getReportJobDetails = db.Database.SqlQuery<jsonvalue>("select * from  usr_stage_move(@p_userid,@p_tranid,@p_option) as json",
        //        new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = Extn },
        //        new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = tranid },
        //        new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "getInputFileName" }).ToList();
        //        var json = new List<object>();

        //        foreach (var item in getReportJobDetails)
        //        {
        //            json.Add(JObject.Parse(item.json));
        //        }

        //        return json;

        //        //string json = db.getdataJson("usr_stage_move", parametr);
        //        //tmp = Newtonsoft.Json.JsonConvert.DeserializeObject<returnojb>(json);
        //        // return tmp.path;
        //    }
        //    catch (Exception ex)
        //    {
        //        //tmp = new returnojb { ErrorObject = ex.Message.ToString(), isProcessSuccess = false };
        //    }
        //    JavaScriptSerializer serializer = new JavaScriptSerializer();
        //    return serializer.Serialize(tmp);
        //}

        private string getfolderName(string pathfold)
        {
            try
            {
                int i = 1;
                rechck:;
                if (Directory.Exists(string.Join("", pathfold, "\\V", i.ToString("000"))))
                {
                    i++;
                    goto rechck;
                }
                else
                {
                    Directory.CreateDirectory(string.Join("", pathfold, "\\V", i.ToString("000")) + "\\IN");
                    Directory.CreateDirectory(string.Join("", pathfold, "\\V", i.ToString("000")) + "\\OUT");
                    return pathfold + "\\V" + i.ToString("000");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return pathfold;
            }
        }

        public static string CopyDirectory(string sourceDir, string destinationDirc)
        {
            string Name = "";
            DirectoryInfo source = new DirectoryInfo(sourceDir);
            DirectoryInfo destination = new DirectoryInfo(destinationDirc);
            if (!destination.Exists)
            {
                destination.Create();
            }
            if (!source.Exists)
            {
                return "erorr";
            }
            FileInfo[] files = source.GetFiles();
            foreach (FileInfo file in files)
            {
                if (file.Name.ToLower().Trim() != "thumbs.db")
                {
                    Name = file.Name;
                    string Dest = System.IO.Path.Combine(destination.FullName, file.Name);
                    if (System.IO.File.Exists(Dest))
                    {
                        System.IO.File.Delete(Dest);
                    }
                    if (!System.IO.File.Exists(Dest))
                    {
                        file.CopyTo(Dest, true);
                    }
                }
            }
            DirectoryInfo[] dirs = source.GetDirectories();
            foreach (DirectoryInfo dir in dirs)
            {
                string destinationDir = System.IO.Path.Combine(destination.FullName, dir.Name);
                string destinationDir1 = dir.FullName;
                CopyDirectory(destinationDir1, destinationDir);
            }
            return Name;
        }


        public class returnojb
        {
            public string path { set; get; }
        }
        public class jobrevertback
        {
            public string stagename_alias { get; set; }
            public Int64 fromorder { get; set; }
            public Int64 toorder { get; set; }
            public Int32 nextstage { get; set; }
        }



    }

    public struct SortedFile
    {
        public int FileOrder { get; set; }
        public String FileName { get; set; }
    }


    public class MergeFileManager
    {
        private static MergeFileManager instance;
        private List<string> MergeFileList;

        private MergeFileManager()
        {
            try
            {
                MergeFileList = new List<string>();
            }
            catch { }
        }

        public static MergeFileManager Instance
        {
            get
            {
                if (instance == null)
                    instance = new MergeFileManager();
                return instance;
            }
        }

        public void AddFile(string BaseFileName)
        {
            MergeFileList.Add(BaseFileName);
        }

        public bool InUse(string BaseFileName)
        {
            return MergeFileList.Contains(BaseFileName);
        }

        public bool RemoveFile(string BaseFileName)
        {
            return MergeFileList.Remove(BaseFileName);
        }



    }
}
