using Dapper;
using LAPS_IOService.Models;
using LAPS_WATCHER;
using LAPS_WATCHER.App_Data;
using LAPS_WATCHER.Configure;
using LAPS_WATCHER.Models;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//using Npgsql;
using RestSharp;
using SimpleImpersonation;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using RequestService.Models;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Xml;
using System.IO.Compression;

namespace RequestService.KLI_IOService
{
    class kli_ioservice
    {
        public static string fileName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\Log.txt";

        CommonRepository oCommonRepository = new CommonRepository();
        
        public static void call_kli_ioservice(string args)
        {
            ServerInfo svrinfo = new ServerInfo();
            try
            {
                if (args != null)
                {
                    if (args.Count() >= 1)
                    {
                        CommonClass.WriteLog("LAP2 Service Started", "Main");

                        Console.WriteLine("===================LAP2 Service Started======================");
                        CommonClass.WriteLog("args: " + args, "Main");
                        var str = args.Split(',');
                        string tranid = str[0];
                        string userid = str[1];
                        string inpath = str[2];
                        string outpath = str[3];
                        var environment = str[4];
                        string appType = str[5];
                        string flag = str[6];
                        string comment = str[7];
                        CommonClass.WriteLog("tranid" + tranid, "Main");
                        eGlob.Environment = environment;
                        CommonClass.WriteLog(environment, "environment");

                        var transdata = new { transactionid = tranid };
                        var jsonstr = JsonConvert.SerializeObject(transdata);
                        var returnres = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", jsonstr, "getdetailsbytranid");
                        if (returnres != null)
                        {
                            try
                            {
                                var i_appType = JsonConvert.DeserializeObject<object>(returnres.ToString());
                                JArray BatchLotDetails2 = JArray.Parse(i_appType.ToString());
                                JObject obj = JObject.Parse(BatchLotDetails2[0].ToString());
                                Console.WriteLine("Job ID: " + obj["jobid"].ToString());
                                Console.WriteLine("Jobworkflow ID: " + obj["jobworkflowid"].ToString());
                                Console.WriteLine("Stage Name: " + obj["stagename_alias"].ToString());
                                Console.WriteLine("Stage ID: " + obj["stageid"].ToString());
                                Console.WriteLine("Lot ID: " + obj["lotid"].ToString());
                                Console.WriteLine("Batch ID: " + obj["batchid"].ToString());
                                Console.WriteLine("Next Stage Jobwobworflowdefid: " + obj["nextstage"].ToString());
                                Console.WriteLine("Transaction ID: " + tranid);
                                Console.WriteLine("User ID: " + userid);
                                Console.WriteLine("Environment Value: " + environment);
                                Console.WriteLine("App Type: " + appType);
                                Console.WriteLine("flag: " + flag);
                                Console.WriteLine("queryraised: " + obj["queryraised"].ToString());

                                Console.WriteLine(Environment.NewLine);

                                ServerInfo servinfo = new ServerInfo();
                                //* ************(Watcher - Checkout ) MS_Preparation ********** */
                                if (obj["stagename_alias"].ToString() == CustomConfiguration.AppSettings["MS_Preparation"].ToString())
                                {
                                    try
                                    {
                                        Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- ioservice starts");
                                        Console.WriteLine("KLI:appType" + appType);
                                        //if (appType.Equals("checkin_apps"))
                                        //{
                                        //    Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + " checkin_apps starts...");
                                        //    string isauthormsreview = string.Empty;
                                        //    var inputdata = new { transactionid = tranid };
                                        //    var inputjson = JsonConvert.SerializeObject(inputdata);
                                        //    var authorreviewres = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", inputjson, "getdetailsbytranid");
                                        //    if (authorreviewres != null)
                                        //    {
                                        //        try
                                        //        {
                                        //            var i = JsonConvert.DeserializeObject<object>(authorreviewres.ToString());
                                        //            JArray jarr = JArray.Parse(i.ToString());
                                        //            JObject authorreviewobj = JObject.Parse(jarr[0].ToString());
                                        //            isauthormsreview = authorreviewobj["isauthormsreview"].ToString();
                                        //            Console.WriteLine("LAPS2 App Watcher:author ms review status:" + isauthormsreview);
                                        //            if (isauthormsreview.ToLower() == "false")
                                        //            {
                                        //                #region APICalls
                                        //                //Code to Call API's
                                        //                //Calling CDBAPI
                                        //                var urlcdb = CustomConfiguration.AppSettings["CM_Approval"].ToString() +"orchestration/api/CdbApi/Author_MS_Review";
                                        //                Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:URL:--->" + urlcdb);
                                        //                IRestResponse responseResultCDB = CallCDBAPI(urlcdb, tranid, userid);
                                        //                Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:" + responseResultCDB.Content.ToString());
                                        //                #endregion
                                        //                if (responseResultCDB.StatusCode.ToString() == "OK")
                                        //                {
                                        //                    //upodate review status in lot transaction table 
                                        //                    Console.WriteLine("LAPS2 App Watcher:to update author ms review status starts:" + tranid);
                                        //                    var i_data = new { transid = tranid, p_option = "updateauthormsreview" };
                                        //                    var i_json = JsonConvert.SerializeObject(i_data);
                                        //                    var _input = JsonConvert.SerializeObject(i_json);
                                        //                    var i_result = CommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", _input);
                                        //                    if (i_result != null)
                                        //                    {
                                        //                        Console.WriteLine("LAPS2 App Watcher:to update author ms review status ends:" + tranid);
                                        //                    }
                                        //                }
                                        //            }

                                        //        }
                                        //        catch (Exception ex)
                                        //        {
                                        //            Console.WriteLine("MSPre:Error in checkin_apps" + ex.Message);
                                        //        }
                                        //    }

                                        //}
                                        //else if (appType.Equals("checkout_apps"))
                                        //{

                                        Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- checkout_apps");
                                        string jobid = obj["jobid"].ToString();

                                        if (obj["isnochange"].ToString() == "False")
                                        {
                                            #region File Movement

                                            var next_tranid = GetNextTranId(obj["jobid"].ToString(), obj["lotid"].ToString(), CustomConfiguration.AppSettings["CM_Review"].ToString());

                                            FileMovement(tranid, next_tranid);


                                            Console.WriteLine("File movement ends");
                                            #endregion

                                        }

                                        // to move directly to CM review stage for MS Preperation
                                        if (obj["isnochange"].ToString() == "True")
                                        {




                                            Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "-no change ioservice starts");
                                            // string jobid = obj["jobid"].ToString();
                                            string nextstage = obj["nextstage"].ToString();
                                            string serverinpath_tranid = string.Empty, serverpath_input = string.Empty; int next_tranid = 0; int batchid = 0;
                                            int CM_Review_tranid = 0;
                                            var data = new { transactionid = tranid };
                                            var input = JsonConvert.SerializeObject(data);
                                            var translist = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getbytransactionid");
                                            var dt = JArray.Parse(translist.ToString());
                                            var objlotrans = JObject.Parse(dt[0].ToString());
                                            if (objlotrans["lotstatus"].ToString().Trim() == "C")
                                            {
                                                var nexttrandata = new { jobid = jobid };
                                                var nexttrandata_jsonstr = JsonConvert.SerializeObject(nexttrandata);
                                                var res = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", nexttrandata_jsonstr, "getdetailsbyjobid");
                                                var a1 = JsonConvert.DeserializeObject<object>(res.ToString());
                                                JArray b = JArray.Parse(a1.ToString());

                                                var CM_Review = b.Where(c => c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CM_Review"].ToString() && c["lotid"].ToString() == obj["lotid"].ToString());
                                                if (CM_Review.Count() != 0)
                                                {
                                                    foreach (var rw1 in CM_Review)
                                                    {
                                                        CM_Review_tranid = Convert.ToInt32(rw1["transactionid"].ToString());
                                                    }
                                                }
                                                Console.WriteLine("KLI to get the GE Review stage id:" + CM_Review_tranid);
                                                var data1 = new { tranid = CM_Review_tranid, fromorder = 3, toorder = 4, option = "F" };
                                                Console.WriteLine("KLI calling the spjobbackforwardfromworkarea - function:" + data1.ToString());

                                                string serverpath_tranid = servinfo.GetServerPath(tranid, "serverinfo", false);
                                                serverinpath_tranid = Path.Combine(serverpath_tranid, CustomConfiguration.AppSettings["ServerOUTPATH"].ToString());
                                                int jobMoveForward = CommonRepository.ExecuteSP_ReturnInt("spjobbackforwardfromworkarea", data1, "jobForward", null);
                                                if (jobMoveForward > 0)
                                                {
                                                    var transdata1 = new { jobid = jobid };
                                                    var jsonstr1 = JsonConvert.SerializeObject(transdata1);
                                                    var returnres1 = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", jsonstr1, "getdetailsbyjobid");
                                                    var i_appType1 = JsonConvert.DeserializeObject<object>(returnres1.ToString());
                                                    JArray lottransdetails1 = JArray.Parse(i_appType1.ToString());
                                                    var batchdts = lottransdetails1.Where(c => c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CM_Approval"].ToString());
                                                    //get batch id
                                                    if (batchdts.Count() != 0)
                                                    {
                                                        int cmapprovaltranid = 0;

                                                        var a = lottransdetails1.Where(c =>
                                                        (c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CM_Approval"].ToString()) && c["lotstatus"].ToString() != "W").FirstOrDefault();
                                                        if (a != null && a.Count() != 0)
                                                        {
                                                            cmapprovaltranid = Convert.ToInt32(a["transactionid"].ToString());
                                                        }
                                                        Console.WriteLine("IOService:cmapprovaltranid:--->" + cmapprovaltranid);
                                                        foreach (var rw in batchdts)
                                                        {
                                                            Console.WriteLine("IOService:rw:--->" + rw);
                                                            batchid = Convert.ToInt32(rw["batchid"].ToString());
                                                            next_tranid = Convert.ToInt32(rw["transactionid"].ToString());

                                                            if (cmapprovaltranid != 0 && cmapprovaltranid != next_tranid)
                                                            {
                                                                var trandata1 = new { p_tranid = next_tranid };
                                                                var transresult1 = CommonRepository.ExecuteSP_ReturnInt("splottransaction", trandata1, "delete", "Üpdate lottrans");
                                                            }

                                                        }
                                                        var checkout = getCheckoutBatch(obj["lotid"].ToString(), batchid.ToString(), userid, "R", "checkout_lotbatch", "0", "");
                                                        if (cmapprovaltranid != 0)
                                                        {
                                                            next_tranid = cmapprovaltranid;
                                                        }
                                                        var data2 = new { transactionid = next_tranid };
                                                        var input2 = JsonConvert.SerializeObject(data2);
                                                        var translist2 = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input2, "getbytransactionid");
                                                        var dt2 = JArray.Parse(translist2.ToString());
                                                        var objlotrans2 = JObject.Parse(dt2[0].ToString());
                                                        if (objlotrans2["lotstatus"].ToString().Trim() == "W")
                                                        {

                                                            var trandata = new { p_tranid = next_tranid, p_status = "R" };
                                                            var transresult = CommonRepository.ExecuteSP_ReturnInt("splottransaction", trandata, "updateStatus", "Üpdate lottrans");
                                                        }
                                                    }

                                                    Console.WriteLine("IOService:GetServerPathbatch:input--->lotid:" + obj["lotid"].ToString());
                                                    Console.WriteLine("IOService:GetServerPathbatch:input--->batchid:" + batchid.ToString());

                                                    FileMovementLot_Batch(tranid, obj["lotid"].ToString(), batchid.ToString(), CustomConfiguration.AppSettings["CM_Approval"].ToString(), true);

                                                }


                                            }
                                            //Code to Call API's
                                            //Calling CDBAPI
                                            var urlcdb1 = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/No_Update_Required";
                                            Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:URL:--->" + urlcdb1);
                                            IRestResponse responseResultCDB1 = CallCDBAPI(urlcdb1, tranid, userid);
                                            Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:" + responseResultCDB1.Content.ToString());

                                        }
                                        //

                                        #region APICalls
                                        //Code to Call API's
                                        //Calling CDBAPI
                                        var urlcdb = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/Author_MS_Submit";
                                        Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:URL:--->" + urlcdb);
                                        IRestResponse responseResultCDB = CallCDBAPI(urlcdb, tranid, userid);
                                        Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:" + responseResultCDB.Content.ToString());
                                        #endregion
                                        // }

                                        Console.Write("KLI:" + obj["stagename_alias"].ToString() + "- ioservice Completes");
                                    }

                                    catch (Exception ex)
                                    {
                                        Console.WriteLine("MSPre:Error" + ex.Message);
                                    }


                                }

                                // code for CM_Review stage
                                if (obj["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CM_Review"].ToString())
                                {

                                    try
                                    {
                                        if (flag == "R")
                                        {
                                            Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- ioservice starts");
                                            string jobid = obj["jobid"].ToString();
                                            string nextstage = obj["nextstage"].ToString();

                                            string serverinpath_tranid = string.Empty, serverpath_input = string.Empty; int next_tranid = 0; int batchid = 0;
                                            int GE_Review_tranid = 0;
                                            var data = new { transactionid = tranid };
                                            var input = JsonConvert.SerializeObject(data);
                                            var translist = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getbytransactionid");
                                            var dt = JArray.Parse(translist.ToString());
                                            var objlotrans = JObject.Parse(dt[0].ToString());
                                            if (objlotrans["lotstatus"].ToString().Trim() == "C")
                                            {
                                                var nexttrandata = new { jobid = jobid };
                                                var nexttrandata_jsonstr = JsonConvert.SerializeObject(nexttrandata);
                                                var res = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", nexttrandata_jsonstr, "getdetailsbyjobid");
                                                var a1 = JsonConvert.DeserializeObject<object>(res.ToString());
                                                JArray b = JArray.Parse(a1.ToString());

                                                var GE_Review = b.Where(c => c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["GE_Review"].ToString());
                                                if (GE_Review.Count() != 0)
                                                {
                                                    foreach (var rw1 in GE_Review)
                                                    {
                                                        GE_Review_tranid = Convert.ToInt32(rw1["transactionid"].ToString());
                                                    }
                                                }
                                                Console.WriteLine("KLI to get the GE Review stage id:" + GE_Review_tranid);
                                                var data1 = new { tranid = GE_Review_tranid, fromorder = 3, toorder = 4, option = "F" };
                                                Console.WriteLine("KLI calling the spjobbackforwardfromworkarea - function:" + data1.ToString());

                                                string serverpath_tranid = servinfo.GetServerPath(tranid, "serverinfo", false);
                                                serverinpath_tranid = Path.Combine(serverpath_tranid, CustomConfiguration.AppSettings["ServerOUTPATH"].ToString());
                                                int jobMoveForward = CommonRepository.ExecuteSP_ReturnInt("spjobbackforwardfromworkarea", data1, "jobForward", null);

                                                if (jobMoveForward > 0)
                                                {
                                                    var transdata1 = new { jobid = jobid };
                                                    var jsonstr1 = JsonConvert.SerializeObject(transdata1);
                                                    var returnres1 = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", jsonstr1, "getdetailsbyjobid");
                                                    var i_appType1 = JsonConvert.DeserializeObject<object>(returnres1.ToString());
                                                    JArray lottransdetails1 = JArray.Parse(i_appType1.ToString());
                                                    var batchdts = lottransdetails1.Where(c => c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CM_Approval"].ToString());
                                                    //get batch id
                                                    if (batchdts.Count() != 0)
                                                    {
                                                        int cmapprovaltranid = 0;

                                                        var a = lottransdetails1.Where(c =>
                                                        (c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CM_Approval"].ToString()) && c["lotstatus"].ToString() != "W").FirstOrDefault();
                                                        if (a != null && a.Count() != 0)
                                                        {
                                                            cmapprovaltranid = Convert.ToInt32(a["transactionid"].ToString());
                                                        }
                                                        Console.WriteLine("IOService:cmapprovaltranid:--->" + cmapprovaltranid);
                                                        foreach (var rw in batchdts)
                                                        {
                                                            Console.WriteLine("IOService:rw:--->" + rw);
                                                            batchid = Convert.ToInt32(rw["batchid"].ToString());
                                                            next_tranid = Convert.ToInt32(rw["transactionid"].ToString());

                                                            if (cmapprovaltranid != 0 && cmapprovaltranid != next_tranid)
                                                            {
                                                                var trandata1 = new { p_tranid = next_tranid };
                                                                var transresult1 = CommonRepository.ExecuteSP_ReturnInt("splottransaction", trandata1, "delete", "Üpdate lottrans");
                                                            }

                                                        }
                                                        var checkout = getCheckoutBatch(obj["lotid"].ToString(), batchid.ToString(), userid, "R", "checkout_lotbatch", "0", "");
                                                        if (cmapprovaltranid != 0)
                                                        {
                                                            next_tranid = cmapprovaltranid;
                                                        }
                                                        var data2 = new { transactionid = next_tranid };
                                                        var input2 = JsonConvert.SerializeObject(data2);
                                                        var translist2 = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input2, "getbytransactionid");
                                                        var dt2 = JArray.Parse(translist2.ToString());
                                                        var objlotrans2 = JObject.Parse(dt2[0].ToString());
                                                        if (objlotrans2["lotstatus"].ToString().Trim() == "W")
                                                        {

                                                            var trandata = new { p_tranid = next_tranid, p_status = "R" };
                                                            var transresult = CommonRepository.ExecuteSP_ReturnInt("splottransaction", trandata, "updateStatus", "Üpdate lottrans");
                                                        }
                                                    }

                                                    Console.WriteLine("IOService:GetServerPathbatch:input--->lotid:" + obj["lotid"].ToString());
                                                    Console.WriteLine("IOService:GetServerPathbatch:input--->batchid:" + batchid.ToString());
                                                    FileMovementLot_Batch(tranid, obj["lotid"].ToString(), batchid.ToString(), CustomConfiguration.AppSettings["CM_Approval"].ToString(), true);
                                                    //var CM_Approval = lottransdetails1.Where(c => c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CM_Approval"].ToString());
                                                    //if (CM_Approval.Count() != 0)
                                                    //{
                                                    //    foreach (var rw in CM_Approval)
                                                    //    {
                                                    //        next_tranid = Convert.ToInt32(rw["transactionid"].ToString());
                                                    //    }
                                                    //    Console.Write("KLI file movement starts from here....");
                                                    //    FileMovement(tranid, next_tranid.ToString());
                                                    //    Console.Write("KLI file movement ends from here....");
                                                    //    //string nextstage_serverpath = servinfo.GetServerPath(next_tranid.ToString(), "serverinfo", true);
                                                    //    //nextstage_serverpath = Path.Combine(nextstage_serverpath, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
                                                    //    //Console.Write("KLI file movement starts from here....");
                                                    //    //if (Directory.Exists(serverinpath_tranid))
                                                    //    //{
                                                    //    //    if (!Directory.Exists(nextstage_serverpath))
                                                    //    //    {
                                                    //    //        Directory.CreateDirectory(serverinpath_tranid);
                                                    //    //        FileMove_ServerTOServer(tranid, serverinpath_tranid, nextstage_serverpath, "");
                                                    //    //    }
                                                    //    //    else
                                                    //    //    {
                                                    //    //        FileInfo[] fi_ = new System.IO.DirectoryInfo(serverinpath_tranid).GetFiles();
                                                    //    //        if (fi_.Length != 0)
                                                    //    //        {
                                                    //    //            for (int m = 0; m <= fi_.Length - 1; m++)
                                                    //    //            {
                                                    //    //                string _filename = string.Empty, filepath_ = string.Empty;
                                                    //    //                filepath_ = fi_[m].FullName.ToString();
                                                    //    //                _filename = Path.GetFileName(fi_[m].Name.ToString());
                                                    //    //                if (!System.IO.File.Exists(Path.Combine(nextstage_serverpath, _filename)))
                                                    //    //                    System.IO.File.Copy(filepath_, Path.Combine(nextstage_serverpath, _filename));
                                                    //    //            }
                                                    //    //        }
                                                    //    //    }
                                                    //    //}
                                                    //    //Console.Write("KLI file movement ends from here....");

                                                    //}
                                                }


                                            }

                                        }
                                        else
                                        {

                                            //    #region Stage Movement

                                            //    //code to complete current stage
                                            //    var checkout = getCheckout(tranid, userid, "C", "checkout_currentstage", "0", "", "0");
                                            //    Console.WriteLine("checkout: Completes");
                                            //    //code to insert new lot transaction for next stage
                                            //    string nextstage = obj["nextstage"].ToString();//this will return next stage jobworkflowdefid
                                            //    var checkout_next = getCheckout("0", "0", "R", "insert_lot_transaction_details_only", nextstage, "", obj["lotid"].ToString());
                                            //    Console.WriteLine("checkout_next: completes");
                                            //    //code to insert comments
                                            //    insertLotComments(null, "", tranid.ToString(), "C", nextstage.ToString().ToString(), obj["jobid"].ToString(), obj["lotid"].ToString());
                                            //    #endregion

                                            //    #region File Movement
                                            //    // filemovement
                                            //    Console.WriteLine("File movement starts");
                                            //    var json = new List<transactionout>();
                                            //    foreach (var checkout_next_item in checkout_next)
                                            //    {
                                            //        JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                            //        json.Add(JsonConvert.DeserializeObject<transactionout>(aa[0].ToString()));
                                            //    }
                                            //    var next_tranid = json[0].tranid.ToString();
                                            //    FileMovementServerToServer(tranid, next_tranid, false);
                                            //    Console.WriteLine("File movement ends");
                                            //    #endregion
                                            #region File Movement

                                            var next_tranid = GetNextTranId(obj["jobid"].ToString(), obj["lotid"].ToString(), CustomConfiguration.AppSettings["GE_Review"].ToString());

                                            FileMovement(tranid, next_tranid);


                                            Console.WriteLine("File movement ends");
                                            #endregion

                                        }

                                        //Code to Call API's
                                        //Calling CDBAPI
                                        var urlcdb = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/CM_MS_Approved";
                                        Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:URL:--->" + urlcdb);
                                        IRestResponse responseResultCDB = CallCDBAPI(urlcdb, tranid, userid);
                                        Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:" + responseResultCDB.Content.ToString());
                                        //Calling CDBAPI if query raised
                                        if (obj["queryraised"].ToString() == "true")
                                        {
                                            var urlcdb1 = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/CM_Author_Comment";
                                            Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:URL:--->" + urlcdb1);
                                            IRestResponse responseResultCDB1 = CallCDBAPI(urlcdb1, tranid, userid);
                                            Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:" + responseResultCDB1.Content.ToString());
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.Write(ex.Message);
                                    }
                                    Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- ioservice completes");
                                }

                                // code for GE_Review stage
                                if (obj["stagename_alias"].ToString() == CustomConfiguration.AppSettings["GE_Review"].ToString())
                                {
                                    try
                                    {
                                        Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- ioservice starts");
                                        string jobid = obj["jobid"].ToString();
                                        string nextstage = obj["nextstage"].ToString();
                                        string serverinpath_tranid = string.Empty, serverpath_input = string.Empty; int next_tranid = 0; int batchid = 0;
                                        //CM Approval stage creation 

                                        var data = new { transactionid = tranid };
                                        var input = JsonConvert.SerializeObject(data);
                                        var translist = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getbytransactionid");
                                        var dt = JArray.Parse(translist.ToString());
                                        var objlotrans = JObject.Parse(dt[0].ToString());
                                        if (objlotrans["lotstatus"].ToString().Trim() == "C")
                                        {
                                            var transdata1 = new { jobid = jobid };
                                            var jsonstr1 = JsonConvert.SerializeObject(transdata1);
                                            Console.WriteLine("splottransactionselect:jsonstr1:getdetailsbyjobid" + jsonstr1);
                                            var returnres1 = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", jsonstr1, "getdetailsbyjobid");

                                            var i_appType1 = JsonConvert.DeserializeObject<object>(returnres1.ToString());
                                            // Console.WriteLine("i_appType1.ToString():" + i_appType1.ToString());
                                            JArray lottransdetails1 = JArray.Parse(i_appType1.ToString());

                                            string serverpath_tranid = servinfo.GetServerPath(tranid, "serverinfo", false);
                                            Console.WriteLine("IOService:serverpath_tranid:--->" + serverpath_tranid);
                                            var batchdts = lottransdetails1.Where(c => c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CM_Approval"].ToString());
                                            Console.WriteLine("IOService:batchdts:--->" + batchdts.Count());
                                            //get batch id
                                            if (batchdts.Count() != 0)
                                            {
                                                int cmapprovaltranid = 0;

                                                var a = lottransdetails1.Where(c =>
                                                (c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CM_Approval"].ToString()) && c["lotstatus"].ToString() != "W").FirstOrDefault();
                                                if (a != null && a.Count() != 0)
                                                {
                                                    cmapprovaltranid = Convert.ToInt32(a["transactionid"].ToString());
                                                }
                                                Console.WriteLine("IOService:cmapprovaltranid:--->" + cmapprovaltranid);
                                                foreach (var rw in batchdts)
                                                {
                                                    Console.WriteLine("IOService:rw:--->" + rw);
                                                    batchid = Convert.ToInt32(rw["batchid"].ToString());
                                                    next_tranid = Convert.ToInt32(rw["transactionid"].ToString());

                                                    if (cmapprovaltranid != 0 && cmapprovaltranid != next_tranid)
                                                    {
                                                        var trandata1 = new { p_tranid = next_tranid };
                                                        var transresult1 = CommonRepository.ExecuteSP_ReturnInt("splottransaction", trandata1, "delete", "Üpdate lottrans");
                                                    }

                                                }
                                                var checkout = getCheckoutBatch(obj["lotid"].ToString(), batchid.ToString(), userid, "R", "checkout_lotbatch", "0", "");
                                                if (cmapprovaltranid != 0)
                                                {
                                                    next_tranid = cmapprovaltranid;
                                                }
                                                var data2 = new { transactionid = next_tranid };
                                                var input2 = JsonConvert.SerializeObject(data2);
                                                var translist2 = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input2, "getbytransactionid");
                                                var dt2 = JArray.Parse(translist2.ToString());
                                                var objlotrans2 = JObject.Parse(dt2[0].ToString());
                                                if (objlotrans2["lotstatus"].ToString().Trim() == "W")
                                                {

                                                    var trandata = new { p_tranid = next_tranid, p_status = "R" };
                                                    var transresult = CommonRepository.ExecuteSP_ReturnInt("splottransaction", trandata, "updateStatus", "Üpdate lottrans");
                                                }
                                            }

                                            Console.WriteLine("IOService:GetServerPathbatch:input--->lotid:" + obj["lotid"].ToString());
                                            Console.WriteLine("IOService:GetServerPathbatch:input--->batchid:" + batchid.ToString());
                                            FileMovementLot_Batch(tranid, obj["lotid"].ToString(), batchid.ToString(), CustomConfiguration.AppSettings["CM_Approval"].ToString(), true);

                                            //Code to Call API's
                                            //Calling CDBAPI
                                            var urlcdb = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/GE_MS_Approved";
                                            Console.WriteLine("IOService:responseResult:CDBAPI:URL:--->" + urlcdb);
                                            IRestResponse responseResultCDB = CallCDBAPI(urlcdb, tranid, userid);
                                            Console.WriteLine("IOService:responseResult:CDBAPI:" + responseResultCDB.Content.ToString());
                                            //Calling CDBAPI if query raised
                                            Console.WriteLine("IOService:queryraised:--->" + obj["queryraised"]);
                                            if (obj["queryraised"] != null && obj["queryraised"].ToString() == "true")
                                            {
                                                var urlcdb1 = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/GE_Author_Comment";
                                                Console.WriteLine("IOService:responseResult:CDBAPI:URL:--->" + urlcdb1);
                                                IRestResponse responseResultCDB1 = CallCDBAPI(urlcdb1, tranid, userid);
                                                Console.WriteLine("IOService:responseResult:CDBAPI:" + responseResultCDB1.Content.ToString());
                                            }
                                            //Calling CDBAPI if document rejected
                                            Console.WriteLine("IOService:docrejected:--->" + obj["docrejected"]);
                                            if (obj["docrejected"] != null && obj["docrejected"].ToString() == "true")
                                            {
                                                var urlcdb1 = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/GE_MS_Rejected";
                                                Console.WriteLine("IOService:responseResult:CDBAPI:URL:--->" + urlcdb1);
                                                IRestResponse responseResultCDB1 = CallCDBAPI(urlcdb1, tranid, userid);
                                                Console.WriteLine("IOService:responseResult:CDBAPI:" + responseResultCDB1.Content.ToString());
                                            }
                                        }
                                        Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- ioservice completes");
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.Write(ex.Message);
                                    }



                                }


                                // code for CM_Approval stage
                                if (obj["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CM_Approval"].ToString())
                                {
                                    Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "-Hits");


                                    ///
                                    #region CMApproval
                                    // var chpdetails = "";
                                    using (IDbConnection dbConnection = ConnectionBase.Connection)
                                    {
                                        DynamicParameters param = new DynamicParameters();
                                        var lotdata = new
                                        {
                                            jobworkflowid = obj["jobworkflowid"].ToString(),
                                            batchid = obj["batchid"].ToString()
                                        };
                                        jsonstr = JsonConvert.SerializeObject(lotdata);
                                        Console.WriteLine("splotbatchdetailsselect:getdetailbybatchjobwid:jsonstr" + jsonstr);
                                        returnres = CommonRepository.ExecuteSP_ReturnList2("splotbatchdetailsselect", jsonstr, "getdetailbybatchjobwid");
                                        if (returnres != null)
                                        {
                                            Console.WriteLine("returnres" + returnres.ToString());
                                            var dt = JArray.Parse(returnres.ToString());
                                            //var objlotrans = JObject.Parse(dt.ToString());
                                            if (dt != null)
                                            {
                                                foreach (var metadatalist in dt)
                                                {
                                                    Console.WriteLine("metadatalist" + metadatalist.ToString());
                                                    var next_tranid = "";
                                                    if (metadatalist["ismovetoproduction"].ToString() == "1")
                                                    {
                                                        List<jsonvalue> checkout = new List<jsonvalue>();
                                                        Console.WriteLine("ismovetoproduction:lotid" + metadatalist["lotid"].ToString());
                                                        ///Code with Copy editing
                                                        if (metadatalist["productionworkflowid"].ToString() == "1" || metadatalist["productionworkflowid"].ToString() == "2")
                                                        {
                                                            checkout = getCheckout(tranid, userid, "P", "checkout_currentstage", "0", "", "0");
                                                            string nextstage = obj["nextstage"].ToString();//this will return next stage jobworkflowdefid
                                                            var checkout_next = getCheckout(tranid, userid, "R", "insert_lot_transaction_details_only", nextstage, "", metadatalist["lotid"].ToString());
                                                            var json = new List<transactionout>();
                                                            foreach (var checkout_next_item in checkout_next)
                                                            {
                                                                JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                                                json.Add(JsonConvert.DeserializeObject<transactionout>(aa[0].ToString()));
                                                            }
                                                            next_tranid = json[0].tranid.ToString();

                                                            FileMovementBatch_Lot(tranid, next_tranid, metadatalist["lotid"].ToString(), obj["batchid"].ToString(), CustomConfiguration.AppSettings["CM_Approval"].ToString(), false);

                                                            #region KLI Lot Batch details
                                                            klilotbatchdetails jsonchap = new klilotbatchdetails();

                                                            var lotdata1 = new
                                                            {
                                                                lotid = Convert.ToInt64(metadatalist["lotid"].ToString()),
                                                            };
                                                            string lotinput = JsonConvert.SerializeObject(lotdata1);
                                                            param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                                                            param.Add("mode_p", dbType: DbType.String, value: "getbylotid", direction: ParameterDirection.Input);
                                                            var getTransid = dbConnection.Query<string>("public.splotmasterselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();

                                                            if (getTransid != null)
                                                            {
                                                                var i1_tranid = JsonConvert.DeserializeObject<object>(getTransid.ToString());
                                                                JArray a1_tranid = JArray.Parse(i1_tranid.ToString());
                                                                JObject obj1_tranid = JObject.Parse(a1_tranid[0].ToString());
                                                                jsonchap.batchname = obj1_tranid["title"].ToString() + "_Batch_" + DateTime.Now.Year.ToString() + "_" + obj1_tranid["sequence"].ToString();
                                                            }
                                                            next_tranid = json[0].tranid.ToString();
                                                            var data1 = new
                                                            {
                                                                tranid = next_tranid,
                                                                lotid = metadatalist["lotid"].ToString(),
                                                                batchname = jsonchap.batchname,
                                                                supplementtype = "Online",
                                                                jobid = obj["jobid"].ToString(),
                                                                jobworkflowid = nextstage
                                                            };
                                                            Console.WriteLine("KLI calling the spjobbackforwardfromworkarea - function:" + data1.ToString());
                                                            int klilotbatchdetails = CommonRepository.ExecuteSP_ReturnInt("sptblklilotbatchdetails", data1, "insert", null);
                                                            #endregion

                                                            #region Call API
                                                            //code to call pubflow api========
                                                            var url = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/PubflowApi/Create_Online_Issue";
                                                            pubflowinputModel opubflowinputModel = getPubflowInput(next_tranid);
                                                            var workflow = metadatalist["productionworkflow"].ToString();
                                                            IRestResponse responseResult = CallPubflowAPICreateOnline(url, userid, next_tranid, opubflowinputModel.Batch, opubflowinputModel.PublicationType, opubflowinputModel.PublicationID, comment, workflow);

                                                            Console.WriteLine("LAPS2 App Watcher:responseResult" + responseResult.Content.ToString());
                                                            //Calling PubflowAPI --- need to check which API for Files to production
                                                            var urlpubflow = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/PubflowApi/Online/Update_Online_Files_to_Production";

                                                            Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:URL:--->" + urlpubflow);
                                                            IRestResponse responseResult1 = CallPubflowAPIUpdateOnline(urlpubflow, userid, next_tranid, opubflowinputModel.Batch, opubflowinputModel.PublicationType, opubflowinputModel.PublicationID, comment);

                                                            //Code to Call API's
                                                            //Calling CDBAPI
                                                            var urlcdb = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/MS_Ready_For_Production";
                                                            Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:URL:--->" + urlcdb);
                                                            IRestResponse responseResultCDB = CallCDBAPI(urlcdb, next_tranid, userid);
                                                            Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:" + responseResultCDB.Content.ToString());

                                                            //============= 
                                                            #endregion

                                                            #region Update move to production status
                                                            var batchobject = new
                                                            {
                                                                lotbatchdetailsid = metadatalist["lotbatchdetailsid"].ToString(),
                                                                ismoved = 1
                                                            };

                                                            jsonstr = JsonConvert.SerializeObject(batchobject);
                                                            Console.WriteLine("jsonstr:splotbatchdetails:updateStatusBybatchdetailid" + jsonstr);
                                                            param = new DynamicParameters();
                                                            string query2 = "splotbatchdetails";
                                                            param.Add("inputjsonstr", jsonstr);
                                                            param.Add("mode_p", dbType: DbType.String, value: "updateStatusBybatchdetailid", direction: ParameterDirection.Input);
                                                            var result2 = dbConnection.Query<string>(query2, param, commandType: CommandType.StoredProcedure);
                                                            #endregion

                                                            StartCEStage(next_tranid, userid, nextstage, metadatalist["lotid"].ToString(), obj["jobid"].ToString(), obj["stagename_alias"].ToString());
                                                        }
                                                        ///Code without copy editing
                                                        else
                                                        {

                                                            checkout = getCheckout(tranid, userid, "P", "checkout_currentstage", "0", "", "0");
                                                            //code to create next stage CE


                                                            string nextstage = obj["nextstage"].ToString();//this will return next stage jobworkflowdefid
                                                            Console.WriteLine(".........With out CE............nextstage" + nextstage);
                                                            var checkout_next = getCheckout("0", "0", "W", "insert_lot_transaction_details_only", nextstage, "", metadatalist["lotid"].ToString());
                                                            var json = new List<transactionout>();
                                                            foreach (var checkout_next_item in checkout_next)
                                                            {
                                                                JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                                                json.Add(JsonConvert.DeserializeObject<transactionout>(aa[0].ToString()));
                                                            }
                                                            next_tranid = json[0].tranid.ToString();

                                                            Console.WriteLine("KLI to get the next_tranid:" + next_tranid);
                                                            var data1 = new { tranid = next_tranid, fromorder = 0, toorder = 0, option = "F" };
                                                            Console.WriteLine("KLI calling the spjobbackforwardfromworkarea - function:" + data1.ToString());

                                                            int jobMoveForward = CommonRepository.ExecuteSP_ReturnInt("spjobbackforwardfromworkarea", data1, "jobForward", null);
                                                            var next_keatranid = jobMoveForward.ToString();
                                                            Console.WriteLine("KEA jobMoveForward:next_tranid" + next_keatranid);

                                                            checkout = getCheckout(next_keatranid, userid, "W", "checkout_currentstage", "0", "", "0");
                                                            FileMovementBatch_Lot(tranid, next_keatranid, metadatalist["lotid"].ToString(), obj["batchid"].ToString(), CustomConfiguration.AppSettings["CM_Approval"].ToString(), false);

                                                            #region KLI LotBatchdetails
                                                            klilotbatchdetails jsonchap = new klilotbatchdetails();

                                                            var lotdata1 = new
                                                            {
                                                                lotid = Convert.ToInt64(metadatalist["lotid"].ToString()),
                                                            };
                                                            string lotinput = JsonConvert.SerializeObject(lotdata1);
                                                            param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                                                            param.Add("mode_p", dbType: DbType.String, value: "getbylotid", direction: ParameterDirection.Input);
                                                            var getTransid = dbConnection.Query<string>("public.splotmasterselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();

                                                            if (getTransid != null)
                                                            {
                                                                var i1_tranid = JsonConvert.DeserializeObject<object>(getTransid.ToString());
                                                                JArray a1_tranid = JArray.Parse(i1_tranid.ToString());
                                                                JObject obj1_tranid = JObject.Parse(a1_tranid[0].ToString());
                                                                jsonchap.batchname = obj1_tranid["title"].ToString() + "_Batch_" + DateTime.Now.Year.ToString() + "_" + obj1_tranid["sequence"].ToString();
                                                            }
                                                            next_tranid = json[0].tranid.ToString();
                                                            var data2 = new
                                                            {
                                                                tranid = next_tranid,
                                                                lotid = metadatalist["lotid"].ToString(),
                                                                batchname = jsonchap.batchname,
                                                                supplementtype = "Online",
                                                                jobid = obj["jobid"].ToString(),
                                                                jobworkflowid = nextstage
                                                            };
                                                            Console.WriteLine("KLI calling the spjobbackforwardfromworkarea - function:" + data2.ToString());
                                                            int klilotbatchdetails = CommonRepository.ExecuteSP_ReturnInt("sptblklilotbatchdetails", data2, "insert", null);
                                                            #endregion



                                                            #region Call API
                                                            //code to call pubflow api========
                                                            var url = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/PubflowApi/Create_Online_Issue";
                                                            pubflowinputModel opubflowinputModel = getPubflowInput(next_tranid);
                                                            var workflow = metadatalist["productionworkflow"].ToString();
                                                            IRestResponse responseResult = CallPubflowAPICreateOnline(url, userid, next_tranid, opubflowinputModel.Batch, opubflowinputModel.PublicationType, opubflowinputModel.PublicationID, comment, workflow);

                                                            Console.WriteLine("LAPS2 App Watcher:responseResult" + responseResult.Content.ToString());
                                                            //Calling PubflowAPI --- need to check which API for Files to production
                                                            var urlpubflow = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/PubflowApi/Online/Update_Online_Files_to_Production";

                                                            Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:URL:--->" + urlpubflow);
                                                            IRestResponse responseResult1 = CallPubflowAPIUpdateOnline(urlpubflow, userid, next_tranid, opubflowinputModel.Batch, opubflowinputModel.PublicationType, opubflowinputModel.PublicationID, comment);

                                                            //Code to Call API's
                                                            //Calling CDBAPI
                                                            var urlcdb = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/MS_Ready_For_Production";
                                                            Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:URL:--->" + urlcdb);
                                                            IRestResponse responseResultCDB = CallCDBAPI(urlcdb, next_tranid, userid);
                                                            Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:" + responseResultCDB.Content.ToString());

                                                            //============= 
                                                            #endregion

                                                            #region Update move to production status
                                                            var batchobject = new
                                                            {
                                                                lotbatchdetailsid = metadatalist["lotbatchdetailsid"].ToString(),
                                                                ismoved = 1
                                                            };

                                                            jsonstr = JsonConvert.SerializeObject(batchobject);
                                                            Console.WriteLine("jsonstr:splotbatchdetails:updateStatusBybatchdetailid" + jsonstr);
                                                            param = new DynamicParameters();
                                                            string query2 = "splotbatchdetails";
                                                            param.Add("inputjsonstr", jsonstr);
                                                            param.Add("mode_p", dbType: DbType.String, value: "updateStatusBybatchdetailid", direction: ParameterDirection.Input);
                                                            var result2 = dbConnection.Query<string>(query2, param, commandType: CommandType.StoredProcedure);
                                                            #endregion


                                                            Console.WriteLine("===========Calling KEA from CMApproval=======");
                                                            //callautostage(tranid, userid);
                                                            Console.WriteLine("tranid" + tranid + " userid: " + userid + " stagename_alias: " + obj["stagename_alias"].ToString() + " jobid: " + obj["jobid"].ToString() + " lotid: " + metadatalist["lotid"].ToString() + " nextstage: " + obj["nextstage"].ToString());



                                                            StartKEAXML(next_keatranid, userid, CustomConfiguration.AppSettings["KEA_XML_Conversion"].ToString(), obj["jobid"].ToString(), metadatalist["lotid"].ToString(), obj["nextstage"].ToString());
                                                        }

                                                    }
                                                    else if (metadatalist["ismovetoproduction"].ToString() == "2")
                                                    {
                                                        var transobject = new
                                                        {
                                                            tranid = metadatalist["transactionid"].ToString(),
                                                            fromorder = 4,
                                                            toorder = 1,
                                                            option = 'B'
                                                        };
                                                        jsonstr = JsonConvert.SerializeObject(transobject);
                                                        Console.WriteLine("jsonstr:spjobbackforwardfromworkarea:jobBackward" + jsonstr);
                                                        param = new DynamicParameters();
                                                        string query = "spjobbackforwardfromworkarea";
                                                        param.Add("inputjsonstr", jsonstr);
                                                        param.Add("mode_p", dbType: DbType.String, value: "jobBackward", direction: ParameterDirection.Input);
                                                        var result = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
                                                        if (result != null)
                                                        {
                                                            //code to move files
                                                            var tras = JsonConvert.DeserializeObject<object>(result.ToList()[0]);
                                                            transdata = new { transactionid = tras.ToString() };
                                                            next_tranid = tras.ToString();
                                                            // FileMovementServerToServer(tranid, next_tranid.ToString(), true);
                                                            FileMovementBatch_Lot(tranid, next_tranid, metadatalist["lotid"].ToString(), obj["batchid"].ToString(), CustomConfiguration.AppSettings["CM_Approval"].ToString(), false);
                                                        }

                                                        var batchobject = new
                                                        {
                                                            lotbatchdetailsid = metadatalist["lotbatchdetailsid"].ToString(),
                                                            ismoved = 1
                                                        };
                                                        jsonstr = JsonConvert.SerializeObject(batchobject);
                                                        Console.WriteLine("jsonstr:splotbatchdetails:updateStatusBybatchdetailid" + jsonstr);
                                                        param = new DynamicParameters();
                                                        string query2 = "splotbatchdetails";
                                                        param.Add("inputjsonstr", jsonstr);
                                                        param.Add("mode_p", dbType: DbType.String, value: "updateStatusBybatchdetailid", direction: ParameterDirection.Input);
                                                        var result2 = dbConnection.Query<string>(query2, param, commandType: CommandType.StoredProcedure);
                                                        #region Call API
                                                        //code to call pubflow api========
                                                        var url = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/PubflowApi/Create_Online_Issue";
                                                        pubflowinputModel opubflowinputModel = getPubflowInput(next_tranid);
                                                        var workflow = metadatalist["productionworkflow"].ToString();
                                                        IRestResponse responseResult = CallPubflowAPICreateOnline(url, userid, next_tranid, opubflowinputModel.Batch, opubflowinputModel.PublicationType, opubflowinputModel.PublicationID, comment, workflow);

                                                        Console.WriteLine("LAPS2 App Watcher:responseResult" + responseResult.Content.ToString());
                                                        //Calling PubflowAPI --- need to check which API for Files to production
                                                        var urlpubflow = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/PubflowApi/Online/Update_Online_Files_to_Production";

                                                        Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:URL:--->" + urlpubflow);
                                                        IRestResponse responseResult1 = CallPubflowAPIUpdateOnline(urlpubflow, userid, next_tranid, opubflowinputModel.Batch, opubflowinputModel.PublicationType, opubflowinputModel.PublicationID, comment);

                                                        //Code to Call API's
                                                        //Calling CDBAPI
                                                        var urlcdb = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/MS_Ready_For_Production";
                                                        Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:URL:--->" + urlcdb);
                                                        IRestResponse responseResultCDB = CallCDBAPI(urlcdb, next_tranid, userid);
                                                        Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:" + responseResultCDB.Content.ToString());

                                                        //============= 
                                                        #endregion
                                                    }
                                                    else if (metadatalist["ismovetoproduction"].ToString() == "3")
                                                    {
                                                        var checkout = getCheckout(tranid, userid, "P", "checkout_currentstage", "0", "", "0");
                                                        var transobject = new
                                                        {
                                                            tranid = metadatalist["transactionid"].ToString(),
                                                            fromorder = 4,
                                                            toorder = 2,
                                                            option = 'B'
                                                        };
                                                        jsonstr = JsonConvert.SerializeObject(transobject);
                                                        Console.WriteLine("jsonstr:spjobbackforwardfromworkarea:jobBackward:ismovetoproduction:3" + jsonstr);
                                                        param = new DynamicParameters();
                                                        string query = "spjobbackforwardfromworkarea";
                                                        param.Add("inputjsonstr", jsonstr);
                                                        param.Add("mode_p", dbType: DbType.String, value: "jobBackward", direction: ParameterDirection.Input);
                                                        var result = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
                                                        if (result != null)
                                                        {
                                                            //code to move files
                                                            var tras = JsonConvert.DeserializeObject<object>(result.ToList()[0]);
                                                            transdata = new { transactionid = tras.ToString() };
                                                            next_tranid = tras.ToString();
                                                            //FileMovementServerToServer(tranid, next_tranid.ToString(), true);
                                                            FileMovementBatch_Lot(tranid, next_tranid, metadatalist["lotid"].ToString(), obj["batchid"].ToString(), CustomConfiguration.AppSettings["CM_Approval"].ToString(), false);
                                                        }

                                                        //Calling CDBAPI if document rejected
                                                        Console.WriteLine("IOService:docrejected:--->" + obj["docrejected"]);
                                                        //if (obj["docrejected"] != null && obj["docrejected"].ToString() == "true")
                                                        //{
                                                        var urlcdb1 = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/CM_MS_Rejected";
                                                        Console.WriteLine("IOService:responseResult:CDBAPI:URL:--->" + urlcdb1);
                                                        IRestResponse responseResultCDB1 = CallCDBAPI(urlcdb1, tranid, userid);
                                                        Console.WriteLine("IOService:responseResult:CDBAPI:" + responseResultCDB1.Content.ToString());
                                                        // }
                                                    }


                                                }
                                            }
                                        }
                                    }
                                    #endregion


                                }

                                // code for CE stage
                                if (obj["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CE"].ToString())
                                {
                                    Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "-Hits");
                                    var data_input = new
                                    {
                                        errormessage = "Tranid: " + tranid + " Jobid: " + obj["jobid"].ToString() + " Jobworkflowid: " + obj["jobworkflowid"].ToString(),
                                        createdby = 0,
                                        controller = "KLI_IO_SERVICE: CE Hits"
                                    };
                                    int retval = CommonRepository.addlog(data_input, "errorlog");

                                    try
                                    {
                                        //string serverpath = servinfo.GetServerPath(tranid, "serverinfo", false);
                                        //string server_inpath = string.Empty;
                                        //string server_outpath = string.Empty;
                                        //server_inpath = Path.Combine(serverpath, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
                                        //server_outpath = Path.Combine(serverpath, CustomConfiguration.AppSettings["ServerOUTPATH"].ToString());
                                        //if (Directory.Exists(inpath)) DirEmpty(new System.IO.DirectoryInfo(inpath));
                                        //if (Directory.Exists(outpath)) DirEmpty(new System.IO.DirectoryInfo(outpath));
                                        //if (!Directory.Exists(inpath)) Directory.CreateDirectory(inpath);
                                        //if (!Directory.Exists(outpath)) Directory.CreateDirectory(outpath);
                                        //FileMove_ServerTOLocal(tranid, serverpath, "IN", inpath, outpath);

                                        if (appType.Equals("checkin_apps"))
                                        {
                                            Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + " checkin_apps starts...");
                                            data_input = new
                                            {
                                                errormessage = "Tranid: " + tranid + " Jobid: " + obj["jobid"].ToString() + " Jobworkflowid: " + obj["jobworkflowid"].ToString(),
                                                createdby = 0,
                                                controller = "KLI_IO_SERVICE: In StartCEStage: CheckinApp Starts"
                                            };
                                            retval = CommonRepository.addlog(data_input, "errorlog");

                                            Console.WriteLine("Calling CE.......testing");//for real scenarion need to send batchid
                                            StartCEStage(tranid, userid, obj["jobworkflowid"].ToString(), obj["lotid"].ToString(), obj["jobid"].ToString(), obj["stagename_alias"].ToString());

                                            data_input = new
                                            {
                                                errormessage = "Tranid: " + tranid + " Jobid: " + obj["jobid"].ToString() + " Jobworkflowid: " + obj["jobworkflowid"].ToString(),
                                                createdby = 0,
                                                controller = "KLI_IO_SERVICE: In StartCEStage: CheckinApp Completed"
                                            };
                                            retval = CommonRepository.addlog(data_input, "errorlog");
                                        }
                                        else if (appType.Equals("checkout_apps"))
                                        {
                                            Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- Checkout App starts");
                                            Console.WriteLine("KLI:testing... dll");
                                            data_input = new
                                            {
                                                errormessage = "Tranid: " + tranid + " Jobid: " + obj["jobid"].ToString() + " Jobworkflowid: " + obj["jobworkflowid"].ToString(),
                                                createdby = 0,
                                                controller = "KLI_IO_SERVICE: In StartCEStage: CheckOutApp Starts"
                                            };
                                            CommonRepository.addlog(data_input, "errorlog");

                                            //Word to HTML Conversion
                                            WORDtoHTML(tranid, userid, obj["lotid"].ToString());

                                            //API call goes here
                                            //Calling PubflowAPI
                                            var urlpubflow = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/PubflowApi/Online/Update_Online_Copy_Editing";
                                            pubflowinputModel opubflowinputModel = getPubflowInput(tranid);
                                            if (opubflowinputModel != null)
                                            {
                                                Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:URL:--->" + urlpubflow);
                                                IRestResponse responseResult = CallPubflowAPIUpdateOnline(urlpubflow, userid, tranid, opubflowinputModel.Batch, opubflowinputModel.PublicationType, opubflowinputModel.PublicationID, comment);
                                                Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:" + responseResult.Content.ToString());
                                            }

                                            //Calling CDBAPI
                                            var urlcdb = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/MS_Copy_Editing";
                                            Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:URL:--->" + urlcdb);
                                            IRestResponse responseResultCDB = CallCDBAPI(urlcdb, tranid, userid);

                                            data_input = new
                                            {
                                                errormessage = "Tranid: " + tranid + " Jobid: " + obj["jobid"].ToString() + " Jobworkflowid: " + obj["jobworkflowid"].ToString(),
                                                createdby = 0,
                                                controller = "KLI_IO_SERVICE: In StartCEStage: CheckOutApp completes"
                                            };
                                            retval = CommonRepository.addlog(data_input, "errorlog");

                                            Console.WriteLine("CE stage movement and file movement....");
                                            //stage movement and file movement
                                            var checkout = getCheckout(tranid, userid, "C", "checkout_currentstage", "0", "", "0");
                                            string nextstage = obj["nextstage"].ToString();//this will return next stage jobworkflowdefid
                                            var checkout_next = getCheckout(tranid, userid, "R", "insert_lot_transaction_details_only", nextstage, "", obj["lotid"].ToString());
                                            var json = new List<transactionout>();
                                            foreach (var checkout_next_item in checkout_next)
                                            {
                                                JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                                json.Add(JsonConvert.DeserializeObject<transactionout>(aa[0].ToString()));
                                            }
                                            var next_tranid = json[0].tranid.ToString();
                                            FileMovement(tranid, next_tranid);
                                            Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- Checkout App ends");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }
                                }


                                // code for Epub_Generation stage
                                if (obj["stagename_alias"].ToString() == CustomConfiguration.AppSettings["KEA_XML_Conversion"].ToString())
                                {
                                    StartKEAXML(tranid, userid, obj["stagename_alias"].ToString(), obj["jobid"].ToString(), obj["lotid"].ToString(), obj["nextstage"].ToString());

                                }

                                if (obj["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CLS_Upload"].ToString())
                                {
                                    Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- Checkout App starts");
                                   
                                    #region CLS Upload stage
                                    Console.WriteLine("KLI:=============CLS Upload================");
                                    //Stage movement file movement
                                    #region Stage Movement
                                    //code to complete current stage
                                    var checkout = getCheckout(tranid, userid, "C", "checkout_currentstage", "0", "", "0");
                                    //code to insert new lot transaction for next stage
                                    string nextstage = obj["nextstage"].ToString();//this will return next stage jobworkflowdefid
                                    var checkout_next = getCheckout(tranid, userid, "R", "insert_lot_transaction_details_only", nextstage, "", obj["lotid"].ToString());
                                    //code to insert comments
                                    insertLotComments(null, "", tranid.ToString(), "C", nextstage.ToString().ToString(), obj["jobid"].ToString(), obj["lotid"].ToString());
                                    #endregion
                                    // code to get next tranid
                                    var json = new List<transactionout>();
                                    foreach (var checkout_next_item in checkout_next)
                                    {
                                        JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                        json.Add(JsonConvert.DeserializeObject<transactionout>(aa[0].ToString()));
                                    }
                                    var next_tranid = json[0].tranid.ToString();
                                    FileMovement(tranid, next_tranid);

                                    Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- Checkout App Ends");
                                    #endregion


                                    #region EPub Generation
                                    Console.WriteLine("=======KLI:Epub_Generation - Auto stage starts======");
                                    tranid = next_tranid;

                                    //Available Input files final.xml, 2 files from KEA XM Conversion(_fm.xml,.html)
                                    string serverinfo = servinfo.GetServerPath(tranid.ToString(), "serverinfo", false);
                                    string KEAstagename = "";
                                    JArray jobdet = GetNextJobworkflowdetails(obj["jobid"].ToString());
                                    var KEA_XML_Conversion = jobdet.Where(c => c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["KEA_XML_Conversion"].ToString());
                                    if (KEA_XML_Conversion.Count() != 0)
                                    {
                                        foreach (var rw1 in KEA_XML_Conversion)
                                        {
                                            Console.WriteLine(rw1);
                                            KEAstagename = rw1["stageid"].ToString()+"_"+ rw1["stagename_alias"].ToString();
                                            
                                        }
                                    }

                                    string KEAXMConversionPath = Path.Combine(Path.GetDirectoryName(serverinfo), KEAstagename, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
                                    Console.WriteLine("KEAXMConversionPath:" + KEAXMConversionPath);
                                    Console.WriteLine("EPubPath:" + Path.Combine(serverinfo, CustomConfiguration.AppSettings["ServerINPATH"].ToString()));
                                    if (Directory.Exists(KEAXMConversionPath) && Directory.GetFiles(KEAXMConversionPath, "*.*").Length > 0)
                                    {
                                        Console.WriteLine("KEAXMConversionPath:" + KEAXMConversionPath +"exists");
                                        //CommonClass.CopyDirectory(KEAXMConversionPath, Path.Combine(serverinfo,             CustomConfiguration.AppSettings["ServerINPATH"].ToString()));

                                        string _fmfile = Directory.GetFiles(KEAXMConversionPath, "*.xml", SearchOption.TopDirectoryOnly)
                                            .Where(x => Path.GetFileName(x.ToString()).Contains("_fm.xml")).FirstOrDefault();

                                        string htmlfile = Directory.GetFiles(KEAXMConversionPath, "*.html", SearchOption.TopDirectoryOnly).FirstOrDefault();

                                        string destfile = Path.Combine(serverinfo, CustomConfiguration.AppSettings["ServerINPATH"].ToString(), Path.GetFileName(_fmfile));
                                        File.Copy(_fmfile, destfile,true);
                                        Console.WriteLine("_fmfile:" + _fmfile + " copied to destfile:"+ destfile);
                                        destfile = Path.Combine(serverinfo, CustomConfiguration.AppSettings["ServerINPATH"].ToString(), Path.GetFileName(htmlfile));
                                        File.Copy(htmlfile, destfile, true);
                                        Console.WriteLine("htmlfile:" + htmlfile + " copied to destfile:" + destfile);
                                        Console.WriteLine("Files copied from KEAXMConversionPath to EPubPath");
                                    }

                                    //code to convert HTML to EPUB=== starts
                                    #region XML to EPUB
                                    Console.WriteLine("KLI:Epub_Generation:lotid" + obj["lotid"].ToString());
                                    HTMLtoEPUB(tranid, userid, obj["lotid"].ToString());
                                    #endregion


                                    Console.WriteLine("KLI:SendMail_EPUB starts");
                                    SendMail_EPUB(tranid, userid, nextstage, obj["jobid"].ToString(), CustomConfiguration.AppSettings["Epub_Generation"].ToString());
                                    Console.WriteLine("KLI:SendMail_EPUB ends");

                                    //Stage movement file movement
                                    #region Stage Movement
                                    checkout = getCheckout(tranid, userid, "C", "checkout_currentstage", "0", "", "0");

                                    string Online_Cycle_Endsjobworkflowid = "";
                                    string lotid = "";
                                    jobdet = GetNextJobworkflowdetails(obj["jobid"].ToString());
                                    var Online_Cycle_Ends = jobdet.Where(c => c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["Online_Cycle_Ends"].ToString());
                                    if (Online_Cycle_Ends.Count() != 0)
                                    {
                                        foreach (var rw1 in Online_Cycle_Ends)
                                        {
                                            Console.WriteLine(rw1);
                                            Online_Cycle_Endsjobworkflowid = rw1["jobworkflowid"].ToString();
                                        }
                                    }
                                    //nextstage = Epub_Generationjobworkflowid;//this will return next stage jobworkflowdefid
                                    checkout_next = getCheckout(tranid, userid, "W", "insert_lot_transaction_details_only", Online_Cycle_Endsjobworkflowid, "", obj["lotid"].ToString());
                                    //code to insert comments
                                    insertLotComments(null, "", tranid.ToString(), "C", Online_Cycle_Endsjobworkflowid.ToString().ToString(), obj["jobid"].ToString(), obj["lotid"].ToString());
                                    #endregion

                                    ////Code for file movement
                                    #region File movement
                                    json = new List<transactionout>();
                                    foreach (var checkout_next_item in checkout_next)
                                    {
                                        JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                        json.Add(JsonConvert.DeserializeObject<transactionout>(aa[0].ToString()));
                                    }
                                    next_tranid = json[0].tranid.ToString();

                                    Console.WriteLine("Online_Cycle_End:next_tranid" + next_tranid);
                                    FileMovement(tranid, next_tranid);
                                    #endregion


                                    //API call starts here
                                    #region API Calls
                                    //Calling PubflowAPI
                                    var urlpubflow = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/PubflowApi/Online/Update_Online_Digital_Offprints_Free_Epub";
                                    pubflowinputModel opubflowinputModel = getPubflowInput(tranid);
                                    if (opubflowinputModel != null)
                                    {
                                        Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:URL:--->" + urlpubflow);
                                        IRestResponse responseResult = CallPubflowAPIUpdateOnline(urlpubflow, userid, tranid, opubflowinputModel.Batch, opubflowinputModel.PublicationType, opubflowinputModel.PublicationID, comment);
                                        Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:" + responseResult.Content.ToString());
                                    }
                                    #endregion

                                    Console.WriteLine("KLI:======Epub_Generation==================- Checkout App ends");
                                    #endregion

                                    #region Online Cycle ends
                                    Console.WriteLine("========KLI: Online cycle ends - Checkin App starts======");
                                    tranid = next_tranid;
                                    //Code for stage movement
                                    #region Stage Movement
                                    checkout = getCheckout(tranid, userid, "C", "checkout_currentstage", "0", "", "0");

                                    string Pre_Review_Endsjobworkflowid = "";
                                    // lotid = "";
                                    jobdet = GetNextJobworkflowdetails(obj["jobid"].ToString());
                                    var Pre_Review = jobdet.Where(c => c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["Pre_Review"].ToString());
                                    if (Pre_Review.Count() != 0)
                                    {
                                        foreach (var rw1 in Pre_Review)
                                        {
                                            Console.WriteLine(rw1);
                                            Pre_Review_Endsjobworkflowid = rw1["jobworkflowid"].ToString();
                                        }
                                    }
                                    //nextstage = Epub_Generationjobworkflowid;//this will return next stage jobworkflowdefid
                                    checkout_next = getCheckout(tranid, userid, "R", "insert_lot_transaction_details_only", Pre_Review_Endsjobworkflowid, "", obj["lotid"].ToString());

                                    //code to insert comments
                                    insertLotComments(null, "", tranid.ToString(), "C", Pre_Review_Endsjobworkflowid.ToString().ToString(), obj["jobid"].ToString(), obj["lotid"].ToString());


                                    #endregion

                                    //code to get files for Online cycle ends
                                    #region GetfilesforOnlineCycle
                                    serverinfo = servinfo.GetServerPath(tranid.ToString(), "serverinfo", false);
                                    string serverinfo_lot = servinfo.GetServerPath(tranid.ToString(), "serverinfo_lot", false);
                                    Console.WriteLine("serverinfo_job" + serverinfo_lot);
                                    string parentfolder = Path.Combine(serverinfo_lot, "Parent");
                                    //code to get final xml from CLS Upload stage
                                    string CLSstagename = "";
                                    jobdet = GetNextJobworkflowdetails(obj["jobid"].ToString());
                                    var CLS_Upload = jobdet.Where(c => c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["CLS_Upload"].ToString());
                                    if (CLS_Upload.Count() != 0)
                                    {
                                        foreach (var rw1 in CLS_Upload)
                                        {
                                            Console.WriteLine(rw1);
                                            CLSstagename = rw1["stageid"].ToString() + "_" + rw1["stagename_alias"].ToString();

                                        }
                                    }

                                    string CLSUploadPath = Path.Combine(Path.GetDirectoryName(serverinfo), CLSstagename, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
                                    Console.WriteLine("CLSUploadPath:" + CLSUploadPath);
                                    Console.WriteLine("OnlineCyclePath:" + Path.Combine(serverinfo, CustomConfiguration.AppSettings["ServerINPATH"].ToString()));
                                    string onlineInPath = Path.Combine(serverinfo, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
                                   System.IO.DirectoryInfo di = new DirectoryInfo(onlineInPath);

                                        foreach (FileInfo file in di.GetFiles())
                                        {
                                            file.Delete();
                                        }
                                        foreach (DirectoryInfo dir in di.GetDirectories())
                                        {
                                            dir.Delete(true);
                                        }
                                    
                                    if (Directory.Exists(CLSUploadPath) && Directory.GetFiles(CLSUploadPath, "*.*").Length > 0)
                                    {
                                        
                                        Console.WriteLine("CLSUploadPath:" + CLSUploadPath + "exists");
                                        //CommonClass.CopyDirectory(KEAXMConversionPath, Path.Combine(serverinfo,             CustomConfiguration.AppSettings["ServerINPATH"].ToString()));
                                        


                                        string xmlfile = Directory.GetFiles(CLSUploadPath, "*.xml", SearchOption.TopDirectoryOnly).FirstOrDefault();
                                           

                                        string destfile = Path.Combine(onlineInPath, Path.GetFileName(xmlfile));
                                        File.Copy(xmlfile, destfile, true);
                                        Console.WriteLine("xmlfile:" + xmlfile + " copied to destfile:" + destfile);

                                        //code to copy xml file to Parent folder
                                        Console.WriteLine("parentfolder: " + parentfolder);
                                        if (!Directory.Exists(parentfolder))
                                        {
                                            Console.WriteLine("parentfolder: not exist ");
                                            System.IO.Directory.CreateDirectory(parentfolder);
                                        }
                                        string destfileparent = Path.Combine(parentfolder, Path.GetFileName(xmlfile));
                                        File.Copy(xmlfile, destfileparent, true);
                                        Console.WriteLine("xmlfile to parent:" + xmlfile + " copied to destfileparent:" + destfileparent);

                                        Console.WriteLine("Files copied from CLSUploadPath to OnlineCyclePath");
                                    }
                                    #endregion

                                    //code to convert xml to html
                                    Console.WriteLine("========Online cycle ends - convert xml to html starts=======");
                                    XMLtoHTML(tranid,userid, obj["lotid"].ToString());
                                    Console.WriteLine("========Online cycle ends - convert xml to html ends=======");

                                    // code to get next tranid
                                    json = new List<transactionout>();
                                    foreach (var checkout_next_item in checkout_next)
                                    {
                                        JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                        json.Add(JsonConvert.DeserializeObject<transactionout>(aa[0].ToString()));
                                    }
                                    next_tranid = json[0].tranid.ToString();
                                    FileMovement(tranid, next_tranid);

                                    //Calling CDBAPI
                                    var urlcdb = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/CdbApi/Published";
                                    Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:URL:--->" + urlcdb);
                                    IRestResponse responseResultCDB = CallCDBAPI(urlcdb, tranid, userid);
                                    Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:" + responseResultCDB.Content.ToString());
                                    Console.WriteLine("===========KLI: Online cycle ends - Checkout App ends============"); 
                                    #endregion
                                }

                                #region commented
                                //if (obj["stagename_alias"].ToString() == CustomConfiguration.AppSettings["Epub_Generation"].ToString())
                                //{
                                //    Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- Checkin App starts");

                                //    //code to convert HTML to EPUB=== starts
                                //    #region XML to EPUB
                                //    HTMLtoEPUB(tranid, userid, obj["lotid"].ToString());
                                //    #endregion

                                //    //Stage movement file movement
                                //    #region Stage Movement
                                //    //code to complete current stage
                                //    var checkout = getCheckout(tranid, userid, "C", "checkout_currentstage", "0", "", "0");

                                //    //code to insert new lot transaction for next stage
                                //    string nextstage = obj["nextstage"].ToString();//this will return next stage jobworkflowdefid
                                //    var checkout_next = getCheckout(tranid, userid, "W", "insert_lot_transaction_details_only", nextstage, "", obj["lotid"].ToString());

                                //    //code to insert comments
                                //    insertLotComments(null, "", tranid.ToString(), "C", nextstage.ToString().ToString(), obj["jobid"].ToString(), obj["lotid"].ToString());
                                //    #endregion
                                //    // code to get next tranid
                                //    var json = new List<transactionout>();
                                //    foreach (var checkout_next_item in checkout_next)
                                //    {
                                //        JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                //        json.Add(JsonConvert.DeserializeObject<transactionout>(aa[0].ToString()));
                                //    }
                                //    var next_tranid = json[0].tranid.ToString();
                                //    FileMovement(tranid, next_tranid);

                                //    //API call starts here
                                //    //Calling PubflowAPI
                                //    var urlpubflow = CustomConfiguration.AppSettings["CM_Approval"].ToString() +"orchestration/api/PubflowApi/Online/Update_Online_Digital_Offprints_Free_Epub";
                                //    pubflowinputModel opubflowinputModel = getPubflowInput(tranid);
                                //    if (opubflowinputModel != null)
                                //    {
                                //        Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:URL:--->" + urlpubflow);
                                //        IRestResponse responseResult = CallPubflowAPIUpdateOnline(urlpubflow, userid, tranid, opubflowinputModel.Batch, opubflowinputModel.PublicationType, opubflowinputModel.PublicationID,comment);
                                //        Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:" + responseResult.Content.ToString());
                                //    }

                                //    Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- Checkout App ends");



                                //    Console.WriteLine("========KLI: Online cycle ends - Checkin App starts======");
                                //    tranid = next_tranid;

                                //    //Code for stage movement
                                //    #region Stage Movement
                                //    //code to complete current stage
                                //     checkout = getCheckout(tranid, userid, "C", "checkout_currentstage", "0", "", "0");

                                //    //code to insert new lot transaction for next stage

                                //    var nexttrandata = new { jobid = obj["jobid"].ToString() };
                                //    var nexttrandata_jsonstr = JsonConvert.SerializeObject(nexttrandata);
                                //    var res = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", nexttrandata_jsonstr, "getdetailsbyjobid");
                                //    var a1 = JsonConvert.DeserializeObject<object>(res.ToString());
                                //    JArray b = JArray.Parse(a1.ToString());
                                //    string  Pre_Review_jobworkflowid = "";
                                //    var Pre_Review = b.Where(c => c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["Pre_Review"].ToString() && c["lotid"].ToString() == obj["lotid"].ToString());
                                //    if (Pre_Review.Count() != 0)
                                //    {
                                //        foreach (var rw1 in Pre_Review)
                                //        {
                                //            Console.WriteLine(rw1);
                                //            Pre_Review_jobworkflowid = rw1["jobworkflowid"].ToString();
                                //        }
                                //    }

                                //    checkout_next = getCheckout(tranid, userid, "R", "insert_lot_transaction_details_only", Pre_Review_jobworkflowid, "", obj["lotid"].ToString());

                                //    //code to insert comments
                                //    insertLotComments(null, "", tranid.ToString(), "C", nextstage.ToString().ToString(), obj["jobid"].ToString(), obj["lotid"].ToString());
                                //    #endregion
                                //    // code to get next tranid
                                //     json = new List<transactionout>();
                                //    foreach (var checkout_next_item in checkout_next)
                                //    {
                                //        JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                //        json.Add(JsonConvert.DeserializeObject<transactionout>(aa[0].ToString()));
                                //    }
                                //     next_tranid = json[0].tranid.ToString();
                                //    FileMovement(tranid, next_tranid);


                                //    //Calling CDBAPI
                                //    var urlcdb = CustomConfiguration.AppSettings["CM_Approval"].ToString() +"orchestration/api/CdbApi/Published";
                                //    Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:URL:--->" + urlcdb);
                                //    IRestResponse responseResultCDB = CallCDBAPI(urlcdb, tranid, userid);
                                //    Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:" + responseResultCDB.Content.ToString());
                                //    Console.WriteLine("===========KLI: Online cycle ends - Checkout App ends============");


                                //}

                                #endregion


                                //code for MC_Review stage
                                if (obj["stagename_alias"].ToString() == CustomConfiguration.AppSettings["MC_Review"].ToString())
                                {
                                    Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- Checkin App starts");
                                    //Code for stage movement


                                    //code for stage movement


                                    //Calling PubflowAPI
                                    var urlpubflow = CustomConfiguration.AppSettings["kli_rootpathbase"].ToString() + "orchestration/api/PubflowApi/Manual/Update_Manual_Final_PDF";
                                    pubflowinputModel opubflowinputModel = getPubflowInput(tranid);
                                    if (opubflowinputModel != null)
                                    {
                                        Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:URL:--->" + urlpubflow);
                                        IRestResponse responseResult = CallPubflowAPIUpdateOnline(urlpubflow, userid, tranid, opubflowinputModel.Batch, opubflowinputModel.PublicationType, opubflowinputModel.PublicationID, comment);
                                        Console.WriteLine("LAPS2 App Watcher:responseResult:PubflowAPI:" + responseResult.Content.ToString());
                                    }

                                    Console.WriteLine("KLI:" + obj["stagename_alias"].ToString() + "- Checkout App ends");
                                }


                                Console.WriteLine("======================Completed===================");
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error:IOService: " + ex.Message.ToString());
                                Console.WriteLine("Error:IOService: " + ex.InnerException.ToString());
                                throw ex;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CommonClass.WriteLog(ex.Message, "Error");
                Console.WriteLine(ex.Message + " at " + ex.StackTrace);
                Console.ReadKey();
            }
        }

        private static void SendMail_EPUB(string tranid, string userid, string cjobworkflowid, string jobid, string stagename_alias)
        {
            try
            {
                Console.WriteLine("KLI:SendMail_EPUB starts");
                var data_input = new
                {
                    errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid,
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: SendMail_EPUB: Method Starts"
                };
                CommonRepository.addlog(data_input, "errorlog");
                ServerInfo servinfo = new ServerInfo();
                string serverpath = servinfo.GetServerPath(tranid, "serverinfo", false);
                string server_inpath = string.Empty;
                string server_outpath = string.Empty;
                server_inpath = Path.Combine(serverpath, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
                server_outpath = Path.Combine(serverpath, CustomConfiguration.AppSettings["ServerOUTPATH"].ToString());
                Console.WriteLine("SendMail_EPUB:server_inpath" + server_inpath);
                Console.WriteLine("SendMail_EPUB:server_outpath" + server_outpath);
                var data = new { transactionid = tranid };
                var input = JsonConvert.SerializeObject(data);
                var translist = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getallbytransid");
                var dt = JArray.Parse(translist.ToString());
                var objtrans = JObject.Parse(dt[0].ToString());
                string transkey = objtrans["transactionkey"].ToString();
                string lottitle = objtrans["lottitle"].ToString();
                string filename = lottitle + ".zip";
                string filePath = server_inpath;
                string jobworkflow_id = cjobworkflowid;
                var mail_data = new { jobworkflowid = jobworkflow_id };
                var mail_input = JsonConvert.SerializeObject(mail_data);
                var mailtemp_list = CommonRepository.ExecuteSP_ReturnList2("spmailtemplatemasterselect", mail_input, "getbyjobworkflowid");
                var mailtemp_dt = JArray.Parse(mailtemp_list.ToString());
                mailtemplateModel mobj = JsonConvert.DeserializeObject<mailtemplateModel>(mailtemp_dt[0].ToString());
                int mailtemplate_id = mobj.mailtemplateid;
                data_input = new
                {
                    errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid + " MailTemplateid: " + mailtemplate_id,
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: In SendMail_EPUB: Getting MailTemplateID to Send Mail"
                };
                CommonRepository.addlog(data_input, "errorlog");


                #region For getting userid from stage mapping
                var returnres1 = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getstagemapingdetailsbytranid");
                var i_appType1 = JsonConvert.DeserializeObject<object>(returnres1.ToString());
                JArray lottransdetails1 = JArray.Parse(i_appType1.ToString());
                Console.WriteLine("SendMail_EPUB:lottransdetails1 :" + lottransdetails1);

                //get user id
                var json = new List<uservalue>();
                if (lottransdetails1.Count() != 0)
                {
                    foreach (var u_obj in lottransdetails1)
                    {
                        //json.Add(JsonConvert.DeserializeObject<uservalue>(u_obj["userid"].ToString()));
                        json.Add(JsonConvert.DeserializeObject<uservalue>(u_obj.ToString()));
                    }
                }
                Console.WriteLine("SendMail_EPUB: lottransdetails :json" + json);
                #endregion

                var usr_mailmap_data = new { mailtemplateid = mailtemplate_id };
                var usr_mailmap_input = JsonConvert.SerializeObject(usr_mailmap_data);
                var usr_mailmap_list = CommonRepository.ExecuteSP_ReturnList2("spusermailtemplatemappingselect", usr_mailmap_input, "getbyid");
                var usr_mailmap_list_dt = JArray.Parse(usr_mailmap_list.ToString());
                var obj_mailmap = JObject.Parse(usr_mailmap_list_dt[0].ToString());
                // dynamic dynJson = JsonConvert.DeserializeObject(obj_mailmap["userid"].ToString());



                var dynJson = JsonConvert.DeserializeObject<List<uservalue>>(obj_mailmap["userid"].ToString());
                Console.WriteLine("SendMail_EPUB: lottransdetails :dynJson" + dynJson);
                var jsons = new List<uservalue>();
                jsons = dynJson;
                // var dynJsons = dynJson;
                foreach (var u_obj in json)
                {
                    var batchdt = dynJson.Where(c => c.userid == u_obj.userid);
                    if (batchdt.Count() == 0)
                    {
                        jsons.Add(u_obj);
                    }
                }
                foreach (var item in jsons)
                //   foreach (var item in dynJson)
                {
                    int c_userid = int.Parse(item.userid);
                    var u_data = new { userid_p = c_userid };
                    var u_input = JsonConvert.SerializeObject(u_data);
                    var u_list = CommonRepository.ExecuteSP_ReturnList2("spusermasterselect", u_input, "getbyid");
                    var u_list_dt = JArray.Parse(u_list.ToString());
                    var u_obj = JObject.Parse(u_list_dt[0].ToString());
                    string c_username = u_obj["username"].ToString();
                    string c_emailid = u_obj["emailid"].ToString();
                    StringBuilder sb_body = new StringBuilder(mobj.body);
                    StringBuilder sb_subject = new StringBuilder(mobj.subject);
                    string serverpathdownload = CustomConfiguration.AppSettings["kli_rootpathbase"] + "/#/DownloaderAny";
                    if (!string.IsNullOrEmpty(serverpathdownload))
                    {
                        sb_body.Replace("$$downloadpath", "<a href='" + serverpathdownload + "?L=" + transkey + "&U=" + c_userid + "&F=" + filename + "&T=" + tranid + "'>here</a>");
                    }
                    sb_body.Replace("$$username", c_username);
                    sb_body.Replace("$$stagename_alias", stagename_alias);
                    sb_body.Replace("$$chapter", lottitle);
                    var j_data = new { jobid = jobid };
                    var j_input = JsonConvert.SerializeObject(j_data);
                    var j_list = CommonRepository.ExecuteSP_ReturnList2("spjobmasterselect", j_input, "getbyjobid");
                    var j_list_dt = JArray.Parse(j_list.ToString());
                    var j_obj = JObject.Parse(j_list_dt[0].ToString());
                    sb_body.Replace("$$jobtitle", j_obj["title"].ToString());
                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid,
                        createdby = userid,
                        controller = "KLI_IO_SERVICE: In SendMail_EPUB: Sending Mail starts"
                    };
                    CommonRepository.addlog(data_input, "errorlog");
                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid,
                        createdby = userid,
                        controller = "KLI_IO_SERVICE: In SendMail_EPUB: Mail ID: " + c_emailid
                    };
                    CommonRepository.addlog(data_input, "errorlog");
                    CommonClass.SendMail(c_emailid, sb_body, sb_subject);
                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid,
                        createdby = userid,
                        controller = "KLI_IO_SERVICE: In SendMail_EPUB: Sending Mail completed"
                    };
                    CommonRepository.addlog(data_input, "errorlog");
                }
            }
            catch (Exception ex)
            {
                var data_input = new
                {
                    errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid + " Error.",
                    createdby = userid,
                    controller = "In SendMail_EPUB: Exception: " + ex.Message
                };
                CommonRepository.addlog(data_input, "errorlog");
            }
        }


        private static void StartKEAXML(string tranid, string userid, string stagename_alias, string jobid, string lotid, string nextjobworkflowid)
        {
            Console.WriteLine("KLI:" + stagename_alias + "- Checkin App starts");

            //Code to convert HTML to XML
            HTMLtoXML(tranid, userid, lotid);
            //Code to stage movement
            #region Stage Movement
            //code to complete current stage

            var checkout = getCheckout(tranid, userid, "C", "checkout_currentautostage", "0", "", "0");

            //code to insert new lot transaction for next stage
            string nextstage = nextjobworkflowid;
            JArray jobdet = GetNextJobworkflowdetails(jobid);
            var res = jobdet.Where(c => (c["stagename_alias"].ToString() == CustomConfiguration.AppSettings["KEA_XML_Conversion"].ToString())).FirstOrDefault();
            if (res != null)
            {
                nextstage = res["nextstage"].ToString();
            }

            Console.WriteLine("KLI:" + stagename_alias + "- nextstage:" + nextstage);
            var checkout_next = getCheckout(tranid, userid, "R", "insert_lot_transaction_details_only", nextstage, "", lotid);

            //code to insert comments
            insertLotComments(null, "", tranid.ToString(), "C", nextstage.ToString().ToString(), jobid, lotid);
            #endregion
            // code to get next tranid
            var json = new List<transactionout>();
            foreach (var checkout_next_item in checkout_next)
            {
                JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                json.Add(JsonConvert.DeserializeObject<transactionout>(aa[0].ToString()));
            }
            var next_tranid = json[0].tranid.ToString();
            FileMovement(tranid, next_tranid);
            //callautostage(tranid, userid);

            Console.WriteLine("KLI:" + stagename_alias + "- Checkout App ends");
        }
        private static void StartCEStage(string tranid, string userid, string cjobworkflowid, string lotid, string jobid, string stagename_alias)
        {
            //#region Stage Movement
            ////code to complete current stage
            //var checkout = getCheckout(Ctranid, userid, "C", "checkout_currentstage", "0", "", "0");
            //Console.WriteLine("checkout: Completes");
            ////code to insert new lot transaction for next stage
            ////string nextstage = obj["nextstage"].ToString();//this will return next stage jobworkflowdefid
            //var checkout_next = getCheckout("0", "0", "R", "insert_lot_transaction_details_only", nextstage, "", lotid);
            //Console.WriteLine("checkout_next: completes");
            ////code to insert comments
            //insertLotComments(null, "", Ctranid.ToString(), "C", nextstage.ToString().ToString(), jobid, lotid);
            //#endregion

            //#region File Movement
            //// filemovement
            //Console.WriteLine("File movement starts");
            //var json = new List<transactionout>();
            //foreach (var checkout_next_item in checkout_next)
            //{
            //    JArray aa = JArray.Parse(checkout_next_item.json.ToString());
            //    json.Add(JsonConvert.DeserializeObject<transactionout>(aa[0].ToString()));
            //}
            //var next_tranid = json[0].tranid.ToString();
            //FileMovementServerToServer(Ctranid, next_tranid, false);
            //Console.WriteLine("File movement ends");
            //#endregion

            Console.WriteLine("============StartCEStage===========");
            try
            {
                Console.WriteLine("Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid);
                var data_input = new
                {
                    errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid,
                    createdby = 0,
                    controller = "KLI_IO_SERVICE: InStartCEStage: Method Starts"
                };
                CommonRepository.addlog(data_input, "errorlog");

                ServerInfo servinfo = new ServerInfo();
                string serverpath = servinfo.GetServerPath(tranid, "serverinfo", false);
                string server_inpath = string.Empty;
                string server_outpath = string.Empty;

                server_inpath = Path.Combine(serverpath, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
                server_outpath = Path.Combine(serverpath, CustomConfiguration.AppSettings["ServerOUTPATH"].ToString());
                Console.WriteLine("CE:server_inpath" + server_inpath);
                Console.WriteLine("CE:server_outpath" + server_outpath);

                var data = new { transactionid = tranid };
                var input = JsonConvert.SerializeObject(data);
                var translist = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getallbytransid");
                var dt = JArray.Parse(translist.ToString());
                var objtrans = JObject.Parse(dt[0].ToString());

                string transkey = objtrans["transactionkey"].ToString();
                string lottitle = objtrans["lottitle"].ToString();
                string filename = lottitle + ".zip";

                data_input = new
                {
                    errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid,
                    createdby = 0,
                    controller = "KLI_IO_SERVICE: In StartCEStage: HTMLtoXML Starts"
                };
                CommonRepository.addlog(data_input, "errorlog");

                HTMLtoWORD(tranid, userid, lotid);

                data_input = new
                {
                    errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid,
                    createdby = 0,
                    controller = "KLI_IO_SERVICE: In StartCEStage: HTMLtoWord completed"
                };
                CommonRepository.addlog(data_input, "errorlog");

                string filePath = server_inpath;
                string jobworkflow_id = cjobworkflowid;
                var mail_data = new { jobworkflowid = jobworkflow_id };
                var mail_input = JsonConvert.SerializeObject(mail_data);
                var mailtemp_list = CommonRepository.ExecuteSP_ReturnList2("spmailtemplatemasterselect", mail_input, "getbyjobworkflowid");
                var mailtemp_dt = JArray.Parse(mailtemp_list.ToString());
                //var obj_mailtemp = JObject.Parse(mailtemp_dt[0].ToString());
                mailtemplateModel mobj = JsonConvert.DeserializeObject<mailtemplateModel>(mailtemp_dt[0].ToString());
                int mailtemplate_id = mobj.mailtemplateid;

                data_input = new
                {
                    errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid + " MailTemplateid: " + mailtemplate_id,
                    createdby = 0,
                    controller = "KLI_IO_SERVICE: In StartCEStage: Getting MailTemplateID to Send Mail"
                };
                CommonRepository.addlog(data_input, "errorlog");
                Console.WriteLine("===========Sending Mail functionality starts==================");
                var usr_mailmap_data = new { mailtemplateid = mailtemplate_id };
                var usr_mailmap_input = JsonConvert.SerializeObject(usr_mailmap_data);
                var usr_mailmap_list = CommonRepository.ExecuteSP_ReturnList2("spusermailtemplatemappingselect", usr_mailmap_input, "getbyid");
                var usr_mailmap_list_dt = JArray.Parse(usr_mailmap_list.ToString());
                var obj_mailmap = JObject.Parse(usr_mailmap_list_dt[0].ToString());

                dynamic dynJson = JsonConvert.DeserializeObject(obj_mailmap["userid"].ToString());
                foreach (var item in dynJson)
                {
                    int c_userid = item.userid;
                    var u_data = new { userid_p = c_userid };
                    var u_input = JsonConvert.SerializeObject(u_data);
                    var u_list = CommonRepository.ExecuteSP_ReturnList2("spusermasterselect", u_input, "getbyid");
                    var u_list_dt = JArray.Parse(u_list.ToString());
                    var u_obj = JObject.Parse(u_list_dt[0].ToString());

                    string c_username = u_obj["username"].ToString();
                    string c_emailid = u_obj["emailid"].ToString();

                    StringBuilder sb_body = new StringBuilder(mobj.body);
                    StringBuilder sb_subject = new StringBuilder(mobj.subject);
                    string serverpathdownload = CustomConfiguration.AppSettings["kli_rootpathbase"] + "/#/downloader";
                    string serverpathupload = CustomConfiguration.AppSettings["kli_rootpathbase"] + "/#/uploader";
                    if (!string.IsNullOrEmpty(serverpathdownload))
                    {
                        sb_body.Replace("$$downloadpath", "<a href='" + serverpathdownload + "?L=" + transkey + "&U=" + c_userid + "&F=" + filename + "&T=" + tranid + "'>here</a>");
                    }
                    if (!string.IsNullOrEmpty(serverpathupload))
                    {
                        sb_body.Replace("$$uploadpath", "<a href='" + serverpathupload + "?L=" + transkey + "&U=" + c_userid + "&T=" + tranid + "'>here</a>");
                    }

                    sb_body.Replace("$$username", c_username);
                    sb_body.Replace("$$stagename_alias", stagename_alias);
                    sb_body.Replace("$$chapter", lottitle);

                    var j_data = new { jobid = jobid };
                    var j_input = JsonConvert.SerializeObject(j_data);
                    var j_list = CommonRepository.ExecuteSP_ReturnList2("spjobmasterselect", j_input, "getbyjobid");
                    var j_list_dt = JArray.Parse(j_list.ToString());
                    var j_obj = JObject.Parse(j_list_dt[0].ToString());

                    sb_body.Replace("$$jobtitle", j_obj["title"].ToString());

                    //var t_data = new { jobid = jobid, jobworkflowid = jobworkflow_id };
                    //var t_input = JsonConvert.SerializeObject(t_data);
                    //var t_list = CommonRepository.ExecuteSP_ReturnList2("spjobworkflowdefinitionselect", t_input, "gettatbyid");
                    //var t_list_dt = JArray.Parse(t_list.ToString());
                    //var t_obj = JObject.Parse(t_list_dt[0].ToString());

                    //string tathours_p = t_obj["tathours"].ToString();
                    //string tattype_p = t_obj["tattype"].ToString();

                    sb_body.Replace("$$duedate", "");

                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid,
                        createdby = 0,
                        controller = "KLI_IO_SERVICE: In StartCEStage: Sending Mail starts"
                    };
                    CommonRepository.addlog(data_input, "errorlog");

                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid,
                        createdby = 0,
                        controller = "KLI_IO_SERVICE: In StartCEStage: Mail ID: " + c_emailid
                    };
                    CommonRepository.addlog(data_input, "errorlog");

                    CommonClass.SendMail(c_emailid, sb_body, sb_subject);

                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid,
                        createdby = 0,
                        controller = "KLI_IO_SERVICE: In StartCEStage: Sending Mail completed"
                    };
                    CommonRepository.addlog(data_input, "errorlog");
                }
                Console.WriteLine("============StartCEStage=======Ends====");
                Console.WriteLine("KLI:CE - Checkin App ends");
            }
            catch (Exception ex)
            {
                var data_input = new
                {
                    errormessage = "Tranid: " + tranid + " Jobid: " + jobid + " Jobworkflowid: " + cjobworkflowid + " Exception: " + ex.Message,
                    createdby = 0,
                    controller = "In StartCEStage: Error"
                };
                int retval = CommonRepository.addlog(data_input, "errorlog");
            }
        }

        public static bool isWindowsWK = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
        public static string localpathwindows = System.AppDomain.CurrentDomain.BaseDirectory;
        public static string htmlFilepathwindows = Path.Combine(localpathwindows, "Temp", "html");
        public static string XMLFilepathwindows = Path.Combine(localpathwindows, "Temp", "OutlineConfig");
        public static string localpathlinux = CustomConfiguration.AppSettings["editortoolspathlinux"];
        public static string htmlFilepathlinux = Path.Combine(localpathlinux, "Temp", "html");
        public static string XMLFilepathlinux = Path.Combine(localpathlinux, "Temp", "OutlineConfig");

        public static string exportwordfilepathlinux = CustomConfiguration.AppSettings["exportwordfilepathlinux"].ToString();

        public static void HTMLtoWORD(string tranid, string userid, string lotid)
        {
            Console.WriteLine("...........HTMLtoWORD........hits");
            //code to get data from tranid
            var data = new { transactionid = tranid, lotid = lotid };
            var input = JsonConvert.SerializeObject(data);
            Console.WriteLine("input:" + input);
            var translist = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getinputforhtmltoxml");
            var dt = JArray.Parse(translist.ToString());
            var objtrans = JObject.Parse(dt[0].ToString());

            string filename = objtrans["filename"].ToString();
            int projectdid = Convert.ToInt32(objtrans["projectdefinitionid"].ToString());
            int projectid = Convert.ToInt32(objtrans["projectid"].ToString());
            string lotkey = objtrans["lotkey"].ToString();
            string stagenm = objtrans["stagename_alias"].ToString();

            var data_input = (dynamic)null;
            try
            {
                ServerInfo servinfo = new ServerInfo();
                string serverinfo = servinfo.GetServerPath(tranid.ToString(), "serverinfo", false);
                string strindir = CustomConfiguration.AppSettings["ServerINPATH"].ToString();
                string stroutdir = CustomConfiguration.AppSettings["ServerOUTPATH"].ToString();
                string serverworkinginpath = System.IO.Path.Combine(serverinfo, strindir);
                string serverworkingoutpath = System.IO.Path.Combine(serverinfo, stroutdir);

                string htmlfileinpath = System.IO.Path.Combine(serverworkinginpath, filename + ".html");
                string serverquerypath = System.IO.Path.Combine(serverworkinginpath, filename + ".qry");

                string conversion_localpath = string.Empty;
                string outlineXML_localpath = string.Empty;
                string query_localpath = string.Empty;
                string html_localpath = string.Empty;
                string exportwordfile_localpath = string.Empty;
                string xml_localpath = string.Empty;
                string errorlog_localpath = string.Empty;

                if (isWindowsWK)
                {
                    conversion_localpath = Path.Combine(localpathwindows, "Temp", "H2W", tranid.ToString());
                    outlineXML_localpath = Path.Combine(XMLFilepathwindows, tranid.ToString());
                    exportwordfile_localpath = Path.Combine(localpathwindows, "Temp", "exportioservice", lotkey.ToString());
                    errorlog_localpath = System.IO.Path.Combine(conversion_localpath, "Export.log");
                }
                else
                {

                    conversion_localpath = Path.Combine(localpathlinux, "Temp", "H2W", tranid.ToString());
                    outlineXML_localpath = Path.Combine(XMLFilepathlinux, tranid.ToString());
                    exportwordfile_localpath = Path.Combine(exportwordfilepathlinux, lotkey.ToString());
                    errorlog_localpath = System.IO.Path.Combine(conversion_localpath, "Export.log");
                }
                Console.WriteLine("conversion_localpath: " + conversion_localpath);
                Console.WriteLine("outlineXML_localpath: " + outlineXML_localpath);
                Console.WriteLine("exportwordfile_localpath: " + exportwordfile_localpath);
                Console.WriteLine("errorlog_localpath: " + errorlog_localpath);

                if (!System.IO.Directory.Exists(conversion_localpath))
                {
                    System.IO.Directory.CreateDirectory(conversion_localpath);
                }
                if (System.IO.File.Exists(errorlog_localpath))
                {
                    System.IO.File.Delete(errorlog_localpath);
                }
                data_input = new
                {
                    errormessage = "Tranid: " + tranid,
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: html to xml Export Started"
                };
                CommonRepository.addlog(data_input, "errorlog");

                Console.WriteLine(conversion_localpath);
                Console.WriteLine("Get Main Template Export Start...");
                GetMainTemplate(projectdid, stagenm, projectid, filename, "", tranid.ToString(), false, "H2W");
                Console.WriteLine("Outline XML Generated.");
                data_input = new
                {
                    errormessage = "Tranid: " + tranid,
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: html to xml Outline XML Generated"
                };
                CommonRepository.addlog(data_input, "errorlog");

                html_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".html");
                outlineXML_localpath = System.IO.Path.Combine(conversion_localpath, filename + "_outline.xml");
                query_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".qry");
                xml_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".xml");
                if (System.IO.File.Exists(htmlfileinpath))
                {
                    if (System.IO.File.Exists(html_localpath))
                    {
                        System.IO.File.Delete(html_localpath);
                    }
                    System.IO.FileInfo fi1 = new System.IO.FileInfo(htmlfileinpath);
                    fi1.CopyTo(html_localpath);
                    Console.WriteLine("HTML File copied to local working directory.");
                    string alltxt = System.IO.File.ReadAllText(html_localpath);
                    alltxt = Regex.Replace(alltxt, "&nbsp;", " ");
                    //alltxt = Regex.Replace(alltxt, "cke_editable cke_editable_inline cke_contents_ltr", "cke_editable");
                    //alltxt = Regex.Replace(alltxt, "cke_editable ICE-Tracking", "cke_editable");
                    //alltxt = Regex.Replace(alltxt, "cke_editable cke_focus", "cke_editable");
                    alltxt = Regex.Replace(alltxt, "<br>", "");
                    System.IO.File.WriteAllText(html_localpath, alltxt);

                    if (System.IO.File.Exists(serverquerypath))
                    {
                        if (System.IO.File.Exists(query_localpath))
                        {
                            System.IO.File.Delete(query_localpath);
                        }
                        System.IO.FileInfo fi2 = new System.IO.FileInfo(serverquerypath);
                        fi2.CopyTo(query_localpath);
                        Console.WriteLine("Query File copied to local working directory.");
                    }
                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid,
                        createdby = userid,
                        controller = "KLI_IO_SERVICE: html to xml- HTML and QUERY FILE COPIED TO LOCAL DIRECTORY"
                    };
                    CommonRepository.addlog(data_input, "errorlog");
                    string localpath = string.Empty;
                    if (isWindowsWK)
                    {
                        localpath = localpathwindows;
                    }
                    else
                    {
                        localpath = localpathlinux;
                    }
                    string H2XExePath = Path.Combine(localpath, "Converters", "html2xml", "html2xml.dll");
                    string KLIConverterExePath = Path.Combine(localpath, "Converters", "KLI_XTW_CORE", "KLI_XTW_CORE.dll");
                    string args = string.Empty;

                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid + "ExePath: " + H2XExePath.ToString(),
                        createdby = userid,
                        controller = "KLI_IO_SERVICE: H2X transformation - localpath"
                    };
                    CommonRepository.addlog(data_input, "errorlog");
                    try
                    {
                        if (System.IO.File.Exists(H2XExePath))
                        {
                            Console.WriteLine("HTML to XML Conversion start...");
                            Console.WriteLine("H2X exe file with location: " + H2XExePath);


                            args = "\"" + H2XExePath + "\" \"" + html_localpath + "\" false";
                            Console.WriteLine("H2X args: " + args);
                            System.Diagnostics.Process procInfo = new System.Diagnostics.Process();
                            procInfo.StartInfo.WorkingDirectory = localpath;
                            procInfo.StartInfo.CreateNoWindow = true;
                            procInfo.StartInfo.UseShellExecute = false;
                            procInfo.StartInfo.RedirectStandardError = true;
                            procInfo.StartInfo.FileName = "dotnet"; //exePath;
                            procInfo.StartInfo.Arguments = args;
                            procInfo.Start();
                            data_input = new
                            {
                                errormessage = "Tranid: " + tranid + " Args: " + args.ToString(),
                                createdby = userid,
                                controller = "KLI_IO_SERVICE: H2X Transformation - run command"
                            };
                            CommonRepository.addlog(data_input, "errorlog");
                            string proError = procInfo.StandardError.ReadToEnd();
                            procInfo.WaitForExit();
                            data_input = new
                            {
                                errormessage = "Tranid: " + tranid,
                                createdby = userid,
                                controller = "KLI_IO_SERVICE: H2X Conversion finished."
                            };
                            CommonRepository.addlog(data_input, "errorlog");
                            Console.WriteLine("HTML to XML Conversion finished...");
                            data_input = new
                            {
                                errormessage = "Tranid: " + tranid,
                                createdby = userid,
                                controller = "KLI_IO_SERVICE: X2W Conversion started."
                            };
                            CommonRepository.addlog(data_input, "errorlog");
                            Console.WriteLine("XML to WORD Conversion started...");
                            Console.WriteLine("xml_localpath:" + xml_localpath);
                            if (System.IO.File.Exists(xml_localpath))
                            {
                                string XMLToWordArg = string.Empty;
                                if (!System.IO.File.Exists(query_localpath))
                                {
                                    query_localpath = "";
                                    data_input = new
                                    {
                                        errormessage = "Tranid: " + tranid,
                                        createdby = userid,
                                        controller = "KLI_IO_SERVICE: X2W - QUERY File is not Present"
                                    };
                                    CommonRepository.addlog(data_input, "errorlog");
                                }
                                Console.WriteLine("outlineXML_localpath:" + outlineXML_localpath);
                                if (!System.IO.File.Exists(outlineXML_localpath))
                                {
                                    outlineXML_localpath = "";
                                    data_input = new
                                    {
                                        errormessage = "Tranid: " + tranid,
                                        createdby = userid,
                                        controller = "KLI_IO_SERVICE: X2W - Outline XML File is not Present"
                                    };
                                    CommonRepository.addlog(data_input, "errorlog");
                                }
                                try
                                {
                                    if (System.IO.File.Exists(KLIConverterExePath))
                                    {
                                        XMLToWordArg = "\"" + KLIConverterExePath + "\" \"" + xml_localpath + "\" \"" + query_localpath + "\" \"" + outlineXML_localpath + "\" \"" + lotkey + "\"";
                                        Console.WriteLine("localpath: " + localpath);
                                        Console.WriteLine("XMLToWordArg: " + XMLToWordArg);
                                        System.Diagnostics.Process procInfo1 = new System.Diagnostics.Process();
                                        procInfo1.StartInfo.WorkingDirectory = localpath;
                                        procInfo1.StartInfo.CreateNoWindow = true;
                                        procInfo1.StartInfo.UseShellExecute = false;
                                        procInfo1.StartInfo.RedirectStandardError = true;
                                        procInfo1.StartInfo.FileName = "dotnet";// KLIConverterExePath;
                                        procInfo1.StartInfo.Arguments = XMLToWordArg;
                                        procInfo1.Start();
                                        data_input = new
                                        {
                                            errormessage = "Tranid: " + tranid,
                                            createdby = userid,
                                            controller = "KLI_IO_SERVICE: X2W Transformation - run command"
                                        };
                                        CommonRepository.addlog(data_input, "errorlog");
                                        string proError11 = procInfo1.StandardError.ReadToEnd();
                                        procInfo1.WaitForExit();
                                    }

                                    string wordFilePath = Path.Combine(conversion_localpath, "output");
                                    string word_localpath = Path.Combine(wordFilePath, filename + ".docx");
                                    string ExportWord_localpath_File = Path.Combine(exportwordfile_localpath, filename + ".docx");
                                    Console.WriteLine("wordFilePath: " + wordFilePath);
                                    Console.WriteLine("word_localpath: " + word_localpath);
                                    Console.WriteLine("ExportWord_localpath_File: " + ExportWord_localpath_File);
                                    if (System.IO.File.Exists(word_localpath))
                                    {
                                        Console.WriteLine("Exported Word File Location: " + word_localpath);
                                        if (!Directory.Exists(exportwordfile_localpath))
                                        {
                                            Directory.CreateDirectory(exportwordfile_localpath);
                                        }
                                        if (System.IO.File.Exists(ExportWord_localpath_File))
                                        {
                                            System.IO.File.Delete(ExportWord_localpath_File);
                                        }
                                        System.IO.FileInfo fi2 = new System.IO.FileInfo(word_localpath);
                                        fi2.CopyTo(ExportWord_localpath_File);
                                        Console.WriteLine("Word File moved to exported location.");
                                        if (System.IO.File.Exists(ExportWord_localpath_File))
                                        {
                                            try
                                            {
                                                byte[] fileBytes = null;
                                                fileBytes = System.IO.File.ReadAllBytes(ExportWord_localpath_File);
                                                Console.WriteLine("X2W conversion Export Completes...");
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine(ex.Message, "KLI_IO_SERVICE: X2W Transformation -Error log");
                                                data_input = new
                                                {
                                                    errormessage = "Tranid: " + tranid + " Error: " + ex.Message.ToString(),
                                                    createdby = userid,
                                                    controller = "KLI_IO_SERVICE: X2W conversion Export Failed"
                                                };
                                                CommonRepository.addlog(data_input, "errorlog");
                                                CommonRepository.WriteLog(ex.Message, "KLI_IO_SERVICE: X2W Transformation -Error log");
                                                throw ex;
                                            }
                                            Console.WriteLine("tranid:" + tranid + "serverinfo:" + serverinfo + "IN" + "conversion_localpath" + conversion_localpath);
                                            FileMove_LocalTOServer(tranid, serverinfo, "IN", "", conversion_localpath);
                                        }
                                        else
                                        {
                                            Console.WriteLine("Imported file does not exist.");
                                            data_input = new
                                            {
                                                errormessage = "Tranid: " + tranid + " Error: Imported file does not exist.",
                                                createdby = userid,
                                                controller = "KLI_IO_SERVICE: X2W conversion Import Failed"
                                            };
                                            CommonRepository.addlog(data_input, "errorlog");
                                        }
                                    }
                                    else
                                    {
                                        data_input = new
                                        {
                                            errormessage = "Tranid: " + tranid + " Error: Word File not present, H2W conversion failed.",
                                            createdby = userid,
                                            controller = "KLI_IO_SERVICE: H2W conversion failed."
                                        };
                                        CommonRepository.addlog(data_input, "errorlog");
                                        Console.WriteLine("Word File not present, H2W conversion failed.");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    data_input = new
                                    {
                                        errormessage = "Tranid: " + tranid + " Error: " + ex.Message.ToString(),
                                        createdby = userid,
                                        controller = "KLI_IO_SERVICE: X2W Transformation - ex.Message"
                                    };
                                    CommonRepository.addlog(data_input, "errorlog");
                                    CommonRepository.WriteLog(ex.Message, "KLI_IO_SERVICE: X2W Transformation - Error log");
                                    throw ex;
                                }
                            }
                            else
                            {
                                Console.WriteLine("XML file not generated", "KLI_IO_SERVICE: html to xml Transformation - Error log");
                                data_input = new
                                {
                                    errormessage = "Tranid: " + tranid + " Error: XML file not generated",
                                    createdby = userid,
                                    controller = "KLI_IO_SERVICE: html to xml Transformation"
                                };
                                CommonRepository.addlog(data_input, "errorlog");
                                CommonRepository.WriteLog("XML file not generated", "KLI_IO_SERVICE: html to xml Transformation - Error log");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        data_input = new
                        {
                            errormessage = "Tranid: " + tranid + " Error: " + ex.Message.ToString(),
                            createdby = userid,
                            controller = "KLI_IO_SERVICE: html to xml Transformation - ex.Message"
                        };
                        CommonRepository.addlog(data_input, "errorlog");
                        CommonRepository.WriteLog(ex.Message, "KLI_IO_SERVICE: html to xml Transformation - Error log");
                        Console.WriteLine("HTML to XML Conversion failed...");
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                data_input = new
                {
                    errormessage = "Tranid: " + tranid + " Error: " + ex.Message.ToString(),
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: html to xml Transformation - ex.Message"
                };
                CommonRepository.addlog(data_input, "errorlog");
                CommonRepository.WriteLog(ex.Message, "KLI_IO_SERVICE: html to xml Transformation -Error log");
                Console.WriteLine(ex.Message + " at " + ex.StackTrace);
                throw ex;
            }
        }
        public static string GetSecurityKey(string strdocpath, string strBaseDirectory)
        {
            string strlotKey = "";
            using (FileStream zipToOpen = new FileStream(strdocpath, FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        if (entry.FullName.EndsWith("customUI.xml", StringComparison.OrdinalIgnoreCase))
                        {
                            entry.ExtractToFile(strBaseDirectory + "//temp.xml", true);
                            XmlDocument odoc = new XmlDocument();
                            odoc.Load(strBaseDirectory + "//temp.xml");
                            strlotKey = odoc.GetElementsByTagName("tab")[0].Attributes["id"].Value;
                            break;
                        }
                    }
                }
            }
            strlotKey = strlotKey.Replace("stylerTab1-", "").Trim();
            return strlotKey;
        }
        public static void WORDtoHTML(string tranid, string userid, string lotid)
        {
            //code to get data from tranid
            var data = new { transactionid = tranid, lotid = lotid };
            var input = JsonConvert.SerializeObject(data);
            var translist = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getinputforhtmltoxml");
            var dt = JArray.Parse(translist.ToString());
            var objtrans = JObject.Parse(dt[0].ToString());

            string filename = objtrans["filename"].ToString();
            int projectdid = Convert.ToInt32(objtrans["projectdefinitionid"].ToString());
            int projectid = Convert.ToInt32(objtrans["projectid"].ToString());
            string lotkey = objtrans["lotkey"].ToString();
            string stagenm = objtrans["stagename_alias"].ToString();

            var data_input = (dynamic)null;
            try
            {
                ServerInfo servinfo = new ServerInfo();
                string serverinfo = servinfo.GetServerPath(tranid.ToString(), "serverinfo", false);
                string strindir = CustomConfiguration.AppSettings["ServerINPATH"].ToString();
                string stroutdir = CustomConfiguration.AppSettings["ServerOUTPATH"].ToString();
                string serverworkinginpath = System.IO.Path.Combine(serverinfo, strindir);
                string serverworkingoutpath = System.IO.Path.Combine(serverinfo, stroutdir);

                string wordfile_outpath = System.IO.Path.Combine(serverworkingoutpath, filename + ".docx");

                string conversion_localpath = string.Empty;
                string outlineXML_localpath = string.Empty;
                string query_localpath = string.Empty;
                string word_localpath = string.Empty;
                string xml_localpath = string.Empty;
                string html_localpath = string.Empty;
                string toc_localpath = string.Empty;
                string errorlog_localpath = string.Empty;

                if (isWindowsWK)
                {
                    conversion_localpath = Path.Combine(localpathwindows, "Temp", "W2H", tranid.ToString());
                    outlineXML_localpath = Path.Combine(XMLFilepathwindows, tranid.ToString());
                    errorlog_localpath = System.IO.Path.Combine(conversion_localpath, "Import.log");
                }
                else
                {
                    conversion_localpath = Path.Combine(localpathlinux, "Temp", "W2H", tranid.ToString());
                    outlineXML_localpath = Path.Combine(XMLFilepathlinux, tranid.ToString());
                    errorlog_localpath = System.IO.Path.Combine(conversion_localpath, "Import.log");
                }
                if (!System.IO.Directory.Exists(conversion_localpath))
                {
                    System.IO.Directory.CreateDirectory(conversion_localpath);
                }
                if (System.IO.File.Exists(errorlog_localpath))
                {
                    System.IO.File.Delete(errorlog_localpath);
                }
                data_input = new
                {
                    errormessage = "Tranid: " + tranid,
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: Word to XML Export Started"
                };
                CommonRepository.addlog(data_input, "errorlog");
                Console.WriteLine(conversion_localpath);

                word_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".docx");
                outlineXML_localpath = System.IO.Path.Combine(conversion_localpath, filename + "_outline.xml");
                query_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".qry");
                xml_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".xml");
                html_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".html");
                toc_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".toc");
                if (System.IO.File.Exists(wordfile_outpath))
                {
                    if (System.IO.File.Exists(word_localpath))
                    {
                        System.IO.File.Delete(word_localpath);
                    }
                    System.IO.FileInfo fi1 = new System.IO.FileInfo(wordfile_outpath);
                    fi1.CopyTo(word_localpath);
                    Console.WriteLine("WORD File copied to local working directory.");
                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid,
                        createdby = userid,
                        controller = "KLI_IO_SERVICE: WORD FILE COPIED TO LOCAL DIRECTORY"
                    };
                    CommonRepository.addlog(data_input, "errorlog");

                    string strlotkeyfromword = GetSecurityKey(word_localpath, Path.GetDirectoryName(word_localpath));

                    if (strlotkeyfromword != lotkey)
                    {
                        CommonRepository.WriteLog("Word file out from LAPs system. Please load correct file.", "KLI_IO_SERVICE: Word to XML Transformation - Error log");
                        data_input = new
                        {
                            errormessage = "Tranid: " + tranid + " Error: Word file out from LAPs system. Please load correct file.",
                            createdby = userid,
                            controller = "KLI_IO_SERVICE: Word to XML Transformation - Error log"
                        };
                        CommonRepository.addlog(data_input, "errorlog");
                    }

                    string localpath = string.Empty;
                    if (isWindowsWK)
                    {
                        localpath = localpathwindows;
                    }
                    else
                    {
                        localpath = localpathlinux;
                    }
                    string WordtoXMLexePath = Path.Combine(localpath, "Converters", "KLI_WTX_CORE", "KLI_WTX_CORE.dll");
                    string XMLtoHTMLExePath = Path.Combine(localpath, "Converters", "xml2html", "xml2html.dll");
                    string args = string.Empty;
                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid + "ExePath: " + WordtoXMLexePath.ToString(),
                        createdby = userid,
                        controller = "KLI_IO_SERVICE: W2X transformation - localpath"
                    };
                    CommonRepository.addlog(data_input, "errorlog");
                    try
                    {
                        if (System.IO.File.Exists(WordtoXMLexePath))
                        {
                            Console.WriteLine("WORD to XML Conversion start...");
                            Console.WriteLine("W2X exe file with location: " + WordtoXMLexePath);
                            Console.WriteLine("W2X args: " + args);
                            args = "\"" + WordtoXMLexePath + "\" \"" + word_localpath + "\"";
                            System.Diagnostics.Process procInfo = new System.Diagnostics.Process();
                            procInfo.StartInfo.WorkingDirectory = localpath;
                            procInfo.StartInfo.CreateNoWindow = true;
                            procInfo.StartInfo.UseShellExecute = false;
                            procInfo.StartInfo.RedirectStandardError = true;
                            procInfo.StartInfo.FileName = "dotnet"; //exePath;
                            procInfo.StartInfo.Arguments = args;
                            procInfo.Start();
                            data_input = new
                            {
                                errormessage = "Tranid: " + tranid + " Args: " + args.ToString(),
                                createdby = userid,
                                controller = "KLI_IO_SERVICE: W2X Transformation - run command"
                            };
                            CommonRepository.addlog(data_input, "errorlog");
                            string proError = procInfo.StandardError.ReadToEnd();
                            procInfo.WaitForExit();
                            data_input = new
                            {
                                errormessage = "Tranid: " + tranid,
                                createdby = userid,
                                controller = "KLI_IO_SERVICE: W2X Conversion finished."
                            };
                            CommonRepository.addlog(data_input, "errorlog");
                            Console.WriteLine("WORD to XML Conversion finished...");
                            data_input = new
                            {
                                errormessage = "Tranid: " + tranid,
                                createdby = userid,
                                controller = "KLI_IO_SERVICE: X2H Conversion started."
                            };
                            CommonRepository.addlog(data_input, "errorlog");
                            Console.WriteLine("XML to HTML Conversion started...");
                            if (System.IO.File.Exists(xml_localpath))
                            {
                                string XMLtoHTMLArg = string.Empty;
                                if (!System.IO.File.Exists(query_localpath))
                                {
                                    query_localpath = "";
                                    data_input = new
                                    {
                                        errormessage = "Tranid: " + tranid,
                                        createdby = userid,
                                        controller = "KLI_IO_SERVICE: X2H - QUERY File is not Present"
                                    };
                                    CommonRepository.addlog(data_input, "errorlog");
                                }
                                Console.WriteLine("Get Main Template Export Start...");
                                GetMainTemplate(projectdid, stagenm, projectid, filename, "", tranid.ToString(), false, "W2H");
                                Console.WriteLine("Outline XML Generated.");
                                data_input = new
                                {
                                    errormessage = "Tranid: " + tranid,
                                    createdby = userid,
                                    controller = "KLI_IO_SERVICE: Word to XML: Outline XML Generated"
                                };
                                CommonRepository.addlog(data_input, "errorlog");
                                if (!System.IO.File.Exists(outlineXML_localpath))
                                {
                                    outlineXML_localpath = "";
                                    data_input = new
                                    {
                                        errormessage = "Tranid: " + tranid,
                                        createdby = userid,
                                        controller = "KLI_IO_SERVICE: X2H - Outline XML File is not Present"
                                    };
                                    CommonRepository.addlog(data_input, "errorlog");
                                }
                                try
                                {
                                    if (System.IO.File.Exists(XMLtoHTMLExePath))
                                    {
                                        XMLtoHTMLArg = "\"" + XMLtoHTMLExePath + "\" \"" + xml_localpath + "\" \"" + outlineXML_localpath + "\"";
                                        System.Diagnostics.Process procInfo1 = new System.Diagnostics.Process();
                                        procInfo1.StartInfo.WorkingDirectory = localpath;
                                        procInfo1.StartInfo.CreateNoWindow = true;
                                        procInfo1.StartInfo.UseShellExecute = false;
                                        procInfo1.StartInfo.RedirectStandardError = true;
                                        procInfo1.StartInfo.FileName = "dotnet";// KLIConverterExePath;
                                        procInfo1.StartInfo.Arguments = XMLtoHTMLArg;
                                        procInfo1.Start();
                                        data_input = new
                                        {
                                            errormessage = "Tranid: " + tranid,
                                            createdby = userid,
                                            controller = "KLI_IO_SERVICE: X2W Transformation - run command"
                                        };
                                        CommonRepository.addlog(data_input, "errorlog");
                                        string proError11 = procInfo1.StandardError.ReadToEnd();
                                        procInfo1.WaitForExit();
                                    }

                                    string XTHErrorlog = Path.Combine(conversion_localpath, filename + ".log");
                                    if (!System.IO.File.Exists(XTHErrorlog))
                                    {
                                        if (System.IO.File.Exists(html_localpath))
                                        {
                                            //file move local to server
                                            FileMove_LocalTOServer(tranid, serverinfo, "OUT", "", conversion_localpath);
                                        }
                                        else
                                        {
                                            data_input = new
                                            {
                                                errormessage = "Tranid: " + tranid + " Error: Failed. HTML file not present",
                                                createdby = 0,
                                                controller = "KLI_IO_SERVICE: X2W Transformation- X2H Conversion"
                                            };
                                            CommonRepository.addlog(data_input, "errorlog");
                                            CommonRepository.WriteLog("Failed to Import XML to HTML", "KLI_IO_SERVICE: html to xml Transformation - Error log");
                                        }
                                    }
                                    else
                                    {
                                        data_input = new
                                        {
                                            errormessage = "Tranid: " + tranid + " Error in X2H conversion:" + XTHErrorlog,
                                            createdby = userid,
                                            controller = "KLI_IO_SERVICE: X2H conversion failed."
                                        };
                                        CommonRepository.addlog(data_input, "errorlog");
                                        Console.WriteLine("Error in X2H conversion:" + XTHErrorlog);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    data_input = new
                                    {
                                        errormessage = "Tranid: " + tranid + " Error: " + ex.Message.ToString(),
                                        createdby = userid,
                                        controller = "KLI_IO_SERVICE: X2W Transformation - ex.Message"
                                    };
                                    CommonRepository.addlog(data_input, "errorlog");
                                    CommonRepository.WriteLog(ex.Message, "KLI_IO_SERVICE: X2W Transformation - Error log");
                                    throw ex;
                                }
                            }
                            else
                            {
                                data_input = new
                                {
                                    errormessage = "Tranid: " + tranid + " Error: XML file not generated",
                                    createdby = userid,
                                    controller = "KLI_IO_SERVICE: Word to XML Transformation"
                                };
                                CommonRepository.addlog(data_input, "errorlog");
                                CommonRepository.WriteLog("XML file not generated", "KLI_IO_SERVICE: Word to XML Transformation - Error log");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        data_input = new
                        {
                            errormessage = "Tranid: " + tranid + " Error: " + ex.Message.ToString(),
                            createdby = userid,
                            controller = "KLI_IO_SERVICE: html to xml Transformation - ex.Message"
                        };
                        CommonRepository.addlog(data_input, "errorlog");
                        CommonRepository.WriteLog(ex.Message, "KLI_IO_SERVICE: html to xml Transformation - Error log");
                        Console.WriteLine("HTML to XML Conversion failed...");
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                data_input = new
                {
                    errormessage = "Tranid: " + tranid + " Error: " + ex.Message.ToString(),
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: html to xml Transformation - ex.Message"
                };
                CommonRepository.addlog(data_input, "errorlog");
                CommonRepository.WriteLog(ex.Message, "KLI_IO_SERVICE: html to xml Transformation -Error log");
                Console.WriteLine(ex.Message + " at " + ex.StackTrace);
                throw ex;
            }
        }
        public static void HTMLtoXML(string tranid, string userid, string lotid)
        {
            Console.WriteLine("HTMLtoXML function hits");
            //code to get data from tranid
            var data = new { transactionid = tranid, lotid = lotid };
            var input = JsonConvert.SerializeObject(data);
            Console.WriteLine("HTMLtoXML:input" + input);
            var translist = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getinputforhtmltoxml");
            var dt = JArray.Parse(translist.ToString());
            var objtrans = JObject.Parse(dt[0].ToString());
            Console.WriteLine("HTMLtoXML:objtrans" + objtrans);
            string filename = objtrans["filename"].ToString();
            int projectdid = Convert.ToInt32(objtrans["projectdefinitionid"].ToString());
            int projectid = Convert.ToInt32(objtrans["projectid"].ToString());
            string lotkey = objtrans["lotkey"].ToString();
            string stagenm = objtrans["stagename_alias"].ToString();
            var data_input = (dynamic)null;
            try
            {
                ServerInfo servinfo = new ServerInfo();
                string serverinfo = servinfo.GetServerPath(tranid.ToString(), "serverinfo", false);
                string strindir = CustomConfiguration.AppSettings["ServerINPATH"].ToString();
                string stroutdir = CustomConfiguration.AppSettings["ServerOUTPATH"].ToString();
                string serverworkinginpath = System.IO.Path.Combine(serverinfo, strindir);
                //string serverworkingoutpath = System.IO.Path.Combine(serverinfo, stroutdir);
                string htmlfileinpath = System.IO.Path.Combine(serverworkinginpath, filename + ".html");
                string serverquerypath = System.IO.Path.Combine(serverworkinginpath, filename + ".qry");
                string conversion_localpath = string.Empty;
                string outlineXML_localpath = string.Empty;
                string query_localpath = string.Empty;
                string html_localpath = string.Empty;
                string exportwordfile_localpath = string.Empty;
                string xml_localpath = string.Empty;
                string errorlog_localpath = string.Empty;
                if (isWindowsWK)
                {
                    conversion_localpath = Path.Combine(localpathwindows, "Temp", "H2W", tranid.ToString());
                    outlineXML_localpath = Path.Combine(XMLFilepathwindows, tranid.ToString());
                    exportwordfile_localpath = Path.Combine(localpathwindows, "Temp", "exportioservice", lotkey.ToString());
                    errorlog_localpath = System.IO.Path.Combine(conversion_localpath, "Export.log");
                }
                else
                {
                    conversion_localpath = Path.Combine(localpathlinux, "Temp", "H2W", tranid.ToString());
                    outlineXML_localpath = Path.Combine(XMLFilepathlinux, tranid.ToString());
                    exportwordfile_localpath = Path.Combine(exportwordfilepathlinux, lotkey.ToString());
                    errorlog_localpath = System.IO.Path.Combine(conversion_localpath, "Export.log");
                }
                if (!System.IO.Directory.Exists(conversion_localpath))
                {
                    System.IO.Directory.CreateDirectory(conversion_localpath);
                }
                if (System.IO.File.Exists(errorlog_localpath))
                {
                    System.IO.File.Delete(errorlog_localpath);
                }
                data_input = new
                {
                    errormessage = "Tranid: " + tranid,
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: html to xml Export Started"
                };
                CommonRepository.addlog(data_input, "errorlog");
                Console.WriteLine(conversion_localpath);
                Console.WriteLine("Get Main Template Export Start...");
                GetMainTemplate(projectdid, stagenm, projectid, filename, "", tranid.ToString(), false, "H2W");
                Console.WriteLine("Outline XML Generated.");
                data_input = new
                {
                    errormessage = "Tranid: " + tranid,
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: html to xml Outline XML Generated"
                };
                CommonRepository.addlog(data_input, "errorlog");
                // html_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".html");
                html_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".html");
                outlineXML_localpath = System.IO.Path.Combine(conversion_localpath, filename + "_outline.xml");
                query_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".qry");
                xml_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".xml");
                if (System.IO.File.Exists(htmlfileinpath))
                {
                    if (System.IO.File.Exists(html_localpath))
                    {
                        System.IO.File.Delete(html_localpath);
                    }
                    System.IO.FileInfo fi1 = new System.IO.FileInfo(htmlfileinpath);
                    fi1.CopyTo(html_localpath);
                    Console.WriteLine("HTML File copied to local working directory.");
                    string alltxt = System.IO.File.ReadAllText(html_localpath);
                    alltxt = Regex.Replace(alltxt, "&nbsp;", " ");
                    //alltxt = Regex.Replace(alltxt, "cke_editable cke_editable_inline cke_contents_ltr", "cke_editable");
                    //alltxt = Regex.Replace(alltxt, "cke_editable ICE-Tracking", "cke_editable");
                    //alltxt = Regex.Replace(alltxt, "cke_editable cke_focus", "cke_editable");
                    alltxt = Regex.Replace(alltxt, "<br>", "");
                    System.IO.File.WriteAllText(html_localpath, alltxt);
                    if (System.IO.File.Exists(serverquerypath))
                    {
                        if (System.IO.File.Exists(query_localpath))
                        {
                            System.IO.File.Delete(query_localpath);
                        }
                        System.IO.FileInfo fi2 = new System.IO.FileInfo(serverquerypath);
                        fi2.CopyTo(query_localpath);
                        Console.WriteLine("Query File copied to local working directory.");
                    }
                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid,
                        createdby = userid,
                        controller = "KLI_IO_SERVICE: html to xml- HTML and QUERY FILE COPIED TO LOCAL DIRECTORY"
                    };
                    CommonRepository.addlog(data_input, "errorlog");
                    string localpath = string.Empty;
                    if (isWindowsWK)
                    {
                        localpath = localpathwindows;
                    }
                    else
                    {
                        localpath = localpathlinux;
                    }
                    string H2XExePath = Path.Combine(localpath, "Converters", "html2xml", "html2xml.dll");
                    string args = string.Empty;
                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid + "ExePath: " + H2XExePath.ToString(),
                        createdby = userid,
                        controller = "KLI_IO_SERVICE: H2X transformation - localpath"
                    };
                    CommonRepository.addlog(data_input, "errorlog");
                    try
                    {
                        if (System.IO.File.Exists(H2XExePath))
                        {
                            Console.WriteLine("HTML to XML Conversion start...");
                            Console.WriteLine("H2X exe file with location: " + H2XExePath);
                            // args = "\"" + H2XExePath + "\" \"" + html_localpath + "\" \"false\" \"true\"";
                            args = "\"" + H2XExePath + "\" \"" + htmlfileinpath + "\" \"false\" \"true\"";
                            Console.WriteLine("H2X args: " + args);
                            System.Diagnostics.Process procInfo = new System.Diagnostics.Process();
                            procInfo.StartInfo.WorkingDirectory = localpath;
                            procInfo.StartInfo.CreateNoWindow = true;
                            procInfo.StartInfo.UseShellExecute = false;
                            procInfo.StartInfo.RedirectStandardError = true;
                            procInfo.StartInfo.FileName = "dotnet"; //exePath;
                            procInfo.StartInfo.Arguments = args;
                            procInfo.Start();
                            data_input = new
                            {
                                errormessage = "Tranid: " + tranid + " Args: " + args.ToString(),
                                createdby = userid,
                                controller = "KLI_IO_SERVICE: H2X Transformation - run command"
                            };
                            CommonRepository.addlog(data_input, "errorlog");
                            string proError = procInfo.StandardError.ReadToEnd();
                            procInfo.WaitForExit();
                            if (System.IO.File.Exists(xml_localpath))
                            {
                                data_input = new
                                {
                                    errormessage = "Tranid: " + tranid,
                                    createdby = userid,
                                    controller = "KLI_IO_SERVICE: H2X Conversion finished."
                                };
                                CommonRepository.addlog(data_input, "errorlog");
                                Console.WriteLine("HTML to XML Conversion finished...");
                            }
                            else
                            {
                                data_input = new
                                {
                                    errormessage = "Tranid: " + tranid + " Error: XML file not generated",
                                    createdby = userid,
                                    controller = "KLI_IO_SERVICE: html to xml Transformation"
                                };
                                CommonRepository.addlog(data_input, "errorlog");
                                CommonRepository.WriteLog("XML file not generated", "KLI_IO_SERVICE: html to xml Transformation - Error log");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        data_input = new
                        {
                            errormessage = "Tranid: " + tranid + " Error: " + ex.Message.ToString(),
                            createdby = userid,
                            controller = "KLI_IO_SERVICE: html to xml Transformation - ex.Message"
                        };
                        CommonRepository.addlog(data_input, "errorlog");
                        CommonRepository.WriteLog(ex.Message, "KLI_IO_SERVICE: html to xml Transformation - Error log");
                        Console.WriteLine("HTML to XML Conversion failed...");
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                data_input = new
                {
                    errormessage = "Tranid: " + tranid + " Error: " + ex.Message.ToString(),
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: html to xml Transformation - ex.Message"
                };
                CommonRepository.addlog(data_input, "errorlog");
                CommonRepository.WriteLog(ex.Message, "KLI_IO_SERVICE: html to xml Transformation -Error log");
                Console.WriteLine(ex.Message + " at " + ex.StackTrace);
                throw ex;
            }
        }

        public static void XMLtoHTML(string tranid, string userid, string lotid)
        {
            Console.WriteLine("XMLtoHTML function hits");
            //code to get data from tranid
            var data = new { transactionid = tranid, lotid = lotid };
            var input = JsonConvert.SerializeObject(data);
            Console.WriteLine("XMLtoHTML:input" + input);
            var translist = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getinputforhtmltoxml");
            var dt = JArray.Parse(translist.ToString());
            var objtrans = JObject.Parse(dt[0].ToString());
            Console.WriteLine("XMLtoHTML:objtrans" + objtrans);
            string filename = objtrans["filename"].ToString();
            int projectdid = Convert.ToInt32(objtrans["projectdefinitionid"].ToString());
            int projectid = Convert.ToInt32(objtrans["projectid"].ToString());
            string lotkey = objtrans["lotkey"].ToString();
            string stagenm = objtrans["stagename_alias"].ToString();
            var data_input = (dynamic)null;
            try
            {
                ServerInfo servinfo = new ServerInfo();
                string serverinfo = servinfo.GetServerPath(tranid.ToString(), "serverinfo", false);
                string strindir = CustomConfiguration.AppSettings["ServerINPATH"].ToString();
                string stroutdir = CustomConfiguration.AppSettings["ServerOUTPATH"].ToString();
                string serverworkinginpath = System.IO.Path.Combine(serverinfo, strindir);
                //string serverworkingoutpath = System.IO.Path.Combine(serverinfo, stroutdir);
                string xmlfileinpath = System.IO.Path.Combine(serverworkinginpath, filename + ".xml");
               // string serverquerypath = System.IO.Path.Combine(serverworkinginpath, filename + ".qry");
                string conversion_localpath = string.Empty;
                string outlineXML_localpath = string.Empty;
               // string query_localpath = string.Empty;
                string html_localpath = string.Empty;
               // string exportwordfile_localpath = string.Empty;
                string xml_localpath = string.Empty;
                string errorlog_localpath = string.Empty;
                if (isWindowsWK)
                {
                    conversion_localpath = Path.Combine(localpathwindows, "Temp", "H2W", tranid.ToString());
                    outlineXML_localpath = Path.Combine(XMLFilepathwindows, tranid.ToString());
              //      exportwordfile_localpath = Path.Combine(localpathwindows, "Temp", "exportioservice", lotkey.ToString());
                    errorlog_localpath = System.IO.Path.Combine(conversion_localpath, "Export.log");
                }
                else
                {
                    conversion_localpath = Path.Combine(localpathlinux, "Temp", "H2W", tranid.ToString());
                    outlineXML_localpath = Path.Combine(XMLFilepathlinux, tranid.ToString());
                //    exportwordfile_localpath = Path.Combine(exportwordfilepathlinux, lotkey.ToString());
                    errorlog_localpath = System.IO.Path.Combine(conversion_localpath, "Export.log");
                }
                if (!System.IO.Directory.Exists(conversion_localpath))
                {
                    System.IO.Directory.CreateDirectory(conversion_localpath);
                }
                if (System.IO.File.Exists(errorlog_localpath))
                {
                    System.IO.File.Delete(errorlog_localpath);
                }
                data_input = new
                {
                    errormessage = "Tranid: " + tranid,
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: xml to html Export Started"
                };
                CommonRepository.addlog(data_input, "errorlog");
                Console.WriteLine(conversion_localpath);
                Console.WriteLine("Get Main Template Export Start...");
                GetMainTemplate(projectdid, stagenm, projectid, filename, "", tranid.ToString(), false, "H2W");
                Console.WriteLine("Outline XML Generated.");
                data_input = new
                {
                    errormessage = "Tranid: " + tranid,
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: html to xml Outline XML Generated"
                };
                CommonRepository.addlog(data_input, "errorlog");
                // html_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".html");
               // html_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".html");
                outlineXML_localpath = System.IO.Path.Combine(conversion_localpath, filename + "_outline.xml");
               // query_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".qry");
                //xml_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".xml");
                if (System.IO.File.Exists(xmlfileinpath))
                {
                    //if (System.IO.File.Exists(html_localpath))
                    //{
                    //    System.IO.File.Delete(html_localpath);
                    //}
                    //System.IO.FileInfo fi1 = new System.IO.FileInfo(xmlfileinpath);
                    //fi1.CopyTo(html_localpath);
                    //Console.WriteLine("HTML File copied to local working directory.");
                    //string alltxt = System.IO.File.ReadAllText(html_localpath);
                    //alltxt = Regex.Replace(alltxt, "&nbsp;", " ");
                    ////alltxt = Regex.Replace(alltxt, "cke_editable cke_editable_inline cke_contents_ltr", "cke_editable");
                    ////alltxt = Regex.Replace(alltxt, "cke_editable ICE-Tracking", "cke_editable");
                    ////alltxt = Regex.Replace(alltxt, "cke_editable cke_focus", "cke_editable");
                    //alltxt = Regex.Replace(alltxt, "<br>", "");
                    //System.IO.File.WriteAllText(html_localpath, alltxt);
                    //if (System.IO.File.Exists(serverquerypath))
                    //{
                    //    if (System.IO.File.Exists(query_localpath))
                    //    {
                    //        System.IO.File.Delete(query_localpath);
                    //    }
                    //    System.IO.FileInfo fi2 = new System.IO.FileInfo(serverquerypath);
                    //    fi2.CopyTo(query_localpath);
                    //    Console.WriteLine("Query File copied to local working directory.");
                    //}
                    //data_input = new
                    //{
                    //    errormessage = "Tranid: " + tranid,
                    //    createdby = userid,
                    //    controller = "KLI_IO_SERVICE: html to xml- HTML and QUERY FILE COPIED TO LOCAL DIRECTORY"
                    //};
                    //CommonRepository.addlog(data_input, "errorlog");
                    string localpath = string.Empty;
                    if (isWindowsWK)
                    {
                        localpath = localpathwindows;
                    }
                    else
                    {
                        localpath = localpathlinux;
                    }
                    string X2HExePath = Path.Combine(localpath, "Converters", "xml2html", "xml2html.dll");
                    string args = string.Empty;
                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid + "ExePath: " + X2HExePath.ToString(),
                        createdby = userid,
                        controller = "KLI_IO_SERVICE: X2H transformation - localpath"
                    };
                    CommonRepository.addlog(data_input, "errorlog");
                    try
                    {
                        if (System.IO.File.Exists(X2HExePath))
                        {
                            Console.WriteLine("XML to HTML Conversion start...");
                            Console.WriteLine("X2H exe file with location: " + X2HExePath);
                            // args = "\"" + H2XExePath + "\" \"" + html_localpath + "\" \"false\" \"true\"";

                            
                            args = "\"" + X2HExePath + "\" \"" + xmlfileinpath + "\" \""+ outlineXML_localpath + "\"";
                            Console.WriteLine("H2X args: " + args);
                            System.Diagnostics.Process procInfo = new System.Diagnostics.Process();
                            procInfo.StartInfo.WorkingDirectory = localpath;
                            procInfo.StartInfo.CreateNoWindow = true;
                            procInfo.StartInfo.UseShellExecute = false;
                            procInfo.StartInfo.RedirectStandardError = true;
                            procInfo.StartInfo.FileName = "dotnet"; //exePath;
                            procInfo.StartInfo.Arguments = args;
                            procInfo.Start();
                            data_input = new
                            {
                                errormessage = "Tranid: " + tranid + " Args: " + args.ToString(),
                                createdby = userid,
                                controller = "KLI_IO_SERVICE: H2X Transformation - run command"
                            };
                            CommonRepository.addlog(data_input, "errorlog");
                            Console.WriteLine("Tranid: " + tranid + " Args: " + args.ToString());
                            Console.WriteLine("KLI_IO_SERVICE: H2X Transformation - run command");
                            string proError = procInfo.StandardError.ReadToEnd();
                            procInfo.WaitForExit();
                            if (System.IO.File.Exists(xml_localpath))
                            {
                                data_input = new
                                {
                                    errormessage = "Tranid: " + tranid,
                                    createdby = userid,
                                    controller = "KLI_IO_SERVICE: H2X Conversion finished."
                                };
                                CommonRepository.addlog(data_input, "errorlog");
                                Console.WriteLine("HTML to XML Conversion finished...");
                            }
                            else
                            {
                                data_input = new
                                {
                                    errormessage = "Tranid: " + tranid + " Error: XML file not generated",
                                    createdby = userid,
                                    controller = "KLI_IO_SERVICE: html to xml Transformation"
                                };
                                CommonRepository.addlog(data_input, "errorlog");
                                CommonRepository.WriteLog("XML file not generated", "KLI_IO_SERVICE: html to xml Transformation - Error log");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        data_input = new
                        {
                            errormessage = "Tranid: " + tranid + " Error: " + ex.Message.ToString(),
                            createdby = userid,
                            controller = "KLI_IO_SERVICE: html to xml Transformation - ex.Message"
                        };
                        CommonRepository.addlog(data_input, "errorlog");
                        CommonRepository.WriteLog(ex.Message, "KLI_IO_SERVICE: html to xml Transformation - Error log");
                        Console.WriteLine("HTML to XML Conversion failed...");
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                data_input = new
                {
                    errormessage = "Tranid: " + tranid + " Error: " + ex.Message.ToString(),
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: html to xml Transformation - ex.Message"
                };
                CommonRepository.addlog(data_input, "errorlog");
                CommonRepository.WriteLog(ex.Message, "KLI_IO_SERVICE: html to xml Transformation -Error log");
                Console.WriteLine(ex.Message + " at " + ex.StackTrace);
                throw ex;
            }
        }
        public static void XMLtoWORD(int tranid, string lotid)
        {
            //code to get data from tranid
            var data = new { transactionid = tranid, lotid = lotid };
            var input = JsonConvert.SerializeObject(data);
            var translist = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getinputforhtmltoxml");
            var dt = JArray.Parse(translist.ToString());
            var objtrans = JObject.Parse(dt[0].ToString());

            string filename = objtrans["filename"].ToString();
            int projectdid = Convert.ToInt32(objtrans["projectdefinitionid"].ToString());
            int projectid = Convert.ToInt32(objtrans["projectid"].ToString());
            string lotkey = objtrans["lotkey"].ToString();
            string stagenm = objtrans["stagename_alias"].ToString();

            string wordFilePath = string.Empty;
            string localXMLFilePath = string.Empty; string sreloclocation = ""; string OulineXMLFileLocalPath = string.Empty; string QueryFileLocalPath = string.Empty; string ExportWordPath = string.Empty; string ExportWordFilePath = ""; string KLIConverterExePath = string.Empty; string localpath = "";
            string wordpassword = lotkey;
            string xmlFileName = filename + ".xml";

            localpath = localpathlinux;

            KLIConverterExePath = Path.Combine(localpath, "Converters", "KLI_XTW_CORE", "KLI_XTW_CORE.dll");
            try
            {
                sreloclocation = Path.Combine(localpathlinux, "Temp", "H2W", tranid.ToString());
                OulineXMLFileLocalPath = Path.Combine(XMLFilepathlinux, tranid.ToString());
                ExportWordFilePath = Path.Combine(exportwordfilepathlinux, lotkey.ToString());
                if (!Directory.Exists(sreloclocation))
                {
                    Directory.CreateDirectory(sreloclocation);
                }
                if (System.IO.File.Exists(Path.Combine(sreloclocation, "Export.log")))
                {
                    System.IO.File.Delete(Path.Combine(sreloclocation, "Export.log"));
                }
                localXMLFilePath = Path.Combine(sreloclocation, xmlFileName);
                if (System.IO.File.Exists(localXMLFilePath))
                {
                    Console.WriteLine(sreloclocation + " Export.log " + "H2X output file: .");
                    string XMLToWordArg = string.Empty;
                    //  XMLToWordArg = localXMLFilePath;
                    if (!System.IO.File.Exists(QueryFileLocalPath))
                    {
                        QueryFileLocalPath = "";
                    }
                    if (!System.IO.File.Exists(OulineXMLFileLocalPath))
                    {
                        OulineXMLFileLocalPath = "";
                        var data_input = new
                        {
                            errormessage = (XMLToWordArg).ToString(),
                            createdby = 0,
                            controller = "WorkAreaApi: xml to word Transformation "
                        };
                        int retval = CommonRepository.addlog(data_input, "errorlog");
                        //return new conres { status = false, res = "Failed: Ouline XML File is not Present", file = null };
                    }
                    try
                    {
                        if (System.IO.File.Exists(KLIConverterExePath))
                        {
                            XMLToWordArg = "\"" + KLIConverterExePath + "\" \"" + localXMLFilePath + "\" \"" + QueryFileLocalPath + "\" \"" + OulineXMLFileLocalPath + "\" \"" + wordpassword + "\"";
                            Console.WriteLine(sreloclocation + "Export.log" + "XML to Word Conversion start..");
                            Console.WriteLine(sreloclocation + "Export.log" + "X2W exe file with location: " + KLIConverterExePath);
                            Console.WriteLine(sreloclocation + "Export.log" + "X2W conversion parameter: " + XMLToWordArg);
                            System.Diagnostics.Process procInfo = new System.Diagnostics.Process();
                            procInfo.StartInfo.WorkingDirectory = localpath;
                            procInfo.StartInfo.CreateNoWindow = true;
                            procInfo.StartInfo.UseShellExecute = false;
                            procInfo.StartInfo.RedirectStandardError = true;
                            procInfo.StartInfo.FileName = "dotnet";// KLIConverterExePath;
                            procInfo.StartInfo.Arguments = XMLToWordArg;
                            procInfo.Start();
                            var data_input = new
                            {
                                errormessage = (KLIConverterExePath + " " + XMLToWordArg).ToString(),
                                createdby = 0,
                                controller = "WorkAreaApi: xml to word Transformation - run command"
                            };
                            int retval = CommonRepository.addlog(data_input, "errorlog");
                            string proError = procInfo.StandardError.ReadToEnd();
                            procInfo.WaitForExit();
                            Console.WriteLine(sreloclocation + "Export.log" + "XML to Word Conversion end..\r\n");
                        }
                        //  wordFilePath = Path.Combine(sreloclocation, "output", filename + ".docx");
                        wordFilePath = Path.Combine(sreloclocation, "output");
                    }
                    catch (Exception ex)
                    {
                        var data_input = new
                        {
                            errormessage = ex.Message.ToString(),
                            createdby = 0,
                            controller = "WorkAreaApi: xml to wordTransformation -  ex.Message"
                        };
                        int retval = CommonRepository.addlog(data_input, "errorlog");
                        CommonRepository.WriteLog(ex.Message, "WorkAreaApi/xml to word Transformation -Error log ");
                        //WriteExportImportLog(sreloclocation, "Export.log", "X2W conversion failed: " + ex.Message);
                        //return new conres { status = false, res = "Failed to Export. X2W conversion failed.", file = null };
                        throw ex;
                    }
                }
                else
                {
                    var data_input = new
                    {
                        errormessage = "XML file not generated",
                        createdby = 0,
                        controller = "WorkAreaApi:html to xml Transformation"
                    };
                    int retval = CommonRepository.addlog(data_input, "errorlog");
                    CommonRepository.WriteLog("XML file not generated", "WorkAreaApi / html to xml Transformation -Error log ");
                    Console.WriteLine(sreloclocation + " Export.log " + "H2X conversion failed: XML file not generated");
                    // return new conres { status = false, res = "Failed to Export: XML file not found.", file = null };
                }
            }
            catch (Exception ex)
            {
                var data_input = new
                {
                    errormessage = ex.Message.ToString(),
                    createdby = 0,
                    controller = "WorkAreaApi:html to xml Transformation -  ex.Message"
                };
                int retval = CommonRepository.addlog(data_input, "errorlog");
                CommonRepository.WriteLog(ex.Message, "WorkAreaApi/ html to xmlTransformation -Error log ");
                //WriteExportImportLog(sreloclocation, "Export.log", "H2X conversion failed");
                //return new conres { status = false, res = "Failed to Export. Issue in Conversion.", file = null };

                throw ex;
            }
        }


        public static void HTMLtoEPUB(string tranid, string userid, string lotid)
        {
            Console.WriteLine("HTMLtoEPUB--- Function Hits");
            var data = new { transactionid = tranid, lotid = lotid };
            var input = JsonConvert.SerializeObject(data);
            var translist = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getinputforhtmltoxml");
            var dt = JArray.Parse(translist.ToString());
            var objtrans = JObject.Parse(dt[0].ToString());

            string filename = objtrans["filename"].ToString();
            ServerInfo servinfo = new ServerInfo();
            string serverinfo = servinfo.GetServerPath(tranid.ToString(), "serverinfo", false);
            string strindir = CustomConfiguration.AppSettings["ServerINPATH"].ToString();
            string stroutdir = CustomConfiguration.AppSettings["ServerOUTPATH"].ToString();
            string serverworkinginpath = System.IO.Path.Combine(serverinfo, strindir);
            string serverworkingoutpath = System.IO.Path.Combine(serverinfo, stroutdir);
            string htmlfileinpath = System.IO.Path.Combine(serverworkinginpath, filename + ".html");


            string localpath = string.Empty;
            //string html_localpath = string.Empty;
            //string conversion_localpath = string.Empty;
            ////string outlineXML_localpath = string.Empty;
            ////string query_localpath = string.Empty;
            ////string exportwordfile_localpath = string.Empty;
            ////string xml_localpath = string.Empty;
            //string errorlog_localpath = string.Empty;

            //if (isWindowsWK)
            //{
            //    conversion_localpath = Path.Combine(localpathwindows, "Temp", "H2E", tranid.ToString());
            //    //outlineXML_localpath = Path.Combine(XMLFilepathwindows, tranid.ToString());
            //    //exportwordfile_localpath = Path.Combine(localpathwindows, "Temp", "exportioservice", lotkey.ToString());
            //    //errorlog_localpath = System.IO.Path.Combine(conversion_localpath, "Export.log");
            //}
            //else
            //{
            //    conversion_localpath = Path.Combine(localpathlinux, "Temp", "H2E", tranid.ToString());
            //    //outlineXML_localpath = Path.Combine(XMLFilepathlinux, tranid.ToString());
            //    //exportwordfile_localpath = Path.Combine(exportwordfilepathlinux, lotkey.ToString());
            //    //errorlog_localpath = System.IO.Path.Combine(conversion_localpath, "Export.log");
            //}
            //if (!System.IO.Directory.Exists(conversion_localpath))
            //{
            //    System.IO.Directory.CreateDirectory(conversion_localpath);
            //}
            //if (System.IO.File.Exists(errorlog_localpath))
            //{
            //    System.IO.File.Delete(errorlog_localpath);
            //}
            //Console.WriteLine("KLI_IO_SERVICE: HTMLtoEPUB Started:Tranid: " + tranid);
            //var data_input = new
            //{
            //    errormessage = "Tranid: " + tranid,
            //    createdby = userid,
            //    controller = "KLI_IO_SERVICE: HTMLtoEPUB Started"
            //};
            //CommonRepository.addlog(data_input, "errorlog");
            //html_localpath = System.IO.Path.Combine(conversion_localpath, filename + ".html");
            ////string htmlfileinpath = System.IO.Path.Combine(serverworkinginpath, filename + ".html");
            Console.WriteLine("HTMLtoEPUB:htmlfileinpath" + htmlfileinpath);
            if (System.IO.File.Exists(htmlfileinpath))
            {
                //if (System.IO.File.Exists(html_localpath))
                //{
                //    System.IO.File.Delete(html_localpath);
                //}
                //System.IO.FileInfo fi1 = new System.IO.FileInfo(htmlfileinpath);
                //fi1.CopyTo(html_localpath);
                //Console.WriteLine("HTML File copied to local working directory.");

                if (isWindowsWK)
                {
                    localpath = localpathwindows;
                }
                else
                {
                    localpath = localpathlinux;
                }
                string H2EpubExePath = Path.Combine(localpath, "Converters", "HTML2EPUB", "html2epub.dll");
                //string KLIConverterExePath = Path.Combine(localpath, "Converters", "KLI_XTW_CORE", "KLI_XTW_CORE.dll");
                string args = string.Empty;
                Console.WriteLine("Tranid: " + tranid + "ExePath: " + H2EpubExePath.ToString());
                var data_input = new
                {
                    errormessage = "Tranid: " + tranid + "ExePath: " + H2EpubExePath.ToString(),
                    createdby = userid,
                    controller = "KLI_IO_SERVICE: HTMLtoEPUB - localpath"
                };
                CommonRepository.addlog(data_input, "errorlog");
                try
                {
                    if (System.IO.File.Exists(H2EpubExePath))
                    {
                        Console.WriteLine("HTML to EPub Conversion start...");
                        Console.WriteLine("H2E exe file with location: " + H2EpubExePath);

                        args = "\"" + H2EpubExePath + "\" \"" + htmlfileinpath + "\"";

                        Console.WriteLine("H2E args: " + args);
                        Console.WriteLine("H2E localpath: " + localpath);
                        System.Diagnostics.Process procInfo = new System.Diagnostics.Process();
                        procInfo.StartInfo.WorkingDirectory = localpath;
                        procInfo.StartInfo.CreateNoWindow = true;
                        procInfo.StartInfo.UseShellExecute = false;
                        procInfo.StartInfo.RedirectStandardError = true;
                        procInfo.StartInfo.FileName = "dotnet"; //exePath;
                        procInfo.StartInfo.Arguments = args;
                        procInfo.Start();
                        data_input = new
                        {
                            errormessage = "Tranid: " + tranid + " Args: " + args.ToString(),
                            createdby = userid,
                            controller = "KLI_IO_SERVICE: HTMLtoEPUB conversion - run command"
                        };
                        CommonRepository.addlog(data_input, "errorlog");
                        string proError = procInfo.StandardError.ReadToEnd();
                        procInfo.WaitForExit();
                        data_input = new
                        {
                            errormessage = "Tranid: " + tranid,
                            createdby = userid,
                            controller = "KLI_IO_SERVICE: HTMLtoEPUB Conversion finished."
                        };
                        CommonRepository.addlog(data_input, "errorlog");
                        Console.WriteLine("HTML to EPub Conversion finished...");
                        data_input = new
                        {
                            errormessage = "Tranid: " + tranid,
                            createdby = userid,
                            controller = "KLI_IO_SERVICE: FileMoveServertoServer."
                        };
                        CommonRepository.addlog(data_input, "errorlog");
                        // FileMove_LocalTOServer(tranid, serverinfo, "IN", "", conversion_localpath);
                        // FileMove_ServerTOServer(tranid, strindir, stroutdir, "", true);
                    }
                }
                catch (Exception ex)
                {
                    data_input = new
                    {
                        errormessage = "Tranid: " + tranid + " Error: " + ex.Message.ToString(),
                        createdby = userid,
                        controller = "KLI_IO_SERVICE: html to xml Transformation - ex.Message"
                    };
                    CommonRepository.addlog(data_input, "errorlog");
                    CommonRepository.WriteLog(ex.Message, "KLI_IO_SERVICE: html to xml Transformation - Error log");
                    Console.WriteLine("HTML to XML Conversion failed...");
                    throw ex;
                }
            }
        }

        public static object GetTemplateContent_pdid(int projectdid, string stagename_alias, int projectid)
        {
            //var data1 = new
            //{
            //    errormessage = projectdid.ToString(),
            //    createdby = 0,
            //    controller = "WorkAreaApi:GetTemplateContent_pdid - projectdid"
            //};
            //int retval = oCommonRepository.addlog(data1, "errorlog");
            var data = new { outlineconfigid = 0, parentid = 0, projectdid = projectdid, stagename_alias = stagename_alias, stageid = 0, projectid = projectid };

            var jsonstr = JsonConvert.SerializeObject(data);
            //JobWorkflow_ oFieldsmodal = new JobWorkflow_();
            //oFieldsmodal.jobid = jobid;
            //var input = JsonConvert.SerializeObject(oFieldsmodal);
            var lotDetails = CommonRepository.ExecuteSP_ReturnList6("spoutlineconfigdetailselect", 0, 0, projectdid, stagename_alias, 0, projectid, "GetOutlinePIDdata");

            //data1 = new
            //{
            //    errormessage = lotDetails.ToString(),
            //    createdby = 0,
            //    controller = "WorkAreaApi:GetTemplateContent_pdid - lotDetails"
            //};
            //retval = oCommonRepository.addlog(data1, "errorlog");
            // public.spoutlineconfigdetailselect_dummy( outlineconfigid_p, parent_p, projectdid_p,	trackid_p, mode_p )
            //var lotDetails = oCommonRepository.ExecuteSP_ReturnList4("spoutlineconfigdetailselect_dummy", 0, 0, projectdid,  1, "GetOutlinePIDdata");

            //XNode node = JsonConvert.DeserializeXNode(lotDetails.ToString(), "Root");

            var json = new List<object>();
            json.Add(lotDetails);

            return lotDetails;

        }
        public static void GetMainTemplate(int projectdid, string stagenm, int projectid, string filename, string serverinpath, string tranid, bool fulltransformation, string convfold)
        {

            var json = new List<object>();
            var _list = GetTemplateContent_pdid(projectdid, stagenm, projectid);
            if (fulltransformation)
            {
                var serverinfile = GetJsontoXML(_list, filename + "_outline.xml", serverinpath, tranid, fulltransformation, convfold);
                var toclist = ConvertjsonToTOC(_list, filename + ".toc", serverinpath, tranid);
                //return Ok(serverinfile);
            }
            else
            {
                var serverinfile = GetJsontoXML(_list, filename + "_outline.xml", serverinpath, tranid, fulltransformation, convfold);
                //return Ok(serverinfile);
            }

        }
        public static object GetJsontoXML(object lotDetails, string filename, string serverinpath, string tranid, bool transformationrequired = true, string convfold = "H2W")
        {
            bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            string OLXMLFilepath = string.Empty;
            string htmlFilepath = string.Empty;
            if (transformationrequired)
            {
                if (isWindowsWK)
                {
                    OLXMLFilepath = XMLFilepathwindows;
                    htmlFilepath = htmlFilepathwindows;
                }
                else
                {
                    OLXMLFilepath = XMLFilepathlinux;
                    htmlFilepath = htmlFilepathlinux;
                }
            }
            else
            {
                if (isWindowsWK)
                {
                    OLXMLFilepath = Path.Combine(localpathwindows, "Temp", convfold);
                    htmlFilepath = Path.Combine(localpathwindows, "Temp", convfold);
                }
                else
                {
                    OLXMLFilepath = Path.Combine(localpathlinux, "Temp", convfold);
                    htmlFilepath = Path.Combine(localpathlinux, "Temp", convfold);
                }
            }
            string stroutlineFile = Path.Combine(OLXMLFilepath, tranid, filename);
            if (!Directory.Exists(Path.GetDirectoryName(stroutlineFile)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(stroutlineFile));
            }
            if (System.IO.File.Exists(stroutlineFile))
            {
                System.IO.File.Delete(stroutlineFile);
            }
            XElement Text = new XElement("Text");
            foreach (object lst in (IEnumerable<object>)lotDetails)
            {
                XNode node = JsonConvert.DeserializeXNode(lst.ToString(), "Section");
                Text.Add(node.Document.Root);
            }
            XDocument xdoc = new XDocument(Text);
            xdoc.Save(stroutlineFile);
            if (transformationrequired)
            {
                string strHtmlFile = Path.GetFileName(stroutlineFile).Replace("_outline.xml", ".html");
                string outfile = Path.Combine(htmlFilepath, tranid, strHtmlFile);
                var serverinfile = Transformation(stroutlineFile, outfile, serverinpath);
                return serverinfile;
            }
            else
            {
                return stroutlineFile;
            }
        }
        public static object ConvertjsonToTOC(object lotDetails, string tocfilename, string serverinpath, string tranid)
        {
            try
            {

                string strFile = "";

                strFile = Path.Combine(XMLFilepathlinux, tranid, tocfilename);

                if (!Directory.Exists(Path.GetDirectoryName(strFile)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(strFile));
                }
                if (System.IO.File.Exists(strFile))
                {
                    System.IO.File.Delete(strFile);
                }
                // XElement Text = new XElement("Text");
                XmlDocument dox = new XmlDocument();
                XmlDeclaration dec = dox.CreateXmlDeclaration("1.0", "utf-8", null);
                dox.AppendChild(dec);
                XmlNode root = dox.CreateElement("Text");
                dox.AppendChild(root);
                foreach (object lst in (IEnumerable<object>)lotDetails)
                {
                    XmlNode node = JsonConvert.DeserializeXmlNode(lst.ToString(), "Section");
                    foreach (XmlNode el in node)
                    {
                        XmlElement secttion = dox.CreateElement("Section");
                        XmlElement levels = dox.CreateElement("levels");
                        levels = GenerateToc(dox, el, levels, secttion);
                        XmlElement headText = dox.CreateElement("headingtext");
                        //XmlNode sequenceno = el.SelectSingleNode("sequenceno");
                        XmlNode htext = el.SelectSingleNode("headingtext");
                        if (htext != null && htext.InnerText != null && headText != null && headText.InnerText != null)
                        {
                            headText.InnerText = htext.InnerText;
                            secttion.AppendChild(headText);
                        }
                        XmlElement outlineconfigdetailid = dox.CreateElement("outlineconfigdetailid");
                        XmlNode outlineconfigdetailid1 = el.SelectSingleNode("outlineconfigdetailid");
                        if (outlineconfigdetailid1 != null && outlineconfigdetailid1.InnerText != null && outlineconfigdetailid != null && outlineconfigdetailid.InnerText != null)
                        {
                            outlineconfigdetailid.InnerText = outlineconfigdetailid1.InnerText;
                            secttion.AppendChild(outlineconfigdetailid);
                        }
                        root.AppendChild(secttion);
                    }
                }
                dox.Save(strFile);
                // string alltxt = System.IO.File.ReadAllText(strFile);
                string filetosave = tocfilename;
                string filepath = Path.Combine(Path.GetDirectoryName(serverinpath), filetosave);
                if (System.IO.File.Exists(filepath))
                {
                    System.IO.File.Delete(filepath);
                }
                System.IO.FileInfo fi1 = new System.IO.FileInfo(strFile);
                fi1.CopyTo(filepath);
                //System.IO.File.WriteAllText(filepath, alltxt);
                dox.Load(filepath);
                XmlNode section = dox.SelectSingleNode("//Section");
                var json = JsonConvert.SerializeObject(section);
                return json;
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(ex.Message);
            }
        }
        private static XmlElement GenerateToc(XmlDocument Flvldoc, XmlNode elArt, XmlElement abstract_textul, XmlElement section)
        {
            try
            {
                int i = 0;
                try
                {
                    XmlNodeList FText_Levellst = null;
                    FText_Levellst = elArt.SelectNodes("levels");
                    string innrtxt = string.Empty;
                    XmlElement topLevel = Flvldoc.CreateElement("levels");
                    foreach (XmlElement FText_Level in FText_Levellst)
                    {
                        abstract_textul = Flvldoc.CreateElement("levels");
                        XmlElement abstract_textli = null;
                        if (FText_Level != null)
                        {
                            abstract_textli = Flvldoc.CreateElement("headingtext");
                            XmlNode node = FText_Level.SelectSingleNode("headingtext");
                            if (node != null && node.InnerText != null)
                            {
                                innrtxt = node.InnerText;
                                abstract_textli.InnerXml = innrtxt;
                            }
                            XmlElement outlineconfigdetailid = Flvldoc.CreateElement("outlineconfigdetailid");
                            XmlNode outlineconfigdetailid1 = FText_Level.SelectSingleNode("outlineconfigdetailid");
                            if (outlineconfigdetailid != null && outlineconfigdetailid1 != null)
                            {
                                if (outlineconfigdetailid.InnerText != null && outlineconfigdetailid1.InnerText != null)
                                {
                                    outlineconfigdetailid.InnerText = outlineconfigdetailid1.InnerText;
                                }
                            }
                            if (FText_Level.SelectNodes("levels").Count > 0)
                            {
                                XmlElement headtext2 = Flvldoc.CreateElement("headingtext");
                                if (headtext2 != null && node != null && headtext2.InnerText != null && node.InnerText != null)
                                {
                                    headtext2.InnerText = node.InnerText;
                                }
                                XmlElement outlineconfigdetailid2 = Flvldoc.CreateElement("outlineconfigdetailid");
                                XmlNode nodedetail = FText_Level.SelectSingleNode("outlineconfigdetailid");
                                if (outlineconfigdetailid2 != null && nodedetail != null && outlineconfigdetailid2.InnerText != null && nodedetail.InnerText != null)
                                {
                                    outlineconfigdetailid2.InnerText = nodedetail.InnerText;
                                }
                                XmlElement abstract_textul2 = Flvldoc.CreateElement("levels");
                                // abstract_textli.AppendChild(GenerateToc(Flvldoc, FText_Level, abstract_textul1,section));
                                foreach (XmlElement FText_Level1 in FText_Level.SelectNodes("levels"))
                                {
                                    XmlElement abstract_textul1 = Flvldoc.CreateElement("levels");
                                    XmlElement abstract_textli1 = null;
                                    abstract_textli1 = Flvldoc.CreateElement("headingtext");
                                    XmlNode node1 = FText_Level1.SelectSingleNode("headingtext");
                                    if (node1 != null && node1.InnerText != null)
                                    {
                                        innrtxt = node1.InnerText;
                                        abstract_textli1.InnerXml = innrtxt;
                                        abstract_textul1.AppendChild(abstract_textli1);
                                    }
                                    XmlElement outdetail = Flvldoc.CreateElement("outlineconfigdetailid");
                                    XmlNode nodeoutdetail = FText_Level1.SelectSingleNode("outlineconfigdetailid");
                                    if (outdetail != null && outdetail.InnerText != null && nodeoutdetail != null && nodeoutdetail.InnerText != null)
                                    {
                                        outdetail.InnerText = nodeoutdetail.InnerText;
                                        abstract_textul1.AppendChild(outdetail);
                                        abstract_textul2.AppendChild(abstract_textul1);
                                    }
                                }
                                abstract_textul2.AppendChild(headtext2);
                                abstract_textul2.AppendChild(outlineconfigdetailid2);
                                section.AppendChild(abstract_textul2);
                                //section.AppendChild(abstract_textli);
                                abstract_textli.InnerXml = "";
                            }
                            if (abstract_textli != null && abstract_textli.InnerXml != "")
                            {
                                abstract_textul.AppendChild(abstract_textli);
                                abstract_textul.AppendChild(outlineconfigdetailid);
                                section.AppendChild(abstract_textul);
                            }
                            i++;
                            //toclvl++;
                        }
                    }
                }
                catch (Exception ex)
                {
                    var data = new
                    {
                        errormessage = ex.Message,
                        createdby = 0,
                        controller = "WorkAreaApi:GetAllOutFilesForDownload - serverpath - tranid"
                    };
                    //int retval = oCommonRepository.addlog(data, "errorlog");
                }
            }
            catch (Exception ex)
            {
                var data = new
                {
                    errormessage = ex.Message,
                    createdby = 0,
                    controller = "WorkAreaApi:GetAllOutFilesForDownload - serverpath - tranid"
                };
                //int retval = oCommonRepository.addlog(data, "errorlog");
            }
            return section;
        }
        private static object Transformation(string InputXML, string OutputHTML, string serverinpath)
        {
            bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            string localpath = "";
            string exefile = string.Empty;
            string args = string.Empty;
            string shellfile = string.Empty;
            string xslFile = Path.Combine(localpath, "OutlineX2H.xsl");
            string javapath = string.Empty;


            localpath = localpathlinux;
            exefile = "sh";
            shellfile = Path.Combine(localpath, "OutlineX2H.sh");
            xslFile = Path.Combine(localpath, xslFile);
            javapath = CustomConfiguration.AppSettings["javapathlinux"];
            args = "\"" + shellfile + "\" \"" + javapath + "\" \"" + OutputHTML + "\" \"" + InputXML + "\" \"" + xslFile + "\" \"" + localpath + "\"";

            //var data = new
            //{
            //    errormessage = localpath.ToString(),
            //    createdby = 0,
            //    controller = "WorkAreaApi:Transformation - localpath"
            //};
            //int retval = oCommonRepository.addlog(data, "errorlog");
            try
            {
                if (System.IO.File.Exists(InputXML))
                {
                    System.Diagnostics.Process procInfo = new System.Diagnostics.Process();
                    procInfo.StartInfo.WorkingDirectory = localpath;
                    procInfo.StartInfo.CreateNoWindow = true;
                    procInfo.StartInfo.UseShellExecute = false;
                    procInfo.StartInfo.RedirectStandardError = true;
                    procInfo.StartInfo.FileName = exefile;
                    procInfo.StartInfo.Arguments = args;
                    procInfo.Start();
                    //data = new
                    //{
                    //    errormessage = (exefile + " " + args).ToString(),
                    //    createdby = 0,
                    //    controller = "WorkAreaApi:Transformation - run command"
                    //};
                    //retval = oCommonRepository.addlog(data, "errorlog");
                    string proError = procInfo.StandardError.ReadToEnd();
                    procInfo.WaitForExit();
                }

                if (System.IO.File.Exists(OutputHTML))
                {
                    string alltxt = System.IO.File.ReadAllText(OutputHTML);
                    alltxt = Regex.Replace(alltxt, "Applicable<", "Applicable</input><");
                    alltxt = Regex.Replace(alltxt, "&nbsp;", " ");
                    alltxt = Regex.Replace(alltxt, "cke_editable cke_editable_inline cke_contents_ltr", "cke_editable");
                    System.IO.File.WriteAllText(OutputHTML, alltxt);
                    System.IO.FileInfo fi1 = new System.IO.FileInfo(OutputHTML);
                    fi1.CopyTo(serverinpath);
                }
                else
                {
                    //data = new
                    //{
                    //    errormessage = "Error in Transformation XML to HTML",
                    //    createdby = 0,
                    //    controller = "WorkAreaApi:Transformation - localfile"
                    //};
                    //retval = oCommonRepository.addlog(data, "errorlog");
                }
                //data = new
                //{
                //    errormessage = serverinpath.ToString(),
                //    createdby = 0,
                //    controller = "WorkAreaApi:Transformation - serverinpath"
                //};
                //retval = oCommonRepository.addlog(data, "errorlog");
                return serverinpath;
            }
            catch (Exception ex)
            {
                throw ex;
                //data = new
                //{
                //    errormessage = ex.Message.ToString(),
                //    createdby = 0,
                //    controller = "WorkAreaApi:Transformation -  ex.Message"
                //};
                //retval = oCommonRepository.addlog(data, "errorlog");
                //oCommonRepository.WriteLog(ex.Message, "WorkAreaApi/Transformation -Error log ");
                //return Ok(serverinpath);
            }
        }
        public static void FileMovementServerToServer(string tranid, string next_tranid, bool isTakeFileBackup)
        {
            Console.WriteLine("FileMovementServerToServer:tranid: " + tranid + " next_tranid: " + next_tranid + "isTakeFileBackup " + isTakeFileBackup);
            ServerInfo servinfo = new ServerInfo();

            string serverinpath_tranid = servinfo.GetServerPath(tranid, "serverinfo", false);
            //string serverinpath_tranid = Path.Combine(serverinpath_tranid, CustomConfiguration.AppSettings["ServerINPATH"].ToString());


            string nextstage_serverpath = servinfo.GetServerPath(next_tranid.ToString(), "serverinfo", true);
            //nextstage_serverpath = Path.Combine(nextstage_serverpath, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
            Console.WriteLine("FileMovementServerToServer:nextstage_serverpath: " + nextstage_serverpath);
            if (Directory.Exists(serverinpath_tranid))
            {
                if (!Directory.Exists(nextstage_serverpath))
                {
                    Directory.CreateDirectory(serverinpath_tranid);
                    FileMove_ServerTOServer(tranid, serverinpath_tranid, nextstage_serverpath, "", isTakeFileBackup);
                }
                else
                {
                    FileMove_ServerTOServer(tranid, serverinpath_tranid, nextstage_serverpath, "", isTakeFileBackup);
                    //FileInfo[] fi_ = new System.IO.DirectoryInfo(serverinpath_tranid).GetFiles();
                    //if (fi_.Length != 0)
                    //{
                    //    for (int m = 0; m <= fi_.Length - 1; m++)
                    //    {
                    //        string _filename = string.Empty, filepath_ = string.Empty;
                    //        filepath_ = fi_[m].FullName.ToString();
                    //        _filename = Path.GetFileName(fi_[m].Name.ToString());
                    //        if (!System.IO.File.Exists(Path.Combine(nextstage_serverpath, _filename)))
                    //            System.IO.File.Copy(filepath_, Path.Combine(nextstage_serverpath, _filename));
                    //    }
                    //}
                }
            }
        }
        public static pubflowinputModel getPubflowInput(string tranid)
        {
            pubflowinputModel opubflowinputModel = new pubflowinputModel();
            // var jsonstr = JsonConvert.SerializeObject(tranid);
            // var returnres = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", jsonstr, "getdetailsbytranid");
            // if (returnres != null)
            // {
            //  var i_appType = JsonConvert.DeserializeObject<object>(returnres.ToString());
            // JArray BatchLotDetails3 = JArray.Parse(i_appType.ToString());
            // JObject obj1 = JObject.Parse(BatchLotDetails3[0].ToString());
            //  Console.WriteLine("Job ID: " + obj1["batchid"].ToString());

            var data = new { tranid = tranid };
            string input = JsonConvert.SerializeObject(data);
            var lotlist = CommonRepository.ExecuteSP_ReturnList2("splotbatchdetailsselect", input, "getsupplementdetailsbylotid");
            if (lotlist != null)
            {
                var dts = JArray.Parse(lotlist.ToString());
                var obj1_jobid = JObject.Parse(dts[0].ToString());
                var Batch = obj1_jobid["batchname"].ToString();
                var PublicationType = obj1_jobid["supplementtype"].ToString();
                var PublicationID = "";
                if (obj1_jobid["jobmetadata"].ToString() != "")
                {
                    var PublicationIDs = JArray.Parse(obj1_jobid["jobmetadata"].ToString());
                    var publicationmetadataId = CustomConfiguration.AppSettings.GetValue<string>("AppSettings:publicationmetadataId");
                    var metadatalists = PublicationIDs.Where(c =>
                    c["jobmetaid"].ToString() == publicationmetadataId);
                    foreach (var metadatalist2 in metadatalists)
                    {
                        PublicationID = metadatalist2["FieldValue"].ToString();
                    }
                }
                opubflowinputModel.Batch = Batch;
                opubflowinputModel.PublicationID = PublicationID;
                opubflowinputModel.PublicationType = PublicationType;
                // }
            }
            return opubflowinputModel;
        }
        public static IRestResponse CallPubflowAPICreateOnline(string url, string userid, string tranid, string Batch, string PublicationType, string PublicationID, string comment, string WorkflowName)
        {

            var client = new RestClient(url);
            var pubflowrequest = new RestRequest(Method.POST);
            pubflowrequest.AddHeader("Content-Type", "application/json");
            pubflowrequest.RequestFormat = DataFormat.Json;
            Console.WriteLine("LAPS2 App Watcher: url" + url);
            Console.WriteLine("LAPS2 App Watcher: UserID" + userid);
            Console.WriteLine("LAPS2 App Watcher: TransId" + tranid);
            Console.WriteLine("LAPS2 App Watcher: Batch" + Batch);
            pubflowrequest.AddParameter("application/json", "" +
                                                        "{ " +
                                                        "\"PublicationType\":\"" + PublicationType + "\"," +
                                                        "\"PublicationID\":\"" + PublicationID + "\"," +
                                                        "\"Batch\":\"" + Batch + "\"," +
                                                        "\"UserID\":\"" + userid + "\"," +
                                                        "\"tranid\":\"" + tranid + "\"," +
                                                        "\"CMNotes\":\"" + comment + "\"," +
                                                        "\"WorkflowName\":\"" + WorkflowName + "\"" +
                                                        "}", ParameterType.RequestBody);
            IRestResponse responseResult = client.Execute(pubflowrequest);
            return responseResult;
        }
        public static IRestResponse CallPubflowAPIUpdateOnline(string url, string userid, string tranid, string Batch, string PublicationType, string PublicationID, string comment, string fileupload = "")
        {

            var client = new RestClient(url);
            var pubflowrequest = new RestRequest(Method.POST);
            pubflowrequest.AddHeader("Content-Type", "application/json");
            pubflowrequest.RequestFormat = DataFormat.Json;
            Console.WriteLine("LAPS2 App Watcher: url" + url);
            Console.WriteLine("LAPS2 App Watcher: UserID" + userid);
            Console.WriteLine("LAPS2 App Watcher: TransId" + tranid);
            Console.WriteLine("LAPS2 App Watcher: Batch" + Batch);
            Console.WriteLine("CallPubflowAPIUpdateOnline");
            if (fileupload == "")
            {
                pubflowrequest.AddParameter("application/json", "" + "{ " +
                                                            "\"PublicationType\":\"" + PublicationType + "\"," +
                                                            "\"PublicationID\":\"" + PublicationID + "\"," +
                                                             "\"ActivityComment\":\"" + comment + "\"," +
                                                            "\"Batch\":\"" + Batch + "\"," +
                                                            "\"UserID\":\"" + userid + "\"," +
                                                            "\"tranid\":\"" + tranid + "\"" +
                                                            "}", ParameterType.RequestBody);
            }
            else
            {
                pubflowrequest.AddParameter("application/json", "" + "{ " +
                                                            "\"PublicationType\":\"" + PublicationType + "\"," +
                                                            "\"PublicationID\":\"" + PublicationID + "\"," +
                                                             "\"ActivityComment\":\"" + comment + "\"," +
                                                            "\"Batch\":\"" + Batch + "\"," +
                                                            "\"UserID\":\"" + userid + "\"," +
                                                            "\"tranid\":\"" + tranid + "\"," +
                                                            "\"UploadFileURL\":\"" + fileupload + "\"" +
                                                            "}", ParameterType.RequestBody);
            }

            IRestResponse responseResult = client.Execute(pubflowrequest);
            return responseResult;
        }
        public static IRestResponse CallPubflowAPIUpdateManual(string url, string userid, string tranid, string SupplementNumber, string PublicationType, string PublicationID, string Notes, string fileupload = "")
        {

            var client = new RestClient(url);
            var pubflowrequest = new RestRequest(Method.POST);
            pubflowrequest.AddHeader("Content-Type", "application/json");
            pubflowrequest.RequestFormat = DataFormat.Json;
            Console.WriteLine("LAPS2 App Watcher: url" + url);
            Console.WriteLine("LAPS2 App Watcher: UserID" + userid);
            Console.WriteLine("LAPS2 App Watcher: TransId" + tranid);
            Console.WriteLine("LAPS2 App Watcher: SupplementNumber" + SupplementNumber);
            Console.WriteLine("CallPubflowAPIUpdateManual");
            if (fileupload == "")
            {
                pubflowrequest.AddParameter("application/json", "" +
                                                        "{ " +
                                                        "\"PublicationType\":\"" + PublicationType + "\"," +
                                                        "\"PublicationID\":\"" + PublicationID + "\"," +
                                                        "\"SupplementNumber\":\"" + SupplementNumber + "\"," +
                                                        "\"UserID\":\"" + userid + "\"," +
                                                        "\"tranid\":\"" + tranid + "\"," +
                                                        "\"Notes\":\"" + Notes + "\"," +
                                                        "}", ParameterType.RequestBody);
            }
            else
            {
                pubflowrequest.AddParameter("application/json", "" +
                                                       "{ " +
                                                       "\"PublicationType\":\"" + PublicationType + "\"," +
                                                       "\"PublicationID\":\"" + PublicationID + "\"," +
                                                       "\"SupplementNumber\":\"" + SupplementNumber + "\"," +
                                                       "\"UserID\":\"" + userid + "\"," +
                                                       "\"tranid\":\"" + tranid + "\"," +
                                                       "\"Notes\":\"" + Notes + "\"," +
                                                        "\"UploadFileURL\":\"" + fileupload + "\"," +
                                                       "}", ParameterType.RequestBody);
            }

            IRestResponse responseResult = client.Execute(pubflowrequest);
            return responseResult;
        }
        public static IRestResponse CallPubflowAPIUpdateBook(string url, string userid, string tranid, string PublicationType, string PublicationID, string Notes, string comment, string fileupload = "")
        {

            var client = new RestClient(url);
            var pubflowrequest = new RestRequest(Method.POST);
            pubflowrequest.AddHeader("Content-Type", "application/json");
            pubflowrequest.RequestFormat = DataFormat.Json;
            Console.WriteLine("LAPS2 App Watcher: url" + url);
            Console.WriteLine("LAPS2 App Watcher: UserID" + userid);
            Console.WriteLine("LAPS2 App Watcher: TransId" + tranid);
            Console.WriteLine("CallPubflowAPIUpdateBook");
            string jsonparam = "";
            if (fileupload == "")
            {
                jsonparam = "" + "{ " +
                                                        "\"PublicationType\":\"" + PublicationType + "\"," +
                                                        "\"PublicationID\":\"" + PublicationID + "\"," +
                                                        "\"UserID\":\"" + userid + "\"," +
                                                        "\"tranid\":\"" + tranid + "\"," +
                                                        "\"Notes\":\"" + Notes + "\"," +
                                                        "}";
                pubflowrequest.AddParameter("application/json", jsonparam, ParameterType.RequestBody);
            }
            else
            {
                jsonparam = "" +
                                                        "{ " +
                                                        "\"PublicationType\":\"" + PublicationType + "\"," +
                                                        "\"PublicationID\":\"" + PublicationID + "\"," +
                                                        "\"UserID\":\"" + userid + "\"," +
                                                        "\"tranid\":\"" + tranid + "\"," +
                                                        "\"Notes\":\"" + Notes + "\"," +
                                                         "\"UploadFileURL\":\"" + fileupload + "\"," +
                                                        "}";
                pubflowrequest.AddParameter("application/json", jsonparam, ParameterType.RequestBody);
            }
            Console.WriteLine("cdborchestrationrequest" + jsonparam.ToString());
            IRestResponse responseResult = client.Execute(pubflowrequest);
            return responseResult;
        }

        public static IRestResponse CallCDBAPI(string url, string tranid, string userid)
        {

            var client = new RestClient(url);
            var cdbrequest = new RestRequest(Method.POST);
            cdbrequest.AddHeader("Content-Type", "application/json");
            cdbrequest.RequestFormat = DataFormat.Json;
            Console.WriteLine("LAPS2 App Watcher: url" + url);
            Console.WriteLine("LAPS2 App Watcher: UserID" + userid);
            Console.WriteLine("LAPS2 App Watcher: TransId" + tranid);
            var jsonparam = "" +
                                                        "{ " +
                                                        "\"tranid\":\"" + tranid + "\"," +
                                                        "\"userid\":\"" + userid + "\"" +
                                                        "}";
            cdbrequest.AddParameter("application/json", jsonparam, ParameterType.RequestBody);
            Console.WriteLine("cdborchestrationrequest" + jsonparam.ToString());

            IRestResponse responseResult = client.Execute(cdbrequest);
            Console.WriteLine("LAPS2 App Watcher:responseResult:CDBAPI:" + responseResult.Content.ToString());
            return responseResult;
        }


        public static void DirEmpty(System.IO.DirectoryInfo directory)
        {
            foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
            foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
        }
        public static string FileMove_ServerTOServerold(string tranid, string inputpath, string outputpath, string StageType = "")
        {
            int transid = Convert.ToInt32(tranid);
            ServerInfo servinfo = new ServerInfo();
            string servertranpath = servinfo.GetServerPath(transid.ToString(), "serverinfo", true);
            string servertran_inpath = Path.Combine(servertranpath, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
            string servertran_outpath = Path.Combine(servertranpath, CustomConfiguration.AppSettings["ServerOUTPATH"].ToString());
            try
            {
                bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                if (isWindows)
                {

                    using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(tranid))
                    {
                        string retinfo = servinfo.GrantFolderPermissions(transid.ToString(), "");
                        var credentials = new UserCredentials(retinfo.Split(',')[0], retinfo.Split(',')[1], retinfo.Split(',')[2]);
                        //Impersonation.RunAsUser(credentials, logonType, () =>
                        //{
                        var SubDir = "IN";
                        if (!Directory.Exists(System.IO.Path.Combine(outputpath, SubDir)))
                            Directory.CreateDirectory(System.IO.Path.Combine(outputpath, SubDir));
                        if (!Directory.Exists(System.IO.Path.Combine(outputpath, "OUT")))
                            Directory.CreateDirectory(System.IO.Path.Combine(outputpath, "OUT"));
                        //Backup folder
                        if (StageType != "checkout_next_merged")
                        {
                            int Inflecnt_Backup = System.IO.Directory.GetFiles(System.IO.Path.Combine(outputpath, SubDir), "*.*").Length;
                            if (Inflecnt_Backup != 0)
                            {
                                var backupDir = CommonClass.GetBackupfolder(System.IO.Path.Combine(outputpath, "V001"));
                                CommonClass.MoveDirectory(System.IO.Path.Combine(outputpath, SubDir), System.IO.Path.Combine(backupDir, SubDir));
                                CommonClass.MoveDirectory(System.IO.Path.Combine(outputpath, "OUT"), System.IO.Path.Combine(backupDir, "OUT"));
                            }
                        }
                        int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "OUT"), "*.*").Length;
                        if (Inflecnt != 0)
                        {
                            CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "OUT"), System.IO.Path.Combine(outputpath, SubDir));
                            return System.IO.Path.Combine(outputpath, SubDir);
                        }
                        else
                        {
                            if (!Directory.Exists(System.IO.Path.Combine(inputpath, "PROCESS")))
                                Directory.CreateDirectory(System.IO.Path.Combine(inputpath, "PROCESS"));
                            int Inflecnt_ = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "PROCESS"), "*.*").Length;
                            if (Inflecnt_ != 0)
                            {
                                CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "PROCESS"), System.IO.Path.Combine(outputpath, SubDir));
                                return System.IO.Path.Combine(outputpath, SubDir);
                            }
                            else
                            {
                                int Inflecnt__ = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "IN"), "*.*").Length;
                                if (Inflecnt__ != 0)
                                {
                                    CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "IN"), System.IO.Path.Combine(outputpath, SubDir));
                                    return System.IO.Path.Combine(outputpath, SubDir);
                                }
                                else
                                {
                                    //CommonClass.WriteLog(fileName, tranid, "FileMove_ServerTOServer File Not Fount");
                                    return "Error";
                                }
                            }
                        }
                        //  });
                    }
                }
                else
                {
                    string retinfo = servinfo.GrantFolderPermissions(transid.ToString(), "");
                    var credentials = new UserCredentials(retinfo.Split(',')[0], retinfo.Split(',')[1], retinfo.Split(',')[2]);
                    //Impersonation.RunAsUser(credentials, logonType, () =>
                    //{
                    var SubDir = "IN";
                    if (!Directory.Exists(System.IO.Path.Combine(outputpath, SubDir)))
                        Directory.CreateDirectory(System.IO.Path.Combine(outputpath, SubDir));
                    if (!Directory.Exists(System.IO.Path.Combine(outputpath, "OUT")))
                        Directory.CreateDirectory(System.IO.Path.Combine(outputpath, "OUT"));
                    //Backup folder
                    if (StageType != "checkout_next_merged")
                    {
                        int Inflecnt_Backup = System.IO.Directory.GetFiles(System.IO.Path.Combine(outputpath, SubDir), "*.*").Length;
                        if (Inflecnt_Backup != 0)
                        {
                            var backupDir = CommonClass.GetBackupfolder(System.IO.Path.Combine(outputpath, "V001"));
                            CommonClass.MoveDirectory(System.IO.Path.Combine(outputpath, SubDir), System.IO.Path.Combine(backupDir, SubDir));
                            CommonClass.MoveDirectory(System.IO.Path.Combine(outputpath, "OUT"), System.IO.Path.Combine(backupDir, "OUT"));
                        }
                    }
                    int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "OUT"), "*.*").Length;
                    if (Inflecnt != 0)
                    {
                        CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "OUT"), System.IO.Path.Combine(outputpath, SubDir));
                        return System.IO.Path.Combine(outputpath, SubDir);
                    }
                    else
                    {
                        if (!Directory.Exists(System.IO.Path.Combine(inputpath, "PROCESS")))
                            Directory.CreateDirectory(System.IO.Path.Combine(inputpath, "PROCESS"));
                        int Inflecnt_ = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "PROCESS"), "*.*").Length;
                        if (Inflecnt_ != 0)
                        {
                            CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "PROCESS"), System.IO.Path.Combine(outputpath, SubDir));
                            return System.IO.Path.Combine(outputpath, SubDir);
                        }
                        else
                        {
                            int Inflecnt__ = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "IN"), "*.*").Length;
                            if (Inflecnt__ != 0)
                            {
                                CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "IN"), System.IO.Path.Combine(outputpath, SubDir));
                                return System.IO.Path.Combine(outputpath, SubDir);
                            }
                            else
                            {
                                //CommonClass.WriteLog(fileName, tranid, "FileMove_ServerTOServer File Not Fount");
                                return "Error";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + " at " + ex.StackTrace);
            }
            return "";
        }

        public static string FileMove_ServerTOServer(string tranid, string inputpath, string outputpath, string StageType = "", bool isTakeFileBackup = true)
        {
            Console.WriteLine("FileMove_ServerTOServer: tranid: " + tranid);
            Console.WriteLine("FileMove_ServerTOServer: inputpath: " + inputpath);
            Console.WriteLine("FileMove_ServerTOServer: outputpath: " + outputpath);
            Console.WriteLine("FileMove_ServerTOServer: StageType: " + StageType);
            Console.WriteLine("FileMove_ServerTOServer: isTakeFileBackup: " + isTakeFileBackup);
            CommonClass.laps2Log("tranid:" + tranid + "inputpath:" + inputpath, "FileMove_ServerTOServer started");
            bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            if (isWindows)
            {
                using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(tranid))
                {
                    var SubDir = "IN";
                    if (!Directory.Exists(System.IO.Path.Combine(outputpath, SubDir)))
                        Directory.CreateDirectory(System.IO.Path.Combine(outputpath, SubDir));
                    if (!Directory.Exists(System.IO.Path.Combine(outputpath, "OUT")))
                        Directory.CreateDirectory(System.IO.Path.Combine(outputpath, "OUT"));
                    //Backup folder
                    var backupDir = CommonClass.GetBackupfolder(System.IO.Path.Combine(outputpath, "V001"));
                    if (StageType != "checkout_next_merged")
                    {
                        if (isTakeFileBackup == true)
                        {
                            int Inflecnt_Backup = System.IO.Directory.GetFiles(System.IO.Path.Combine(outputpath, SubDir), "*.*").Length;
                            if (Inflecnt_Backup != 0)
                            {

                                CommonClass.MoveDirectory(System.IO.Path.Combine(outputpath, SubDir), System.IO.Path.Combine(backupDir, SubDir));
                                CommonClass.MoveDirectory(System.IO.Path.Combine(outputpath, "OUT"), System.IO.Path.Combine(backupDir, "OUT"));
                            }
                        }
                    }

                    int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "OUT"), "*.*").Length;
                    if (Inflecnt != 0)
                    {

                        CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "OUT"), System.IO.Path.Combine(outputpath, SubDir));
                        return System.IO.Path.Combine(outputpath, SubDir);
                    }
                    else
                    {
                        if (!Directory.Exists(System.IO.Path.Combine(inputpath, "PROCESS")))
                            Directory.CreateDirectory(System.IO.Path.Combine(inputpath, "PROCESS"));
                        int Inflecnt_ = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "PROCESS"), "*.*").Length;
                        if (Inflecnt_ != 0)
                        {

                            CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "PROCESS"), System.IO.Path.Combine(outputpath, SubDir));
                            return System.IO.Path.Combine(outputpath, SubDir);
                        }
                        else
                        {
                            int Inflecnt__ = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "IN"), "*.*").Length;
                            if (Inflecnt__ != 0)
                            {

                                CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "IN"), System.IO.Path.Combine(outputpath, SubDir));
                                return System.IO.Path.Combine(outputpath, SubDir);
                            }
                            else
                            {
                                CommonClass.WriteLog(fileName, tranid, "FileMove_ServerTOServer File Not Fount");
                                return "Error";
                            }
                        }
                    }
                }
            }
            else
            {
                var SubDir = "IN";
                if (!Directory.Exists(System.IO.Path.Combine(outputpath, SubDir)))
                    Directory.CreateDirectory(System.IO.Path.Combine(outputpath, SubDir));
                if (!Directory.Exists(System.IO.Path.Combine(outputpath, "OUT")))
                    Directory.CreateDirectory(System.IO.Path.Combine(outputpath, "OUT"));
                //Backup folder
                var backupDir = CommonClass.GetBackupfolder(System.IO.Path.Combine(outputpath, "V001"));
                if (StageType != "checkout_next_merged")
                {
                    Console.WriteLine("FileMove_ServerTOServer:checkout_next_merged... reached");
                    if (isTakeFileBackup == true)
                    {
                        int Inflecnt_Backup = System.IO.Directory.GetFiles(System.IO.Path.Combine(outputpath, SubDir), "*.*").Length;
                        if (Inflecnt_Backup != 0)
                        {

                            CommonClass.MoveDirectory(System.IO.Path.Combine(outputpath, SubDir), System.IO.Path.Combine(backupDir, SubDir));
                            CommonClass.MoveDirectory(System.IO.Path.Combine(outputpath, "OUT"), System.IO.Path.Combine(backupDir, "OUT"));
                        }
                    }
                }

                int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "OUT"), "*.*").Length;
                if (Inflecnt != 0)
                {
                    Console.WriteLine("FileMove_ServerTOServer:... checking OUT" + System.IO.Path.Combine(outputpath, SubDir));
                    Console.WriteLine("FileMove_ServerTOServer:... source Path:" + System.IO.Path.Combine(inputpath, "OUT"));
                    Console.WriteLine("FileMove_ServerTOServer:... dest Path:" + System.IO.Path.Combine(outputpath, SubDir));
                    CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "OUT"), System.IO.Path.Combine(outputpath, SubDir));
                    return System.IO.Path.Combine(outputpath, SubDir);
                }
                else
                {
                    if (!Directory.Exists(System.IO.Path.Combine(inputpath, "PROCESS")))
                        Directory.CreateDirectory(System.IO.Path.Combine(inputpath, "PROCESS"));
                    int Inflecnt_ = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "PROCESS"), "*.*").Length;
                    if (Inflecnt_ != 0)
                    {
                        Console.WriteLine("FileMove_ServerTOServer:... checking PROCESS");

                        CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "PROCESS"), System.IO.Path.Combine(outputpath, SubDir));
                        return System.IO.Path.Combine(outputpath, SubDir);
                    }
                    else
                    {
                        Console.WriteLine("FileMove_ServerTOServer:... checking process else ");

                        int Inflecnt__ = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "IN"), "*.*").Length;
                        if (Inflecnt__ != 0)
                        {
                            Console.WriteLine("FileMove_ServerTOServer:... checking IN ");
                            Console.WriteLine("FileMove_ServerTOServer:... source Path:" + System.IO.Path.Combine(inputpath, "IN"));
                            Console.WriteLine("FileMove_ServerTOServer:... dest Path:" + System.IO.Path.Combine(outputpath, SubDir));
                            CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "IN"), System.IO.Path.Combine(outputpath, SubDir));
                            return System.IO.Path.Combine(outputpath, SubDir);
                        }
                        else
                        {
                            CommonClass.WriteLog(fileName, tranid, "FileMove_ServerTOServer File Not Fount");
                            return "Error";
                        }
                    }
                }
            }

        }
        public static string FileMove_ServerTOLocal(string tranid, string serverpath, string SubDir, string Process_Path, string outpath)
        {
            ServerInfo servinfo = new ServerInfo();
            string servertranpath = servinfo.GetServerPath(tranid, "serverinfo", true);
            string servertran_inpath = Path.Combine(servertranpath, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
            string servertran_outpath = Path.Combine(servertranpath, CustomConfiguration.AppSettings["ServerOUTPATH"].ToString());

            try
            {
                bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                if (isWindows)
                {
                    using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(tranid))
                    {
                        // string retinfo = servinfo.GrantFolderPermissions(tranid.ToString(), "");
                        //var credentials = new UserCredentials(retinfo.Split(',')[0], retinfo.Split(',')[1], retinfo.Split(',')[2]);
                        //Impersonation.RunAsUser(credentials, logonType, () =>
                        //{
                        if (!Directory.Exists(System.IO.Path.Combine(serverpath, SubDir)))
                        {
                            Directory.CreateDirectory(System.IO.Path.Combine(serverpath, SubDir));
                        }
                        if (!Directory.Exists(outpath))
                        {
                            Directory.CreateDirectory(outpath);
                        }
                        int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(serverpath, "OUT"), "*.*").Length;
                        if (Inflecnt != 0)
                        {
                            CommonClass.CopyDirectory(System.IO.Path.Combine(serverpath, "OUT"), Process_Path);
                            return System.IO.Path.Combine(Process_Path);
                        }
                        Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(serverpath, SubDir), "*.*").Length;
                        if (Inflecnt != 0)
                        {
                            CommonClass.CopyDirectory(System.IO.Path.Combine(serverpath, SubDir), Process_Path);
                            return System.IO.Path.Combine(Process_Path);
                        }
                        else
                        {
                            //CommonClass.WriteLog("", tranid, "FileMove_ServerTOLocal File Not Found");
                            return "Error";
                        }
                        // });
                    }
                }
                else
                {
                    if (!Directory.Exists(System.IO.Path.Combine(serverpath, SubDir)))
                    {
                        Directory.CreateDirectory(System.IO.Path.Combine(serverpath, SubDir));
                    }
                    if (!Directory.Exists(outpath))
                    {
                        Directory.CreateDirectory(outpath);
                    }
                    int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(serverpath, "OUT"), "*.*").Length;
                    if (Inflecnt != 0)
                    {
                        CommonClass.CopyDirectory(System.IO.Path.Combine(serverpath, "OUT"), Process_Path);
                        return System.IO.Path.Combine(Process_Path);
                    }
                    Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(serverpath, SubDir), "*.*").Length;
                    if (Inflecnt != 0)
                    {
                        CommonClass.CopyDirectory(System.IO.Path.Combine(serverpath, SubDir), Process_Path);
                        return System.IO.Path.Combine(Process_Path);
                    }
                    else
                    {
                        //CommonClass.WriteLog("", tranid, "FileMove_ServerTOLocal File Not Found");
                        return "Error";
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + " at " + ex.StackTrace);
            }
            return "";
        }
        public static string FileMove_LocalTOServer(string tranid, string serverpath, string SubDir, string StageType, string Process_Path)
        {
            ServerInfo servinfo = new ServerInfo();
            string servertranpath = servinfo.GetServerPath(tranid, "serverinfo", true);
            string servertran_inpath = Path.Combine(servertranpath, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
            string servertran_outpath = Path.Combine(servertranpath, CustomConfiguration.AppSettings["ServerOUTPATH"].ToString());

            try
            {
                bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                if (isWindows)
                {
                    using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(tranid))
                    {
                        //string retinfo = servinfo.GrantFolderPermissions(tranid.ToString(), "");
                        // var credentials = new UserCredentials(retinfo.Split(',')[0], retinfo.Split(',')[1], retinfo.Split(',')[2]);
                        //Impersonation.RunAsUser(credentials, logonType, () =>
                        //{
                        if (!Directory.Exists(System.IO.Path.Combine(serverpath, SubDir)))
                        {
                            Directory.CreateDirectory(System.IO.Path.Combine(serverpath, SubDir));
                        }
                        //Backup folder
                        if (StageType != "checkout_next_merged")
                        {
                            int Inflecnt_Backup = System.IO.Directory.GetFiles(System.IO.Path.Combine(serverpath, SubDir), "*.*").Length;
                            if (Inflecnt_Backup != 0)
                            {
                                var backupDir = CommonClass.GetBackupfolder(System.IO.Path.Combine(serverpath, "V001"));
                                CommonClass.MoveDirectory(System.IO.Path.Combine(serverpath, SubDir), System.IO.Path.Combine(backupDir, SubDir));
                            }
                        }
                        int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(Process_Path), "*.*").Length;
                        if (Inflecnt != 0)
                        {
                            CommonClass.CopyDirectory(System.IO.Path.Combine(Process_Path), System.IO.Path.Combine(serverpath, SubDir));
                            return System.IO.Path.Combine(serverpath, SubDir);
                        }
                        else
                        {
                            // CommonClass.WriteLog(fileName, tranid, "FileMove_LocalTOServer File Not Fount");
                            return "Error";
                        }
                        //});
                    }
                }
                else
                {
                    if (!Directory.Exists(System.IO.Path.Combine(serverpath, SubDir)))
                    {
                        Directory.CreateDirectory(System.IO.Path.Combine(serverpath, SubDir));
                    }
                    //Backup folder
                    if (StageType != "checkout_next_merged")
                    {
                        int Inflecnt_Backup = System.IO.Directory.GetFiles(System.IO.Path.Combine(serverpath, SubDir), "*.*").Length;
                        if (Inflecnt_Backup != 0)
                        {
                            var backupDir = CommonClass.GetBackupfolder(System.IO.Path.Combine(serverpath, "V001"));
                            CommonClass.MoveDirectory(System.IO.Path.Combine(serverpath, SubDir), System.IO.Path.Combine(backupDir, SubDir));
                        }
                    }
                    int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(Process_Path), "*.*").Length;
                    if (Inflecnt != 0)
                    {
                        CommonClass.CopyDirectory(System.IO.Path.Combine(Process_Path), System.IO.Path.Combine(serverpath, SubDir));
                        return System.IO.Path.Combine(serverpath, SubDir);
                    }
                    else
                    {
                        // CommonClass.WriteLog(fileName, tranid, "FileMove_LocalTOServer File Not Fount");
                        return "Error";
                    }
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + " at " + ex.StackTrace);
            }
            return "";
        }
        public static object insertLotComments(string comment, string filename, string transid, string doption, string tostage, string jobid, string lotid)
        {
            insertcomments oInsertComments = new insertcomments();
            oInsertComments.transid = Convert.ToUInt32(transid);
            oInsertComments.comments = comment;
            oInsertComments.filename = filename;
            oInsertComments.doption = doption;
            oInsertComments.jobid = Convert.ToUInt32(jobid);
            oInsertComments.lotid = Convert.ToUInt32(lotid);
            oInsertComments.p_option = "insertlotcomments";
            var input = JsonConvert.SerializeObject(oInsertComments);
            return CommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);

        }

        //public static int insert_lot_cmapprove(Int64 lotid, Int64 jworkflowid)
        //{
        //    int tranid = 0;
        //    try
        //    {
        //        Guid id = Guid.NewGuid();
        //        string sQry = "insert_lot_transaction_details_batch_only";
        //        List<NpgsqlParameter> paramet = new List<NpgsqlParameter>();
        //        paramet.Add(new NpgsqlParameter() { DbType = DbType.Int64, ParameterName = "p_jobworkflowid", Value = jworkflowid });
        //        paramet.Add(new NpgsqlParameter() { DbType = DbType.Int64, ParameterName = "p_lotid", Value = lotid });
        //        paramet.Add(new NpgsqlParameter() { DbType = DbType.Guid, ParameterName = "p_lotkey", Value = Guid.Parse(id.ToString()) });
        //        tranid = modcommon.nz(DB_Library.InsertDataScalar(sQry, paramet));
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine("Error at " + ex.StackTrace);
        //        return 0;
        //    }
        //    return tranid;

        //}
        //public static int insert_lot_cmareview(Int64 lotid, Int64 jworkflowid, Int64 batchid)
        //{
        //    int tranid = 0;
        //    try
        //    {
        //        Guid id = Guid.NewGuid();
        //        // string sQry = "insert_lot_transaction_details_batch_only";
        //        string sQry = "insert_lottran_cmreview";
        //        List<NpgsqlParameter> paramet = new List<NpgsqlParameter>();
        //        paramet.Add(new NpgsqlParameter() { DbType = DbType.Int64, ParameterName = "p_jobworkflowid", Value = jworkflowid });
        //        paramet.Add(new NpgsqlParameter() { DbType = DbType.Int64, ParameterName = "p_lotid", Value = lotid });
        //        paramet.Add(new NpgsqlParameter() { DbType = DbType.Int64, ParameterName = "p_batchid", Value = batchid });
        //        paramet.Add(new NpgsqlParameter() { DbType = DbType.Guid, ParameterName = "p_lotkey", Value = Guid.Parse(id.ToString()) });
        //        tranid = modcommon.nz(DB_Library.InsertDataScalar(sQry, paramet));
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine("Error at " + ex.StackTrace);
        //        return 0;
        //    }
        //    return tranid;
        //}

        public static List<jsonvalue> getCheckout(string trans_id, string p_userid, string status, string option, string jobworkflowid, string p_comments = "", string lotid = "0")
        {
            if (lotid == "") { lotid = "0"; }
            if (jobworkflowid == "") { jobworkflowid = "0"; }
            var data = new { p_tranid = trans_id, p_userid = p_userid, p_status = status, p_option = option, n_jobworkflowid = jobworkflowid, p_comments = p_comments, n_lotid = lotid };
            var jsonstr = JsonConvert.SerializeObject(data);
            Console.WriteLine("Param:jsonstr" + jsonstr);
            var res = CommonRepository.ExecuteSP_ReturnList1("spusrlottranupdatev2", jsonstr);

            Console.WriteLine("RequestConsumer:getCheckout:p_status" + status);
            Console.WriteLine("RequestConsumer:getCheckout:trans_id" + trans_id);
            Console.WriteLine("RequestConsumer:getCheckout:option" + option);
            Console.WriteLine("RequestConsumer:getCheckout:jobworkflowid" + jobworkflowid);
            Console.WriteLine("RequestConsumer:getCheckout:lotid" + lotid);

            System.Collections.Generic.List<jsonvalue> appdetails1 = new List<jsonvalue>();
            jsonvalue dd = new jsonvalue();
            dd.json = res.ToString();
            appdetails1.Add(dd);

            return appdetails1;
        }
        public static List<jsonvalue> getCheckoutBatch(string lotid, string batchid, string p_userid, string status, string option, string jobworkflowid, string p_comments = "")
        {

            var data = new { n_batchid = batchid, p_userid = p_userid, p_status = status, p_option = option, n_jobworkflowid = jobworkflowid, p_comments = p_comments, n_lotid = lotid };
            var jsonstr = JsonConvert.SerializeObject(data);
            Console.WriteLine("Param:jsonstr" + jsonstr);
            var res = CommonRepository.ExecuteSP_ReturnList1("spusrlottranupdatev2", jsonstr);

            Console.WriteLine("RequestConsumer:getCheckout:p_status" + status);
            Console.WriteLine("RequestConsumer:getCheckout:p_batchid" + batchid);
            Console.WriteLine("RequestConsumer:getCheckout:option" + option);
            Console.WriteLine("RequestConsumer:getCheckout:jobworkflowid" + jobworkflowid);
            Console.WriteLine("RequestConsumer:getCheckout:lotid" + lotid);

            System.Collections.Generic.List<jsonvalue> appdetails1 = new List<jsonvalue>();
            jsonvalue dd = new jsonvalue();
            dd.json = res.ToString();
            appdetails1.Add(dd);

            return appdetails1;
        }
        private static void callautostage(string nexttranid, string userid)
        {
            Console.WriteLine(CustomConfiguration.AppSettings["kli_rootpath"].ToString() + "/api/WorkAreaApi/Call_Msmq_watcher?p_tranid=" + nexttranid + "&p_userid=" + userid + "&checkout=checkout_stage_withfile_watcher&cfalg=A");

            var client = new RestClient(CustomConfiguration.AppSettings["kli_rootpath"].ToString() + "/api/WorkAreaApi/Call_Msmq_watcher?p_tranid=" + nexttranid + "&p_userid=" + userid + "&checkout=checkout_stage_withfile_watcher&cfalg=A");
            var request = new RestRequest(Method.POST);
            request.AddHeader("cache-control", "no-cache");
            IRestResponse response = client.Execute(request);
            Console.WriteLine("IO Service:callautostage:" + response.Content.ToString());

        }
        private static void callwatchercheckoutnextwithfilemovement(string nexttranid, string userid)
        {
            Console.WriteLine(CustomConfiguration.AppSettings["kli_rootpath"].ToString() + "/api/WorkAreaApi/Call_Msmq_watcher?p_tranid=" + nexttranid + "&p_userid=" + userid + "&checkout=checkout_stage_withfile_watcher&cfalg=F");
            var client = new RestClient(CustomConfiguration.AppSettings["kli_rootpath"].ToString() + "/api/WorkAreaApi/Call_Msmq_watcher?p_tranid=" + nexttranid + "&p_userid=" + userid + "&checkout=checkout_stage_withfile_watcher&cfalg=F");
            var request = new RestRequest(Method.POST);
            request.AddHeader("cache-control", "no-cache");
            IRestResponse response = client.Execute(request);
        }

        private static void FileMovement(string tranid, string next_tranid)
        {
            Console.WriteLine("IOService:FileMovementLot to Lot");
            ServerInfo servinfo = new ServerInfo();
            string serverinpath_tranid = servinfo.GetServerPath(tranid, "serverinfo", false);

            // serverinpath_tranid = Path.Combine(serverinpath_tranid, CustomConfiguration.AppSettings["ServerOUTPATH"].ToString());
            Console.WriteLine("IOService:serverinpath_tranid:--->" + serverinpath_tranid);
            string nextstage_serverpath = servinfo.GetServerPath(next_tranid.ToString(), "serverinfo", true);
            //  nextstage_serverpath = Path.Combine(nextstage_serverpath, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
            Console.WriteLine("IOService:nextstage_serverpath:--->" + nextstage_serverpath);
            if (Directory.Exists(serverinpath_tranid))
            {
                if (!Directory.Exists(nextstage_serverpath))
                {
                    Directory.CreateDirectory(serverinpath_tranid);
                    FileMove_ServerTOServer(tranid, serverinpath_tranid, nextstage_serverpath, "");
                }
                else
                {
                    FileMove_ServerTOServer(tranid, serverinpath_tranid, nextstage_serverpath, "");
                    //FileInfo[] fi_ = new System.IO.DirectoryInfo(serverinpath_tranid).GetFiles();
                    //if (fi_.Length != 0)
                    //{
                    //    for (int m = 0; m <= fi_.Length - 1; m++)
                    //    {
                    //        string _filename = string.Empty, filepath_ = string.Empty;
                    //        filepath_ = fi_[m].FullName.ToString();
                    //        _filename = Path.GetFileName(fi_[m].Name.ToString());
                    //        if (!System.IO.File.Exists(Path.Combine(nextstage_serverpath, _filename)))
                    //            System.IO.File.Copy(filepath_, Path.Combine(nextstage_serverpath, _filename));
                    //    }
                    //}
                }
            }
        }


        private static void FileMovementBatch_Lot(string tranid, string next_tranid, string lotid, string batchid, string stagename, bool createdir)
        {
            Console.WriteLine("IOService:FileMovementBatch_Lot");
            ServerInfo servinfo = new ServerInfo();
            // string serverinpath_tranid = CommonRepository.GetServerPathbatch(lotid, Convert.ToInt32(batchid), false, "serverinfo_batch");
            string serverinpath_tranid = CommonRepository.GetServerPathbatchWithStage(lotid, batchid, stagename, "serverinfo_batch", createdir);
            //   serverinpath_tranid = Path.Combine(serverinpath_tranid, CustomConfiguration.AppSettings["ServerOUTPATH"].ToString());

            Console.WriteLine("IOService:serverinpath_tranid:--->" + serverinpath_tranid);
            string nextstage_serverpath = servinfo.GetServerPath(next_tranid.ToString(), "serverinfo", true);
            // nextstage_serverpath = Path.Combine(nextstage_serverpath, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
            Console.WriteLine("IOService:nextstage_serverpath:--->" + nextstage_serverpath);
            if (Directory.Exists(serverinpath_tranid))
            {
                Console.WriteLine("IOService:FileMovementBatch_Lot:serverinpath_tranid exists");
                if (!Directory.Exists(nextstage_serverpath))
                {
                    Console.WriteLine("IOService:FileMovementBatch_Lot:nextstage_serverpath not exists");
                    Directory.CreateDirectory(serverinpath_tranid);
                    FileMove_ServerTOServer(tranid, serverinpath_tranid, nextstage_serverpath, "");
                }
                else
                {
                    Console.WriteLine("IOService:FileMovementBatch_Lot:nextstage_serverpath exists");
                    FileMove_ServerTOServer(tranid, serverinpath_tranid, nextstage_serverpath, "");
                    //FileInfo[] fi_ = new System.IO.DirectoryInfo(serverinpath_tranid).GetFiles();
                    //if (fi_.Length != 0)
                    //{
                    //    for (int m = 0; m <= fi_.Length - 1; m++)
                    //    {
                    //        string _filename = string.Empty, filepath_ = string.Empty;
                    //        filepath_ = fi_[m].FullName.ToString();
                    //        _filename = Path.GetFileName(fi_[m].Name.ToString());
                    //        if (!System.IO.File.Exists(Path.Combine(nextstage_serverpath, _filename)))
                    //            System.IO.File.Copy(filepath_, Path.Combine(nextstage_serverpath, _filename));
                    //    }
                    //}
                }
            }
        }
        private static void FileMovementLot_Batch(string tranid, string lotid, string batchid, string stagename, bool createdir)
        {
            Console.WriteLine("IOService:FileMovementLot_Batch");
            ServerInfo servinfo = new ServerInfo();
            string serverinpath = servinfo.GetServerPath(tranid, "serverinfo", false);
            // serverinpath = Path.Combine(serverinpath, CustomConfiguration.AppSettings["ServerOUTPATH"].ToString());
            Console.WriteLine("IOService:serverinpath:--->" + serverinpath);
            //string nextstage_serverpath = CommonRepository.GetServerPathbatch(lotid,Convert.ToInt32(batchid), false, "serverinfo_batch");
            string nextstage_serverpath = CommonRepository.GetServerPathbatchWithStage(lotid, batchid, stagename, "serverinfo_batch", createdir);
            // nextstage_serverpath = Path.Combine(nextstage_serverpath, CustomConfiguration.AppSettings["ServerINPATH"].ToString());
            Console.WriteLine("IOService:nextstage_serverpath:--->" + nextstage_serverpath);
            if (Directory.Exists(serverinpath))
            {
                // nextstage_serverpath = nextstage_serverpath + "/";
                if (!Directory.Exists(nextstage_serverpath))
                {
                    Console.WriteLine("IOService:Directory not exists");
                    Directory.CreateDirectory(nextstage_serverpath);

                    FileMove_ServerTOServer(tranid, serverinpath, nextstage_serverpath, "", createdir);
                }
                else
                {
                    Console.WriteLine("IOService:Directory exists:nextstage_serverpath" + nextstage_serverpath);
                    Console.WriteLine("IOService:Directory exists");
                    FileMove_ServerTOServer(tranid, serverinpath, nextstage_serverpath, "", createdir);
                    //FileInfo[] fi_ = new System.IO.DirectoryInfo(serverinpath).GetFiles();
                    //if (fi_.Length != 0)
                    //{
                    //    for (int m = 0; m <= fi_.Length - 1; m++)
                    //    {
                    //        string _filename = string.Empty, filepath_ = string.Empty;
                    //        filepath_ = fi_[m].FullName.ToString();
                    //        _filename = Path.GetFileName(fi_[m].Name.ToString());
                    //        if (!System.IO.File.Exists(Path.Combine(nextstage_serverpath, _filename)))
                    //            System.IO.File.Copy(filepath_, Path.Combine(nextstage_serverpath, _filename));
                    //    }
                    //}
                }
            }

            ////copying in out path also
            // nextstage_serverpath = CommonRepository.GetServerPathbatchWithStage(lotid, batchid, stagename, "serverinfo_batch", createdir);
            //nextstage_serverpath = Path.Combine(nextstage_serverpath, CustomConfiguration.AppSettings["ServerOUTPATH"].ToString());
            //Console.WriteLine("IOService:nextstage_serverpath:--->" + nextstage_serverpath);
            //if (Directory.Exists(serverinpath))
            //{
            //    // nextstage_serverpath = nextstage_serverpath + "/";
            //    if (!Directory.Exists(nextstage_serverpath))
            //    {
            //        Console.WriteLine("IOService:Directory not exists");
            //        Directory.CreateDirectory(nextstage_serverpath);

            //        FileMove_ServerTOServer(tranid, serverinpath, nextstage_serverpath, "", createdir);
            //    }
            //    else
            //    {
            //        Console.WriteLine("IOService:Directory exists:nextstage_serverpath" + nextstage_serverpath);
            //        Console.WriteLine("IOService:Directory exists");
            //        FileInfo[] fi_ = new System.IO.DirectoryInfo(serverinpath).GetFiles();
            //        if (fi_.Length != 0)
            //        {
            //            for (int m = 0; m <= fi_.Length - 1; m++)
            //            {
            //                string _filename = string.Empty, filepath_ = string.Empty;
            //                filepath_ = fi_[m].FullName.ToString();
            //                _filename = Path.GetFileName(fi_[m].Name.ToString());
            //                if (!System.IO.File.Exists(Path.Combine(nextstage_serverpath, _filename)))
            //                    System.IO.File.Copy(filepath_, Path.Combine(nextstage_serverpath, _filename));
            //            }
            //        }
            //    }
            //}


        }

        private static string GetNextTranId(string jobid, string lotid, string stagename)
        {
            var transdata1 = new { jobid = jobid };
            var jsonstr1 = JsonConvert.SerializeObject(transdata1);
            Console.WriteLine("splottransactionselect:jsonstr1:getdetailsbyjobid" + jsonstr1);
            var returnres1 = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", jsonstr1, "getdetailsbyjobid");

            var i_appType1 = JsonConvert.DeserializeObject<object>(returnres1.ToString());
            Console.WriteLine("i_appType1.ToString():" + i_appType1.ToString());
            JArray lottransdetails1 = JArray.Parse(i_appType1.ToString());
            string nexttranid = "";

            var a = lottransdetails1.Where(c =>
            (c["stagename_alias"].ToString() == stagename) && (c["lotid"].ToString() == lotid)).FirstOrDefault();
            if (a != null && a.Count() != 0)
            {
                nexttranid = a["transactionid"].ToString();
            }
            return nexttranid;
        }

        private static JArray GetNextJobworkflowdetails(string jobid)
        {
            var transdata1 = new { jobid = jobid };
            var jsonstr1 = JsonConvert.SerializeObject(transdata1);
            Console.WriteLine("splottransactionselect:getdetailsbyjobid:jsonstr1:" + jsonstr1);
            var returnres1 = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", jsonstr1, "getjobworkflowbyjobid");
            var i_appType1 = JsonConvert.DeserializeObject<object>(returnres1.ToString());
            JArray lottransdetails1 = JArray.Parse(i_appType1.ToString());

            return lottransdetails1;
        }

        private static string GetJobWorkFlowId(string jobid, string stagename)
        {

            var inputdata = new { jobid = jobid };
            var jsonstr1 = JsonConvert.SerializeObject(inputdata);
            Console.WriteLine("splottransactionselect:getjobworkflowdefbyjobid:jsonstr1:" + jsonstr1);
            var returnres1 = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", jsonstr1, "getjobworkflowdefbyjobid");
            var i_appType1 = JsonConvert.DeserializeObject<object>(returnres1.ToString());
            JArray lottransdetails1 = JArray.Parse(i_appType1.ToString());
            string jobworflowid = "";

            var a = lottransdetails1.Where(c =>
            (c["stagename_alias"].ToString() == stagename)).FirstOrDefault();
            if (a != null && a.Count() != 0)
            {
                jobworflowid = a["jobworflowid"].ToString();
            }
            return jobworflowid;
        }
    }

    public class pubflowinputModel
    {
        public string Batch { get; set; }
        public string PublicationType { get; set; }
        public string PublicationID { get; set; }
    }
    public class klilotbatchdetails
    {
        public long? lotbatchdetailid { get; set; }
        public long? lotid { get; set; }
        public string batchname { get; set; }
        public string supplementtype { get; set; }
        public long? jobid { get; set; }
        public long? tranid { get; set; }
        public long? jobworkflowid { get; set; }
    }
}