laatzen/Common/Service/MeterProcessState/Controllers/FileUpToDateController.cs
Thomas Wiedebusch ef0d333d66 MeterSize moved from "Logic.PrdctionToProductMapper" to "ProductionOrderCore",
RegionRadio split to Region (string) and RadioFrequencyMhz (Int32?),
CoreRevision changed from string to Int32?,
Service\MeterProcessState\Controllers\GetCorondelFw changed to GetCordonelFw and corrected
2022-12-06 13:15:53 +01:00

904 lines
38 KiB
C#

using Logic.ProductionToProductMapper.Cordonel;
using Newtonsoft.Json;
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;
using Xylem.Common.Logic.ProductionOrderCore.OrderData;
using Xylem.Common.Logic.ServiceCore;
namespace Xylem.Common.Service.MeterProcessState.Controllers
{
/// <summary>
///
/// </summary>
[RoutePrefix("api/FileUpToDate")]
public class FileUpToDateController : ApiController
{
public static class GlobalConfig
{
public static Lazy<String> connectionString = new Lazy<String>(()
=>
System.Configuration.ConfigurationManager.ConnectionStrings["default"].ConnectionString
);
}
private async Task<HttpResponseMessage> InsertFileDb(String FileName, String FileContent = null, Boolean 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, Boolean 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();
}
}
/// <summary>
/// Set TextFile content PostFileJsonContent
/// </summary>
/// <returns></returns>
[Route("PostFileJsonContent"), HttpPost]
public async Task<HttpResponseMessage> 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);
}
/// <summary>
/// Set TextFile content PostFileJsonContent
/// </summary>
/// <returns></returns>
[Route("PostFwUpdateReportFile"), HttpPost]
public async Task<HttpResponseMessage> PostFwUpdateReportFile(Int32 PcbId, Int32 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");
});
}
/// <summary>
/// Set LUT JSON content
/// </summary>
/// <returns></returns>
[Route("PostLutFile"), HttpPost]
public async Task<HttpResponseMessage> PostLutFile(Int32 DataLength, String version, Int32 crc, Int32 Metersize, String Region)
{
var httpFiles = HttpContext.Current.Request.Files;
var listOfFiles = new List<Tuple<String, Byte[]>>();
foreach (var a in httpFiles)
{
try
{
if (HttpContext.Current.Request.Files[a.ToString()] is HttpPostedFile f)
{
listOfFiles.Add(new Tuple<String, Byte[]>(f.FileName, GetFileBytes(f)));
}
}
catch (Exception)
{
}
}
var fileID = 0;
return await Task.Run(() =>
{
try
{
Int32? retId = null;
Int32 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 "); // [CurrentVersionForProd]
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;
}
/// <summary>
/// Set LUT JSON content
/// </summary>
/// <returns></returns>
[Route("GetLutFiles"), HttpGet]
public async Task<HttpResponseMessage> GetLutFiles(Int32? Metersize = null, String Region = null, Boolean? 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($" ,[CurrentVersionForProd] ");
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 CurrentVersionForProd ={(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");
}
/// <summary>
/// Set TextFile content PostFileJsonContent
/// </summary>
/// <returns></returns>
[Route("PostFWFileBinaryContent"), HttpPost]
public async Task<HttpResponseMessage> PostFWFileBinaryContent(Boolean IsDevloper, String FWname, MeterSize? meterSize = null, CordonelFWTypeEnum? fWTypeEnum = null, Int32 FileCategoryID = 1, String FileDateString = "CURRENT_TIMESTAMP")
{
var httpFiles = HttpContext.Current.Request.Files;
var listOfFiles = new List<Tuple<String, Byte[]>>();
foreach (var a in httpFiles)
{
try
{
if (HttpContext.Current.Request.Files[a.ToString()] is HttpPostedFile f)
{
listOfFiles.Add(new Tuple<String, Byte[]>(a.ToString(), GetFileBytes(f)));
}
}
catch (Exception)
{
}
}
return await Task.Run(() =>
{
Int32? retId = null;
Int32 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 Int32 StoreFiles(out Int32? FileClusterStoreId, Boolean IsDevloper, String FWname, MeterSize? meterSize = null, CordonelFWTypeEnum? fWTypeEnum = null, Int32 FileCategoryID = 1, String FileDateString = "CURRENT_TIMESTAMP", List<Tuple<String, Byte[]>> 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 = (Int32)((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 = (Int32)((Decimal)ret.Rows[0][0]);
}
}
Int32 FileCounter = 0;
if (listOfFiles.Any())
{
//addMapEntrie
for (Int32 i = 0; i < listOfFiles.Count; i++)
{
var content = listOfFiles[i].Item2;
using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value))
{
var parameters = new List<System.Data.SqlClient.SqlParameter>();
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 = (Int32)((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 && (Int32)((Decimal)retDTMap.Rows[0][0]) > -1)
{
FileCounter = FileCounter + 1;
}
}
}
}
return FileCounter;
}
/// <summary>
/// Returns filtered FW files for Cordonel without content
/// </summary>
/// <returns></returns>
[Route("GetCordonelFw"), HttpGet]
public async Task<HttpResponseMessage> GetCordonelFw(Int32? meterSize = null, Int32? radioFrequencyMhz = null,
String region = null, Boolean? forProd = null, Boolean? deleted = false)
{
try
{
return await Task.Run(() =>
{
var ret = new List<CordonelFwPackageInfo>();
using (var dataAccess = new SqlDataAccess(GlobalConfig.connectionString.Value))
{
var sb = new StringBuilder();
sb.AppendLine($" SELECT [Id] ");
sb.AppendLine($" ,[RadioFrequencyMhz] ");
sb.AppendLine($" ,[FlexnetAppId] ");
sb.AppendLine($" ,[Version] ");
sb.AppendLine($" ,[Name] ");
sb.AppendLine($" ,[Deleted] ");
sb.AppendLine($" ,[Metersize] ");
sb.AppendLine($" ,[Region] ");
sb.AppendLine($" ,[CurrentForProd] ");
sb.AppendLine($" ,[FileClusterStoreId] ");
sb.AppendLine($" ,[CoreRevisionMin] ");
sb.AppendLine($" ,[CoreRevisionMax] ");
sb.AppendLine($" ,[MetrologyVersion] ");
sb.AppendLine($" ,[IsReleased] ");
sb.AppendLine($" ,[ReleaseDate] ");
sb.AppendLine($" ,[Remark] ");
sb.AppendLine($" ,[FileName] ");
sb.AppendLine($" FROM[Auftrag].[dbo].[Cordonel_CurrentFw] ");
sb.AppendLine($" left outer join [Auftrag].[dbo].[FileClusterStore] on [FileId] = [FileClusterStoreId]");
sb.AppendLine($" where 1= 1 ");
if (meterSize != null)
{
sb.AppendLine($" and Metersize={meterSize} ");
}
if (radioFrequencyMhz != null)
{
sb.AppendLine($" and radioFrequencyMhz={radioFrequencyMhz} ");
}
if (region != null)
{
sb.AppendLine($" and Region ='{region}' ");
}
if (forProd.HasValue)
{
sb.AppendLine($" and currentForProd ={(forProd.Value ? "1" : "0") } ");
}
if (deleted.HasValue)
{
sb.AppendLine($" and Deleted is {(deleted.Value ? "not" : "")} null");
}
var retDT = dataAccess.ExecuteQuery(sb.ToString());
foreach (DataRow item in retDT.Rows)
{
var add = new CordonelFwPackageInfo
{
Id = (Int32)item["Id"],
RadioFrequencyMhz = (Int32?)item["RadioFrequencyMhz"],
Name = (String)item["Name"],
FlexnetAppId = (Int32)item["FlexnetAppId"],
Version = (Int32)item["Version"],
FileClusterStoreId = (Int32)item["FileClusterStoreId"],
FileName = ""
};
if (item["FileName"].GetType() != typeof(DBNull))
{
add.FileName = (String)item["FileName"];
}
if (item["Deleted"].GetType() != typeof(DBNull))
{
add.DeletedDate = (DateTime)item["Deleted"];
}
if (item["Metersize"].GetType() != typeof(DBNull))
{
add.MeterSize = MeterSizeConverter.ConvertMeterSizeEnumToSizeName((MeterSize)(Int16)item["Metersize"]);
}
add.CurrentForProd = false;
if (item["CurrentForProd"].GetType() != typeof(DBNull))
{
add.CurrentForProd = (Boolean)item["CurrentForProd"];
}
if (item["Region"].GetType() != typeof(DBNull))
{
var reg = (String)item["Region"];
add.Region = reg.Replace(" ","");
}
if (item["CoreRevisionMin"].GetType() != typeof(DBNull))
{
add.CoreRevisionMin = (Int32)item["CoreRevisionMin"];
}
add.CoreRevisionMax = null;
if (item["CoreRevisionMax"].GetType() != typeof(DBNull))
{
add.CoreRevisionMax = (Int32)item["CoreRevisionMax"];
}
add.MetrologyVersion = null;
if (item["MetrologyVersion"].GetType() != typeof(DBNull))
{
add.MetrologyVersion = (Int32)item["MetrologyVersion"];
}
add.IsReleased = false;
if (item["IsReleased"].GetType() != typeof(DBNull))
{
add.IsReleased = (Boolean)item["IsReleased"];
}
add.ReleaseDate = null;
if (item["ReleaseDate"].GetType() != typeof(DBNull))
{
add.ReleaseDate = (DateTime)item["ReleaseDate"];
}
add.Remark = "blalb";
if (item["Remark"].GetType() != typeof(DBNull))
{
add.Remark = (String)item["Remark"];
}
ret.Add(add);
}
return Request.CreateResponse(HttpStatusCode.OK, ret);
}
});
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
}
}
/// <summary>
/// Returns a list of all Fw Files (FileCategoryID = 1) that match the filters and are not deleted
/// </summary>
/// <param name="FileId">null for all</param>
/// <param name="FileName">"" for all, use a like to serach</param>
/// <param name="FileIsLatest">null for all</param>
/// <param name="FileIsForDeveloperOnly">null for all</param>
/// <param name="CordonelFwFile_Dn">null for all</param>
/// <param name="CordonelFwFile_Type">null for all</param>
/// <returns></returns>
[Route("GetFwFiles"), HttpGet]
public async Task<HttpResponseMessage> GetFwFiles(Int32? FileId = null, String FileName = "", Boolean? FileIsLatest = null, Boolean? FileIsForDeveloperOnly = null, Int32? CordonelFwFile_Dn = null, Int32? CordonelFwFile_Type = null, Int32? 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);
}
});
}
/// <summary>
/// Get text file content if client file date is older or empty other wisre return empty string
/// </summary>
/// <returns></returns>
[Route("GetFileParts"), HttpGet]
public async Task<HttpResponseMessage> GetFileParts(Int32? ParentFileId = null, Int32? FileId = null, String FileName = "", Boolean 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);
}
});
}
///// <summary>
///// Get text file content if client file date is older or empty other wisre return empty string
///// </summary>
///// <returns></returns>
//[Route("GetFileBinaryContent"), HttpGet]
//public async Task<HttpResponseMessage> GetFwFiles(string FileName, DateTimeOffset? ClientFileDate = null, bool isDeveloper = false)
//{
//}
/// <summary>
/// Get text file content if client file date is older or empty other wisre return empty string
/// </summary>
/// <returns></returns>
[Route("GetUpdateFileContent"), HttpGet]
public async Task<HttpResponseMessage> GetUpdateFileContent(String FileName, DateTimeOffset? ClientFileDate = null, Boolean 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);
}
}
/// <summary>
/// Get TextFile content
/// </summary>
/// <returns></returns>
[Route("GetFileList"), HttpGet]
public async Task<HttpResponseMessage> GetFileList(Int32? FileID = null, String FileName = "", Boolean? latest = null, Boolean? 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<BaseFile> GetFiles(Int32? FileID = null, String FileName = "", Boolean? latest = true, Boolean? isDeveloper = false, DateTime? FileDateIsGreaterThan = null)
{
var ret = new List<BaseFile>();
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 = (Int32)row["FileId"],
FileName = (String)row["FileName"],
FileContent = (String)row["FileContent"],
IsLatest = (Boolean)row["FileIsLatest"],
UploadDate = (DateTime)row["FileDate"],
ForDeveloper = (Boolean)row["FileIsForDeveloperOnly"],
});
}
return ret;
}
}
/// <summary>
/// Get TextFile content
/// </summary>
/// <returns></returns>
[Route("GetFileContent"), HttpGet]
public async Task<HttpResponseMessage> GetFileContent(Int32? FileID = null, String FileName = "", Boolean isDeveloper = false)
{
try
{
return await Task.Run(async () =>
{
Boolean? 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);
}
}
}
}