| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617 |
- using Dapper;
- using iTextSharp.text.pdf;
- using MassTransit;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using Npgsql;
- using RabbitMQ.Client.Framing.Impl;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.IO;
- using System.IO.Compression;
- using System.Linq;
- using System.Net;
- using System.Reflection.PortableExecutable;
- using System.Security.Cryptography;
- using System.Security.Principal;
- using System.Text.RegularExpressions;
- using System.Threading.Tasks;
- using System.Xml.Linq;
- using WK_KLI_LAPS_COMMONTOOL_Service.App_Data;
- using WK_KLI_LAPS_COMMONTOOL_Service.Models;
- using static MassTransit.Logging.LogCategoryName;
- namespace WK_KLI_LAPS_COMMONTOOL_Service.Controllers.WorkArea
- {
- [Route("api/[controller]")]
- [ApiController]
- public class WorkAreaApiController : ControllerBase
- {
- CommonRepository oCommonRepository = new CommonRepository();
- WorkAreaService oWorkAreaService = new WorkAreaService();
- string baseurl = Startup.Configuration.GetValue<string>("AppSettings:serverroot");
- [AllowAnonymous]
- [HttpPost("getCheckout")]
- public IActionResult getCheckout([FromBody] object data)
- {
- try
- {
- var _list = oWorkAreaService.getCheckout(data);
- return Ok(_list);
- }
- catch (Exception ex)
- {
- oCommonRepository.ErrorLog(ex);
- // return error message if there was an exception
- return BadRequest(new { message = ex.Message });
- }
- }
- [AllowAnonymous]
- [HttpPost("usrstagemove")]
- public IActionResult usrstagemove([FromBody] lottraninfo data)
- {
- try
- {
- var _list = oWorkAreaService.usrstagemove(data);
- return Ok(_list);
- }
- catch (Exception ex)
- {
- oCommonRepository.ErrorLog(ex);
- // return error message if there was an exception
- return BadRequest(new { message = ex.Message });
- }
- }
- [AllowAnonymous]
- [HttpPost("getJobDetails")]
- public IActionResult getJobDetails([FromBody] object data)
- {
- var _list = oWorkAreaService.getJobDetails(data);
- return Ok(_list);
- }
- [AllowAnonymous]
- [HttpPost("getLotDetailsComments")]
- public IActionResult getLotDetailsComments([FromBody] object data)
- {
- var _list = oWorkAreaService.getLotDetailsComments(data);
- return Ok(_list);
- }
- [HttpPost("getLotDetailsOCR")]
- public IActionResult GetLotDetailsOCR([FromBody] JobRequest request)
- {
- if (request == null || request.JobId <= 0)
- return BadRequest("Invalid job ID");
- string serverinfo = string.Empty;
- var resultObj = oWorkAreaService.getLotDetailsOCR(request.JobId);
- // Convert to int safely
- int tranid = 0;
- if (resultObj != null)
- {
- // If resultObj is a list and you want the first item:
- var list = resultObj as IEnumerable<object>;
- if (list != null && list.Any())
- {
- tranid = Convert.ToInt32(list.First());
- }
- serverinfo = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
- }
- return Ok(serverinfo);
- }
- [HttpGet("DownloadFile")]
- public async Task<IActionResult> DownloadFile([FromQuery] string path, [FromQuery] string title, [FromQuery] string jobid)
- {
- if (string.IsNullOrWhiteSpace(path))
- return BadRequest("Folder path is required.");
- try
- {
- // ✅ Validate allowed network base path
- string allowedBasePath = @"\\pdynxfs\OEB_xml";
- if (!path.StartsWith(allowedBasePath, StringComparison.OrdinalIgnoreCase))
- return BadRequest("Access to this path is not allowed.");
- // ✅ Append subfolder if needed
- path = Path.Combine(path, "IN");
- if (!Directory.Exists(path))
- return NotFound("Folder not found.");
- // ✅ Fallback title
- if (string.IsNullOrWhiteSpace(title))
- title = "Download";
- var zipFileName = $"{title}.zip";
- // ✅ Use application temp folder instead of system temp
- string tempBase = Path.Combine(System.AppContext.BaseDirectory, "TempZips");
- Directory.CreateDirectory(tempBase); // ensure exists
- var tempZipPath = Path.Combine(tempBase, zipFileName);
- // ✅ Remove existing temp ZIP (if any)
- if (System.IO.File.Exists(tempZipPath))
- System.IO.File.Delete(tempZipPath);
- // ✅ Impersonate with granted folder permission
- using (var permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- await WindowsIdentity.RunImpersonated(newId.AccessToken, async () =>
- {
- // Step 1: Create ZIP (no compression = faster)
- ZipFile.CreateFromDirectory(path, tempZipPath, CompressionLevel.NoCompression, includeBaseDirectory: true);
- await Task.CompletedTask; // keep async signature clean
- });
- }
- // Step 2: Stream ZIP asynchronously to response
- Response.ContentType = "application/zip";
- Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{zipFileName}\"");
- await using (var stream = new FileStream(tempZipPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
- {
- await stream.CopyToAsync(Response.Body);
- }
- // Step 3: Delete temporary ZIP
- try
- {
- System.IO.File.Delete(tempZipPath);
- }
- catch
- {
- // ignore file delete issues
- }
- return new EmptyResult(); // response already written
- }
- catch (Exception ex)
- {
- // ✅ Log the error
- oCommonRepository.addlog(new
- {
- errormessage = "Error: " + ex.Message,
- createdby = 0,
- controller = "WorkAreaApi: DownloadFile"
- }, "errorlog");
- return StatusCode(500, $"Error while downloading folder: {ex.Message}");
- }
- }
- [HttpPost]
- public object PostValidateQA(Fields fields)
- {
- //DBContext db = new DBContext();
- //db.CheckLogin();
- var json = new List<object>();
- //try
- //{
- // BLDatamanipulation db_ = new BLDatamanipulation();
- // DataTable svrpath = db_.GetDataTable(db, string.Format("select * from usr_server_path_info({0},'serverinfo')", fields.transid), null);
- // string serverpath = svrpath.Rows[0]["serverpath"].ToString();
- // serverpath = "\\\\" + serverpath.Replace("/", "\\");
- // string serveroutpath = System.IO.Path.Combine(serverpath, "OUT");
- // string serverinpath = System.IO.Path.Combine(serverpath, "IN");
- // var ext = new List<string> { ".pdf", ".xml" };
- // if (Directory.Exists(serveroutpath) && Directory.Exists(serverinpath))
- // {
- // List<string> infile = Directory.GetFiles(serverinpath, "*.*", SearchOption.AllDirectories)
- // .Where(s => ext.Contains(Path.GetExtension(s).ToLower())).Select(x => Path.GetFileName(x)).ToList();
- // List<string> outfile = Directory.GetFiles(serveroutpath, "*.*", SearchOption.AllDirectories)
- // .Where(s => ext.Contains(Path.GetExtension(s).ToLower())).Select(x => Path.GetFileName(x)).ToList();
- // List<string> exept = infile.Except(outfile).ToList();
- // if (exept.Count > 0)
- // {
- // json.Add(JObject.Parse("{\"success\":false}"));
- // json.Add(JObject.Parse("{\"log\":\"Please completed QA process then proceed.\"}"));
- // }
- // else
- // {
- // if (File.Exists(Path.Combine(serveroutpath, "error.txt")))
- // {
- // json.Add(JObject.Parse("{\"success\":false}"));
- // json.Add(JObject.Parse("{\"log\":\"Please clear the validation error then proceed.\"}"));
- // }
- // else
- // json.Add(JObject.Parse("{\"success\":true}"));
- // }
- // }
- // else { json.Add(JObject.Parse("{\"success\":false}")); json.Add(JObject.Parse("{\"log\":\"Please completed QA process then proceed.\"}")); }
- //}
- //catch (Exception ex)
- //{
- // json.Add(JObject.Parse("{\"success\":false}"));
- // json.Add(JObject.Parse("{\"log\":\"Process failed. " + ex.Message + "\"}"));
- //}
- return json;
- }
- //raji
- [Authorize]
- [HttpPost("savefilechecker")]
- public object savefilechecker()
- {
- bool dirvalidate = false;
- bool filevalidate = false;
- string message = "";
- try
- {
- //var json =[];
- var httpRequest = HttpContext.Request.Form;
- string filepath = string.Empty;
- string actualdirectory = string.Empty;
- string filepath_name = string.Empty;
- string lottitles = string.Empty;
- string jobtitle = string.Empty;
- string dirName = string.Empty;
- //int charIndex = 0;
- string retmsg = string.Empty;
- string jobid = Request.Form["jobid"].ToString();
- string kvpmode = Request.Form["kvpmode"].ToString();
- string kvpvalue = Request.Form["kvpvalue"].ToString();
- string tranid = Request.Form["tranid"].ToString();
- string serverinfo = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
- string serverpath = Path.Combine(serverinfo, "OUT");
- string templatefileserverpath = string.Empty;
- var titleqry = oWorkAreaService.spfiletypevalidation(tranid.ToString(), jobid);
- var titleqry_jsonList = new List<string>();
- if (titleqry != null)
- {
- var titleqry_filetype = JsonConvert.DeserializeObject<object>(titleqry.ToString());
- JArray titleqry_a_filetype = JArray.Parse(titleqry_filetype.ToString());
- lottitles = titleqry_a_filetype[0]["titlecur"].ToString();
- jobtitle = titleqry_a_filetype[0]["jobtitle"].ToString();
- lottitles = lottitles.Replace("-img", "");
- lottitles = lottitles.Replace("-txt", "");
- }
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- if (httpRequest.Files.Count > 0)
- {
- if (!Directory.Exists(serverpath))
- {
- Directory.CreateDirectory(serverpath);
- }
- if (!string.IsNullOrEmpty(kvpmode) && !string.IsNullOrEmpty(kvpvalue))
- {
- if (kvpmode == "file")
- {
- filepath = Directory.GetDirectories(serverpath, lottitles, SearchOption.TopDirectoryOnly).FirstOrDefault();
- if (!string.IsNullOrEmpty(filepath) && Directory.Exists(filepath))
- {
- dirvalidate = true;
- }
- else
- {
- //dirvalidate = true;
- if (!Directory.Exists(Path.Combine(serverpath, lottitles)))
- {
- Directory.CreateDirectory(Path.Combine(serverpath, lottitles));
- dirvalidate = true;
- }
- }
- for (int i = 0; i < httpRequest.Files.Count; i++)
- {
- var outfile = httpRequest.Files[i];
- dirName = "";
- dirName = Path.GetDirectoryName(outfile.FileName);
- if (dirName == "")
- {
- filepath_name = Path.GetFileNameWithoutExtension(outfile.FileName);
- if (kvpvalue == "_Redacted")
- {
- filevalidate = true;
- if (!filepath_name.ToString().EndsWith(kvpvalue) || !filepath_name.ToLower().Contains(lottitles.ToLower()))
- {
- filevalidate = false;
- }
- }
- else if (filepath_name.ToString().EndsWith(kvpvalue))
- {
- filevalidate = true;
- break;
- }
- }
- }
- }
- else
- {
- filevalidate = true;
- actualdirectory = string.Empty;
- actualdirectory = Path.Combine(serverpath, jobtitle + kvpvalue);
- string visf_folder = string.Empty;
- string[] extensionFilters = new string[] { kvpvalue };
- visf_folder = Directory.GetDirectories(serverpath, "*.*", SearchOption.TopDirectoryOnly)
- .Where(filename => extensionFilters.Any(x =>
- filename.EndsWith(x, StringComparison.OrdinalIgnoreCase))).FirstOrDefault();
- if (!string.IsNullOrEmpty(visf_folder))
- {
- dirvalidate = true;
- }
- else
- {
- if (!Directory.Exists(actualdirectory))
- {
- Directory.CreateDirectory(actualdirectory);
- dirvalidate = true;
- }
- }
- }
- //}
- if (kvpmode == "file")
- {
- if (filevalidate == false)
- {
- message = "" + kvpvalue + " file missing please check";
- }
- else
- {
- if (dirvalidate == false)
- {
- message = "file is not placed properly in lotname against job";
- }
- }
- }
- else
- {
- if (dirvalidate == false)
- {
- message = "" + kvpvalue + " folder missing against job.Please Check";
- }
- }
- }
- //else
- //{
- // message = "Unknown stage processor.please check";
- // var json = new { dirresult = dirvalidate, fileresults = filevalidate, Message = message };
- // return json;
- //}
- }
- });
- }
- var json1 = new { dirresult = dirvalidate, fileresults = filevalidate, Message = message };
- return json1;
- }
- catch (Exception ex)
- {
- message = ex.Message;
- dirvalidate = false;
- filevalidate = false;
- var json = new { dirresult = dirvalidate, fileresults = filevalidate, Message = message };
- return json;
- }
- }
- //rajii
- [Authorize]
- [HttpPost]
- public object PostUpdatelot_transaction(Fields fields)
- {
- //DBContext db = new DBContext();
- //db.CheckLogin();
- //long transactionid = fields.transid;
- //string option = fields.option;
- //string comment = fields.comment;
- //if (fields.fields != "null")
- //{
- // BLDatamanipulation db_ = new BLDatamanipulation();
- // List<NpgsqlParameter> parms = new List<NpgsqlParameter>();
- // db_.InsertQuery(db, "update lot_master set lotmastermetafields = '" + fields.fields + "' where lotid in (select a.lotid from lot_transaction a where a.transactionid = " + fields.transid + ")", parms);
- // db_.InsertQuery(db, "update lot_transaction set lotmetafields = '" + fields.fields + "' where transactionid = " + fields.transid + "", parms);
- //}
- //lot_tran_info lotinfo = new lot_tran_info();
- //lotinfo.p_tranid = transactionid.ToString();
- //lotinfo.p_userid = (HttpContext.Current.Session["UserID"] as string);
- //lotinfo.p_option = option;
- //lotinfo.p_holdreason = comment;
- //if (option == "checkout")
- // Checkout_transaction(lotinfo);
- //else if (option == "hold")
- // getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "I", "hold", "0", lotinfo.p_holdreason);
- //else if (option == "checkin")
- // getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "P", "hold", "0", lotinfo.p_holdreason);
- return "Done";
- }
- public void TriggerMail(string tranid, string ordernumber, string nxttranid)
- {
- try
- {
- if (ordernumber == "1")
- {
- System.Threading.Tasks.Parallel.Invoke(() => SendMailRequest(string.Join("", baseurl, "/api/DashboardApi/Postmail_PM?tranid=", tranid, "&sflag=", "1")));
- System.Threading.Tasks.Parallel.Invoke(() => SendMailRequest(string.Join("", baseurl, "/api/DashboardApi/Postmail_Ack?tranid=", tranid, "&sflag=", "2")));
- }
- else if (ordernumber == "2")
- {
- System.Threading.Tasks.Parallel.Invoke(() => SendMailRequest(string.Join("", baseurl, "/api/DashboardApi/Postmail_SignOff?tranid=", nxttranid, "&jobworkflowid=", 0, "&sflag=", "2", "&curtranid=", tranid)));
- }
- }
- catch (Exception ex)
- {
- var data_input = new
- {
- errormessage = "Error: " + ex.Message,
- createdby = 0,
- controller = "UploaderApi: Downloader"
- };
- oCommonRepository.addlog(data_input, "errorlog");
- }
- }
- public void SendMailRequest(string apiUrl)
- {
- try
- {
- HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
- authRequest.ContentType = "application/xml";
- authRequest.Method = "POST";
- authRequest.ContentLength = 0;
- WebResponse authResponseTwitter = authRequest.GetResponse();
- }
- catch (Exception ex)
- {
- var data_input = new
- {
- errormessage = "Error: " + ex.Message,
- createdby = 0,
- controller = "UploaderApi: Downloader"
- };
- oCommonRepository.addlog(data_input, "errorlog");
- }
- }
- [HttpPost]
- public object getbronsdetails(string jobid)
- {
- //DBContext db = new DBContext();
- //db.CheckLogin();
- //string qry = "select * from getbronsbyid(@p_job) as json";
- //var data = db.Database.SqlQuery<jsonvalue>(qry, new Npgsql.NpgsqlParameter { ParameterName = "@p_job", Value = Convert.ToInt64(jobid) }).ToList();
- var json = new List<object>();
- //foreach (var item in data)
- //{
- // json.Add(JObject.Parse(item.json));
- //}
- return json;
- }
- [HttpPost]
- public object isdeleted(string jobid, string lotid)
- {
- //DBContext db = new DBContext();
- //db.CheckLogin();
- //var menudetails = db.Database.SqlQuery<jsonvalue>("select json_build_object('articalstatus', wa.article_status)as json from wkb_articleinfo wa inner join lot_master lm on lm.jobid=wa.jobid and lm.lotid=wa.lotid where lm.jobid=@jobid and lm.lotid=@lotid",
- // new Npgsql.NpgsqlParameter { ParameterName = "@jobid", Value = jobid }, new Npgsql.NpgsqlParameter { ParameterName = "@lotid", Value = lotid }).ToList();
- var json = new List<object>();
- //foreach (var item in menudetails)
- //{
- // json.Add(JObject.Parse(item.json));
- //}
- return json;
- }
- [HttpPost("test")]
- public object test()
- {
- return "done";
- }
- //[HttpPost]
- //public object getAllbronsdetails(string jobid_BUP)
- //{
- // DBContext db = new DBContext();
- // db.CheckLogin();
- // string qry = "select * from getbronsNewbyid(@p_job) as json";
- // var data = db.Database.SqlQuery<jsonvalue>(qry, new Npgsql.NpgsqlParameter { ParameterName = "@p_job", Value = Convert.ToInt64(jobid_BUP) }
- // ).ToList();
- // return data;
- //}
- //[HttpPost]
- //public object loadweblink(string jobid_o, long tranid)
- //{
- // DBContext db = new DBContext();
- // db.CheckLogin();
- // var json = new List<object>();
- // string jobid = getjobid(tranid);
- // BLDatamanipulation db12 = new BLDatamanipulation();
- // DataTable dt2 = db12.GetDataTable(db, "select isignoreable,websiteurl from wkb_job_details a where a.jobid = " + jobid + "", null);
- // if (dt2.Rows.Count > 0)
- // {
- // string isignore = dt2.Rows[0]["isignoreable"].ToString().ToLower();
- // string websiteurl = dt2.Rows[0]["websiteurl"].ToString().ToLower();
- // json.Add(JObject.Parse("{\"isignoreable\":'" + isignore + "',\"websiteurl\":'" + websiteurl + "'}"));
- // }
- // return json;
- //}
- public string getjobid(long p_tranid)
- {
- try
- {
- //DataTable svrpath = getdatatable("usr_server_path_info", new List<Npgsql.NpgsqlParameter>(){ new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = p_tranid },
- // new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "serverinfo" }});
- return "";// svrpath.Rows[0]["jobid"].ToString();
- }
- catch (Exception ex)
- {
- return string.Join("", "Error : ", ex.Message.ToString());
- }
- }
- //[HttpPost]
- //public object Checkout_transaction(lot_tran_info lotinfo)
- //{
- // var trans_id = lotinfo.p_tranid;
- // var checkout = getCheckout(trans_id, lotinfo.p_userid, "C", "checkout_only", "0", lotinfo.p_holdreason);
- // if (checkout.Count > 0)
- // {
- // foreach (var item in checkout)
- // {
- // JobWorkflow_ obj = JsonConvert.DeserializeObject<JobWorkflow_>(item.json);
- // List<StageData> lst = new List<StageData>();
- // //******************* Get Next Stage Details **************
- // lst = getNextStageDetails(obj.jobid, obj.jobworkflowid);
- // //*******************
- // List<StageData> newList = lst
- // .Where(m => m.CURRENT == obj.jobworkflowid)
- // .ToList();
- // //******************* To Check Next Stage
- // foreach (var items in newList)
- // {
- // var next_workflow_id = "";
- // if (items.NEXT != null)
- // next_workflow_id = items.NEXT;
- // else if (items.PARALLEL != null)
- // next_workflow_id = items.PARALLEL;
- // else if (items.MOVEBACKNO != null)
- // next_workflow_id = items.MOVEBACKNO;
- // else if (items.MOVEBACKYES != null)
- // next_workflow_id = items.MOVEBACKYES;
- // //*******************
- // if (next_workflow_id != null)
- // {
- // next_workflow_id = next_workflow_id.Trim();
- // List<StageData> checkParallalList = lst
- // .Where(m => m.NEXT == next_workflow_id || m.PARALLEL == next_workflow_id || m.MOVEBACKYES == next_workflow_id || m.MOVEBACKNO == next_workflow_id)
- // .ToList();
- // if (checkParallalList.Count > 0)
- // {
- // var if_check_parallel = true;
- // //***************** Only One Next Stage
- // if (checkParallalList.Count == 1)
- // {
- // var checkout_next = getCheckout(trans_id, lotinfo.p_userid, "R", "checkout_next", next_workflow_id, lotinfo.p_holdreason);
- // var json = new List<transout>();
- // foreach (var checkout_next_item in checkout_next)
- // json.Add(JsonConvert.DeserializeObject<transout>(checkout_next_item.json));
- // sendmail(lotinfo, json[0].p_tranid, obj.jobworkflowid);
- // }
- // //***************** More than One Next Stage
- // else
- // {
- // foreach (var item_checkParallalList in checkParallalList)
- // {
- // //***************** To Check All Parallal stage are completed or put Wait
- // var checkout_check_parallel = getCheckout(trans_id, lotinfo.p_userid, "C", "checkout_parallel_check", item_checkParallalList.CURRENT);
- // if (checkout_check_parallel.Count > 0)
- // {
- // foreach (var parallel_item in checkout_check_parallel)
- // {
- // JobWorkflow_ parallel_item_obj = JsonConvert.DeserializeObject<JobWorkflow_>(parallel_item.json);
- // if (parallel_item_obj.lotstatus == "P" || parallel_item_obj.lotstatus == "R" || parallel_item_obj.lotstatus == "W" || parallel_item_obj.lotstatus == "" || parallel_item_obj.lotstatus == null)
- // {
- // if_check_parallel = false;
- // }
- // }
- // }
- // }
- // if (if_check_parallel == true)
- // {
- // var checkout_next = getCheckout(trans_id, lotinfo.p_userid, "R", "checkout_next", next_workflow_id, lotinfo.p_holdreason);
- // var json = new List<transout>();
- // foreach (var checkout_next_item in checkout_next)
- // json.Add(JsonConvert.DeserializeObject<transout>(checkout_next_item.json));
- // sendmail(lotinfo, json[0].p_tranid, obj.jobworkflowid.ToString());
- // }
- // else
- // { var checkout_next = getCheckout(trans_id, lotinfo.p_userid, "W", "checkout_next", next_workflow_id, lotinfo.p_holdreason); }
- // }
- // }
- // }
- // //*******************
- // }
- // }
- // }
- // return "Done";
- //}
- //public List<jsonvalue> getCheckout(string trans_id, string p_userid, string status, string option, string jobworkflowid, string p_comments = "")
- //{
- // DBContext db1 = new DBContext();
- // return db1.Database.SqlQuery<jsonvalue>("select * from usr_lot_tran_update_v2(@p_tranid,@p_userid,@p_status,@p_option,@jobworkflowid,@p_comments) as json",
- // new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = trans_id },
- // new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = p_userid },
- // new Npgsql.NpgsqlParameter { ParameterName = "@p_status", Value = status },
- // new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = option },
- // new Npgsql.NpgsqlParameter { ParameterName = "@p_comments", Value = p_comments },
- // new Npgsql.NpgsqlParameter { ParameterName = "@jobworkflowid", Value = jobworkflowid }).ToList();
- // //List<Npgsql.NpgsqlParameter> Parmtr = new List<NpgsqlParameter>();
- // //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = trans_id });
- // //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = p_userid });
- // //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@p_status", Value = status });
- // //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = option });
- // //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@jobworkflowid", Value = jobworkflowid });
- // //string json = db.getdataJson("usr_lot_tran_update_v2", Parmtr);
- // //return Newtonsoft.Json.JsonConvert.DeserializeObject<List<JobWorkflow_>>(string.Join("", json));
- //}
- public List<StageData> getNextStageDetails(string jobid, string jobworkflowid)
- {
- //BLDatamanipulation db = new BLDatamanipulation();
- //DBContext dbcontext_ = new DBContext();
- //string qry1 = @"select concat((case when jm.nextstage is not null and jm.movebackstage is null
- // then
- // concat('CURRENT:',cast(jm.jobworkflowid as text),',NEXT:',cast(nextjm.jobworkflowid as text)
- // ,case when (select count(1) from job_workflow_master where parallelstage=jm.nextstage)>0
- // then (select string_agg(concat(chr(10),',CURRENT:',cast(jm.jobworkflowid as text),',PARALLEL:',cast(jobWorkflowID as text)), '') from job_workflow_master where parallelstage=jm.nextstage)
- // else '' end)
- // else concat('CURRENT:',cast(jm.jobworkflowid as text)) end )
- // , (case when backjm.jobworkflowid is null then '' else concat(chr(10),',MOVEBACKYES:',cast(backjm.jobworkflowid as text),chr(10),',MOVEBACKNO:',cast(nextjm.jobworkflowid as text),
- // case when (select count(1) from job_workflow_master where parallelstage=nextjm.jobworkflowid)>0 then
- // (select concat(chr(10),'CURRENT:',cast(jm.jobworkflowid as text),'MOVEBACKNO:',cast(jobWorkflowID as text)) from job_workflow_master where parallelstage=nextjm.jobworkflowid) else '' end) end)) as Flowchart
- // from job_workflow_master jm
- // inner join stage_type_master st on st.stagetypeid=jm.stage_type
- // left join job_workflow_master nextjm on nextjm.jobworkflowid =jm.nextstage
- // left join job_workflow_master backjm on backjm.jobworkflowid =jm.movebackstage
- // where jm.jobid=" + jobid + " and jm.active=1 order by jm.stageorder";
- List<StageData> lst = new List<StageData>();
- //System.Data.DataTable data1 = db.GetDataTable(dbcontext_, qry1, null);
- //if (data1.Rows.Count > 0)
- //{
- // for (int i = 0; i <= data1.Rows.Count - 1; i++)
- // {
- // var splite = data1.Rows[i][0].ToString().Split(',');
- // if (splite.Length > 0)
- // {
- // var current = "";
- // foreach (string word in splite)
- // {
- // var stemp = ""; StageData st = new StageData();
- // var innersplite = word.ToString().Split(':');
- // for (int j = 0; j <= innersplite.Length; j++)
- // {
- // if (innersplite[0] == "CURRENT")
- // current = innersplite[1].Trim();
- // }
- // for (int j = 0; j <= innersplite.Length; j++)
- // {
- // st.CURRENT = current;
- // if (innersplite[0] == "CURRENT")
- // stemp = "CURRENT";
- // else if (innersplite[0] == "NEXT")
- // st.NEXT = innersplite[1].Trim();
- // else if (innersplite[0] == "PARALLEL")
- // st.PARALLEL = innersplite[1].Trim();
- // else if (innersplite[0] == "MOVEBACKNO")
- // st.MOVEBACKNO = innersplite[1].Trim();
- // else if (innersplite[0] == "MOVEBACKYES")
- // st.MOVEBACKYES = innersplite[1].Trim();
- // }
- // if (stemp != "CURRENT")
- // lst.Add(st);
- // }
- // }
- // }
- //}
- return lst;
- }
- public void sendmail(lot_tran_info lotinfo, string nexttranval, string jobworkflowid)
- {
- // (HttpContext.Current.Session["UserID"] as string)
- long userId_t = Convert.ToInt64("4"); // need to add logged in userid
- RabbitMq sendmsg = new RabbitMq();
- sendmsg.SendMqMail(lotinfo.p_tranid.ToString(), jobworkflowid.ToString(), "2", nexttranval.ToString(), userId_t.ToString());
- //var JobMetaFields = GetJobMetaData(nexttranval.ToString(), lotinfo.p_tranid.ToString(), jobworkflowid);
- //Postmail_SignOff(nexttranval, jobworkflowid, "", lotinfo.p_tranid.ToString(), JobMetaFields);
- //TriggerMail(lotinfo.p_tranid.ToString(), "2", nexttranval);
- //System.Threading.Thread.Sleep(100);
- //TriggerMail(lotinfo.p_tranid.ToString(), "1", (HttpContext.Current.Session["UserID"] as string));
- }
- public List<jobmetafields> GetJobMetaData(string tranid, string completedtranid, string jobworkflowid)
- {
- //DBContext db = new DBContext();
- //BLDatamanipulation db1 = new BLDatamanipulation();
- var finalout = new List<jobmetafields>();
- //var workflowid = "";
- //var completed_workflowid = ""; var job_id = "";
- //DataTable dt = db1.GetDataTable(db, "select wfdid,jobid from job_workflow_master a where a.jobworkflowid = " + jobworkflowid + "", null);
- //if (dt.Rows.Count > 0)
- //{
- // completed_workflowid = dt.Rows[0]["wfdid"].ToString();
- // job_id = dt.Rows[0]["jobid"].ToString();
- //}
- //var str = "select b.jobmetafields as jobworkflow_metafields,b.wfdid,c.lotmastermetafields as lot_metafields from lot_transaction a left outer join job_workflow_master b on a.jobworkflowid = b.jobworkflowid left outer join lot_master c on c.lotid = a.lotid where a.transactionid = @tranid";
- //var jobmeta = db.Database.SqlQuery<lot_tran_metafields>(str, new Npgsql.NpgsqlParameter { ParameterName = "@tranid", Value = tranid }).ToList();
- //if (jobmeta.Count > 0)
- //{
- // //jobworkflow_metafields
- // var jobworkflow_metafields = new List<jobmetafields>();
- // var lotmastermetafields = new List<jobmetafields>();
- // foreach (var item in jobmeta)
- // {
- // if (item.jobworkflow_metafields != null)
- // {
- // dynamic json = JsonConvert.DeserializeObject(item.jobworkflow_metafields);
- // workflowid = item.wfdid.ToString();
- // for (int i = 0; i < json.Count; i++)
- // {
- // var jdata = new jobmetafields();
- // foreach (var s in json[i])
- // {
- // if (s.Name == "name")
- // jdata.name = string.Join(",", s);
- // else if (s.Name == "type")
- // jdata.type = string.Join(",", s);
- // else if (s.Name == "value")
- // jdata.value = string.Join(",", s);
- // else if (s.Name == "workflowdid")
- // jdata.workflowdid = string.Join(",", s);
- // else if (s.Name == "label")
- // jdata.label = string.Join(",", s);
- // }
- // jobworkflow_metafields.Add(jdata);
- // }
- // //lotmastermetafields
- // dynamic json_ = JsonConvert.DeserializeObject(item.lot_metafields);
- // for (int i = 0; i < json_.Count; i++)
- // {
- // var jdata = new jobmetafields();
- // foreach (var s in json_[i])
- // {
- // if (s.Name == "name")
- // jdata.name = string.Join(",", s);
- // else if (s.Name == "type")
- // jdata.type = string.Join(",", s);
- // else if (s.Name == "value")
- // jdata.value = string.Join(",", s);
- // else if (s.Name == "workflowdid")
- // jdata.workflowdid = string.Join(",", s);
- // else if (s.Name == "label")
- // jdata.label = string.Join(",", s);
- // }
- // lotmastermetafields.Add(jdata);
- // }
- // }
- // }
- // var completed_field = (from job in jobworkflow_metafields
- // join lot in lotmastermetafields on new { job.workflowdid, job.name } equals new { lot.workflowdid, lot.name } //where lot.workflowdid == completed_workflowid
- // select new
- // {
- // lot.name,
- // lot.type,
- // job.label,
- // lot.workflowdid,
- // lot.value,
- // lot.status
- // }).ToList();
- // var current_field = (from job in jobworkflow_metafields
- // where job.workflowdid == workflowid
- // select new
- // {
- // job.name,
- // job.type,
- // job.label,
- // job.workflowdid,
- // job.value,
- // job.status
- // }).ToList();
- // foreach (var item in completed_field)
- // {
- // var stemp = new jobmetafields();
- // stemp.name = item.name;
- // stemp.type = item.type;
- // stemp.label = item.label.Replace("$$JobNo", job_id);
- // stemp.workflowdid = item.workflowdid;
- // stemp.value = item.value;
- // stemp.status = "Completed";
- // finalout.Add(stemp);
- // }
- // foreach (var item in current_field)
- // {
- // var stemp = new jobmetafields();
- // stemp.name = item.name;
- // stemp.type = item.type;
- // stemp.label = item.label;
- // stemp.workflowdid = item.workflowdid;
- // stemp.value = item.value;
- // stemp.status = "Current";
- // finalout.Add(stemp);
- // }
- //}
- return finalout;
- }
- private void CreateZip(string directoryPathToZip, string outputZipFileName)
- {
- //try
- //{
- // if (File.Exists(outputZipFileName))
- // File.Delete(outputZipFileName);
- // using (ZipFile outputZip = new ZipFile(outputZipFileName))
- // {
- // outputZip.AddDirectory(directoryPathToZip);
- // outputZip.Save();
- // }
- //}
- //catch (Exception ex)
- //{ }
- }
- [Authorize]
- [HttpPost("saveOutputFile")]
- public object saveOutputFile()
- {
- try
- {
- var httpRequest = HttpContext.Request.Form;
- string filepath = string.Empty;
- string dirName = string.Empty;
- int charIndex = 0;
- string lottitles = string.Empty;
- string jobtitle = string.Empty;
- string filepath_name = string.Empty;
- string projectsubtitle = string.Empty;
- // string currentstagename = string.Empty;
- string retmsg = string.Empty;
- bool lottitle_ = false;
- string jobid = Request.Form["jobid"].ToString();
- string tranid = Request.Form["tranid"].ToString();
- string pdid = Request.Form["pdid"].ToString();
- string kvpmode = Request.Form["kvpmode"].ToString();
- string kvpvalue = Request.Form["kvpvalue"].ToString();
- string fileID = Request.Form["fileID"].ToString();
- string totalchunk = Request.Form["totalChunks"].ToString();
- string filename = Request.Form["filename"].ToString();
- string currentstagename = Request.Form["currentstagename"].ToString();
- string merged_lot = string.Empty;
- string templatefileserverpath = string.Empty;
- var titleqry = oWorkAreaService.spfiletypevalidation(tranid.ToString(), jobid);
- var titleqry_jsonList = new List<string>();
- if (currentstagename == "OCR1")
- {
- //if (file == null || file.Length == 0)
- // return BadRequest("No file uploaded.");
- // Read PDF bytes directly from the uploaded file
- var file = HttpContext.Request.Form.Files.FirstOrDefault();
- if (file == null || file.Length == 0)
- return BadRequest("No file uploaded.");
- // ✅ Check file extension
- if (!file.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
- return BadRequest("Only PDF files are supported.");
- try
- {
- using (var memoryStream = new MemoryStream())
- {
- file.CopyTo(memoryStream);
- memoryStream.Position = 0; // ✅ Reset stream before reading
- // ✅ Validate PDF structure using iTextSharp
- using (PdfReader reader = new PdfReader(memoryStream))
- {
- Dictionary<string, string> info = reader.Info;
- string producer = info.ContainsKey("Producer") ? info["Producer"] : "Not available";
- string creator = info.ContainsKey("Creator") ? info["Creator"] : "Not available";
- // ✅ Check if it’s ABBYY FineReader
- if ((producer?.IndexOf("ABBYY", StringComparison.OrdinalIgnoreCase) >= 0) ||
- (creator?.IndexOf("ABBYY", StringComparison.OrdinalIgnoreCase) >= 0))
- {
- return Ok(new
- {
- Message = "Valid PDF. Created using ABBYY FineReader.",
- Producer = producer,
- Creator = creator
- });
- }
- else
- {
- return BadRequest(new
- {
- Message = "Invalid PDF. Not created using ABBYY FineReader.",
- Producer = producer,
- Creator = creator
- });
- }
- }
- }
- }
- catch (iTextSharp.text.exceptions.InvalidPdfException ex)
- {
- // 🚫 Handle “PDF signature not found” case
- return BadRequest("Uploaded file is not a valid PDF or is corrupted.");
- }
- catch (Exception ex)
- {
- // 🧩 Handle other unexpected errors
- return StatusCode(500, "An error occurred while validating the file: " + ex.Message);
- }
- }
- if (titleqry != null)
- {
- var titleqry_filetype = JsonConvert.DeserializeObject<object>(titleqry.ToString());
- JArray titleqry_a_filetype = JArray.Parse(titleqry_filetype.ToString());
- lottitles = titleqry_a_filetype[0]["titlecur"].ToString();
- merged_lot = titleqry_a_filetype[0]["merged_lot"].ToString();
- jobtitle = titleqry_a_filetype[0]["jobtitle"].ToString();
- projectsubtitle = titleqry_a_filetype[0]["project_subtitle"].ToString();
- }
- //if (httpRequest.Files.Count > 0)
- // {
- string serverinfo = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
- string serverinpath = Path.Combine(serverinfo, "IN");
- string serverpath = Path.Combine(serverinfo, "OUT");
- var filetype = oWorkAreaService.getFileTypeOutput(tranid);
- var jsonList = new List<string>();
- var uploadExtentionList = new List<string>();
- string resultList = string.Empty;
- if (filetype != null)
- {
- var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
- JArray a_filetype = JArray.Parse(i_filetype.ToString());
- foreach (var a in a_filetype)
- {
- JObject obj_filetype = JObject.Parse(a.ToString());
- jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
- }
- }
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- if (!Directory.Exists(serverpath))
- {
- Directory.CreateDirectory(serverpath);
- }
- string finalFilePath = Path.Combine(serverpath, filename);
- string chunkFolder = Path.Combine("TempUploads", tranid.ToString());
- using (var finalStream = new FileStream(finalFilePath, FileMode.Create))
- {
- for (int i = 0; i < Convert.ToInt64(totalchunk); i++)
- {
- string partPath = Path.Combine(chunkFolder, $"{i}.part");
- using (var partStream = new FileStream(partPath, FileMode.Open))
- {
- partStream.CopyTo(finalStream);
- }
- }
- }
- Directory.Delete(chunkFolder, true);
- });
- }
- /*if (jsonList.Count != 0 && jsonList[0].ToString() != ".*")
- {
- for (int i = 0; i < httpRequest.Files.Count; i++)
- {
- var outfile = httpRequest.Files[i];
- uploadExtentionList.Add(Path.GetExtension(outfile.FileName));
- }
- //var jsonlist_filter = jsonList.Except(uploadExtentionList).ToArray();
- var extentionlist_filter = uploadExtentionList.Except(jsonList).ToArray();
- for (int i = 0; i < extentionlist_filter.Length; i++)
- {
- resultList = string.Concat(resultList, extentionlist_filter[i], ",");
- }
- if (!string.IsNullOrEmpty(resultList))
- {
- return Ok("Extra files with extension '" + resultList.TrimEnd(',') + "' are not allowed kindly remove it and then proceed.");
- }
- }*/
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- // using (ServerInfo.GrantFolderPermission imp = new ServerInfo.GrantFolderPermission(jobid))
- // {
- if (!Directory.Exists(serverpath))
- {
- Directory.CreateDirectory(serverpath);
- }
- var curr_stageid = oWorkAreaService.getCurrentStage(tranid);
- string current_stageid = "";
- if (curr_stageid != null)
- {
- var i_curr_stageid = JsonConvert.DeserializeObject<object>(curr_stageid.ToString());
- JArray a_curr_stageid = JArray.Parse(i_curr_stageid.ToString());
- JObject obj_curr_stageid = JObject.Parse(a_curr_stageid[0].ToString());
- current_stageid = obj_curr_stageid["stageid"].ToString();
- }
- if (string.IsNullOrEmpty(kvpmode) && string.IsNullOrEmpty(kvpvalue))
- {
- for (int i = 0; i < httpRequest.Files.Count; i++)
- {
- var outfile = httpRequest.Files[i];
- dirName = Path.GetDirectoryName(outfile.FileName);
- if (jsonList.Count > 0)
- {
- if (jsonList.Count == 1 && jsonList[0].ToString() == ".*")
- {
- if (dirName.Contains("\\"))
- {
- charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
- dirName = dirName.Substring(charIndex + 1);
- filepath = Path.Combine(serverpath, dirName, Path.GetFileName(outfile.FileName));
- }
- else
- {
- filepath = Path.Combine(serverpath, Path.GetFileName(outfile.FileName));
- }
- if (!Directory.Exists(Path.GetDirectoryName(filepath)))
- {
- Directory.CreateDirectory(Path.GetDirectoryName(filepath));
- }
- using (var stream = new FileStream(filepath, FileMode.Create))
- {
- outfile.CopyTo(stream);
- }
- }
- else
- {
- if (jsonList.Contains(Path.GetExtension(outfile.FileName).ToLower()))
- {
- if (dirName.Contains("\\"))
- {
- charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
- dirName = dirName.Substring(charIndex + 1);
- filepath = Path.Combine(serverpath, dirName, Path.GetFileName(outfile.FileName));
- }
- else
- {
- filepath = Path.Combine(serverpath.ToString(), Path.GetFileName(outfile.FileName));
- }
- if (!Directory.Exists(Path.GetDirectoryName(filepath)))
- {
- Directory.CreateDirectory(Path.GetDirectoryName(filepath));
- }
- using (var stream = new FileStream(filepath, FileMode.Create))
- {
- outfile.CopyTo(stream);
- }
- // outfile.SaveAs(filepath);
- }
- }
- }
- else
- {
- if (dirName.Contains("\\"))
- {
- charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
- dirName = dirName.Substring(charIndex + 1);
- filepath = Path.Combine(serverpath.ToString(), dirName, Path.GetFileName(outfile.FileName));
- }
- else
- {
- filepath = Path.Combine(serverpath.ToString(), Path.GetFileName(outfile.FileName));
- }
- if (!Directory.Exists(Path.GetDirectoryName(filepath)))
- {
- Directory.CreateDirectory(Path.GetDirectoryName(filepath));
- }
- // outfile.SaveAs(filepath);
- using (var stream = new FileStream(filepath, FileMode.Create))
- {
- outfile.CopyTo(stream);
- }
- }
- }
- }
- else
- {
- lottitles = lottitles.Replace("-img", "");
- lottitles = lottitles.Replace("-txt", "");
- for (int i = 0; i < httpRequest.Files.Count; i++)
- {
- var outfile = httpRequest.Files[i];
- dirName = Path.GetDirectoryName(outfile.FileName);
- if (kvpmode == "file")
- {
- if (dirName.Contains("\\"))
- {
- charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
- dirName = dirName.Substring(charIndex + 1);
- filepath = Path.Combine(serverpath.ToString(), dirName, Path.GetFileName(outfile.FileName));
- }
- else
- {
- filepath_name = Path.GetFileNameWithoutExtension(outfile.FileName);
- if (filepath_name.ToString().EndsWith(kvpvalue))
- {
- filepath = Path.Combine(serverpath.ToString(), lottitles, Path.GetFileName(outfile.FileName));
- }
- else
- {
- filepath = Path.Combine(serverpath.ToString(), Path.GetFileName(outfile.FileName));
- }
- }
- }
- else
- {
- if (dirName.Contains("\\"))
- {
- charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
- dirName = dirName.Substring(charIndex + 1);
- filepath = Path.Combine(serverpath.ToString(), dirName, Path.GetFileName(outfile.FileName));
- }
- else
- {
- filepath_name = Path.GetExtension(outfile.FileName);
- if (filepath_name.ToString().EndsWith(".txt"))
- {
- filepath = Path.Combine(serverpath.ToString(), jobtitle + kvpvalue, Path.GetFileName(outfile.FileName));
- }
- else
- {
- filepath = Path.Combine(serverpath.ToString(), Path.GetFileName(outfile.FileName));
- }
- }
- }
- if (!Directory.Exists(Path.GetDirectoryName(filepath)))
- {
- Directory.CreateDirectory(Path.GetDirectoryName(filepath));
- }
- // outfile.SaveAs(filepath);
- using (var stream = new FileStream(filepath, FileMode.Create))
- {
- outfile.CopyTo(stream);
- }
- }
- }
- //}
- });
- }
- // }
- return Ok(1);
- }
- catch (Exception ex)
- {
- var data_input = new
- {
- errormessage = "Error: " + ex.Message,
- createdby = 0,
- controller = "UploaderApi: Downloader"
- };
- oCommonRepository.addlog(data_input, "errorlog");
- return null;
- }
- }
- [HttpPost("chunk")]
- public async Task<IActionResult> UploadChunk([FromForm] IFormFile filechunk,
- [FromForm] string fileId,
- [FromForm] int index,
- [FromForm] int tranid)
- {
- try
- {
- var dir = Path.Combine("TempUploads", tranid.ToString());
- Directory.CreateDirectory(dir);
- var chunkPath = Path.Combine(dir, $"{index}.part");
- using (var stream = new FileStream(chunkPath, FileMode.Create, FileAccess.Write))
- {
- await filechunk.CopyToAsync(stream);
- }
- return Ok(new { success = true });
- }
- catch (Exception ex)
- {
- return Ok(ex.Message);
- }
- }
- // [Authorize]
- [HttpGet("GetAllFilesForDownload")]
- public List<FileDetails> GetAllFilesForDownload(int jobid, int tranid)
- {
- List<FileDetails> AllFiles = new List<FileDetails>();
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- WindowsIdentity useri = WindowsIdentity.GetCurrent();
- System.Console.WriteLine(useri.Name);
- string serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
- serverpath = Path.Combine(serverpath, "IN");
- var filetype = oWorkAreaService.getFileTypeInput(tranid.ToString());
- var jsonList = new List<string>();
- string[] inputfiles;
- if (filetype != null)
- {
- var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
- JArray a_filetype = JArray.Parse(i_filetype.ToString());
- foreach (var a in a_filetype)
- {
- JObject obj_filetype = JObject.Parse(a.ToString());
- jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
- }
- }
- if (jsonList.Count() == 1 && jsonList[0].ToString().Contains(".*"))
- {
- inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).ToArray();
- }
- else
- {
- inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
- if (inputfiles.Length == 0)
- {
- inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).ToArray();
- //inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
- }
- }
- foreach (var item in inputfiles)
- {
- FileDetails filedetails = new FileDetails();
- filedetails.FileName = Path.GetFileName(item);
- filedetails.FilePath = item;
- AllFiles.Add(filedetails);
- }
- });
- }
- return AllFiles;
- }
- // [Authorize]
- [HttpGet("GetAllOutputFiles")]
- public List<FileDetails> GetAllOutputFiles(int jobid, int tranid)
- {
- List<FileDetails> AllFiles = new List<FileDetails>();
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- WindowsIdentity useri = WindowsIdentity.GetCurrent();
- System.Console.WriteLine(useri.Name);
- var filetype = oWorkAreaService.getFileTypeOutput(tranid.ToString());
- var jsonList = new List<string>();
- string[] inputfiles;
- if (filetype != null)
- {
- var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
- JArray a_filetype = JArray.Parse(i_filetype.ToString());
- foreach (var a in a_filetype)
- {
- JObject obj_filetype = JObject.Parse(a.ToString());
- jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
- }
- }
- // using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(jobid.ToString()))
- // {
- string serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
- serverpath = Path.Combine(serverpath, "OUT");
- string[] outputfiles = null;
- if (Directory.Exists(serverpath))
- {
- //outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories);
- outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
- }
- else
- {
- AllFiles = null;
- }
- if (outputfiles.Length == 0)
- {
- // outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories);
- outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
- }
- foreach (var item in outputfiles)
- {
- FileDetails filedetails = new FileDetails();
- filedetails.FileName = Path.GetFileName(item);
- filedetails.FilePath = item;
- AllFiles.Add(filedetails);
- }
- });
- }
- // }
- return AllFiles;
- }
- // [Authorize]
- [HttpGet("GetAllOutFilesForDownload")]
- public List<FileDetails> GetAllOutFilesForDownload(int jobid, int tranid)
- {
- List<FileDetails> AllFiles = new List<FileDetails>();
- string serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
- serverpath = Path.Combine(serverpath, "OUT");
- var filetype = oWorkAreaService.getFileTypeOutput(tranid.ToString());
- var jsonList = new List<string>();
- if (filetype != null)
- {
- var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
- JArray a_filetype = JArray.Parse(i_filetype.ToString());
- foreach (var a in a_filetype)
- {
- JObject obj_filetype = JObject.Parse(a.ToString());
- jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
- }
- }
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- WindowsIdentity useri = WindowsIdentity.GetCurrent();
- System.Console.WriteLine(useri.Name);
- string[] inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly)
- .Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
- if (inputfiles.Length == 0)
- {
- inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories)
- .Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
- }
- foreach (var item in inputfiles)
- {
- FileDetails filedetails = new FileDetails();
- filedetails.FileName = Path.GetFileName(item);
- filedetails.FilePath = item;
- AllFiles.Add(filedetails);
- }
- });
- }
- return AllFiles;
- }
- // [Authorize]
- [HttpPost("downloadInputFiles")]
- public IActionResult downloadInputFiles(dynamic fileData)
- {
- string jobid = fileData.jobid.ToString();
- string tranid = fileData.tranid.ToString();
- string type = fileData.type.ToString();
- string pdid = fileData.pdid.ToString();
- string code = fileData.code.ToString();
- string jobtitle = fileData.jobtitle.ToString();
- string serverpath;
- string zipname = string.Empty;
- var jsonList = new List<string>();
- string filepath = string.Empty;
- string[] inputfiles;
- //string current_stagename = db1.GetDataTable(db, @"select jw.stagename_alias from lot_transaction lt
- // inner join job_workflow_master jw on jw.jobworkflowid = lt.jobworkflowid
- // where lt.transactionid = '" + tranid + "'", null).Rows[0][0].ToString();
- // if (type == "stage")
- // {
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
- {
- serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
- serverpath = Path.Combine(serverpath, "IN");
- zipname = jobtitle + "_" + tranid + ".zip";
- var filetype = oWorkAreaService.getFileTypeInput(tranid);
- if (filetype != null)
- {
- var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
- JArray a_filetype = JArray.Parse(i_filetype.ToString());
- foreach (var a in a_filetype)
- {
- JObject obj_filetype = JObject.Parse(a.ToString());
- jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
- }
- }
- var curr_stageid = oWorkAreaService.getCurrentStage(tranid);
- string current_stageid = "";
- if (curr_stageid != null)
- {
- var i_curr_stageid = JsonConvert.DeserializeObject<object>(curr_stageid.ToString());
- JArray a_curr_stageid = JArray.Parse(i_curr_stageid.ToString());
- JObject obj_curr_stageid = JObject.Parse(a_curr_stageid[0].ToString());
- current_stageid = obj_curr_stageid["stageid"].ToString();
- }
- if (jsonList.Count > 0)
- {
- string zipPath = Path.Combine(serverpath, zipname + ".zip");
- string tempFolderName = "temp_" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
- string tempPath = Path.Combine(serverpath, tempFolderName);
- if (!Directory.Exists(tempPath))
- Directory.CreateDirectory(tempPath);
- if (jsonList.Count == 1 && jsonList[0].ToString() == ".*")
- {
- ZipFile.CreateFromDirectory(tempPath, zipPath);
- filepath = zipPath;
- Directory.Delete(tempPath, true);
- if (filepath != "" || filepath.Length > 0)
- {
- byte[] file = System.IO.File.ReadAllBytes(filepath);
- System.IO.File.Delete(filepath);
- return Ok(new { File = file });
- }
- else
- {
- return BadRequest(new { message = "File notfound" });
- }
- }
- else
- {
- inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
- if (inputfiles.Length == 0)
- {
- inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories)
- .Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
- }
- byte[] fileBytes = null;
- using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
- {
- using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
- {
- foreach (string f in inputfiles)
- {
- // add the item name to the zip
- System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(Path.GetFileName(f) + "." + Path.GetExtension(f));
- // add the item bytes to the zip entry by opening the original file and copying the bytes
- using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(f)))
- {
- using (System.IO.Stream entryStream = zipItem.Open())
- {
- originalFileMemoryStream.CopyTo(entryStream);
- }
- }
- }
- }
- fileBytes = memoryStream.ToArray();
- return Ok(new { File = fileBytes });
- // return Ok(new { File = File(fileBytes, "application/zip", zipname) });
- }
- }
- }
- else { return BadRequest(new { message = "File notfound" }); }
- // }
- }
- }
- // [Authorize]
- [HttpPost("DownloadInOutFiles")]
- public async Task<IActionResult> DownloadInOutFiles([FromBody] filedownload fileData)
- {
- string jobid = fileData.jobid.ToString() ?? "";
- string tranid = fileData.tranid.ToString() ?? "";
- string pdid = fileData.pdid.ToString() ?? "";
- string option = fileData.option.ToString() ?? "";
- string jobtitle = fileData.jobtitle.ToString() ?? "";
- if (string.IsNullOrWhiteSpace(tranid))
- return BadRequest("Transaction ID is required.");
- try
- {
- // ✅ Step 1: Build server path
- string serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
- if (!string.IsNullOrWhiteSpace(option))
- serverpath = Path.Combine(serverpath, option);
- if (!Directory.Exists(serverpath))
- return NotFound("Source folder not found.");
- // ✅ Step 2: Prepare ZIP name
- string zipFileName = (!string.IsNullOrEmpty(option) && (option.Contains("IN") || option.Contains("OUT")))
- ? $"{jobtitle}_{tranid}_{option}.zip"
- : $"{jobtitle}_{tranid}.zip";
- // ✅ Step 3: Create app-specific temporary folder (not C:\Windows\Temp)
- string tempBase = Path.Combine(System.AppContext.BaseDirectory, "TempZips");
- Directory.CreateDirectory(tempBase); // ensure it exists
- string tempZipPath = Path.Combine(tempBase, zipFileName);
- // Clean existing temp file if present
- if (System.IO.File.Exists(tempZipPath))
- System.IO.File.Delete(tempZipPath);
- // ✅ Step 4: Use impersonation to access the server folder
- using (var permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- await WindowsIdentity.RunImpersonated(newId.AccessToken, async () =>
- {
- // Create ZIP under impersonated context (no compression = faster)
- ZipFile.CreateFromDirectory(serverpath, tempZipPath, CompressionLevel.NoCompression, includeBaseDirectory: true);
- await Task.CompletedTask; // keep async signature clean
- });
- }
- // ✅ Step 5: Stream ZIP to client
- Response.ContentType = "application/zip";
- Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{zipFileName}\"");
- await using (var zipStream = new FileStream(tempZipPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
- {
- await zipStream.CopyToAsync(Response.Body);
- }
- // ✅ Step 6: Clean up temporary ZIP safely
- try
- {
- System.IO.File.Delete(tempZipPath);
- }
- catch
- {
- // ignore cleanup errors
- }
- return new EmptyResult(); // response already written
- }
- catch (Exception ex)
- {
- // ✅ Step 7: Log and return error
- oCommonRepository.addlog(new
- {
- errormessage = "Error: " + ex.Message,
- createdby = 0,
- controller = "WorkAreaApi: DownloadInOutFiles"
- }, "errorlog");
- return StatusCode(500, $"Error while downloading files: {ex.Message}");
- }
- }
- //public async Task<IActionResult> DownloadInOutFiles([FromBody] filedownload fileData)
- //{
- // try
- // {
- // string jobid = fileData.jobid.ToString() ?? "";
- // string tranid = fileData.tranid.ToString() ?? "";
- // string pdid = fileData.pdid.ToString() ?? "";
- // string option = fileData.option.ToString() ?? "";
- // string jobtitle = fileData.jobtitle.ToString() ?? "";
- // // Build server path
- // string serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
- // serverpath = Path.Combine(serverpath, option);
- // // Build ZIP filename
- // string zipname = (option.Contains("IN") || option.Contains("OUT"))
- // ? $"{jobtitle}_{tranid}_{option}.zip"
- // : $"{jobtitle}_{tranid}.zip";
- // DirectoryInfo dirinfo = new DirectoryInfo(serverpath);
- // if (!dirinfo.Exists)
- // return NotFound("Source folder not found.");
- // // Create in-memory zip (streamed, not loaded fully)
- // var memoryStream = new MemoryStream();
- // using (var permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
- // {
- // WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- // await WindowsIdentity.RunImpersonated(newId.AccessToken, async () =>
- // {
- // using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
- // {
- // foreach (var file in dirinfo.GetFiles("*.*", SearchOption.AllDirectories))
- // {
- // string relativePath = file.FullName.Substring(dirinfo.FullName.Length + 1);
- // var entry = archive.CreateEntry(relativePath, CompressionLevel.Fastest);
- // using var entryStream = entry.Open();
- // using var fileStream = System.IO.File.OpenRead(file.FullName);
- // await fileStream.CopyToAsync(entryStream);
- // }
- // }
- // });
- // }
- // memoryStream.Position = 0; // reset stream for reading
- // // Return the zip file to Angular
- // return File(memoryStream, "application/zip", zipname);
- // }
- // catch (Exception ex)
- // {
- // oCommonRepository.addlog(new
- // {
- // errormessage = "Error: " + ex.Message,
- // createdby = 0,
- // controller = "WorkAreaApi: DownloadInOutFiles"
- // }, "errorlog");
- // return BadRequest(new { message = "Error: " + ex.Message });
- // }
- //}
- //public IActionResult DownloadInOutFiles(filedownload fileData)
- //{
- // try
- // {
- // // Extract file data from the request
- // string jobid = fileData.jobid.ToString();
- // string tranid = fileData.tranid.ToString();
- // string pdid = fileData.pdid.ToString();
- // string option = fileData.option.ToString();
- // string jobtitle = fileData.jobtitle.ToString();
- // string serverpath;
- // // Get the server path based on the transaction ID and other parameters
- // serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
- // serverpath = Path.Combine(serverpath, option);
- // // Generate the zip file name
- // string zipname = string.Empty;
- // if (option.Contains("IN") || option.Contains("OUT"))
- // {
- // zipname = $"{jobtitle}_{tranid}_{option}.zip";
- // }
- // else
- // {
- // zipname = $"{jobtitle}_{tranid}.zip";
- // }
- // // Get the directory info for the given path
- // System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(serverpath);
- // // Check if the directory exists
- // if (!dirinfo.Exists)
- // {
- // return BadRequest(new { message = "Directory does not exist." });
- // }
- // // Create a list of file entries from the directory, including subdirectories
- // FileInfo[] inputfiles = dirinfo.GetFiles("*.*", SearchOption.AllDirectories);
- // if (inputfiles.Length == 0)
- // {
- // return BadRequest(new { message = "No files found in the directory." });
- // }
- // byte[] fileBytes = null;
- // using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
- // {
- // using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
- // {
- // foreach (FileInfo file in inputfiles)
- // {
- // // Create a zip entry for each file while maintaining the folder structure
- // string relativePath = file.FullName.Substring(dirinfo.FullName.Length + 1); // Get relative path of the file
- // System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(relativePath);
- // // Open the original file and copy its contents into the zip entry
- // using (System.IO.Stream originalFileStream = file.OpenRead())
- // {
- // using (System.IO.Stream entryStream = zipItem.Open())
- // {
- // originalFileStream.CopyTo(entryStream);
- // }
- // }
- // }
- // }
- // // Convert memory stream to byte array
- // fileBytes = memoryStream.ToArray();
- // }
- // // Return the zip file as byte array
- // return Ok(new { File = fileBytes });
- // // Alternatively, you can return the file directly as:
- // // return File(fileBytes, "application/zip", zipname);
- // }
- // catch (Exception ex)
- // {
- // // Log the error
- // var data_input = new
- // {
- // errormessage = "Error: " + ex.Message,
- // createdby = 0,
- // controller = "UploaderApi: Downloader"
- // };
- // oCommonRepository.addlog(data_input, "errorlog");
- // // Return an error message
- // return BadRequest(new { message = "An error occurred while processing the files." });
- // }
- //}
- //public IActionResult DownloadInOutFiles(filedownload fileData)
- //{
- // try
- // {
- // string jobid = fileData.jobid.ToString();
- // string tranid = fileData.tranid.ToString();
- // string pdid = fileData.pdid.ToString();
- // string option = fileData.option.ToString();
- // string jobtitle = fileData.jobtitle.ToString();
- // string serverpath;
- // serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
- // serverpath = Path.Combine(serverpath, option);
- // string zipname = string.Empty;
- // if (option.IndexOf("IN") != -1 || option.IndexOf("OUT") != -1)
- // {
- // zipname = jobtitle + "_" + tranid + "_" + option + ".zip";
- // }
- // else
- // {
- // zipname = jobtitle + "_" + tranid + ".zip";
- // }
- // string[] inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly).ToArray();
- // byte[] fileBytes = null;
- // using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
- // {
- // using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
- // {
- // foreach (string f in inputfiles)
- // {
- // // add the item name to the zip
- // System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(Path.GetFileName(f) + "." + Path.GetExtension(f));
- // // add the item bytes to the zip entry by opening the original file and copying the bytes
- // using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(f)))
- // {
- // using (System.IO.Stream entryStream = zipItem.Open())
- // {
- // originalFileMemoryStream.CopyTo(entryStream);
- // }
- // }
- // }
- // }
- // fileBytes = memoryStream.ToArray();
- // return Ok(new { File = fileBytes });
- // // return Ok(new { File = File(fileBytes, "application/zip", zipname) });
- // }
- // }
- // catch (Exception ex)
- // {
- // var data_input = new
- // {
- // errormessage = "Error: " + ex.Message,
- // createdby = 0,
- // controller = "UploaderApi: Downloader"
- // };
- // oCommonRepository.addlog(data_input, "errorlog");
- // return BadRequest(new { message = "File notfound" });
- // }
- //}
- [HttpGet("ValidateOutFileExist")]
- public object ValidateOutFileExist(int jobid, int tranid, string stagename_alias, int projectdefinitionid, string lottitle)
- {
- List<FileDetails> AllFiles = new List<FileDetails>();
- string[] outputfiles = null;
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- WindowsIdentity useri = WindowsIdentity.GetCurrent();
- System.Console.WriteLine(useri.Name);
- // using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(jobid.ToString()))
- // {
- string serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
- serverpath = Path.Combine(serverpath, "OUT");
- if (Directory.Exists(serverpath))
- {
- outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories);
- }
- else
- {
- AllFiles = null;
- }
- });
- }
- if (outputfiles.Length == 0)
- {
- var json = new { result = false };
- return json;
- }
- else
- {
- if (stagename_alias == "LARE Review")
- {
- int htmlFilesCount = outputfiles.Count(file => file.EndsWith(".html", StringComparison.OrdinalIgnoreCase));
- if (htmlFilesCount == 0)
- {
- var json = new { result = false };
- return json;
- }
- else
- {
- var json = new { result = true };
- return json;
- }
- }
- else if (
- (stagename_alias == "Redaction and Styling"
- || stagename_alias == "OCR and Styling")
- && projectdefinitionid == 366
- )
- {
- int htmlFilesCount = outputfiles.Count(file => file.Contains(lottitle, StringComparison.OrdinalIgnoreCase) &&
- file.EndsWith(".xml", StringComparison.OrdinalIgnoreCase));
- if (htmlFilesCount == 0)
- {
- var json = new { result = false };
- return json;
- }
- else
- {
- var json = new { result = true };
- return json;
- }
- }
- else if (stagename_alias == "Redaction and Styling" && projectdefinitionid == 364)
- {
- int htmlFilesCount = outputfiles.Count(file => file.EndsWith("_Redacted.pdf", StringComparison.OrdinalIgnoreCase));
- if (htmlFilesCount == 0)
- {
- var json = new { result = false };
- return json;
- }
- else
- {
- var json = new { result = true };
- return json;
- }
- }
- else
- {
- var json = new { result = true };
- return json;
- }
- }
- }
- // [Authorize]
- //[AllowAnonymous]
- [HttpPost("getdispatchid")]
- public object getdispatchid(long jobid, long tranid, long lotid, string projectsubtitle)
- {
- int jobWorkflowId = 0;
- int dispatchtranid = 0;
- int Allocationtranid = 0;
- string[] inputfiles;
- try
- {
- using (IDbConnection dbConnection = ConnectionBase.Connection)
- {
- dbConnection.Open();
- string query = @"
- SELECT lt.transactionid
- FROM tbllottransaction lt
- JOIN tbljobworkflowdefinition jwd ON jwd.jobworkflowid = lt.jobworkflowid
- WHERE jwd.stagename_alias = 'Dispatch' AND jwd.jobid = @jobid order by lt.starttime desc limit(1)";
- var result = dbConnection.QueryFirstOrDefault<int>(query, new { jobid = jobid });
- if (result != 0)
- {
- dispatchtranid = result; // store the transactionid or use it further
- }
- string updateQuerys = @"
- UPDATE tbllottransaction
- SET lotstatus = 'W'
- WHERE transactionid = @transactionid ;
- ";
- int rowsAffecteds = dbConnection.Execute(updateQuerys, new { transactionid = dispatchtranid });
- if (projectsubtitle == "LN_BPM")
- {
- string querys = @"
- SELECT lt.transactionid
- FROM tbllottransaction lt
- JOIN tbljobworkflowdefinition jwd ON jwd.jobworkflowid = lt.jobworkflowid
- WHERE jwd.stagename_alias = 'Allocation' AND jwd.jobid = @jobid AND lt.lotstatus='F' order by lt.starttime desc limit(1) ";
- var result1 = dbConnection.QueryFirstOrDefault<int>(querys, new { jobid = jobid });
- if (result1 != 0)
- {
- Allocationtranid = result1; // store the transactionid or use it further
- }
- string updateQuery = @"
- UPDATE tbllottransaction
- SET active = '0'
- WHERE transactionid = @transactionid ;
- ";
- int rowsAffected = dbConnection.Execute(updateQuery, new { transactionid = Allocationtranid });
- }
- else
- {
- string querys = @"
- SELECT lt.transactionid
- FROM tbllottransaction lt
- JOIN tbljobworkflowdefinition jwd ON jwd.jobworkflowid = lt.jobworkflowid
- WHERE jwd.stagename_alias = 'XML Review' AND jwd.jobid = @jobid AND lt.lotstatus='F' order by lt.starttime desc limit(1) ";
- var result1 = dbConnection.QueryFirstOrDefault<int>(querys, new { jobid = jobid });
- if (result1 != 0)
- {
- Allocationtranid = result1; // store the transactionid or use it further
- }
- string updateQuery = @"
- UPDATE tbllottransaction
- SET active = '0'
- WHERE transactionid = @transactionid ;
- ";
- int rowsAffected = dbConnection.Execute(updateQuery, new { transactionid = Allocationtranid });
- }
- }
- string redactserverinfo = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
- string serverpaths = Path.Combine(redactserverinfo, "IN");
- inputfiles = Directory.GetFiles(serverpaths, "*.pdf", SearchOption.AllDirectories).ToArray();
- foreach (var file in inputfiles)
- {
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid.ToString()))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- // using (ServerInfo.GrantFolderPermission imp = new ServerInfo.GrantFolderPermission(jobid))
- string serverinfo = oWorkAreaService.GetServerPath(dispatchtranid.ToString(), false, "serverinfo");
- string serverpath = Path.Combine(serverinfo, "IN");
- string destinationFilePath = Path.Combine(serverinfo, "IN", Path.GetFileName(file));
- if (!Directory.Exists(serverpath))
- {
- Directory.CreateDirectory(serverpath);
- }
- //string destinationFilePath = Path.Combine(serverpath, Path.GetFileName(file));
- // try
- // {
- System.IO.File.Copy(file, destinationFilePath, true);
- // }
- });
- }
- }
- }
- catch (Exception ex)
- {
- return Ok(new { jobid = ex.Message });
- }
- return Ok(new { jobid = jobid }); // or any other return value you need
- }
- [HttpPost]
- [Route("forwardstage")]
- public IActionResult forwardstage([FromBody] JObject data)
- {
- Guid id = Guid.NewGuid();
- //int next_tranid = InsertLotTransaction(Convert.ToInt32(data1.Rows[0]["lotid"].ToString()), AIstage.ToString(), Path.GetFileNameWithoutExtension(inpath), tranid);
- // var _listlt = oWorkAreaService.usrLotTransactionInsert(data.p_userid, data.p_lotid, data.p_jobworkflowid, id.ToString(), "insertlottransactiondetailonly");
- long tranid = 0;
- // Safely parse properties from JObject
- int userid = data["p_userid"]?.ToObject<int>() ?? 0;
- long lotid = data["p_lotid"]?.ToObject<long>() ?? 0;
- // long jobworkflowid = Convert.ToInt32(data.p_jobworkflowid) + 1;
- // using (IDbConnection dbConnection = ConnectionBase.Connection)
- // {
- // dbConnection.Open();
- // string querys = @"
- //SELECT jobworkflowid
- //FROM tbljobworkflowdefinition
- //WHERE jobid = @jobid
- //AND stagename_alias='HTML Generation'";
- // var jobworkflow = dbConnection.Query<int>(querys, new { jobid = data.p_jobid }).ToList();
- // string sQry = "insert_lot_transaction_details_only";
- // using (var cmd = new NpgsqlCommand(sQry, (NpgsqlConnection)dbConnection))
- // {
- // cmd.CommandType = CommandType.StoredProcedure;
- // //cmd.Parameters.Add(new NpgsqlParameter("p_jobworkflowid", NpgsqlTypes.NpgsqlDbType.Bigint) { Value = Convert.ToInt64(jobworkflow) });
- // if (jobworkflow != null && jobworkflow.Any())
- // {
- // cmd.Parameters.Add(new NpgsqlParameter("p_jobworkflowid", NpgsqlTypes.NpgsqlDbType.Bigint)
- // {
- // Value = Convert.ToInt64(jobworkflow.First())
- // });
- // }
- // cmd.Parameters.Add(new NpgsqlParameter("p_lotid", NpgsqlTypes.NpgsqlDbType.Bigint) { Value = lotid });
- // cmd.Parameters.Add(new NpgsqlParameter("p_lotkey", NpgsqlTypes.NpgsqlDbType.Uuid) { Value = Guid.Parse(id.ToString()) });
- // object result = cmd.ExecuteScalar();
- // // Replace modcommon.nz with your own null check or conversion
- // if (result == null || result == DBNull.Value)
- // {
- // tranid = 0; // or default value you want
- // }
- // else
- // {
- // tranid = Convert.ToInt64(result);
- // }
- // }
- // long transactionId = Convert.ToInt64(data.p_tranid);
- // string query = @"Update tbllottransaction set lotstatus='F' where transactionid=@transactionid"
- // ;
- // var lotIds = dbConnection.Query<int>(query, new { transactionid = transactionId }).ToList();
- // }
- // var _listlt = oWorkAreaService.usrLotTransactionInsert(userid, lotid, jobworkflowid, id.ToString(), "insertlottransactiondetailonly");
- //string nextstage_serverpath = oCommonRepository.GetServerPath(data.p_tranid.ToString(), "serverinfo",true);
- //RabbitMq sendmsg = new RabbitMq(_requestClient);
- //sendmsg.SendMq_StageComplete(tranid.ToString(), "0", "checkin_apps", "server", "", "A", "");
- return Ok("Success");
- }
- //[Authorize]
- [HttpPost("DownloadSingleFile")]
- public IActionResult DownloadSingleFile(filedownload fileData)
- {
- try
- {
- string type = fileData.type.ToString();
- string path = fileData.path.ToString();
- string jobid = fileData.jobid.ToString();
- byte[] fileBytes = null;
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- WindowsIdentity useri = WindowsIdentity.GetCurrent();
- fileBytes = System.IO.File.ReadAllBytes(path);
- string fileName = Path.GetFileName(path);
- });
- }
- return Ok(new { File = fileBytes });
- }
- catch (Exception ex)
- {
- var data_input = new
- {
- errormessage = "Error: " + ex.Message,
- createdby = 0,
- controller = "UploaderApi: Downloader"
- };
- oCommonRepository.addlog(data_input, "errorlog");
- throw;
- }
- }
- // [Authorize]
- [HttpPost("DownloadSingleOutFile")]
- public IActionResult DownloadSingleOutFile(filedownload fileData)
- {
- try
- {
- string type = fileData.type.ToString();
- string path = fileData.path.ToString();
- string jobid = fileData.jobid.ToString();
- byte[] fileBytes = null;
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- WindowsIdentity useri = WindowsIdentity.GetCurrent();
- fileBytes = System.IO.File.ReadAllBytes(path);
- string fileName = Path.GetFileName(path);
- });
- }
- return Ok(new { File = fileBytes });
- }
- catch (Exception ex)
- {
- var data_input = new
- {
- errormessage = "Error: " + ex.Message,
- createdby = 0,
- controller = "UploaderApi: Downloader"
- };
- oCommonRepository.addlog(data_input, "errorlog");
- throw;
- }
- }
- // [Authorize]
- [HttpPost("RemoveIOFiles")]
- public object RemoveIOFiles(dynamic fileData)
- {
- string path = fileData.path.ToString();
- string jobid = fileData.jobid.ToString();
- try
- {
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- WindowsIdentity useri = WindowsIdentity.GetCurrent();
- System.IO.File.Delete(path);
- });
- }
- var json = new { result = true, filename = Path.GetFileName(path) };
- return json;
- }
- catch (Exception ex)
- {
- var data_input = new
- {
- errormessage = "Error: " + ex.Message,
- createdby = 0,
- controller = "UploaderApi: Downloader"
- };
- oCommonRepository.addlog(data_input, "errorlog");
- var json = new { result = false, filename = Path.GetFileName(path) };
- return json;
- }
- }
- // [Authorize]
- [HttpPost("DownloadFolder")]
- public IActionResult DownloadFolder(dynamic fileData)
- {
- try
- {
- string jobid = fileData.jobid.ToString();
- string FolderPath = fileData.path.ToString();
- string tranid = fileData.tranid.ToString();
- string jobtitle = fileData.jobtitle.ToString();
- string zipname = string.Empty;
- byte[] fileBytes = null;
- bool fail = false;
- zipname = jobtitle + "_" + tranid + ".zip";
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- WindowsIdentity useri = WindowsIdentity.GetCurrent();
- if (Directory.Exists(FolderPath))
- {
- string[] inputfiles = Directory.GetFiles(FolderPath, "*.*", SearchOption.TopDirectoryOnly).ToArray();
- using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
- {
- using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
- {
- foreach (string f in inputfiles)
- {
- // add the item name to the zip
- System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(Path.GetFileName(f) + "." + Path.GetExtension(f));
- // add the item bytes to the zip entry by opening the original file and copying the bytes
- using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(f)))
- {
- using (System.IO.Stream entryStream = zipItem.Open())
- {
- originalFileMemoryStream.CopyTo(entryStream);
- }
- }
- }
- }
- fileBytes = memoryStream.ToArray();
- }
- }
- else
- {
- fail = true;
- }
- });
- }
- if (!fail) { return Ok(new { File = File(fileBytes, "application/zip", zipname) }); }
- else
- {
- return BadRequest(new { message = "Folder notfound" });
- }
- }
- catch (Exception ex)
- {
- var data_input = new
- {
- errormessage = "Error: " + ex.Message,
- createdby = 0,
- controller = "UploaderApi: Downloader"
- };
- oCommonRepository.addlog(data_input, "errorlog");
- return BadRequest(new { message = "Folder notfound" });
- }
- }
- [HttpGet("GetOutfileExtension")]
- public object GetOutfileExtension(long tranid)
- {
- var filetype = oWorkAreaService.getFileTypeOutput(tranid.ToString());
- var jsonList = new List<string>();
- if (filetype != null)
- {
- var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
- JArray a_filetype = JArray.Parse(i_filetype.ToString());
- foreach (var a in a_filetype)
- {
- JObject obj_filetype = JObject.Parse(a.ToString());
- jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
- }
- }
- return Ok(jsonList);
- }
- [HttpGet("getOutfileupdated")]
- public object getOutfileupdated(long tranid, string option)
- {
- using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString(), "", ""))
- {
- WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- WindowsIdentity useri = WindowsIdentity.GetCurrent();
- string renamedvalue = string.Empty;
- string anyfiles = string.Empty;
- string anyfolder = string.Empty;
- var renametype = oWorkAreaService.getFilerenameInput(tranid.ToString());
- var titleqry_jsonList = new List<string>();
- if (renametype != null)
- {
- var titleqry_filetype = JsonConvert.DeserializeObject<object>(renametype.ToString());
- JArray titleqry_a_filetype = JArray.Parse(titleqry_filetype.ToString());
- renamedvalue = titleqry_a_filetype[0]["filename"].ToString();
- string serverpath;
- serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
- serverpath = Path.Combine(serverpath, option);
- if (Directory.Exists(serverpath))
- {
- string[] folderextensionFilters = new string[] { ".pdf", ".visf" };
- string[] allfolder = Directory.GetDirectories(serverpath, "*.*", SearchOption.TopDirectoryOnly)
- .Where(filename => folderextensionFilters.Any(x =>
- filename.EndsWith(x, StringComparison.OrdinalIgnoreCase))).ToArray();
- if (allfolder.Count() > 1)
- {
- foreach (var folder in allfolder)
- {
- anyfolder = string.Empty;
- anyfolder = folder;
- if (anyfolder.Contains(".pdf"))
- {
- anyfiles = string.Empty;
- anyfiles = Directory.GetFiles(anyfolder, "*.pdf", SearchOption.TopDirectoryOnly).FirstOrDefault();
- if (!string.IsNullOrEmpty(anyfiles) && System.IO.File.Exists(anyfiles))
- {
- string destinationPath = Path.Combine(anyfolder, renamedvalue + Path.GetExtension(anyfiles));
- System.IO.File.Move(anyfiles, destinationPath, true);
- }
- }
- else
- {
- anyfiles = Directory.GetFiles(anyfolder, "*.txt", SearchOption.TopDirectoryOnly).Where(x => !x.EndsWith("_Validation_report.txt")).FirstOrDefault();
- if (!string.IsNullOrEmpty(anyfiles) && System.IO.File.Exists(anyfiles))
- {
- string destinationPath = Path.Combine(anyfolder, renamedvalue + Path.GetExtension(anyfiles));
- System.IO.File.Move(anyfiles, destinationPath, true);
- }
- }
- }
- }
- anyfiles = string.Empty;
- anyfiles = Directory.GetFiles(serverpath, "*.docx", SearchOption.TopDirectoryOnly).FirstOrDefault();
- if (!string.IsNullOrEmpty(anyfiles))
- {
- string destinationPath = Path.Combine(serverpath, renamedvalue + Path.GetExtension(anyfiles));
- System.IO.File.Move(anyfiles, destinationPath, true);
- }
- //string actulavlue = Startup.Configuration.GetValue<string>("AppSettings:QA_File_type");
- //actulavlue = Regex.Replace(actulavlue, @""", "\"", RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Singleline);
- //string[] extensionFilters = new string[] { ".pdf", ".docx", ".zip" };
- //string anyfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly)
- // .Where(filename => extensionFilters.Any(x =>
- // filename.EndsWith(x, StringComparison.OrdinalIgnoreCase))).FirstOrDefault();
- //if (!string.IsNullOrEmpty(anyfiles))
- //{
- // try
- // {
- // string destinationPath = Path.Combine(serverpath, renamedvalue+Path.GetExtension(anyfiles));
- // System.IO.File.Move(anyfiles, destinationPath, true);
- // }
- // catch(Exception ex)
- // {
- // }
- //}
- }
- }
- });
- }
- return Ok(1);
- }
- [AllowAnonymous]
- [HttpPost("pushback")]
- public IActionResult PushBack([FromForm] PushBackRequest request)
- {
- try
- {
- // Get base server path
- string serverinfo = oWorkAreaService
- .GetServerPath(request.tranid.ToString(), false, "serverinfo");
- // Combine folder paths
- string outFolderPath = Path.Combine(serverinfo, "OUT");
- string inFolderPath = Path.Combine(serverinfo, "IN");
- using (CommonRepository.GrantFolderPermission permit =
- new CommonRepository.GrantFolderPermission("", "", "", request.jobid.ToString()))
- {
- WindowsIdentity newId = permit.GetImpartunate()?.AllowAccesstoServer();
- if (newId == null)
- return StatusCode(500, "Impersonation failed");
- WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
- {
- // Delete OUT folder files
- if (Directory.Exists(outFolderPath))
- {
- var outFiles = Directory.GetFiles(outFolderPath);
- foreach (var file in outFiles)
- {
- System.IO.File.Delete(file);
- }
- }
- // Delete IN folder files
- if (Directory.Exists(inFolderPath))
- {
- var inFiles = Directory.GetFiles(inFolderPath);
- foreach (var file in inFiles)
- {
- System.IO.File.Delete(file);
- }
- }
- });
- }
- var result = oWorkAreaService.PushBack(request);
- return Ok(result);
- }
- catch (Exception ex)
- {
- return StatusCode(500, ex.Message);
- }
- }
- [AllowAnonymous]
- [HttpPost("workflowdecision")]
- public IActionResult workflowdecision([FromBody] object data)
- {
- var _list = oWorkAreaService.workflowdecision(data);
- return Ok(_list);
- }
- public class JobRequest
- {
- public long JobId { get; set; }
- }
- public class PushBackRequest
- {
- public long jobid { get; set; }
- public long lotid { get; set; }
- public long tranid { get; set; }
- public string lottitle { get; set; }
- }
- }
- }
|