using Logic.ProductionToProductMapper.Cordonel; using Newtonsoft.Json; using Service.Core; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Http; using Xylem.Common.Logic.ProductionOrderCore.File; using Xylem.Common.Logic.ProductionOrderCore.FW; namespace Xylem.Common.Service.MeterProcessState.Controllers { [RoutePrefix("api/FileUpToDate")] public class FileUpToDateController : ApiController { public static class GlobalConfig { public static Lazy connectionString = new Lazy(() => System.Configuration.ConfigurationManager.ConnectionStrings["default"].ConnectionString ); } private async Task InsertFileDb(string FileName, string FileContent = null, bool isForDevloper = true) { try { return await Task.Run(() => { return Request.CreateResponse(HttpStatusCode.OK, DbAccessWriteFile(FileName, FileContent, isForDevloper)); }); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.InternalServerError, ex); } } private string DbAccessWriteFile(string FileName, string FileContent, bool isForDevloper) { if (string.IsNullOrEmpty(FileName)) { throw new Exception("at FileName requierd"); } using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value)) { var devstring = isForDevloper ? "1" : "0"; var sb = new StringBuilder(); sb.AppendLine($" declare @fileName as nvarchar(50) "); sb.AppendLine($" set @fileName = '{FileName}' "); sb.AppendLine($" update [Auftrag].[dbo].[TextFileStore] set FileIsLatest = 0 "); sb.AppendLine($" where FileIsLatest = 1 and [FileName] = @fileName and FileIsForDeveloperOnly = {devstring} "); sb.AppendLine($" INSERT INTO [dbo].[TextFileStore]"); sb.AppendLine($" ([FileName]"); sb.AppendLine($" ,[FileContent]"); sb.AppendLine($" ,[FileIsLatest]"); sb.AppendLine($" ,[FileDate]"); sb.AppendLine($" ,[FileIsForDeveloperOnly])"); sb.AppendLine($" VALUES"); sb.AppendLine($" (@fileName"); if (FileContent != null) { sb.AppendLine($" ,'{FileContent.Replace("\'", "\'\'")}'"); } else { throw new ApplicationException("No FileContent to update"); } sb.AppendLine($" ,1"); sb.AppendLine($" ,CURRENT_TIMESTAMP"); sb.AppendLine($" ,{devstring})"); sb.AppendLine($" select SCOPE_IDENTITY() "); var dbResult = dataacces.ExecuteQuery(sb.ToString()); if (dbResult.Rows.Count != 1) { throw new ApplicationException("Can not insert a TextFile"); } return dbResult.Rows[0][0].ToString(); } } /// /// Set TextFile content PostFileJsonContent /// /// [Route("PostFileJsonContent"), HttpPost] public async Task PostFileJsonContent([FromBody] BaseFile file) { //why file is empty on large files?? string jsonData = JsonConvert.SerializeObject(file); return await InsertFileDb(file.FileName, file.FileContent, file.ForDeveloper ?? true); } /// /// Set TextFile content PostFileJsonContent /// /// [Route("PostFwUpdateReportFile"), HttpPost] public async Task PostFwUpdateReportFile(int PcbId, int UserId, [FromBody] BaseFile file) { //why file is empty on large files?? string jsonData = JsonConvert.SerializeObject(file); var a = await InsertFileDb(file.FileName, file.FileContent, file.ForDeveloper ?? true); var fileID = 0; return await Task.Run(() => { try { if (int.TryParse(DbAccessWriteFile(file.FileName, file.FileContent, false), out fileID)) { using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value)) { var sb = new StringBuilder(); sb.AppendLine($" insert into [Cordonel_FwUpdateReport] "); sb.AppendLine($" select "); sb.AppendLine($" {PcbId} ");//[CordonelFwUpdateReport_PcbId] [int] NOT NULL, sb.AppendLine($" , {UserId} ");//[CordonelFwUpdateReport_User] [int] NOT NULL, sb.AppendLine($" , {fileID} ");//[CordonelFwUpdateReport_FileId] [int] NOT NULL sb.AppendLine($" select @@IDENTITY "); var retDT = dataacces.ExecuteQuery(sb.ToString()); return Request.CreateResponse(HttpStatusCode.OK, retDT.Rows[0][0]); } } } catch (Exception ex) { throw new ApplicationException($"file was not uploaded {ex.Message}"); } throw new ApplicationException("file was not uploaded"); }); } /// /// Set LUT JSON content /// /// [Route("PostLutFile"), HttpPost] public async Task PostLutFile(int DataLength, string version, int crc, int Metersize, string Region) { var httpFiles = HttpContext.Current.Request.Files; var listOfFiles = new List>(); foreach (var a in httpFiles) { try { if (HttpContext.Current.Request.Files[a.ToString()] is HttpPostedFile f) { listOfFiles.Add(new Tuple(f.FileName, GetFileBytes(f))); } } catch (Exception) { } } var fileID = 0; return await Task.Run(() => { try { int? retId = null; int FileCounter = StoreFiles(out retId, true, listOfFiles.First().Item1, FileCategoryID: 7, listOfFiles: listOfFiles); if (FileCounter == listOfFiles.Count && retId.HasValue) { fileID = retId.Value; } if (fileID != 0) { using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value)) { var sb = new StringBuilder(); sb.AppendLine($" insert into [Cordonel_Lut] "); sb.AppendLine($" select "); sb.AppendLine($" {fileID} "); sb.AppendLine($" , {DataLength} "); sb.AppendLine($" , '{version}' "); sb.AppendLine($" , '{crc}' "); sb.AppendLine($" , '{Metersize}' "); sb.AppendLine($" , '{Region}' "); sb.AppendLine($" , 0 "); // [CurrentVerionForProd] sb.AppendLine($" select @@IDENTITY "); var retDT = dataacces.ExecuteQuery(sb.ToString()); return Request.CreateResponse(HttpStatusCode.OK, retDT.Rows[0][0]); } } else { throw new ApplicationException($"file was not uploaded. Without error"); } } catch (Exception ex) { throw new ApplicationException($"file was not uploaded {ex.Message}"); } throw new ApplicationException("file was not uploaded"); }); } public virtual byte[] GetFileBytes(HttpPostedFile uploadedFile) { var bytes = new byte[uploadedFile.ContentLength]; uploadedFile.InputStream.Read(bytes, 0, uploadedFile.ContentLength); return bytes; } /// /// Set LUT JSON content /// /// [Route("GetLutFiles"), HttpGet] public async Task GetLutFiles(int? Metersize = null, string Region = null, bool? ForProd = null) { try { return await Task.Run(() => { using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value)) { var sb = new StringBuilder(); sb.AppendLine($" SELECT [Id] "); sb.AppendLine($" ,lut.[FileID] "); sb.AppendLine($" ,[DataLength] "); sb.AppendLine($" ,[Version] "); sb.AppendLine($" ,[FileCrc] "); sb.AppendLine($" ,[MeterSize] "); sb.AppendLine($" ,[Region] "); sb.AppendLine($" ,[CurrentVerionForProd] "); sb.AppendLine($" ,files.[FileName] "); sb.AppendLine($" ,files.FileContent "); sb.AppendLine($" FROM [Auftrag].[dbo].[Cordonel_Lut] lut "); sb.AppendLine($" inner join [Auftrag].[dbo].[FileClusterStore] fileMaster on fileMaster.FileId = lut.[FileID] "); sb.AppendLine($" inner join [Auftrag].[dbo].[FileMapToCluster] map on fileMaster.FileIsDeleted = 0 and fileMaster.FileId = map.[FileMapToCluster_FileClusterId] "); sb.AppendLine($" inner join [Auftrag].[dbo].[File] files on files.FileId = map.[FileMapToCluster_FileId] "); sb.AppendLine($" where 1= 1 "); if (Metersize.HasValue) { sb.AppendLine($" and MeterSize= {Metersize.Value} "); } if (!string.IsNullOrEmpty(Region)) { sb.AppendLine($" and Region ='{Region}' "); } if (ForProd.HasValue) { sb.AppendLine($" and CurrentVerionForProd ={(ForProd.Value? "1" : "0") } "); } var retDT = dataacces.ExecuteQuery(sb.ToString()); return Request.CreateResponse(HttpStatusCode.OK, retDT); } }); } catch (Exception ex) { throw new ApplicationException($"file was not uploaded {ex.Message}"); } throw new ApplicationException("file was not uploaded"); } /// /// Set TextFile content PostFileJsonContent /// /// [Route("PostFWFileBinaryContent"), HttpPost] public async Task PostFWFileBinaryContent(bool IsDevloper, string FWname, MeterSize? meterSize = null, CordonelFWTypeEnum? fWTypeEnum = null, int FileCategoryID = 1, string FileDateString = "CURRENT_TIMESTAMP") { var httpFiles = HttpContext.Current.Request.Files; var listOfFiles = new List>(); foreach (var a in httpFiles) { try { if (HttpContext.Current.Request.Files[a.ToString()] is HttpPostedFile f) { listOfFiles.Add(new Tuple(a.ToString(), GetFileBytes(f))); } } catch (Exception) { } } return await Task.Run(() => { int? retId = null; int FileCounter = StoreFiles(out retId, IsDevloper, FWname, meterSize, fWTypeEnum, FileCategoryID, FileDateString, listOfFiles); if (FileCounter == listOfFiles.Count && retId.HasValue) { return Request.CreateResponse(HttpStatusCode.OK, retId.Value); } return Request.CreateResponse(HttpStatusCode.InternalServerError, "Not all files where stored!"); }); } public int StoreFiles(out int? FileClusterStoreId, bool IsDevloper, string FWname, MeterSize? meterSize = null, CordonelFWTypeEnum? fWTypeEnum = null, int FileCategoryID = 1, string FileDateString = "CURRENT_TIMESTAMP", List> listOfFiles = null) { //1 Cordonel FW //2 Cordonel Configruation File //3 Cordonel Logger File //4 Cordonel Update Safe //5 Cordonel Update Sotware //6 Cordonel Release Config //7 Cordonel Look up table FileClusterStoreId = null; using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value)) { var sb = new StringBuilder(); sb.AppendLine($" INSERT INTO [dbo].[FileClusterStore] "); sb.AppendLine($" ([FileName] "); sb.AppendLine($" ,[FileIsLatest] "); sb.AppendLine($" ,[FileDate] "); sb.AppendLine($" ,[FileIsForDeveloperOnly] "); sb.AppendLine($" ,[FileCategoryID] "); sb.AppendLine($" ,[FileIsDeleted]) "); sb.AppendLine($" VALUES "); sb.AppendLine($" ('{FWname}' "); sb.AppendLine($" ,0 "); sb.AppendLine($" ,{FileDateString} "); sb.AppendLine($" ,{(IsDevloper ? '1' : '0')} "); sb.AppendLine($" ,{FileCategoryID} "); sb.AppendLine($" ,0) "); sb.AppendLine($" SELECT @@IDENTITY "); var ret = dataacces.ExecuteQuery(sb.ToString()); FileClusterStoreId = (int)((decimal)ret.Rows[0][0]); if (meterSize.HasValue && fWTypeEnum.HasValue) { sb = new StringBuilder(); sb.AppendLine($" INSERT INTO[dbo].[CordonelFwFile]"); sb.AppendLine($" ([CordonelFwFile_FileClusterStoreId]"); sb.AppendLine($" ,[CordonelFwFile_Dn]"); sb.AppendLine($" ,[CordonelFwFile_Type])"); sb.AppendLine($" VALUES"); sb.AppendLine($" ({FileClusterStoreId}"); sb.AppendLine($" ,{meterSize.Value.GetHashCode()}"); sb.AppendLine($" ,{fWTypeEnum.Value.GetHashCode()})"); sb.AppendLine($" SELECT @@IDENTITY "); ret = dataacces.ExecuteQuery(sb.ToString()); var CordonelFwFileId = (int)((decimal)ret.Rows[0][0]); } } int FileCounter = 0; if (listOfFiles.Any()) { //addMapEntrie for (int i = 0; i < listOfFiles.Count; i++) { var content = listOfFiles[i].Item2; using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value)) { var parameters = new List(); var FileContent = new System.Data.SqlClient.SqlParameter("@FileContent", SqlDbType.VarBinary); var FileName = new System.Data.SqlClient.SqlParameter("@FileName", SqlDbType.NVarChar, 150); FileName.Value = listOfFiles[i].Item1; FileContent.Value = content; parameters.Add(FileName); parameters.Add(FileContent); var retDT = dataacces.ExecuteQuery("INSERT INTO [dbo].[File] ([FileContent], [FileName]) VALUES (@FileContent, @FileName) ;SELECT @@IDENTITY ", parameters); var FileId = (int)((decimal)retDT.Rows[0][0]); var sb = new StringBuilder(); sb.AppendLine($" INSERT INTO [dbo].[FileMapToCluster] ([FileMapToCluster_FileId],[FileMapToCluster_FileClusterId]) "); sb.AppendLine($" VALUES "); sb.AppendLine($" ({FileId}, "); sb.AppendLine($" {FileClusterStoreId}) "); sb.AppendLine($" SELECT @@IDENTITY"); var retDTMap = dataacces.ExecuteQuery(sb.ToString()); if (retDTMap != null && retDTMap.Rows.Count > 0 && (int)((decimal)retDTMap.Rows[0][0]) > -1) { FileCounter = FileCounter + 1; } } } } return FileCounter; } /// /// Returns a list of all Fw Files (FileCategoryID = 1) that match the filters and are not deleted /// /// null for all /// "" for all, use a like to serach /// null for all /// null for all /// null for all /// null for all /// [Route("GetFwFiles"), HttpGet] public async Task GetFwFiles(int? FileId = null, string FileName = "", bool? FileIsLatest = null, bool? FileIsForDeveloperOnly = null, int? CordonelFwFile_Dn = null, int? CordonelFwFile_Type = null, int? FileCategoryID = 1) { return await Task.Run(() => { using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value)) { var sb = new StringBuilder(); sb.AppendLine(dataacces.GenerateParam("FileId", "int", FileId)); sb.AppendLine(dataacces.GenerateParam("FileName", "nvarchar(50)", FileName)); sb.AppendLine(dataacces.GenerateParam("FileIsLatest", "bit", FileIsLatest)); sb.AppendLine(dataacces.GenerateParam("FileIsForDeveloperOnly", "bit", FileIsForDeveloperOnly)); sb.AppendLine(dataacces.GenerateParam("FileCategoryID", "int", FileCategoryID)); sb.AppendLine(dataacces.GenerateParam("CordonelFwFile_Dn", "int", CordonelFwFile_Dn)); sb.AppendLine(dataacces.GenerateParam("CordonelFwFile_Type", "int", CordonelFwFile_Type)); sb.AppendLine($" select * from [Auftrag].[dbo].[FileClusterStore] fileMaster"); sb.AppendLine($" left outer join [Auftrag].[dbo].[CordonelFwFile] fw on fileMaster.FileIsDeleted = 0 and fileMaster.FileId = fw.CordonelFwFile_FileClusterStoreId"); sb.AppendLine($" where (@FileIsForDeveloperOnly is null or FileIsForDeveloperOnly = @FileIsForDeveloperOnly)"); sb.AppendLine($" and (@FileId is null or FileId = @FileId)"); sb.AppendLine($" and (@FileName is null or [FileName] like @FileName)"); sb.AppendLine($" and (@FileIsLatest is null or FileIsLatest = @FileIsLatest)"); sb.AppendLine($" and (@FileCategoryID is null or FileCategoryID = @FileCategoryID)"); sb.AppendLine($" and (@CordonelFwFile_Dn is null or CordonelFwFile_Dn = @CordonelFwFile_Dn )"); sb.AppendLine($" and (@CordonelFwFile_Type is null or CordonelFwFile_Type = @CordonelFwFile_Type)"); var retDT = dataacces.ExecuteQuery(sb.ToString()); return Request.CreateResponse(HttpStatusCode.OK, retDT); } }); } /// /// Get text file content if client file date is older or empty other wisre return empty string /// /// [Route("GetFileParts"), HttpGet] public async Task GetFileParts(int? ParentFileId = null, int? FileId = null, string FileName = "", bool readContent = false) { return await Task.Run(() => { using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value)) { var sb = new StringBuilder(); sb.AppendLine(dataacces.GenerateParam("ParentFileId", "int", ParentFileId)); sb.AppendLine(dataacces.GenerateParam("FileId", "int", FileId)); sb.AppendLine(dataacces.GenerateParam("FileName", "nvarchar(50)", FileName)); sb.AppendLine($" select "); sb.AppendLine($" fileMaster.FileId as ParentFileId,files.FileId,files.[FileName] "); if (readContent) { sb.AppendLine($" ,files.FileContent "); } sb.AppendLine($" from [Auftrag].[dbo].[FileClusterStore] fileMaster "); sb.AppendLine($" inner join [Auftrag].[dbo].[FileMapToCluster] map on fileMaster.FileIsDeleted = 0 and fileMaster.FileId = map.[FileMapToCluster_FileClusterId] "); sb.AppendLine($" inner join [Auftrag].[dbo].[File] files on files.FileId = map.[FileMapToCluster_FileId] "); sb.AppendLine($" where "); sb.AppendLine($" (@ParentFileId is null or fileMaster.FileId = @ParentFileId)"); sb.AppendLine($" and (@FileId is null or files.FileId = @FileId)"); sb.AppendLine($" and (@FileName is null or files.[FileName] like @FileName)"); sb.AppendLine($" order by fileMaster.FileId desc"); var retDT = dataacces.ExecuteQuery(sb.ToString()); return Request.CreateResponse(HttpStatusCode.OK, retDT); } }); } ///// ///// Get text file content if client file date is older or empty other wisre return empty string ///// ///// //[Route("GetFileBinaryContent"), HttpGet] //public async Task GetFwFiles(string FileName, DateTimeOffset? ClientFileDate = null, bool isDeveloper = false) //{ //} /// /// Get text file content if client file date is older or empty other wisre return empty string /// /// [Route("GetUpdateFileContent"), HttpGet] public async Task GetUpdateFileContent(string FileName, DateTimeOffset? ClientFileDate = null, bool isDeveloper = false) { try { return await Task.Run(async () => { DateTime? ClientFileDateUtc = null; if (ClientFileDate.HasValue) { ClientFileDateUtc = ClientFileDate.Value.UtcDateTime; } var retList = GetFiles(FileName: FileName, isDeveloper: isDeveloper, latest: true, FileDateIsGreaterThan: ClientFileDateUtc); if (retList.Count != 1) { return Request.CreateResponse(HttpStatusCode.OK, string.Empty); } return Request.CreateResponse(HttpStatusCode.OK, retList[0]); }); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.InternalServerError, ex); } } /// /// Get TextFile content /// /// [Route("GetFileList"), HttpGet] public async Task GetFileList(int? FileID = null, string FileName = "", bool? latest = null, bool? isDeveloper = null) { try { return await Task.Run(async () => { var retList = GetFiles(FileID, FileName, latest, isDeveloper); return Request.CreateResponse(HttpStatusCode.OK, retList); }); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.InternalServerError, ex); } } private List GetFiles(int? FileID = null, string FileName = "", bool? latest = true, bool? isDeveloper = false, DateTime? FileDateIsGreaterThan = null) { var ret = new List(); using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value)) { var sb = new StringBuilder(); sb.AppendLine($" SELECT FileId, FileName, FileContent, FileIsLatest, FileDate, FileIsForDeveloperOnly"); sb.AppendLine($" FROM TextFileStore "); sb.AppendLine($" where FileId > 0"); if (FileID.HasValue) { sb.AppendLine($" and FileId = {FileID.Value}"); } else { if (!String.IsNullOrEmpty(FileName)) { sb.AppendLine($" and FileName like '%{FileName}%' "); } if (latest.HasValue) { if (latest.Value) { sb.AppendLine($" and FileIsLatest = 1 "); } else { sb.AppendLine($" and FileIsLatest = 0 "); } } if (isDeveloper.HasValue) { if (isDeveloper.Value) { //sb.AppendLine($" and FileIsForDeveloperOnly = 1 "); } else { sb.AppendLine($" and FileIsForDeveloperOnly = 0 "); } } if (FileDateIsGreaterThan.HasValue) { sb.AppendLine($" and FileDate > CONVERT(datetime, '{FileDateIsGreaterThan.Value.ToString("yyyy-MM-dd HH:mm:ss:fff")}',120) "); } } sb.AppendLine($" order by FileId desc "); var dbResult = dataacces.ExecuteQuery(sb.ToString()); foreach (DataRow row in dbResult.Rows) { ret.Add( new BaseFile() { FileId = (int)row["FileId"], FileName = (string)row["FileName"], FileContent = (string)row["FileContent"], IsLatest = (bool)row["FileIsLatest"], UploadDate = (DateTime)row["FileDate"], ForDeveloper = (bool)row["FileIsForDeveloperOnly"], }); } return ret; } } /// /// Get TextFile content /// /// [Route("GetFileContent"), HttpGet] public async Task GetFileContent(int? FileID = null, string FileName = "", bool isDeveloper = false) { try { return await Task.Run(async () => { bool? islatest = null; if (!String.IsNullOrEmpty(FileName) && !FileID.HasValue) { islatest = true; } var retList = GetFiles(FileID, FileName, isDeveloper); if (retList.Count != 1) { return Request.CreateResponse(HttpStatusCode.InternalServerError, "Can not find a TextFile for your request"); } return Request.CreateResponse(HttpStatusCode.OK, retList[0]); }); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.InternalServerError, ex); } } } }