diff --git a/BExIS.Modules.Lui.UI.csproj b/BExIS.Modules.Lui.UI.csproj index f25fbe0..ea669a8 100644 --- a/BExIS.Modules.Lui.UI.csproj +++ b/BExIS.Modules.Lui.UI.csproj @@ -18,7 +18,7 @@ Properties BExIS.Modules.Lui.UI BExIS.Modules.Lui.UI - v4.5.2 + v4.8 false true @@ -30,6 +30,7 @@ ..\..\..\..\packages\WebGrease.1.5.2\lib + true @@ -63,22 +64,33 @@ ..\..\..\..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll + + ..\..\..\..\packages\Microsoft.IdentityModel.JsonWebTokens.5.3.0\lib\net461\Microsoft.IdentityModel.JsonWebTokens.dll + + + ..\..\..\..\packages\Microsoft.IdentityModel.Logging.5.3.0\lib\net461\Microsoft.IdentityModel.Logging.dll + + + ..\..\..\..\packages\Microsoft.IdentityModel.Tokens.5.3.0\lib\net461\Microsoft.IdentityModel.Tokens.dll + ..\..\..\..\packages\Microsoft.AspNet.WebHelpers.3.2.3\lib\net45\Microsoft.Web.Helpers.dll ..\..\..\..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll - - ..\..\..\..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + + ..\..\..\..\packages\Newtonsoft.Json.10.0.1\lib\net45\Newtonsoft.Json.dll ..\..\..\..\packages\System.Buffers.4.4.0\lib\netstandard1.1\System.Buffers.dll - + + ..\..\..\..\packages\System.IdentityModel.Tokens.Jwt.5.3.0\lib\net461\System.IdentityModel.Tokens.Jwt.dll + ..\..\..\..\packages\System.Memory.4.5.0\lib\netstandard1.1\System.Memory.dll @@ -86,12 +98,16 @@ ..\..\..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll - - ..\..\..\..\packages\System.Runtime.CompilerServices.Unsafe.4.5.0\lib\netstandard1.0\System.Runtime.CompilerServices.Unsafe.dll + + ..\..\..\..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + ..\..\..\..\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll + + + ..\..\..\..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.Helpers.dll @@ -120,51 +136,14 @@ ..\..\..\..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Razor.dll - + ..\..\..\..\packages\TelerikMvcExtensions.2013.2.611\lib\net40\Telerik.Web.Mvc.dll - - - ..\..\..\..\Libraries\Vaiona\Vaiona.Entities.Orm.NH.dll - - - ..\..\..\..\Libraries\Vaiona\Vaiona.IoC.dll - - - ..\..\..\..\Libraries\Vaiona\Vaiona.Logging.dll - - - ..\..\..\..\Libraries\Vaiona\Vaiona.Model.dll - - - ..\..\..\..\Libraries\Vaiona\Vaiona.MultiTenancy.Api.dll - - - ..\..\..\..\Libraries\Vaiona\Vaiona.MultiTenancy.Services.dll - - - ..\..\..\..\Libraries\Vaiona\Vaiona.Persistence.Api.dll - - - ..\..\..\..\Libraries\Vaiona\Vaiona.PersistenceProviders.NH.dll - - - ..\..\..\..\Libraries\Vaiona\Vaiona.Utils.dll - - - ..\..\..\..\Libraries\Vaiona\Vaiona.Web.dll - - - ..\..\..\..\Libraries\Vaiona\Vaiona.Web.Mvc.dll - - - ..\..\..\..\Libraries\Vaiona\Vaiona.Web.Mvc.Modularity.dll - ..\..\..\..\packages\WebActivator.1.2.0.0\lib\NETFramework40\WebActivator.dll @@ -186,7 +165,6 @@ - @@ -211,8 +189,10 @@ - + + + @@ -270,10 +250,62 @@ {681C8BC4-55F0-4F43-A685-90E246A88CB1} BExIS.Security.Services + + {455EC826-9A92-40FF-BD3B-388C288955CE} + BExIS.IO.Transform.Output + + + {6EAD7D02-02F7-42FF-85E4-90BB892D3846} + BExIS.Utils.Config + {782b71c1-707f-4ab1-80e9-90d2880635b4} BExIS.Utils + + {c4d4bc9e-8832-4966-be58-cb684e9a74e8} + Vaiona.Entities.Orm.NH + + + {0815D220-3625-4E23-BBBC-8152345637FE} + Vaiona.Entities + + + {29a7be0f-a17c-4ae8-8ca1-15fe4dd74129} + Vaiona.IoC + + + {e8b37581-1cac-463d-903b-b4bee8b2b0e3} + Vaiona.Logging + + + {a60ac05f-8c9a-4efd-9826-452e6049da4d} + Vaiona.Model + + + {640bf81d-354a-4bf0-85fc-f0ad587cf8a2} + Vaiona.Persistence.Api + + + {8c5c0209-69a3-4579-9f9b-4d5f084a3b85} + Vaiona.Persistence.NH + + + {63fcacaa-9534-4fdd-a082-78dcc06baf28} + Vaiona.Utils + + + {705f8751-e58a-453e-a7fd-0c310fd3cae8} + Vaiona.Web.Mvc.Modularity + + + {5f5d22e8-8c05-49cd-854e-8fe8eff1aa6c} + Vaiona.Web.Mvc + + + {5b48b5a8-eae8-4ef8-8f2c-7fedb1b095d3} + Vaiona.Web + 10.0 @@ -305,7 +337,7 @@ mkdir "$(SolutionDir)Console\Workspace\Modules\LUI" -C:\Windows\System32\xcopy "$(ProjectDir)Lui.Settings.xml" "$(SolutionDir)Console\Workspace\Modules\LUI" /C /Y /I +C:\Windows\System32\xcopy "$(ProjectDir)Lui.Settings.json" "$(SolutionDir)Console\Workspace\Modules\LUI" /C /Y /I diff --git a/Controllers/LUICalculationController.cs b/Controllers/LUICalculationController.cs index b5df4b0..1927130 100644 --- a/Controllers/LUICalculationController.cs +++ b/Controllers/LUICalculationController.cs @@ -22,11 +22,21 @@ using System.Web.Routing; using Microsoft.AspNet.Identity; using System.Globalization; +using BExIS.Utils.Config; +using Microsoft.IdentityModel.Tokens; +using System.Security.Claims; +using System.IdentityModel.Tokens.Jwt; namespace BExIS.Modules.Lui.UI.Controllers { public class LUICalculationController : Controller { + private readonly UserManager _userManager; + + public LUICalculationController(UserManager userManager) + { + _userManager = userManager; + } #region constants // page title private static string TITLE = "LUI Calculation"; @@ -36,7 +46,7 @@ public class LUICalculationController : Controller private static string SESSION_FILE = "lui:resultFile"; // namespace for download files - private static string FILE_NAMESPACE = Models.Settings.get("lui:filename:namespace") as string; + private static string FILE_NAMESPACE = ModuleManager.GetModuleSettings("lui").GetValueByKey("lui:filename:namespace") as string; #endregion // GET: Main @@ -47,11 +57,12 @@ public ActionResult Index() // set page title ViewBag.Title = PresentationModel.GetViewTitleForTenant(TITLE, this.Session.GetTenant()); + var settings = ModuleManager.GetModuleSettings("lui"); //create model LUIQueryModel model = new LUIQueryModel(); bool dataMissing = false; - string datasetId = Models.Settings.get("lui:datasetDefaultComponentsSet").ToString(); + string datasetId = settings.GetValueByKey("lui:datasetDefaultComponentsSet").ToString(); List statisticModels = DataAccess.GetStatistic(datasetId, GetServerInformation()); DataTable years = statisticModels.Where(a => a.VariableName == "Year").Select(c => c.uniqueValues).FirstOrDefault(); foreach(DataRow dataRow in years.Rows) @@ -74,15 +85,15 @@ public ActionResult Index() model.IsPublicAccess = true; } - model.DefaultComponentsSetDatasetId = Models.Settings.get("lui:datasetDefaultComponentsSet").ToString(); + model.DefaultComponentsSetDatasetId = settings.GetValueByKey("lui:datasetDefaultComponentsSet").ToString(); var datasetInfo = DataAccess.GetDatasetInfo(model.DefaultComponentsSetDatasetId, GetServerInformation()); model.DefaultComponentsSetDatasetVersion = DataAccess.GetDatasetInfo(model.DefaultComponentsSetDatasetId, GetServerInformation()).Version; XmlDocument doc = DataAccess.GetMetadata(model.DefaultComponentsSetDatasetId, GetServerInformation()); model.DefaultComponentsSetLastUpdate = DateTime.Parse(doc.GetElementsByTagName("metadataLastModificationDateType")[0].InnerText).ToString("yyyy-MM-dd"); model.AvailableYearsDataDefault = GetAvailableYears(model.DefaultComponentsSetDatasetId, model.IsPublicAccess); - model.AvailableYearsDataTill2019 = GetAvailableYears(Models.Settings.get("lui:datasetTill2019ComponentsSet").ToString(), model.IsPublicAccess); - model.AvailableYearsDataTill2023 = GetAvailableYears(Models.Settings.get("lui:datasetTill2023ComponentsSet").ToString(), model.IsPublicAccess); + model.AvailableYearsDataTill2019 = GetAvailableYears(settings.GetValueByKey("lui:datasetTill2019ComponentsSet").ToString(), model.IsPublicAccess); + model.AvailableYearsDataTill2023 = GetAvailableYears(settings.GetValueByKey("lui:datasetTill2023ComponentsSet").ToString(), model.IsPublicAccess); return View("Index", model); @@ -144,20 +155,22 @@ public ActionResult CalculateLUI(LUIQueryModel model) Session["DataStructureId"] = null; + var settings = ModuleManager.GetModuleSettings("lui"); + if (model.ComponentsSet.SelectedValue == "historic set till 2019") { - selectedDataStructureId = (int)Models.Settings.get("lui:datastructureTill2019ComponentsSet"); - model.DownloadDatasetId = Models.Settings.get("lui:datasetTill2019ComponentsSet").ToString(); + selectedDataStructureId = int.Parse(settings.GetValueByKey("lui:datastructureTill2019ComponentsSet").ToString()); + model.DownloadDatasetId = settings.GetValueByKey("lui:datasetTill2019ComponentsSet").ToString(); } else if(model.ComponentsSet.SelectedValue == "historic set till 2023") { - selectedDataStructureId = (int)Models.Settings.get("lui:datastructureTill2023ComponentsSet"); - model.DownloadDatasetId = Models.Settings.get("lui:datasetTill2023ComponentsSet").ToString(); + selectedDataStructureId = int.Parse(settings.GetValueByKey("lui:datastructureTill2023ComponentsSet").ToString()); + model.DownloadDatasetId = settings.GetValueByKey("lui:datasetTill2023ComponentsSet").ToString(); } else { - selectedDataStructureId = (int)Models.Settings.get("lui:datastructureDefaultComponentsSet"); - model.DownloadDatasetId = Models.Settings.get("lui:datasetDefaultComponentsSet").ToString(); + selectedDataStructureId = int.Parse(settings.GetValueByKey("lui:datastructureDefaultComponentsSet").ToString()); + model.DownloadDatasetId = settings.GetValueByKey("lui:datasetDefaultComponentsSet").ToString(); } @@ -169,13 +182,13 @@ public ActionResult CalculateLUI(LUIQueryModel model) switch (model.ComponentsSet.SelectedValue) { case "historic set till 2019": - dsId = Models.Settings.get("lui:datasetTill2019ComponentsSet").ToString(); + dsId = settings.GetValueByKey("lui:datasetTill2019ComponentsSet").ToString(); break; case "historic set till 2023": - dsId = Models.Settings.get("lui:datasetTill2023ComponentsSet").ToString(); + dsId = settings.GetValueByKey("lui:datasetTill2023ComponentsSet").ToString(); break; case "default components set": - dsId = Models.Settings.get("lui:datasetDefaultComponentsSet").ToString(); + dsId = settings.GetValueByKey("lui:datasetDefaultComponentsSet").ToString(); break; } @@ -211,7 +224,8 @@ public ActionResult PrepareDownloadFile(string mimeType) // filename // use unix timestamp to make filenames unique - string filename = Models.Settings.get("lui:filename:download") as string; + var settings = ModuleManager.GetModuleSettings("lui"); + string filename = settings.GetValueByKey("lui:filename:download") as string; //result datatable DataTable downloadData = new DataTable(); @@ -332,40 +346,42 @@ public ActionResult DownloadFile(string mimeType) //messsage for log string logMessage = ""; - + //send mail - var es = new EmailService(); - string user; + using (var es = new EmailService()) + { + string user; - LUIQueryModel model = (LUIQueryModel)Session["LUICalModel"]; + LUIQueryModel model = (LUIQueryModel)Session["LUICalModel"]; - string datasetId; - if (model.ComponentsSet.SelectedValue == "historic set till 2019") - datasetId = Models.Settings.get("lui:datasetTill2019ComponentsSet").ToString(); + var settings = ModuleManager.GetModuleSettings("lui"); - else if (model.ComponentsSet.SelectedValue == "historic set till 2023") - datasetId = Models.Settings.get("lui:datasetTill2023ComponentsSet").ToString(); - else - datasetId = Models.Settings.get("lui:datasetDefaultComponentsSet").ToString(); + string datasetId; + if (model.ComponentsSet.SelectedValue == "historic set till 2019") + datasetId = settings.GetValueByKey("lui:datasetTill2019ComponentsSet").ToString(); - string version = DataAccess.GetDatasetInfo(datasetId, GetServerInformation()).Version; + else if (model.ComponentsSet.SelectedValue == "historic set till 2023") + datasetId = settings.GetValueByKey("lui:datasetTill2023ComponentsSet").ToString(); + else + datasetId = settings.GetValueByKey("lui:datasetDefaultComponentsSet").ToString(); - if (model.IsPublicAccess) - { - user = "public downloaded"; - logMessage = "LUI Calculation public download. Id: " + datasetId + ", Version: " + version + ""; - } - else - { - logMessage = "LUI Calculation download. Id: " + datasetId + ", Version: " + version + ""; - using (UserManager userManager = new UserManager()) + string version = DataAccess.GetDatasetInfo(datasetId, GetServerInformation()).Version; + + if (model.IsPublicAccess) { - user = "downloaded by " + userManager.FindByNameAsync(HttpContext.User.Identity.Name).Result.DisplayName; + user = "public downloaded"; + logMessage = "LUI Calculation public download. Id: " + datasetId + ", Version: " + version + ""; + } + else + { + logMessage = "LUI Calculation download. Id: " + datasetId + ", Version: " + version + ""; + + user = "downloaded by " + _userManager.FindByNameAsync(HttpContext.User.Identity.Name).Result.DisplayName; } - } - string text = "LUI Calculation file \"" + Path.GetFileName(pathData) + "\" with id (" + datasetId + ") version (" + version + ") was " + user + ""; - es.Send("LUI data was downloaded (Id: " + datasetId + ", Version: " + version + ")", text, "bexis-sys@listserv.uni-jena.de"); + string text = "LUI Calculation file \"" + Path.GetFileName(pathData) + "\" with id (" + datasetId + ") version (" + version + ") was " + user + ""; + es.Send("LUI data was downloaded (Id: " + datasetId + ", Version: " + version + ")", text, "bexis-sys@listserv.uni-jena.de"); + } Vaiona.Logging.LoggerFactory.LogCustom(logMessage); @@ -394,24 +410,26 @@ private bool checkPreconditions() { // check for LUI new dataset bool exists = false; + var settings = ModuleManager.GetModuleSettings("lui"); + try { // check for LUI default dataset - string luiIdDefault = Models.Settings.get("lui:datasetDefaultComponentsSet").ToString(); + string luiIdDefault = settings.GetValueByKey("lui:datasetDefaultComponentsSet").ToString(); List statisticsDefault = DataAccess.GetStatistic(luiIdDefault, GetServerInformation()); var countDefault = statisticsDefault.Select(a => a.count).FirstOrDefault(); if(countDefault == "0") return exists == false; // check for LUI dataset till 2019 - string luiId2019 = Models.Settings.get("lui:datasetTill2019ComponentsSet").ToString(); + string luiId2019 = settings.GetValueByKey("lui:datasetTill2019ComponentsSet").ToString(); List statistics2019 = DataAccess.GetStatistic(luiId2019, GetServerInformation()); var count2019 = statistics2019.Select(a => a.count).FirstOrDefault(); if (count2019 == "0") return exists == false; // check for LUI dataset till 2023 - string luiId2023 = Models.Settings.get("lui:datasetTill2023ComponentsSet").ToString(); + string luiId2023 = settings.GetValueByKey("lui:datasetTill2023ComponentsSet").ToString(); List statistics2023 = DataAccess.GetStatistic(luiId2023, GetServerInformation()); var count2023 = statistics2023.Select(a => a.count).FirstOrDefault(); if (count2023 == "0") @@ -432,46 +450,68 @@ private bool checkPreconditions() /// Get current server und user information /// /// - public ServerInformation GetServerInformation() + /// + /// Get server information form json file in workspace + /// + /// + private ServerInformation GetServerInformation() { - //string filePath = Path.Combine(AppConfiguration.GetModuleWorkspacePath("LUI"), "Credentials.json"); - //string text = System.IO.File.ReadAllText(filePath); ServerInformation serverInformation = new ServerInformation(); var uri = System.Web.HttpContext.Current.Request.Url; - serverInformation.ServerName = uri.GetLeftPart(UriPartial.Authority); - serverInformation.Token = GetUserToken(); - + serverInformation.ServerName = uri.GetLeftPart(UriPartial.Authority) + "/"; + var settings = ModuleManager.GetModuleSettings("lui"); + serverInformation.UsernamePassword = settings.GetValueByKey("username") + ":" + settings.GetValueByKey("password"); return serverInformation; } + /// /// Get bexis token from logged-in user /// /// private string GetUserToken() { - var identityUserService = new IdentityUserService(); - var userManager = new UserManager(); - + string jwt_token = ""; try { - long userId = 0; - long.TryParse(this.User.Identity.GetUserId(), out userId); - if(userId==0) - return ""; - - var user = identityUserService.FindById(userId); - - user = identityUserService.FindById(userId); - var token = userManager.GetTokenAsync(user).Result; - return token; + var jwtConfiguration = GeneralSettings.JwtConfiguration; + + long userId = 0; + long.TryParse(this.User.Identity.GetUserId(), out userId); + var user = _userManager.FindByIdAsync(userId).Result; + //var user = identityUserService.FindById(userId); + + if (user != null) + { + var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfiguration.IssuerSigningKey)); + var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); + + //Create a List of Claims, Keep claims name short + var permClaims = new List + { + new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), + new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), + new Claim(ClaimTypes.Name, user.UserName) + }; + + //Create Security Token object by giving required parameters + var token = new JwtSecurityToken(jwtConfiguration.ValidIssuer, + jwtConfiguration.ValidAudience, + permClaims, + notBefore: DateTime.Now, + expires: DateTime.Now.AddHours(100000000), + signingCredentials: credentials); ; + + jwt_token = new JwtSecurityTokenHandler().WriteToken(token); + } } - finally + catch { - identityUserService.Dispose(); - userManager.Dispose(); + } + return jwt_token; + } /// diff --git a/Controllers/LUIComponentCalculationController.cs b/Controllers/LUIComponentCalculationController.cs index fe2593d..1715a24 100644 --- a/Controllers/LUIComponentCalculationController.cs +++ b/Controllers/LUIComponentCalculationController.cs @@ -1,24 +1,38 @@ using BExIS.Modules.Lui.UI.Helper; using BExIS.Modules.Lui.UI.Models; using BExIS.Security.Services.Subjects; +using BExIS.Utils.Config; using Microsoft.AspNet.Identity; +using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.Data; using System.Globalization; +using System.IdentityModel.Tokens.Jwt; using System.IO; using System.Linq; using System.Net; +using System.Security.Claims; +using System.Text; using System.Web; using System.Web.Mvc; using Vaiona.Utils.Cfg; using Vaiona.Web.Extensions; using Vaiona.Web.Mvc.Models; +using Vaiona.Web.Mvc.Modularity; namespace BExIS.Modules.Lui.UI.Controllers { public class LUIComponentCalculationController : Controller { + + private readonly UserManager _userManager; + + public LUIComponentCalculationController(UserManager userManager) + { + _userManager = userManager; + } + // GET: LUIComponentCalculation public ActionResult Index() { @@ -31,7 +45,10 @@ public ActionResult Index() public ActionResult CalculateCompontents() { Session["ComponentData"] = null; - string datasetId = Models.Settings.get("lui:lanuDataset").ToString(); + + var settings = ModuleManager.GetModuleSettings("lui"); + + string datasetId = settings.GetValueByKey("lui:lanuDataset").ToString(); //get data structureId long structureId = long.Parse(DataAccess.GetDatasetInfo(datasetId, GetServerInformation()).DataStructureId, CultureInfo.InvariantCulture); @@ -45,7 +62,7 @@ public ActionResult CalculateCompontents() //get plottype infos - string datasetIdPlots = Models.Settings.get("lui:epPlotsDataset").ToString(); + string datasetIdPlots = settings.GetValueByKey("lui:epPlotsDataset").ToString(); //get data structureId long structureIdPlots = long.Parse(DataAccess.GetDatasetInfo(datasetIdPlots, GetServerInformation()).DataStructureId, CultureInfo.InvariantCulture); DataTable plotTypes = DataAccess.GetData(datasetIdPlots, structureIdPlots, GetServerInformation()); @@ -126,7 +143,10 @@ public ActionResult UploadSelectedRows(int[] rowIds) DataApiModel model = new DataApiModel(); - model.DatasetId = Convert.ToInt64(Models.Settings.get("lui:datasetNewComponentsSet")); + + var settings = ModuleManager.GetModuleSettings("lui"); + + model.DatasetId = Convert.ToInt64(settings.GetValueByKey("lui:datasetNewComponentsSet")); model.DecimalCharacter = DecimalCharacter.point; //get col names @@ -156,8 +176,11 @@ public ActionResult UploadSelectedRows(int[] rowIds) DataRow row = copy.AsEnumerable().Where(a => a.Field("Id") == id).FirstOrDefault(); row.Table.Columns.Remove("Id"); - string[] stringArray = row.ItemArray.Cast().ToArray(); - dataArrays.Add(stringArray); + string[] stringArray = row.ItemArray + .Select(item => item?.ToString() ?? string.Empty) + .ToArray(); + + dataArrays.Add(stringArray); if (idsToUpload.Last() == id) result += id.ToString() + " "; @@ -188,48 +211,72 @@ public ActionResult UploadSelectedRows(int[] rowIds) private string GetUserToken() { - var identityUserService = new IdentityUserService(); - var userManager = new UserManager(); - + string jwt_token = ""; try { - long userId = 0; - long.TryParse(this.User.Identity.GetUserId(), out userId); + var jwtConfiguration = GeneralSettings.JwtConfiguration; + + long userId = 0; + long.TryParse(this.User.Identity.GetUserId(), out userId); + var user = _userManager.FindByIdAsync(userId).Result; + //var user = identityUserService.FindById(userId); - var user = identityUserService.FindById(userId); + if (user != null) + { + var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfiguration.IssuerSigningKey)); + var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); - user = identityUserService.FindById(userId); - var token = userManager.GetTokenAsync(user).Result; - return token; + //Create a List of Claims, Keep claims name short + var permClaims = new List + { + new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), + new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), + new Claim(ClaimTypes.Name, user.UserName) + }; + + //Create Security Token object by giving required parameters + var token = new JwtSecurityToken(jwtConfiguration.ValidIssuer, + jwtConfiguration.ValidAudience, + permClaims, + notBefore: DateTime.Now, + expires: DateTime.Now.AddHours(100000000), + signingCredentials: credentials); ; + + jwt_token = new JwtSecurityTokenHandler().WriteToken(token); + } } - finally + catch { - identityUserService.Dispose(); - userManager.Dispose(); + } + return jwt_token; + } /// /// Get server information form json file in workspace /// /// - public ServerInformation GetServerInformation() + /// + /// Get server information form json file in workspace + /// + /// + private ServerInformation GetServerInformation() { - //string filePath = Path.Combine(AppConfiguration.GetModuleWorkspacePath("LUI"), "Credentials.json"); - //string text = System.IO.File.ReadAllText(filePath); ServerInformation serverInformation = new ServerInformation(); var uri = System.Web.HttpContext.Current.Request.Url; serverInformation.ServerName = uri.GetLeftPart(UriPartial.Authority) + "/"; - serverInformation.Token = GetUserToken(); - + var settings = ModuleManager.GetModuleSettings("lui"); + serverInformation.UsernamePassword = settings.GetValueByKey("username") + ":" + settings.GetValueByKey("password"); return serverInformation; } - private int[] CheckDuplicates(DataTable newCompData, int[] rowIds) { - string luiIdNew = Models.Settings.get("lui:datasetNewComponentsSet").ToString(); + var settings = ModuleManager.GetModuleSettings("lui"); + + string luiIdNew = settings.GetValueByKey("lui:datasetNewComponentsSet").ToString(); long structureId = long.Parse(DataAccess.GetDatasetInfo(luiIdNew, GetServerInformation()).DataStructureId, CultureInfo.InvariantCulture); DataTable allCompData = DataAccess.GetData(luiIdNew, structureId, GetServerInformation()); diff --git a/Helper/DataAccess.cs b/Helper/DataAccess.cs index 7006e59..b9b9a9c 100644 --- a/Helper/DataAccess.cs +++ b/Helper/DataAccess.cs @@ -14,11 +14,13 @@ using System.Web.Script.Serialization; using System.Xml; using Vaiona.Utils.Cfg; +using Vaiona.Web.Mvc.Modularity; namespace BExIS.Modules.Lui.UI.Helper { public class DataAccess { + /// /// Get metadata /// @@ -28,7 +30,9 @@ public static XmlDocument GetMetadata(string datasetId, ServerInformation server { string link = serverInformation.ServerName + "/api/metadata/" + datasetId; HttpWebRequest request = WebRequest.Create(link) as HttpWebRequest; - request.Headers.Add("Authorization", "Bearer " + serverInformation.Token); + request.UseDefaultCredentials = true; + string myCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(serverInformation.UsernamePassword)); + request.Headers.Add("Authorization", "Basic " + myCredentials); XmlDocument document = new XmlDocument(); @@ -53,7 +57,9 @@ public static DataTable GetData(string datasetId, long structureId, ServerInform { string link = serverInformation.ServerName + "/api/data/" + datasetId; HttpWebRequest request = WebRequest.Create(link) as HttpWebRequest; - request.Headers.Add("Authorization", "Bearer " + serverInformation.Token); + request.UseDefaultCredentials = true; + string myCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(serverInformation.UsernamePassword)); + request.Headers.Add("Authorization", "Basic " + myCredentials); List statistics = GetStatistic(datasetId, serverInformation); @@ -61,10 +67,10 @@ public static DataTable GetData(string datasetId, long structureId, ServerInform //create datatable using data structure info DataTable data = new DataTable(); - foreach (var variable in dataStructureObject.Variables) + foreach (var variable in dataStructureObject.variables) { - DataColumn col = new DataColumn(variable.Label); - col.DataType = System.Type.GetType("System." + variable.SystemType); + DataColumn col = new DataColumn(variable.label); + col.DataType = System.Type.GetType("System." + variable.systemType); col.AllowDBNull = true; data.Columns.Add(col); } @@ -110,9 +116,29 @@ public static DataTable GetData(string datasetId, long structureId, ServerInform if (data.Columns[j].DataType == typeof(DateTime)) { - var format = dataStructureObject.Variables.Where(e => e.Label == data.Columns[j].ColumnName).FirstOrDefault().DataType; - format = format.Split('-').ToArray()[1]; - dr[data.Columns[j].ColumnName] = ParseValue(data.Columns[j].DataType.ToString(), value, format); + DateTime parsedDate; + + if (DateTime.TryParseExact( + value.ToString(), + "yyyy", + CultureInfo.InvariantCulture, + DateTimeStyles.None, + out parsedDate)) + { + dr[data.Columns[j].ColumnName] = parsedDate; + } + else if (DateTime.TryParse( + value.ToString(), + CultureInfo.InvariantCulture, + DateTimeStyles.None, + out parsedDate)) + { + dr[data.Columns[j].ColumnName] = parsedDate; + } + else + { + dr[data.Columns[j].ColumnName] = DBNull.Value; + } } else dr[data.Columns[j].ColumnName] = value; @@ -128,7 +154,7 @@ public static DataTable GetData(string datasetId, long structureId, ServerInform } catch (Exception e) { - + throw new Exception("Fehler beim Lesen der CSV/API-Daten", e); } @@ -139,7 +165,10 @@ public static List GetStatistic(string datasetId, ServerI { string link = serverInformation.ServerName + "/api/datastatistic/" + datasetId; HttpWebRequest request = WebRequest.Create(link) as HttpWebRequest; - request.Headers.Add("Authorization", "Bearer " + serverInformation.Token); + request.UseDefaultCredentials = true; + string myCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(serverInformation.UsernamePassword)); + request.Headers.Add("Authorization", "Basic " + myCredentials); + List data = new List(); @@ -171,7 +200,9 @@ public static List GetStatistic(string datasetId, ServerI public static List GetMissingComponentData(ServerInformation serverInformation) { List data = new List(); - string datasetId = Models.Settings.get("lui:datasetDefaultComponentsSet").ToString(); + var settings = ModuleManager.GetModuleSettings("lui"); + + string datasetId = settings.GetValueByKey("lui:datasetDefaultComponentsSet").ToString(); long structureId = long.Parse(DataAccess.GetDatasetInfo(datasetId, serverInformation).DataStructureId, CultureInfo.InvariantCulture); DataTable compData = GetData(datasetId, structureId, serverInformation); @@ -213,7 +244,10 @@ public static DatasetObject GetDatasetInfo(string datasetId, ServerInformation s { string link = serverInformation.ServerName + "/api/dataset/" + datasetId; HttpWebRequest request = WebRequest.Create(link) as HttpWebRequest; - request.Headers.Add("Authorization", "Bearer " + serverInformation.Token); + request.UseDefaultCredentials = true; + string myCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(serverInformation.UsernamePassword)); + request.Headers.Add("Authorization", "Basic " + myCredentials); + DatasetObject datasetObject = new DatasetObject(); @@ -246,7 +280,10 @@ public static DataStructureObject GetDataStructure(long structId, ServerInformat { string link = serverInformation.ServerName + "/api/structures/" + structId; HttpWebRequest request = WebRequest.Create(link) as HttpWebRequest; - request.Headers.Add("Authorization", "Bearer " + serverInformation.Token); + request.UseDefaultCredentials = true; + string myCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(serverInformation.UsernamePassword)); + request.Headers.Add("Authorization", "Basic " + myCredentials); + DataStructureObject dataStructureObject = new DataStructureObject(); @@ -278,12 +315,16 @@ public static DataStructureObject GetDataStructure(long structId, ServerInformat /// list of grasland ep plot ids public static List getAllGrasslandPlots(ServerInformation serverInformation) { - string datasetId = Models.Settings.get("lui:epPlotsDataset").ToString(); + var settings = ModuleManager.GetModuleSettings("lui"); + + string datasetId = settings.GetValueByKey("lui:epPlotsDataset").ToString(); string link = serverInformation.ServerName + "/api/data/" + datasetId; HttpWebRequest request = WebRequest.Create(link) as HttpWebRequest; - //request.PreAuthenticate = true; - request.Headers.Add("Authorization", "Bearer " + serverInformation.Token); + request.UseDefaultCredentials = true; + string myCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(serverInformation.UsernamePassword)); + request.Headers.Add("Authorization", "Basic " + myCredentials); + DataTable epPlotTable = new DataTable(); epPlotTable.Columns.Add("EP_Plotid"); @@ -339,8 +380,11 @@ public static string Upload(DataApiModel data, ServerInformation serverInformati { string link = serverInformation.ServerName + "/api/Data/"; HttpWebRequest request = WebRequest.Create(link) as HttpWebRequest; - //request.PreAuthenticate = true; - request.Headers.Add("Authorization", "Bearer " + serverInformation.Token); + request.UseDefaultCredentials = true; + string myCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(serverInformation.UsernamePassword)); + request.Headers.Add("Authorization", "Basic " + myCredentials); + + request.Method = "PUT"; request.ContentType = "application/json"; diff --git a/Helper/Settings.cs b/Helper/Settings.cs deleted file mode 100644 index 57fbe92..0000000 --- a/Helper/Settings.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml; -using System.Xml.Linq; -using Vaiona.Utils.Cfg; - -namespace BExIS.Modules.Lui.UI.Models -{ - public class Settings - { - - private static String filePath = Path.Combine(AppConfiguration.GetModuleWorkspacePath("LUI"), "Lui.settings.xml"); - private static Dictionary settings = new Dictionary(); - - /// - /// setup settings model - /// * load settings from settings.xml - /// - static Settings() - { - // intial loading of settings - reloadSettings(); - - // set up file watcher to listen for changes - using (FileSystemWatcher fw = new FileSystemWatcher()) - { - fw.Path = Path.GetDirectoryName(filePath); - fw.Filter = Path.GetFileName(filePath); - fw.Changed += new FileSystemEventHandler(fw_Changed); - fw.EnableRaisingEvents = true; - } - - } - - /// - /// retrieve a value from the settings file - /// - /// the key for the parameter - /// the respective value - public static object get( String key ) - { - if( settings.ContainsKey( key ) ) - { - return settings[ key ]; - } - else - { - return null; - } - } - - /// - /// add or change an entry in the settings - /// TODO persist changes in workflow file - /// - /// - /// - public static void set( String key, object value ) - { - if (settings.ContainsKey(key)) - { - settings[ key ] = value; - } - else - { - settings.Add( key, value ); - } - } - - /// - /// Handler to listen for changes in settings file - /// - /// - /// - private static void fw_Changed(object sender, FileSystemEventArgs e) - { - reloadSettings(); - } - - /// - /// load settings anew from settings.xml - /// - private static void reloadSettings() - { - // get XML data - XDocument xDoc = XDocument.Load(filePath); - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.Load(xDoc.CreateReader()); - - // empty old settings list - settings.Clear(); - - // parse values - foreach (XmlNode node in xmlDoc.SelectNodes("//settings/entry")) - { - // shortcuts - var key = node.Attributes["key"] != null ? node.Attributes["key"].Value : null; - var value = node.Attributes["value"] != null ? node.Attributes["value"].Value : null; - var type = node.Attributes["type"] != null ? node.Attributes["type"].Value : null; - - // only parse valid entries - if ((null == key) || (null == value)) - { - continue; - } - - // convert types - switch (type) - { - case "int": - int intVal; - if (Int32.TryParse(value, out intVal)) - { - settings.Add(key, intVal); - } - else - { - settings.Add(key, value); - } - break; - - // default is string - default: - settings.Add(key, value); - break; - } - } - } - - } -} \ No newline at end of file diff --git a/Lui.Settings.json b/Lui.Settings.json new file mode 100644 index 0000000..7f051ce --- /dev/null +++ b/Lui.Settings.json @@ -0,0 +1,137 @@ +{ + "id": "lui", + "name": "Index of land-use intensity", + "description": "...", + "entries": [ + { + "key": "help", + "title": "Help URL", + "value": "", + "type": "String", + "description": "URL to the manual. If empty, it links to the latest manual from BEXIS2" + }, + { + "key": "lui:datasetTill2019ComponentsSet", + "title": "dataset till 2019 componentsSet", + "value": 19266, + "description": "", + "type": "Int16", + "options": [] + }, + { + "key": "lui:datastructureTill2019ComponentsSet", + "title": "datastructure till 2019 componentsSet", + "value": 663, + "description": "", + "type": "Int16", + "options": [] + }, + { + "key": "lui:datasetTill2023ComponentsSet", + "title": "dataset till 2023 componentsSet", + "value": 25086, + "description": "", + "type": "Int16", + "options": [] + }, + { + "key": "lui:datastructureTill2023ComponentsSet", + "title": "datastructure till 2023 componentsSet", + "value": 1056, + "description": "", + "type": "Int16", + "options": [] + }, + { + "key": "lui:datasetDefaultComponentsSet", + "title": "dataset default componentsSet", + "value": 25086, + "description": "", + "type": "Int16", + "options": [] + }, + { + "key": "lui:datastructureDefaultComponentsSet", + "title": "datastructure default componentsSet", + "value": 1056, + "description": "", + "type": "Int16", + "options": [] + }, + { + "key": "lui:lanuDataset", + "title": "lanuDataset", + "value": 26487, + "description": "", + "type": "Int16", + "options": [] + }, + { + "key": "lui:epPlotsDataset", + "title": "epPlotsDataset", + "value": 20826, + "description": "", + "type": "Int16", + "options": [] + }, + { + "key": "lui:filename:download", + "title": "filename:download", + "value": "LUI", + "description": "", + "type": "String", + "options": [] + }, + { + "key": "lui:filename:namespace", + "title": "filename:namespace", + "value": "LUI", + "description": "", + "type": "String", + "options": [] + }, + { + "key": "lui:msg:alb", + "title": "", + "value": "", + "description": "", + "type": "String", + "options": [] + }, + { + "key": "lui:msg:hai", + "title": "", + "value": "", + "description": "", + "type": "String", + "options": [] + }, + { + "key": "lui:msg:sch", + "title": "", + "value": "", + "description": "", + "type": "String", + "options": [] + }, + { + "key": "username", + "title": "Username", + "value": "", + "description": "", + "type": "String", + "options": [] + }, + { + "key": "password", + "title": "Password", + "value": "", + "description": "", + "type": "String", + "options": [] + } + + + + ] +} \ No newline at end of file diff --git a/Models/ApiModels.cs b/Models/ApiModels.cs index c29ad7f..01d8099 100644 --- a/Models/ApiModels.cs +++ b/Models/ApiModels.cs @@ -1,4 +1,5 @@ -using System; +using BExIS.IO.Transform.Output; +using System; using System.Collections.Generic; using System.Data; using System.Linq; @@ -14,7 +15,7 @@ namespace BExIS.Modules.Lui.UI.Models public class ServerInformation { public string ServerName { get; set; } - public string Token { get; set; } + public string UsernamePassword { get; set; } } @@ -25,25 +26,52 @@ public class ServerInformation /// public class DataStructureObject { - public string Id { get; set; } - public string Title { get; set; } - public string Description { get; set; } - public string inUse { get; set; } - public string Structured { get; set; } - public List Variables { get; set; } + public int id { get; set; } + public string title { get; set; } + public string desciption { get; set; } + public bool inUse { get; set; } + public List variables { get; set; } } - public class Variables + public class Constraint { - public string Id { get; set; } - public string Label { get; set; } - public string Description { get; set; } - public string isOptional { get; set; } - public string Unit { get; set; } - public string DataType { get; set; } - public string SystemType { get; set; } - public string AttributeName { get; set; } - public string AttributeDescription { get; set; } + public int id { get; set; } + public string name { get; set; } + public string type { get; set; } + public string description { get; set; } + } + + public class Unit + { + public int id { get; set; } + public string name { get; set; } + public string abbrevation { get; set; } + public string description { get; set; } + public Dimension dimension { get; set; } + public string measurementSystem { get; set; } + } + + public class Dimension + { + public string name { get; set; } + public string description { get; set; } + public string specification { get; set; } + } + + public class Variable + { + public int id { get; set; } + public string label { get; set; } + public string description { get; set; } + public bool isOptional { get; set; } + public string dataType { get; set; } + public string systemType { get; set; } + public string displayPattern { get; set; } + public Unit unit { get; set; } + public List missingValues { get; set; } + public Template template { get; set; } + public List meanings { get; set; } + public List constraints { get; set; } } /// diff --git a/Properties/PublishProfiles/BexisServer_2010-testsite.pubxml b/Properties/PublishProfiles/BexisServer_2030-testsite.pubxml similarity index 93% rename from Properties/PublishProfiles/BexisServer_2010-testsite.pubxml rename to Properties/PublishProfiles/BexisServer_2030-testsite.pubxml index cafd5e3..83877a2 100644 --- a/Properties/PublishProfiles/BexisServer_2010-testsite.pubxml +++ b/Properties/PublishProfiles/BexisServer_2030-testsite.pubxml @@ -12,7 +12,7 @@ indem Sie diese MSBuild-Datei bearbeiten. Weitere Informationen hierzu finden Si True False - C:\inetpub\wwwroot\2010-TestSite\Site\Areas\LUI + C:\inetpub\wwwroot\2030-TestSite\Site\Areas\LUI False \ No newline at end of file diff --git a/Properties/PublishProfiles/BexisServer_BE_ProdSite.pubxml b/Properties/PublishProfiles/BexisServer_BE_ProdSite.pubxml new file mode 100644 index 0000000..d4eb971 --- /dev/null +++ b/Properties/PublishProfiles/BexisServer_BE_ProdSite.pubxml @@ -0,0 +1,18 @@ + + + + + FileSystem + FileSystem + Release + Any CPU + + True + False + C:\inetpub\wwwroot\BE_ProdSite\Site\Areas\LUI + False + + diff --git a/Views/LUICalculation/Index.cshtml b/Views/LUICalculation/Index.cshtml index 8ca1a11..ec18c59 100644 --- a/Views/LUICalculation/Index.cshtml +++ b/Views/LUICalculation/Index.cshtml @@ -1,9 +1,15 @@ @model BExIS.Modules.Lui.UI.Models.LUIQueryModel @using BExIS.Modules.Lui.UI.Models +@using Vaiona.Web.Mvc.Modularity; @section scripts { } +@{ + var settings = ModuleManager.GetModuleSettings("lui"); + +} + @using (Ajax.BeginForm( @@ -51,7 +57,7 @@
Plot coverage:
- @foreach(var percentage in missingCompData.ExploPercentage) + @foreach (var percentage in missingCompData.ExploPercentage) {
@percentage.Key : @percentage.Value
} @@ -66,7 +72,7 @@ }
- + } } @@ -92,9 +98,9 @@

Please select if you want to extract the raw data (unstandardized) OR if you want to calculate the LUI (standardized).

@@ -202,7 +208,7 @@
-
@Settings.get("lui:msg:alb")
@Settings.get("lui:msg:hai")
@Settings.get("lui:msg:sch")
+
@settings.GetValueByKey("lui:msg:alb").ToString()
@settings.GetValueByKey("lui:msg:hai").ToString()
@settings.GetValueByKey("lui:msg:sch").ToString()
@@ -247,7 +253,7 @@ data-downloadurl="@Url.Action("DownloadFile", "LUICalculation")" data-isPublic="@Model.IsPublicAccess"> -
Fetching Data
+
Fetching Data
@**@
diff --git a/packages.config b/packages.config index 9ae45e0..937c54b 100644 --- a/packages.config +++ b/packages.config @@ -2,7 +2,7 @@ - + @@ -21,16 +21,20 @@ + + + - + - - - + + + + diff --git a/web.config b/web.config index c953e67..fa53710 100644 --- a/web.config +++ b/web.config @@ -1,7 +1,15 @@  + - + @@ -14,7 +22,7 @@ - + @@ -54,7 +62,7 @@ - + @@ -74,19 +82,24 @@ - + + + + + - + - \ No newline at end of file + + \ No newline at end of file