From e2dbc825f78eefb4680164a637ccca70eb035569 Mon Sep 17 00:00:00 2001 From: Tobias Burger Date: Thu, 18 Aug 2022 15:10:36 +0200 Subject: [PATCH] Format with csharpier --- CDB/GetAccommodationDataCDB.cs | 685 +++++- DSS/GetDSSData.cs | 41 +- DSS/Parser/ParseDSSToODHActivityPoi.cs | 388 ++- DataModel/BDPResponse.cs | 2 +- DataModel/FCMModels.cs | 2 +- DataModel/GenericResults.cs | 36 +- DataModel/GpsConverter.cs | 25 +- DataModel/JsonBData.cs | 1 - DataModel/JsonRaw.cs | 12 +- DataModel/JsonResult.cs | 4 +- DataModel/MssResponse.cs | 21 +- DataModel/PushServerModels.cs | 86 +- DataModel/ReducedModels.cs | 45 +- DataModel/SuedtirolDB.cs | 652 +++-- DataModel/SuedtirolDBDestinationData.cs | 51 +- DataModel/SuedtirolDBLinked.cs | 1087 ++++++--- DataModel/SuedtirolDBMobile.cs | 35 +- DataModel/SuedtirolDBSpecial.cs | 9 +- EBMS/ImportEBMSData.cs | 94 +- Helper/Alpinebits/AlpineBitsHelper.cs | 1 - Helper/Extensions/DictionaryExtensions.cs | 7 +- Helper/Extensions/GpsExtensions.cs | 8 +- Helper/Extensions/QueryFactoryExtension.cs | 136 +- Helper/Extensions/String2HashExtensions.cs | 8 +- Helper/Flags/AccoListCreator.cs | 63 +- Helper/Flags/ActivityPoiListCreator.cs | 300 +-- Helper/Flags/ArticleListCreator.cs | 31 +- Helper/Flags/CommonListCreator.cs | 24 +- Helper/Flags/EventListCreator.cs | 3 - Helper/Flags/Flags.cs | 887 ++++++- Helper/Flags/FlagsHelper.cs | 38 +- Helper/Flags/GastronomyListCreator.cs | 53 +- Helper/Flags/VenueListCreator.cs | 2 - Helper/Generic/CopyClassHelper.cs | 13 +- Helper/Generic/CreateSeed.cs | 2 - Helper/Generic/DateTimeHelper.cs | 39 +- Helper/Generic/GeoSearchHelper.cs | 134 +- Helper/Generic/HasLanguageHelper.cs | 92 +- Helper/Generic/IdGenerator.cs | 84 +- Helper/Generic/LicenseHelper.cs | 64 +- Helper/Generic/MetaInfoHelper.cs | 65 +- Helper/Generic/ODHTypeHelper.cs | 74 +- Helper/Generic/PublishedOnHelper.cs | 2 +- Helper/GetAdditionalTypeInfo.cs | 48 +- Helper/JsonGeneratorHelper.cs | 78 +- Helper/JsonPathException.cs | 14 +- Helper/JsonTransformer/JsonTransformer.cs | 68 +- .../JsonTransformer/JsonTransformerMethods.cs | 258 +- Helper/Location/GetLocationInfo.cs | 294 ++- Helper/Location/LocHelper.cs | 4 +- Helper/Location/LocationListCreator.cs | 112 +- Helper/Models/HttpRequestLog.cs | 1 + Helper/Models/LogOutput.cs | 2 +- Helper/Models/WriteLog.cs | 10 +- Helper/Postgres/PostGresSQLHelper.cs | 160 +- Helper/Postgres/PostGresSQLHelperException.cs | 23 +- Helper/Postgres/PostgresSQLOrderByBuilder.cs | 107 +- Helper/Postgres/PostgresSQLQueryExtensions.cs | 2131 ++++++++++------- Helper/Postgres/PostgresSQLWhereBuilder.cs | 1029 +++++--- Helper/PostgresLicenseCountHelper.cs | 56 +- Helper/PushServer/PushServerMessageHelper.cs | 9 +- Helper/Reduced/ReduceDataHelper.cs | 344 ++- Helper/RoomCalculationHelper.cs | 77 +- Helper/StringHelpers.cs | 22 +- Helper/Tagging/GenericTaggingHelper.cs | 55 +- Helper/Tagging/LTSTaggingHelper.cs | 8 +- Helper/Tagging/ODHTagHelper.cs | 118 +- Helper/Tagging/SmgTagTransformer.cs | 73 +- JsonLDTransformer/Objects/LDDataTypes.cs | 53 +- JsonLDTransformer/TransformToLD.cs | 96 +- JsonLDTransformer/TransformToSchemaNet.cs | 1644 ++++++++++--- LCS/AccommodationDataLCS.cs | 89 +- LCS/GetActivityDataLCS.cs | 128 +- LCS/GetGastronomicDataLCS.cs | 42 +- LCS/GetPoiDataLCS.cs | 76 +- LCS/GetSnowReport.cs | 89 +- LCS/GetWeatherDataLCS.cs | 62 +- LCS/Parser/ParseAccoSearchResult.cs | 117 +- LCS/Parser/ParseActivityData.cs | 1174 +++++++-- LCS/Parser/ParseGastronomicData.cs | 693 +++++- LCS/Parser/ParseMeasuringPoint.cs | 82 +- LCS/Parser/ParsePoiData.cs | 683 ++++-- LCS/Parser/ParseSnowDataLive.cs | 220 +- LCS/Parser/ParseWebcamData.cs | 133 +- LCS/ServiceReferenceConfig.cs | 23 +- MSS/GetMssData.cs | 93 +- MSS/GetMssRoomList.cs | 66 +- MSS/GetMssSpecial.cs | 226 +- MSS/MssRequest.cs | 609 +++-- MSS/ParseMssResponse.cs | 683 +++++- MSS/ParseMssRoomResponse.cs | 76 +- MSS/ParseMssSpecialResponse.cs | 457 +++- MSS/Room.cs | 2 +- NINJA/GetNinjaInfo.cs | 17 +- NINJA/NinjaModels.cs | 7 +- NINJA/Parser/ParseNinjaData.cs | 189 +- .../Binders/CommaSeparatedArrayBinder.cs | 19 +- OdhApiCore/Binders/LegacyBool.cs | 8 +- OdhApiCore/Binders/PageSize.cs | 10 +- .../alpinebits/AlpineBitsApiController.cs | 229 +- .../api/AccommodationApiController.cs | 985 +++++--- .../Controllers/api/ActivityApiController.cs | 371 ++- .../Controllers/api/ArticleApiController.cs | 357 ++- .../Controllers/api/CommonApiController.cs | 1238 +++++++--- .../Controllers/api/EventApiController.cs | 387 ++- .../api/EventShortApiController.cs | 908 +++++-- .../api/GastronomyApiController.cs | 360 ++- .../api/ODHActivityPoiController.cs | 503 ++-- .../Controllers/api/OdhTagController.cs | 232 +- .../Controllers/api/PoiApiController.cs | 335 ++- .../Controllers/api/SearchController.cs | 184 +- OdhApiCore/Controllers/api/TagController.cs | 240 +- .../Controllers/api/VenueApiController.cs | 361 ++- .../Controllers/api/WeatherApiController.cs | 865 ++++--- .../api/WebcamInfoApiController.cs | 206 +- OdhApiCore/Controllers/base/MainController.cs | 23 +- OdhApiCore/Controllers/base/OdhController.cs | 117 +- .../Controllers/helper/AccommodationHelper.cs | 97 +- .../Controllers/helper/ActivityHelper.cs | 93 +- .../Controllers/helper/ArticleHelper.cs | 63 +- OdhApiCore/Controllers/helper/CommonHelper.cs | 51 +- OdhApiCore/Controllers/helper/EventHelper.cs | 78 +- .../Controllers/helper/EventShortHelper.cs | 68 +- .../Controllers/helper/GastronomyHelper.cs | 85 +- .../Controllers/helper/GenericHelper.cs | 58 +- OdhApiCore/Controllers/helper/LcsHelper.cs | 56 +- .../helper/MeasuringPointsHelper.cs | 70 +- OdhApiCore/Controllers/helper/MssHelper.cs | 64 +- .../helper/ODHActivityPoiHelper.cs | 205 +- OdhApiCore/Controllers/helper/PoiHelper.cs | 69 +- OdhApiCore/Controllers/helper/VenueHelper.cs | 81 +- .../Controllers/helper/WeatherHelper.cs | 37 +- .../Controllers/helper/WebcamInfoHelper.cs | 32 +- OdhApiCore/Controllers/helper/WineHelper.cs | 51 +- .../other/CompatiblityApiController.cs | 1926 +++++++++++---- .../Controllers/other/DeprecatedController.cs | 12 +- .../Controllers/other/FileUploadController.cs | 48 +- OdhApiCore/Controllers/other/GpxController.cs | 14 +- .../other/JsonGeneratorController.cs | 240 +- .../Controllers/other/JsonLDController.cs | 193 +- .../other/LicenseCountController.cs | 275 ++- .../Controllers/other/LocationController.cs | 475 +++- .../Controllers/other/ODHProxyController.cs | 11 +- OdhApiCore/Controllers/other/OdhAuthorize.cs | 9 +- .../other/PushNotificationController.cs | 85 +- .../Controllers/other/TestController.cs | 75 +- .../Controllers/other/UpdateApiController.cs | 649 ++++- OdhApiCore/Controllers/sta/STAController.cs | 149 +- .../DistributedCachingExtensions.cs | 26 +- .../Extensions/HttpContextExtensions.cs | 11 +- OdhApiCore/Factories/PostgresQueryFactory.cs | 17 +- .../AvailabilitySearchInterceptorAttribute.cs | 585 ++++- ...ullStringParameterActionFilterAttribute.cs | 6 +- OdhApiCore/Filters/OdhCacheOutputAttribute.cs | 3 +- .../Filters/RequestInterceptorAttribute.cs | 90 +- OdhApiCore/Formatters/CsvOutputFormatter.cs | 41 +- .../Formatters/JsonLdOutputFormatter.cs | 82 +- .../Formatters/RawdataOutputFormatter.cs | 29 +- .../GenericHelpers/CustomCacheKeyGenerator.cs | 9 +- OdhApiCore/GenericHelpers/RemoteIpHelper.cs | 11 +- OdhApiCore/GenericHelpers/STARequestHelper.cs | 257 +- .../Middleware/HttpRequestMiddleware.cs | 235 +- OdhApiCore/Middleware/RateLimitMiddleware.cs | 122 +- OdhApiCore/Pages/Index.cshtml.cs | 7 +- OdhApiCore/Program.cs | 7 +- OdhApiCore/Responses/ResponseHelpers.cs | 106 +- OdhApiCore/Settings.cs | 165 +- OdhApiCore/Startup.cs | 264 +- .../DeprecatedAttributeSchemaFilter.cs | 12 +- .../Swagger/EnumAttributeSchemaFilter.cs | 12 +- OdhApiCoreTests/Helper/FlagsHelperTests.cs | 37 +- .../Helper/JsonTransformerTests.cs | 12 +- .../Helper/PostgresSQLOrderByBuilderTests.cs | 6 +- .../Helper/PostgresSQLWhereBuilderTests.cs | 210 +- .../Helper/SmgTagTransformerTests.cs | 18 +- .../ActivityApiControllerTests.cs | 36 +- .../CustomWebApplicationFactory.cs | 7 +- .../IntegrationTests/FilterTests.cs | 17 +- .../IntegrationTests/PoiApiControllerTests.cs | 36 +- .../Controllers/DataModifyApiController.cs | 108 +- .../Controllers/JsonGeneratorController.cs | 45 +- OdhApiImporter/Controllers/TestController.cs | 1 - .../Controllers/UpdateApiController.cs | 333 ++- OdhApiImporter/DefaultBackgroundTaskQueue.cs | 18 +- .../Factories/PostgresQueryFactory.cs | 3 +- .../Helpers/CUSTOM/CustomDataOperation.cs | 138 +- OdhApiImporter/Helpers/DSS/DSSImportHelper.cs | 549 +++-- .../Helpers/EBMS/EBMSImportHelper.cs | 146 +- OdhApiImporter/Helpers/IImportHelper.cs | 22 +- .../Helpers/NINJA/NINJAImportHelper.cs | 200 +- .../Helpers/RAVEN/RAVENImportHelper.cs | 616 ++++- .../Helpers/SIAG/SIAGImportHelper.cs | 439 +++- OdhApiImporter/Helpers/STA/STAImportHelper.cs | 115 +- .../SUEDTIROLWEINImportHelper.cs | 21 +- OdhApiImporter/IBackgroundTaskQueue.cs | 6 +- OdhApiImporter/MonitorLoop.cs | 12 +- OdhApiImporter/Program.cs | 5 +- OdhApiImporter/QueuedHostedService.cs | 21 +- OdhApiImporter/Settings.cs | 77 +- OdhApiImporter/Startup.cs | 1 + PushServer/FCMMessageConstructor.cs | 21 +- PushServer/FCMPushNotification.cs | 88 +- PushServer/GetPushServerMessages.cs | 261 +- PushServer/SendToPushServer.cs | 181 +- RAVEN/GetDataFromRaven.cs | 37 +- RAVEN/TransformToPGObject.cs | 191 +- SIAG/GetMuseumDataFromSiag.cs | 13 +- SIAG/GetWeatherData.cs | 186 +- SIAG/GetWeatherFromSIAG.cs | 84 +- SIAG/Model/SiagWeatherModel.cs | 2 +- SIAG/Parser/ParseMuseum.cs | 23 +- SIAG/Parser/ParseWeather.cs | 834 +++++-- STA/GetDataFromSTA.cs | 18 +- STA/Models/STAVendingPoint.cs | 76 +- STA/Parser/ParseSTAPois.cs | 214 +- SuedtirolWein/GetSuedtirolWeinData.cs | 21 +- SuedtirolWein/Parser/ParseAwardData.cs | 26 +- SuedtirolWein/Parser/ParseCompanyData.cs | 259 +- 218 files changed, 28722 insertions(+), 10858 deletions(-) diff --git a/CDB/GetAccommodationDataCDB.cs b/CDB/GetAccommodationDataCDB.cs index 15e50359e..b210cba83 100644 --- a/CDB/GetAccommodationDataCDB.cs +++ b/CDB/GetAccommodationDataCDB.cs @@ -7,22 +7,38 @@ namespace CDB public class GetAccommodationDataCDB { public static CDBDataSoapClient.EndpointConfiguration GetEndpointConfig() - { + { //TODO CHECK IF THIS WORKS - CDBDataSoapClient.EndpointConfiguration myconfig = new CDBDataSoapClient.EndpointConfiguration(); + CDBDataSoapClient.EndpointConfiguration myconfig = + new CDBDataSoapClient.EndpointConfiguration(); return myconfig; } - //Hotel Daten S4 Methode - public static XDocument GetHotelDatafromCDB(string A0RIDList, string user, string pswd, string serviceurl) - { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); - + //Hotel Daten S4 Methode + public static XDocument GetHotelDatafromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) + { + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); + proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -31,14 +47,32 @@ public static XDocument GetHotelDatafromCDB(string A0RIDList, string user, strin } //Hotel Daten S4 Methode mit Sprache - public static XDocument GetHotelDatafromCDB(string A0RIDList, string language, string user, string pswd, string serviceurl) + public static XDocument GetHotelDatafromCDB( + string A0RIDList, + string language, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -46,15 +80,30 @@ public static XDocument GetHotelDatafromCDB(string A0RIDList, string language, s return myresponse; } - //Hotel Kategorieen - public static XDocument GetHotelCategoryfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + //Hotel Kategorieen + public static XDocument GetHotelCategoryfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -63,14 +112,29 @@ public static XDocument GetHotelCategoryfromCDB(string A0RIDList, string user, s } //Hotel Address Koord - public static XDocument GetHotelAddressCoordfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelAddressCoordfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -79,14 +143,29 @@ public static XDocument GetHotelAddressCoordfromCDB(string A0RIDList, string use } //Hotel Addresse - public static XDocument GetHotelAddressfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelAddressfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -95,14 +174,29 @@ public static XDocument GetHotelAddressfromCDB(string A0RIDList, string user, st } //Hotel Webdata - public static XDocument GetHotelWebdatafromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelWebdatafromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -110,15 +204,30 @@ public static XDocument GetHotelWebdatafromCDB(string A0RIDList, string user, st return myresponse; } - //Hotel Werbetexte - public static XDocument GetHotelPublicityfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + //Hotel Werbetexte + public static XDocument GetHotelPublicityfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -127,14 +236,29 @@ public static XDocument GetHotelPublicityfromCDB(string A0RIDList, string user, } //Hotel Position - public static XDocument GetHotelPositionfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelPositionfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -143,14 +267,29 @@ public static XDocument GetHotelPositionfromCDB(string A0RIDList, string user, s } //Hotel Overview - public static XDocument GetHotelOverviewfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelOverviewfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -159,14 +298,29 @@ public static XDocument GetHotelOverviewfromCDB(string A0RIDList, string user, s } //Hotel Features TINS - public static XDocument GetHotelTinfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelTinfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -175,14 +329,29 @@ public static XDocument GetHotelTinfromCDB(string A0RIDList, string user, string } //Hotel Foto - public static XDocument GetHotelFotofromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelFotofromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -191,14 +360,29 @@ public static XDocument GetHotelFotofromCDB(string A0RIDList, string user, strin } //Hotel Toursimverein? - public static XDocument GetHotelVGfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelVGfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -207,14 +391,29 @@ public static XDocument GetHotelVGfromCDB(string A0RIDList, string user, string } //Hotel POS Data - public static XDocument GetHotelPOSfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelPOSfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -223,14 +422,29 @@ public static XDocument GetHotelPOSfromCDB(string A0RIDList, string user, string } //Hotel TV PAy - public static XDocument GetHotelTVPayfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelTVPayfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -239,14 +453,29 @@ public static XDocument GetHotelTVPayfromCDB(string A0RIDList, string user, stri } //Hotel Iban - public static XDocument GetHotelIbanfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelIbanfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -255,14 +484,29 @@ public static XDocument GetHotelIbanfromCDB(string A0RIDList, string user, strin } //Hotel BAnkcoordinaten - public static XDocument GetHotelBankdatafromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelBankdatafromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -271,14 +515,29 @@ public static XDocument GetHotelBankdatafromCDB(string A0RIDList, string user, s } //HotelAdresstype - public static XDocument GetHotelTypeOfAddressfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelTypeOfAddressfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -287,14 +546,29 @@ public static XDocument GetHotelTypeOfAddressfromCDB(string A0RIDList, string us } //Hotelgallery - public static XDocument GetHotelGalleryfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelGalleryfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -303,14 +577,29 @@ public static XDocument GetHotelGalleryfromCDB(string A0RIDList, string user, st } //Hotel AstatDaten - public static XDocument GetHotelAstatBaseDatafromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelAstatBaseDatafromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -319,14 +608,29 @@ public static XDocument GetHotelAstatBaseDatafromCDB(string A0RIDList, string us } //Hotel GroupBase Data ?? - public static XDocument GetHotelGroupBaseDatafromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelGroupBaseDatafromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -335,14 +639,29 @@ public static XDocument GetHotelGroupBaseDatafromCDB(string A0RIDList, string us } //Hotel GroupName ?? - public static XDocument GetHotelGroupNamefromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelGroupNamefromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -351,14 +670,29 @@ public static XDocument GetHotelGroupNamefromCDB(string A0RIDList, string user, } //Hotel Group Definition - public static XDocument GetHotelGroupDefinitionfromCDB(string A0RIDList, string user, string pswd, string serviceurl) + public static XDocument GetHotelGroupDefinitionfromCDB( + string A0RIDList, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -369,12 +703,20 @@ public static XDocument GetHotelGroupDefinitionfromCDB(string A0RIDList, string //Alle Districts public static XDocument GetDistrictfromCDB(string user, string pswd, string serviceurl) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -385,12 +727,20 @@ public static XDocument GetDistrictfromCDB(string user, string pswd, string serv //Booking POS public static XDocument GetBookingPosfromCDB(string user, string pswd, string serviceurl) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -399,14 +749,29 @@ public static XDocument GetBookingPosfromCDB(string user, string pswd, string se } //Alle TINS - public static XDocument GetTinfromCDB(string showall, string user, string pswd, string serviceurl) + public static XDocument GetTinfromCDB( + string showall, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -417,12 +782,20 @@ public static XDocument GetTinfromCDB(string showall, string user, string pswd, //Tin Gruppen? public static XDocument GetTinGroupfromCDB(string user, string pswd, string serviceurl) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -431,14 +804,32 @@ public static XDocument GetTinGroupfromCDB(string user, string pswd, string serv } //Geänderte Hotels - public static XDocument GetHotelChangedfromCDB(DateTime startdate, string A0Ene, string user, string pswd, string serviceurl) + public static XDocument GetHotelChangedfromCDB( + DateTime startdate, + string A0Ene, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -447,14 +838,26 @@ public static XDocument GetHotelChangedfromCDB(DateTime startdate, string A0Ene, } //Hotel Categories (alle kategorien) - public static XDocument GetHotelCategorysfromCDB(string user, string pswd, string serviceurl) + public static XDocument GetHotelCategorysfromCDB( + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -465,12 +868,20 @@ public static XDocument GetHotelCategorysfromCDB(string user, string pswd, strin //Alle VGroupData public static XDocument GetVGroupDatafromCDB(string user, string pswd, string serviceurl) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -479,14 +890,29 @@ public static XDocument GetVGroupDatafromCDB(string user, string pswd, string se } //Alle VGroupData - public static XDocument GetVGroupBaseDatafromCDB(string G0RIDs, string user, string pswd, string serviceurl) + public static XDocument GetVGroupBaseDatafromCDB( + string G0RIDs, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -495,19 +921,31 @@ public static XDocument GetVGroupBaseDatafromCDB(string G0RIDs, string user, str } //Alle VGroupData - //G0RID RID of view (divided by ';') - //G0ID Group ID - //G0Typ Group-type: 0=general; 1=tourist association; 2=holiday regions; - //3= touristic area (Tourismusregion); 4=municipality; 5=Skiing region; 6=touristic relevant site - //(touristisch relevanter Ort) - public static XDocument GetVGroupHierarchyfromCDB(string user, string pswd, string serviceurl) + //G0RID RID of view (divided by ';') + //G0ID Group ID + //G0Typ Group-type: 0=general; 1=tourist association; 2=holiday regions; + //3= touristic area (Tourismusregion); 4=municipality; 5=Skiing region; 6=touristic relevant site + //(touristisch relevanter Ort) + public static XDocument GetVGroupHierarchyfromCDB( + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -518,12 +956,20 @@ public static XDocument GetVGroupHierarchyfromCDB(string user, string pswd, stri //VGroup NAme mit G0RID public static XDocument GetVGroupNamefromCDB(string user, string pswd, string serviceurl) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -534,12 +980,20 @@ public static XDocument GetVGroupNamefromCDB(string user, string pswd, string se //Group DAta public static XDocument GetGroupDatafromCDB(string user, string pswd, string serviceurl) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); @@ -548,14 +1002,29 @@ public static XDocument GetGroupDatafromCDB(string user, string pswd, string ser } //Independent - public static XDocument GetIndependentDatafromCDB(string A0RID, string user, string pswd, string serviceurl) + public static XDocument GetIndependentDatafromCDB( + string A0RID, + string user, + string pswd, + string serviceurl + ) { - var proxy = new ServiceReferenceCDBData.CDBDataSoapClient(GetEndpointConfig(), serviceurl); + var proxy = new ServiceReferenceCDBData.CDBDataSoapClient( + GetEndpointConfig(), + serviceurl + ); proxy.ClientCredentials.UserName.UserName = user; proxy.ClientCredentials.UserName.Password = pswd; - string sinput = ""; + string sinput = + ""; var xresponse = proxy.SendData(sinput); XDocument myresponse = XDocument.Parse(xresponse); diff --git a/DSS/GetDSSData.cs b/DSS/GetDSSData.cs index 6591151f8..4ebb8f47c 100644 --- a/DSS/GetDSSData.cs +++ b/DSS/GetDSSData.cs @@ -18,14 +18,19 @@ public class GetDSSData public const string serviceurlslopebase = "pistebasis"; public const string serviceurlslopestatus = "pistenstatus"; - - private static async Task RequestDSSInfo(DSSRequestType dssRequestType, string dssuser, string dsspswd, string serviceurl) + + private static async Task RequestDSSInfo( + DSSRequestType dssRequestType, + string dssuser, + string dsspswd, + string serviceurl + ) { try - { - switch(dssRequestType) + { + switch (dssRequestType) { - case DSSRequestType.liftbase: + case DSSRequestType.liftbase: serviceurl = serviceurl + serviceurlliftbase; break; case DSSRequestType.liftstatus: @@ -53,19 +58,33 @@ private static async Task RequestDSSInfo(DSSRequestType dss } catch (Exception ex) { - return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(ex.Message) }; + return new HttpResponseMessage + { + StatusCode = HttpStatusCode.BadRequest, + Content = new StringContent(ex.Message) + }; } } - - public static async Task GetDSSDataAsync(DSSRequestType dssRequestType, string dssuser, string dsspswd, string serviceurl) + + public static async Task GetDSSDataAsync( + DSSRequestType dssRequestType, + string dssuser, + string dsspswd, + string serviceurl + ) { //Request - HttpResponseMessage response = await RequestDSSInfo(dssRequestType, dssuser, dsspswd, serviceurl); + HttpResponseMessage response = await RequestDSSInfo( + dssRequestType, + dssuser, + dsspswd, + serviceurl + ); //Parse JSON Response to var responsetask = await response.Content.ReadAsStringAsync(); dynamic? responseobject = JsonConvert.DeserializeObject(responsetask); return responseobject; - } + } } -} \ No newline at end of file +} diff --git a/DSS/Parser/ParseDSSToODHActivityPoi.cs b/DSS/Parser/ParseDSSToODHActivityPoi.cs index 1cd4bf05c..abf911f22 100644 --- a/DSS/Parser/ParseDSSToODHActivityPoi.cs +++ b/DSS/Parser/ParseDSSToODHActivityPoi.cs @@ -10,9 +10,12 @@ namespace DSS.Parser { public class ParseDSSToODHActivityPoi - { - public static ODHActivityPoiLinked ParseDSSLiftDataToODHActivityPoi(ODHActivityPoiLinked? myodhactivitypoilinked, dynamic dssitem) - { + { + public static ODHActivityPoiLinked ParseDSSLiftDataToODHActivityPoi( + ODHActivityPoiLinked? myodhactivitypoilinked, + dynamic dssitem + ) + { if (myodhactivitypoilinked == null) myodhactivitypoilinked = new ODHActivityPoiLinked(); @@ -34,14 +37,13 @@ public static ODHActivityPoiLinked ParseDSSLiftDataToODHActivityPoi(ODHActivityP myodhactivitypoilinked.Mapping.TryAddOrUpdate("dss", dssidmap); - myodhactivitypoilinked.Type = "Anderes"; myodhactivitypoilinked.SubType = "Aufstiegsanlagen"; myodhactivitypoilinked.SmgTags = new List(); myodhactivitypoilinked.SmgTags.Add(myodhactivitypoilinked.Type.ToLower()); myodhactivitypoilinked.SmgTags.Add(myodhactivitypoilinked.SubType.ToLower()); - myodhactivitypoilinked.SmgTags.Add("weitere aufstiegsanlagen"); //? + myodhactivitypoilinked.SmgTags.Add("weitere aufstiegsanlagen"); //? myodhactivitypoilinked.HasLanguage = new List() { "de", "it", "en" }; @@ -50,8 +52,10 @@ public static ODHActivityPoiLinked ParseDSSLiftDataToODHActivityPoi(ODHActivityP var lastchangeobj = (string)dssitem["update-date"]; - if(double.TryParse(lastchangeobj, out double updatedate)) - myodhactivitypoilinked.LastChange = Helper.DateTimeHelper.UnixTimeStampToDateTime(updatedate); + if (double.TryParse(lastchangeobj, out double updatedate)) + myodhactivitypoilinked.LastChange = Helper.DateTimeHelper.UnixTimeStampToDateTime( + updatedate + ); //name var namede = (string)dssitem["name"]["de"]; @@ -73,16 +77,53 @@ public static ODHActivityPoiLinked ParseDSSLiftDataToODHActivityPoi(ODHActivityP var infotextsummerit = (string)dssitem["info-text-summer"]["it"]; var infotextsummeren = (string)dssitem["info-text-summer"]["en"]; - var additionaltextde = !String.IsNullOrEmpty(infotextwinterde) ? infotextwinterde : !String.IsNullOrEmpty(infotextsummerde) ? infotextsummerde : null; - var additionaltextit = !String.IsNullOrEmpty(infotextwinterit) ? infotextwinterit : !String.IsNullOrEmpty(infotextsummerit) ? infotextsummerit : null; - var additionaltexten = !String.IsNullOrEmpty(infotextwinteren) ? infotextwinteren : !String.IsNullOrEmpty(infotextsummeren) ? infotextsummeren : null; - - myodhactivitypoilinked.Detail.TryAddOrUpdate("de", new Detail() { Language = "de", Title= namede, BaseText = descde, AdditionalText = additionaltextde }); - myodhactivitypoilinked.Detail.TryAddOrUpdate("it", new Detail() { Language = "it", Title = nameit, BaseText = descit }); - myodhactivitypoilinked.Detail.TryAddOrUpdate("en", new Detail() { Language = "en", Title = nameen, BaseText = descen }); + var additionaltextde = !String.IsNullOrEmpty(infotextwinterde) + ? infotextwinterde + : !String.IsNullOrEmpty(infotextsummerde) + ? infotextsummerde + : null; + var additionaltextit = !String.IsNullOrEmpty(infotextwinterit) + ? infotextwinterit + : !String.IsNullOrEmpty(infotextsummerit) + ? infotextsummerit + : null; + var additionaltexten = !String.IsNullOrEmpty(infotextwinteren) + ? infotextwinteren + : !String.IsNullOrEmpty(infotextsummeren) + ? infotextsummeren + : null; + + myodhactivitypoilinked.Detail.TryAddOrUpdate( + "de", + new Detail() + { + Language = "de", + Title = namede, + BaseText = descde, + AdditionalText = additionaltextde + } + ); + myodhactivitypoilinked.Detail.TryAddOrUpdate( + "it", + new Detail() + { + Language = "it", + Title = nameit, + BaseText = descit + } + ); + myodhactivitypoilinked.Detail.TryAddOrUpdate( + "en", + new Detail() + { + Language = "en", + Title = nameen, + BaseText = descen + } + ); //lifttype TODO Mapping - if(dssitem["lifttype"] != null) + if (dssitem["lifttype"] != null) { List lifftype = ParseDSSTypeToODHType(dssitem["lifttype"]); foreach (var tag in lifftype) @@ -90,20 +131,26 @@ public static ODHActivityPoiLinked ParseDSSLiftDataToODHActivityPoi(ODHActivityP myodhactivitypoilinked.SmgTags.Add(tag); } } - - //skiresort TODO Mapping + + //skiresort TODO Mapping //Operationschedule (opening-times, opening-times-summer, season-summer, season-winter) myodhactivitypoilinked.OperationSchedule = new List(); - var winteroperationschedule = ParseDSSLiftToODHOperationScheduleFormat("winter", dssitem.data); + var winteroperationschedule = ParseDSSLiftToODHOperationScheduleFormat( + "winter", + dssitem.data + ); - if(winteroperationschedule != null) + if (winteroperationschedule != null) myodhactivitypoilinked.OperationSchedule.Add(winteroperationschedule); - var summeroperationschedule = ParseDSSLiftToODHOperationScheduleFormat("summer", dssitem.data); + var summeroperationschedule = ParseDSSLiftToODHOperationScheduleFormat( + "summer", + dssitem.data + ); - if(summeroperationschedule != null) + if (summeroperationschedule != null) myodhactivitypoilinked.OperationSchedule.Add(summeroperationschedule); //Properties (length, capacity, capacity-per-hour, altitude-start, altitude-end, height-difference, summercard-points, bike-transport, duration) @@ -122,32 +169,29 @@ public static ODHActivityPoiLinked ParseDSSLiftDataToODHActivityPoi(ODHActivityP var biketransport = (bool?)dssitem["data"]["bike-transport"]; myodhactivitypoilinked.BikeTransport = biketransport; - var capacity = (int?)dssitem["data"]["capacity"]; var capacityperhour = (int?)dssitem["data"]["capacity-per-hour"]; var summercardpointsup = (int?)dssitem["data"]["summercard-points"]["up"]; var summercardpointsdown = (int?)dssitem["data"]["summercard-points"]["down"]; - //Other (regionId, duration, state-winter, state-summer, datacenterId, number, winterOperation, sorter, summerOperation, sorterSummer) - var duration = (string)dssitem["duration"]; + var duration = (string)dssitem["duration"]; myodhactivitypoilinked.DistanceDuration = ConvertToDistanceDuration(duration); var number = (string)dssitem["number"]; myodhactivitypoilinked.Number = number; - var regionid = (int?)dssitem["regionId"]; //Isopen - var statewinter = (int?)dssitem["state-winter"]; + var statewinter = (int?)dssitem["state-winter"]; //isopen? var statesummer = (int?)dssitem["state-summer"]; if (statewinter == 1 || statesummer == 1) myodhactivitypoilinked.IsOpen = true; else - myodhactivitypoilinked.IsOpen = false; + myodhactivitypoilinked.IsOpen = false; //? var datacenterId = (string?)dssitem["datacenterId"]; @@ -159,10 +203,17 @@ public static ODHActivityPoiLinked ParseDSSLiftDataToODHActivityPoi(ODHActivityP var sorterSummer = (bool?)dssitem["sorterSummer"]; //TODO SKIAREAINFO - - myodhactivitypoilinked.GpsTrack = ParseToODHGpsTrack((string)dssitem["geoPositionFile"]); - List gpsinfolist = ParseDSSLiftToODHGpsInfo(dssitem["location"], dssitem["locationMountain"], altitudestart, altitudeend); + myodhactivitypoilinked.GpsTrack = ParseToODHGpsTrack( + (string)dssitem["geoPositionFile"] + ); + + List gpsinfolist = ParseDSSLiftToODHGpsInfo( + dssitem["location"], + dssitem["locationMountain"], + altitudestart, + altitudeend + ); myodhactivitypoilinked.GpsInfo = gpsinfolist; //myodhactivitypoilinked.GpsPoints = gpsinfolist.ConvertGpsInfoToGpsPointsLinq(); @@ -174,7 +225,10 @@ public static ODHActivityPoiLinked ParseDSSLiftDataToODHActivityPoi(ODHActivityP return myodhactivitypoilinked; } - public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivityPoiLinked? myodhactivitypoilinked, dynamic dssitem) + public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi( + ODHActivityPoiLinked? myodhactivitypoilinked, + dynamic dssitem + ) { if (myodhactivitypoilinked == null) myodhactivitypoilinked = new ODHActivityPoiLinked(); @@ -198,7 +252,6 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity myodhactivitypoilinked.Mapping.TryAddOrUpdate("dss", dssidmap); - myodhactivitypoilinked.Type = "Winter"; myodhactivitypoilinked.SubType = "Skirundtouren Pisten"; @@ -208,7 +261,7 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity myodhactivitypoilinked.SmgTags.Add("pisten"); myodhactivitypoilinked.SmgTags.Add("ski alpin"); myodhactivitypoilinked.SmgTags.Add("piste"); - myodhactivitypoilinked.SmgTags.Add("weitere pisten"); //? + myodhactivitypoilinked.SmgTags.Add("weitere pisten"); //? myodhactivitypoilinked.HasLanguage = new List() { "de", "it", "en" }; @@ -218,7 +271,9 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity var lastchangeobj = (string)dssitem["update-date"]; if (double.TryParse(lastchangeobj, out double updatedate)) - myodhactivitypoilinked.LastChange = Helper.DateTimeHelper.UnixTimeStampToDateTime(updatedate); + myodhactivitypoilinked.LastChange = Helper.DateTimeHelper.UnixTimeStampToDateTime( + updatedate + ); //name var namede = (string)dssitem["name"]["de"]; @@ -235,35 +290,68 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity var infotextsummerit = (string)dssitem["info-text-winter"]["it"]; var infotextsummeren = (string)dssitem["info-text-winter"]["en"]; - var additionaltextde = !String.IsNullOrEmpty(infotextsummerde) ? infotextsummerde : null; - var additionaltextit = !String.IsNullOrEmpty(infotextsummerit) ? infotextsummerit : null; - var additionaltexten = !String.IsNullOrEmpty(infotextsummeren) ? infotextsummeren : null; - - myodhactivitypoilinked.Detail.TryAddOrUpdate("de", new Detail() { Language = "de", Title = namede, BaseText = descde, AdditionalText = additionaltextde }); - myodhactivitypoilinked.Detail.TryAddOrUpdate("it", new Detail() { Language = "it", Title = nameit, BaseText = descit }); - myodhactivitypoilinked.Detail.TryAddOrUpdate("en", new Detail() { Language = "en", Title = nameen, BaseText = descen }); + var additionaltextde = !String.IsNullOrEmpty(infotextsummerde) + ? infotextsummerde + : null; + var additionaltextit = !String.IsNullOrEmpty(infotextsummerit) + ? infotextsummerit + : null; + var additionaltexten = !String.IsNullOrEmpty(infotextsummeren) + ? infotextsummeren + : null; + + myodhactivitypoilinked.Detail.TryAddOrUpdate( + "de", + new Detail() + { + Language = "de", + Title = namede, + BaseText = descde, + AdditionalText = additionaltextde + } + ); + myodhactivitypoilinked.Detail.TryAddOrUpdate( + "it", + new Detail() + { + Language = "it", + Title = nameit, + BaseText = descit + } + ); + myodhactivitypoilinked.Detail.TryAddOrUpdate( + "en", + new Detail() + { + Language = "en", + Title = nameen, + BaseText = descen + } + ); var slopetype = (string)dssitem["slopetype"]; var slopetypecolor = (string)dssitem["slopeType"]; - //Slopetype Mapping if (slopetype != null || slopetypecolor != null) { - string parseddifficulty = ParseDSSSlopeTypeToODHDifficulty(slopetypecolor, slopetype); + string parseddifficulty = ParseDSSSlopeTypeToODHDifficulty( + slopetypecolor, + slopetype + ); myodhactivitypoilinked.Difficulty = parseddifficulty; myodhactivitypoilinked.Ratings = new Ratings() { Difficulty = parseddifficulty }; } - //skiresort TODO Mapping + //skiresort TODO Mapping //Operationschedule (opening-times, opening-times-summer, season-summer, season-winter) myodhactivitypoilinked.OperationSchedule = new List(); var operationschedule = ParseDSSSlopeToODHOperationScheduleFormat(dssitem); - if(operationschedule != null) + if (operationschedule != null) myodhactivitypoilinked.OperationSchedule.Add(operationschedule); //Properties (length, capacity, capacity-per-hour, altitude-start, altitude-end, height-difference, summercard-points, bike-transport, duration) @@ -283,7 +371,6 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity var floodlighted = (bool?)dssitem["data"]["flood-lighted"]; var valleyrun = (bool?)dssitem["data"]["valley-run"]; - //Other (regionId, duration, state-winter, state-summer, datacenterId, number, winterOperation, sorter, summerOperation, sorterSummer) var duration = (string)dssitem["duration"]; @@ -292,19 +379,20 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity var number = (string)dssitem["number"]; myodhactivitypoilinked.Number = number; - var regionid = (int?)dssitem["regionId"]; //isopen? var state = (int?)dssitem["state"]; myodhactivitypoilinked.IsOpen = Convert.ToBoolean(state); - //? + //? var datacenterId = (string?)dssitem["data"]["datacenterId"]; var sorterSummer = (bool?)dssitem["sorter"]; //TODO SKIAREAINFO - myodhactivitypoilinked.GpsTrack = ParseToODHGpsTrack((string)dssitem["geoPositionFile"]); + myodhactivitypoilinked.GpsTrack = ParseToODHGpsTrack( + (string)dssitem["geoPositionFile"] + ); List gpsinfolist = ParseDSSSlopeToODHGpsInfo(dssitem["location"], altitudeend); @@ -318,12 +406,15 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity return myodhactivitypoilinked; } - private static OperationSchedule? ParseDSSLiftToODHOperationScheduleFormat(string season, dynamic data) + private static OperationSchedule? ParseDSSLiftToODHOperationScheduleFormat( + string season, + dynamic data + ) { string summer = ""; - Dictionary seasonname = new Dictionary(); - if(season == "summer") + Dictionary seasonname = new Dictionary(); + if (season == "summer") { summer = "-summer"; seasonname.Add("de", "Sommersaison"); @@ -337,7 +428,6 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity seasonname.Add("en", "winterseason"); } - var seasonstart = (double?)data["season-" + season]["start"]; var seasonend = (double?)data["season-" + season]["end"]; @@ -347,19 +437,25 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity OperationSchedule operationSchedule = new OperationSchedule(); operationSchedule.Type = "1"; operationSchedule.OperationscheduleName = seasonname; - operationSchedule.Start = Helper.DateTimeHelper.UnixTimeStampToDateTime(seasonstart.Value); - operationSchedule.Stop = Helper.DateTimeHelper.UnixTimeStampToDateTime(seasonend.Value); - + operationSchedule.Start = Helper.DateTimeHelper.UnixTimeStampToDateTime( + seasonstart.Value + ); + operationSchedule.Stop = Helper.DateTimeHelper.UnixTimeStampToDateTime( + seasonend.Value + ); var openingtimestart = (string)data["opening-times" + summer]["start"]; var openingtimeend = (string)data["opening-times" + summer]["end"]; - var openingtimestartafternoon = (string)data["opening-times" + summer]["startAfternoon"]; - var openingtimeendafternoon = (string)data["opening-times" + summer]["endAfternoon"]; - + var openingtimestartafternoon = (string) + data["opening-times" + summer]["startAfternoon"]; + var openingtimeendafternoon = (string) + data["opening-times" + summer]["endAfternoon"]; operationSchedule.OperationScheduleTime = new List(); - if (!string.IsNullOrEmpty(openingtimestart) && !string.IsNullOrEmpty(openingtimeend)) + if ( + !string.IsNullOrEmpty(openingtimestart) && !string.IsNullOrEmpty(openingtimeend) + ) { OperationScheduleTime operationScheduleTime = new OperationScheduleTime(); operationScheduleTime.Timecode = 1; @@ -376,11 +472,16 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity operationSchedule.OperationScheduleTime.Add(operationScheduleTime); } - //Check if there is one or two openingtimes - if (!string.IsNullOrEmpty(openingtimestartafternoon) && !string.IsNullOrEmpty(openingtimeendafternoon) && openingtimestartafternoon != "00:00" && openingtimeendafternoon != "00:00") + if ( + !string.IsNullOrEmpty(openingtimestartafternoon) + && !string.IsNullOrEmpty(openingtimeendafternoon) + && openingtimestartafternoon != "00:00" + && openingtimeendafternoon != "00:00" + ) { - OperationScheduleTime operationScheduleTimeafternoon = new OperationScheduleTime(); + OperationScheduleTime operationScheduleTimeafternoon = + new OperationScheduleTime(); operationScheduleTimeafternoon.Timecode = 1; operationScheduleTimeafternoon.Monday = true; operationScheduleTimeafternoon.Tuesday = true; @@ -389,7 +490,9 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity operationScheduleTimeafternoon.Saturday = true; operationScheduleTimeafternoon.Sunday = true; - operationScheduleTimeafternoon.Start = TimeSpan.Parse(openingtimestartafternoon); + operationScheduleTimeafternoon.Start = TimeSpan.Parse( + openingtimestartafternoon + ); operationScheduleTimeafternoon.End = TimeSpan.Parse(openingtimeendafternoon); operationSchedule.OperationScheduleTime.Add(operationScheduleTimeafternoon); @@ -418,8 +521,12 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity OperationSchedule operationSchedule = new OperationSchedule(); operationSchedule.Type = "1"; operationSchedule.OperationscheduleName = seasonname; - operationSchedule.Start = Helper.DateTimeHelper.UnixTimeStampToDateTime(seasonstart.Value); - operationSchedule.Stop = Helper.DateTimeHelper.UnixTimeStampToDateTime(seasonend.Value); + operationSchedule.Start = Helper.DateTimeHelper.UnixTimeStampToDateTime( + seasonstart.Value + ); + operationSchedule.Stop = Helper.DateTimeHelper.UnixTimeStampToDateTime( + seasonend.Value + ); return operationSchedule; } @@ -427,19 +534,42 @@ public static ODHActivityPoiLinked ParseDSSSlopeDataToODHActivityPoi(ODHActivity return null; } - private static List ParseDSSLiftToODHGpsInfo(dynamic location, dynamic locationMountain, int? altitudestart = 0, int? altitudeend = 0) + private static List ParseDSSLiftToODHGpsInfo( + dynamic location, + dynamic locationMountain, + int? altitudestart = 0, + int? altitudeend = 0 + ) { List gpsinfolist = new List(); - if(location != null) + if (location != null) { var lat = (double?)location["lat"]; var lon = (double?)location["lon"]; - if(lat != null && lon != null) + if (lat != null && lon != null) { - gpsinfolist.Add(new GpsInfo() { AltitudeUnitofMeasure = "m", Altitude = altitudestart, Gpstype = "position", Latitude = lat.Value, Longitude = lon.Value }); - gpsinfolist.Add(new GpsInfo() { AltitudeUnitofMeasure = "m", Altitude = altitudestart, Gpstype = "valleystationpoint", Latitude = lat.Value, Longitude = lon.Value }); + gpsinfolist.Add( + new GpsInfo() + { + AltitudeUnitofMeasure = "m", + Altitude = altitudestart, + Gpstype = "position", + Latitude = lat.Value, + Longitude = lon.Value + } + ); + gpsinfolist.Add( + new GpsInfo() + { + AltitudeUnitofMeasure = "m", + Altitude = altitudestart, + Gpstype = "valleystationpoint", + Latitude = lat.Value, + Longitude = lon.Value + } + ); } } @@ -450,14 +580,26 @@ private static List ParseDSSLiftToODHGpsInfo(dynamic location, dynamic if (lat != null && lon != null) { - gpsinfolist.Add(new GpsInfo() { AltitudeUnitofMeasure = "m", Altitude = altitudeend, Gpstype = "mountainstationpoint", Latitude = lat.Value, Longitude = lon.Value }); + gpsinfolist.Add( + new GpsInfo() + { + AltitudeUnitofMeasure = "m", + Altitude = altitudeend, + Gpstype = "mountainstationpoint", + Latitude = lat.Value, + Longitude = lon.Value + } + ); } } return gpsinfolist; } - private static List ParseDSSSlopeToODHGpsInfo(dynamic location, int? altitudeend = 0) + private static List ParseDSSSlopeToODHGpsInfo( + dynamic location, + int? altitudeend = 0 + ) { List gpsinfolist = new List(); @@ -468,7 +610,16 @@ private static List ParseDSSSlopeToODHGpsInfo(dynamic location, int? al if (lat != null && lon != null) { - gpsinfolist.Add(new GpsInfo() { AltitudeUnitofMeasure = "m", Altitude = altitudeend, Gpstype = "position", Latitude = lat.Value, Longitude = lon.Value }); + gpsinfolist.Add( + new GpsInfo() + { + AltitudeUnitofMeasure = "m", + Altitude = altitudeend, + Gpstype = "position", + Latitude = lat.Value, + Longitude = lon.Value + } + ); } } @@ -478,8 +629,8 @@ private static List ParseDSSSlopeToODHGpsInfo(dynamic location, int? al private static List ParseToODHGpsTrack(dynamic geoPositionFile) { List gpstracklist = new List(); - - if(geoPositionFile != null && !String.IsNullOrEmpty(geoPositionFile)) + + if (geoPositionFile != null && !String.IsNullOrEmpty(geoPositionFile)) { GpsTrack track = new GpsTrack(); track.GpxTrackUrl = geoPositionFile; @@ -491,7 +642,7 @@ private static List ParseToODHGpsTrack(dynamic geoPositionFile) return gpstracklist; } - private static List ParseDSSTypeToODHType(dynamic lifttype) + private static List ParseDSSTypeToODHType(dynamic lifttype) { List odhtagstoadd = new List(); @@ -505,7 +656,7 @@ private static List ParseDSSTypeToODHType(dynamic lifttype) if (flagstring != null) odhtagstoadd.Add(flagstring.ToLower()); - //TODO Add Sessellift if it is of type + //TODO Add Sessellift if it is of type } return odhtagstoadd; } @@ -527,41 +678,47 @@ private static double ConvertToDistanceDuration(string distanceduration) else return 0; } - private static string ParseDSSSlopeTypeToODHDifficulty(string? slopeType, string? slopediff) { - if(!string.IsNullOrEmpty(slopeType)) + if (!string.IsNullOrEmpty(slopeType)) { switch (slopeType) { - case "blue": return "2"; - case "red": return "4"; - case "black": return "6"; - default: return "4"; + case "blue": + return "2"; + case "red": + return "4"; + case "black": + return "6"; + default: + return "4"; } } else { switch (slopediff) { - case "easy": return "2"; - case "medium": return "4"; - case "hard": return "6"; - default: return "4"; + case "easy": + return "2"; + case "medium": + return "4"; + case "hard": + return "6"; + default: + return "4"; } } - } } } //lifttype rid: 1, Seilbahn --> Seilbahn -//lifttype rid: 2, +//lifttype rid: 2, //lifttype rid: 3, Kabinenbahn --> Kabinenbahn //lifttype rid: 4, Unterirdische Bahn --> Unterirdische Bahn -//lifttype rid: 5, -//lifttype rid: 6, +//lifttype rid: 5, +//lifttype rid: 6, //lifttype rid: 7, Sessellift 2 --> Sessellift //lifttype rid: 8, Sessellift 3 --> Sessellift //lifttype rid: 9, Skilift --> Skilift @@ -575,41 +732,41 @@ private static string ParseDSSSlopeTypeToODHDifficulty(string? slopeType, string //lifttype rid: 17, Sessellift 6 --> Sessellift //lifttype rid: 18, Sessellift 8 --> Sessellift //lifttype rid: 19, Skiförderband --> Förderband -//lifttype rid: 20, +//lifttype rid: 20, //lifttype rid: 21, Sessellift 4 mit Kuppel --> 4er Sessellift kuppelbar //lifttype rid: 22, Sessellift 6 mit Kuppel --> 6er Sessellift kuppelbar //lifttype rid: 22, Sessellift 8 mit Kuppel --> 8er Sessellift kuppelbar //Skiresort rid 1 Falzarego -//Skiresort rid 8 Auronzo +//Skiresort rid 8 Auronzo //Skiresort rid 7 San Vito di Cadore --> not found -//Skiresort rid 4 Faloria -//Skiresort rid 2 Tofana -//Skiresort rid 5 Cristallo +//Skiresort rid 4 Faloria +//Skiresort rid 2 Tofana +//Skiresort rid 5 Cristallo //Skiresort rid 6 Misurina -//Skiresort rid 76 Fedare +//Skiresort rid 76 Fedare //Skiresort rid 9 Kronplatz -//Skiresort rid 10 Corvara -//Skiresort rid 11 Colfosco +//Skiresort rid 10 Corvara +//Skiresort rid 11 Colfosco //Skiresort rid 12 Stern -//Skiresort rid 13 San Cassiano -//Skiresort rid 14 Badia -//Skiresort rid 19 Wolkenstein - Dantercepies -//Skiresort rid 21 Wolkenstein - Plan de Gralba +//Skiresort rid 13 San Cassiano +//Skiresort rid 14 Badia +//Skiresort rid 19 Wolkenstein - Dantercepies +//Skiresort rid 21 Wolkenstein - Plan de Gralba //Skiresort rid 22 Wolkenstein - Sellajoch -//Skiresort rid 20 St. Cristina - Ciampinoi - Wolkenstein -//Skiresort rid 18 St. Cristina - Monte Pana -//Skiresort rid 16 St. Ulrich - Resciesa - Seceda - Col Raiser - St. Cristina +//Skiresort rid 20 St. Cristina - Ciampinoi - Wolkenstein +//Skiresort rid 18 St. Cristina - Monte Pana +//Skiresort rid 16 St. Ulrich - Resciesa - Seceda - Col Raiser - St. Cristina //Skiresort rid 17 St. Ulrich - Palmer - Furdenan -//Skiresort rid 23 Seiser Alm +//Skiresort rid 23 Seiser Alm //Skiresort rid 26 Canazei - Belvedere //Skiresort rid 27 Campitello Col Rodella -//Skiresort rid 25 Alba - Ciampac -//Skiresort rid 28 Pozza - Buffaure +//Skiresort rid 25 Alba - Ciampac +//Skiresort rid 28 Pozza - Buffaure //Skiresort rid 29 Vigo - Catinaccio -//Skiresort rid 31 Passo Fedaia - Marmolada -//Skiresort rid 30 Karerpass +//Skiresort rid 31 Passo Fedaia - Marmolada +//Skiresort rid 30 Karerpass //Skiresort rid 55 Arabba //Skiresort rid 65 Marmolada //Skiresort rid 32 Helm - Stiergarten - Rotwand @@ -620,7 +777,7 @@ private static string ParseDSSSlopeTypeToODHDifficulty(string? slopeType, string //Skiresort rid 38 Prags //Skiresort rid 77 Padola //Skiresort rid 39 Alpe Cermis -//Skiresort rid 43 Bellamonte +//Skiresort rid 43 Bellamonte //Skiresort rid 79 Alpe Lusia //Skiresort rid 28624570 Jochgrimm //Skiresort rid 44 Passo Lavazé @@ -633,8 +790,8 @@ private static string ParseDSSSlopeTypeToODHDifficulty(string? slopeType, string //Skiresort rid 47 San Martino di Castrozza - Carosello delle Malghe //Skiresort rid 48 San Martino di Castrozza - Colverde //Skiresort rid 49 San Martino di Castrozza - Pra delle Nasse -//Skiresort rid 70 Gitschberg - Jochtal -//Skiresort rid 69 Plose - Brixen +//Skiresort rid 70 Gitschberg - Jochtal +//Skiresort rid 69 Plose - Brixen //Skiresort rid 72 Feldthurns //Skiresort rid 73 Lüsen //Skiresort rid 74 Vilnösstal @@ -646,4 +803,3 @@ private static string ParseDSSSlopeTypeToODHDifficulty(string? slopeType, string //Skiresort rid 52 Zoldo //Skiresort rid 53 Palafavera //Skiresort rid 54 Selva di Cadore - diff --git a/DataModel/BDPResponse.cs b/DataModel/BDPResponse.cs index 3c0af573e..c4ed9558d 100644 --- a/DataModel/BDPResponse.cs +++ b/DataModel/BDPResponse.cs @@ -20,7 +20,7 @@ public class BDPData //public string sname { get; set; } //public string sorigin { get; set; } public BDPMetaData smetadata { get; set; } - //public BDPCoordinate scoordinate { get; set; } + //public BDPCoordinate scoordinate { get; set; } } public class BDPMetaData diff --git a/DataModel/FCMModels.cs b/DataModel/FCMModels.cs index c642d55d2..c493738f1 100644 --- a/DataModel/FCMModels.cs +++ b/DataModel/FCMModels.cs @@ -20,5 +20,5 @@ public class FCMNotification public string? sound { get; set; } public string? link { get; set; } public string? icon { get; set; } - } + } } diff --git a/DataModel/GenericResults.cs b/DataModel/GenericResults.cs index 51ec512ac..b33258333 100644 --- a/DataModel/GenericResults.cs +++ b/DataModel/GenericResults.cs @@ -55,17 +55,31 @@ public static UpdateDetail MergeUpdateDetail(IEnumerable updatedet int? created = 0; int? deleted = 0; - foreach(var updatedetail in updatedetails) + foreach (var updatedetail in updatedetails) { created = updatedetail.created + created; updated = updatedetail.updated + updated; deleted = updatedetail.deleted + deleted; } - return new UpdateDetail() { created = created, updated = updated, deleted = deleted }; + return new UpdateDetail() + { + created = created, + updated = updated, + deleted = deleted + }; } - public static UpdateResult GetSuccessUpdateResult(string id, string source, string operation, string updatetype, string message, string otherinfo, UpdateDetail detail, bool createlog) + public static UpdateResult GetSuccessUpdateResult( + string id, + string source, + string operation, + string updatetype, + string message, + string otherinfo, + UpdateDetail detail, + bool createlog + ) { var result = new UpdateResult() { @@ -84,14 +98,24 @@ public static UpdateResult GetSuccessUpdateResult(string id, string source, stri stacktrace = null }; - if(createlog) + if (createlog) Console.WriteLine(JsonConvert.SerializeObject(result)); return result; } - public static UpdateResult GetErrorUpdateResult(string id, string source, string operation, string updatetype, string message, string otherinfo, UpdateDetail detail, Exception ex, bool createlog) - { + public static UpdateResult GetErrorUpdateResult( + string id, + string source, + string operation, + string updatetype, + string message, + string otherinfo, + UpdateDetail detail, + Exception ex, + bool createlog + ) + { var result = new UpdateResult() { id = id, diff --git a/DataModel/GpsConverter.cs b/DataModel/GpsConverter.cs index 0030a6230..7d6bfb010 100644 --- a/DataModel/GpsConverter.cs +++ b/DataModel/GpsConverter.cs @@ -9,8 +9,10 @@ namespace DataModel { public static class GpsConverter { - - public static IDictionary ToGpsPointsDictionary(this ICollection gpsinfos, bool ltsactivitypoi = false) + public static IDictionary ToGpsPointsDictionary( + this ICollection gpsinfos, + bool ltsactivitypoi = false + ) { //ODHActivityPoi should already pass if (!ltsactivitypoi) @@ -22,7 +24,7 @@ public static IDictionary ToGpsPointsDictionary(this ICollectio .ToDictionary(x => x.Gpstype!, x => x); else return new Dictionary(); - } + } //For LTS POI & LTS Activity else { @@ -30,16 +32,22 @@ public static IDictionary ToGpsPointsDictionary(this ICollectio var positioncount = 0; foreach (var gpsinfo in gpsinfos) - { + { string postionstr = "position"; if (positioncount > 0) postionstr = postionstr + positioncount; - + if (gpsinfo.Gpstype == "Endpunkt" || gpsinfo.Gpstype == "Bergstation") gpspoints.Add("endposition", gpsinfo); - if (gpsinfo.Gpstype == "position" || gpsinfo.Gpstype == "Standpunkt" || gpsinfo.Gpstype == "Startpunkt" || gpsinfo.Gpstype == "Start und Ziel" || gpsinfo.Gpstype == "Talstation") + if ( + gpsinfo.Gpstype == "position" + || gpsinfo.Gpstype == "Standpunkt" + || gpsinfo.Gpstype == "Startpunkt" + || gpsinfo.Gpstype == "Start und Ziel" + || gpsinfo.Gpstype == "Talstation" + ) gpspoints.Add(postionstr, gpsinfo); positioncount = gpspoints.Where(x => x.Key == "position").Count(); @@ -47,12 +55,8 @@ public static IDictionary ToGpsPointsDictionary(this ICollectio return gpspoints; } - - - } - //public IDictionary GpsPoints //{ // get @@ -69,6 +73,5 @@ public static IDictionary ToGpsPointsDictionary(this ICollectio // } // } //} - } } diff --git a/DataModel/JsonBData.cs b/DataModel/JsonBData.cs index d0f22db1a..59f9ea607 100644 --- a/DataModel/JsonBData.cs +++ b/DataModel/JsonBData.cs @@ -30,4 +30,3 @@ public class RawDataStore public string raw { get; set; } } } - diff --git a/DataModel/JsonRaw.cs b/DataModel/JsonRaw.cs index 8cb84b2bc..1a2f40152 100644 --- a/DataModel/JsonRaw.cs +++ b/DataModel/JsonRaw.cs @@ -18,7 +18,13 @@ public override void WriteJson(JsonWriter writer, JsonRaw? value, JsonSerializer writer.WriteRawValue(value.Value); } - public override JsonRaw ReadJson(JsonReader reader, Type objectType, JsonRaw? existingValue, bool hasExistingValue, JsonSerializer serializer) + public override JsonRaw ReadJson( + JsonReader reader, + Type objectType, + JsonRaw? existingValue, + bool hasExistingValue, + JsonSerializer serializer + ) { string json = reader.ReadAsString(); return new JsonRaw(json); @@ -49,7 +55,9 @@ public void AddParameter(IDbCommand command, string name) public override string? ToString() { - throw new InvalidOperationException("ToString on JsonRaw shouldn't be called, there is somewhere an implicit ToString() happening (maybe from a manual JSON serialization)."); + throw new InvalidOperationException( + "ToString on JsonRaw shouldn't be called, there is somewhere an implicit ToString() happening (maybe from a manual JSON serialization)." + ); } public static explicit operator JsonRaw(string x) => new JsonRaw(x); diff --git a/DataModel/JsonResult.cs b/DataModel/JsonResult.cs index 8c8d89369..12740f7fa 100644 --- a/DataModel/JsonResult.cs +++ b/DataModel/JsonResult.cs @@ -54,6 +54,7 @@ public class JsonResultWithOnlineResultsAndResultIdLowercase : IResponse public int onlineResults { get; set; } public string? resultId { get; set; } public IEnumerable items { get; set; } = Enumerable.Empty(); + [JsonIgnore] public IEnumerable Items => items; } @@ -62,7 +63,8 @@ public class SearchResult : IResponse { public uint totalResults { get; set; } public string? searchTerm { get; set; } - public Dictionary detailedResults { get; set; } = new Dictionary(); + public Dictionary detailedResults { get; set; } = + new Dictionary(); public IEnumerable Items { get; set; } = Enumerable.Empty(); } diff --git a/DataModel/MssResponse.cs b/DataModel/MssResponse.cs index 1ea4689a9..2ce804527 100644 --- a/DataModel/MssResponse.cs +++ b/DataModel/MssResponse.cs @@ -10,7 +10,8 @@ public class MssResult public string? CheapestChannel { get; set; } public double? Cheapestprice { get; set; } public int? bookableHotels { get; set; } - public virtual ICollection MssResponseShort { get; set; } = new HashSet(); + public virtual ICollection MssResponseShort { get; set; } = + new HashSet(); } public class MssResponseShort @@ -48,7 +49,6 @@ public MssResponseShort() public virtual ICollection RoomDetails { get; set; } = new List(); public virtual ICollection CheapestOfferDetail { get; set; } - } public class RoomDetails @@ -69,14 +69,17 @@ public class RoomDetails //Zusatz RoomMax public int? Roommax { get; set; } + //Zusatz RoomMin public int? Roommin { get; set; } + //Zusatz RoomStd public int? Roomstd { get; set; } public string? Roomtitle { get; set; } public string? Roomdesc { get; set; } public string? RoomChannelLink { get; set; } + //public string Service { get; set; } public string? TotalPriceString { get; set; } @@ -121,7 +124,7 @@ public class CancelPolicy public DateTime? RefundableUntil { get; set; } public string? Description { get; set; } - public List Penalties { get; set; } //=> new List(); + public List Penalties { get; set; } //=> new List(); } public class Penalty @@ -140,7 +143,6 @@ public class CheapestOffer public int? RoomFree { get; set; } } - public class CheapestRoomCombination { public CheapestRoomCombination() @@ -155,14 +157,15 @@ public double Price { get { - return this.CheapestRoomCombinationDetail != null && this.CheapestRoomCombinationDetail.Count > 0 ? this.CheapestRoomCombinationDetail.Sum(x => x.Price) : 0; + return + this.CheapestRoomCombinationDetail != null + && this.CheapestRoomCombinationDetail.Count > 0 + ? this.CheapestRoomCombinationDetail.Sum(x => x.Price) + : 0; } } } - //TODO - public class MssResponseComplete - { - } + public class MssResponseComplete { } } diff --git a/DataModel/PushServerModels.cs b/DataModel/PushServerModels.cs index aae3dd883..302591d30 100644 --- a/DataModel/PushServerModels.cs +++ b/DataModel/PushServerModels.cs @@ -2,47 +2,45 @@ namespace DataModel { - public class PushServerMessage - { - public PushServerMessage() - { - - } - - public string? title { get; set; } - public string? text { get; set; } - public string? image { get; set; } - public string video { get; set; } - public PushServerDestination destination { get; set; } - } - - public class PushServerDestination - { - public string group { get; set; } - public string language { get; set; } - } - - public class PushServerCustomMessage - { - public PushServerCustomMessage() - { - destination = new Dictionary>(); - } - - public string title { get; set; } - public string text { get; set; } - - public PushServerCustom custom { get; set; } - //public Dictionary image { get; set; } - //public Dictionary video { get; set; } - public Dictionary> destination { get; set; } - } - - public class PushServerCustom - { - public string group { get; set; } - public string listId { get; set; } - public string listName { get; set; } - public string listOwner { get; set; } - } -} \ No newline at end of file + public class PushServerMessage + { + public PushServerMessage() { } + + public string? title { get; set; } + public string? text { get; set; } + public string? image { get; set; } + public string video { get; set; } + public PushServerDestination destination { get; set; } + } + + public class PushServerDestination + { + public string group { get; set; } + public string language { get; set; } + } + + public class PushServerCustomMessage + { + public PushServerCustomMessage() + { + destination = new Dictionary>(); + } + + public string title { get; set; } + public string text { get; set; } + + public PushServerCustom custom { get; set; } + + //public Dictionary image { get; set; } + //public Dictionary video { get; set; } + public Dictionary> destination { get; set; } + } + + public class PushServerCustom + { + public string group { get; set; } + public string listId { get; set; } + public string listName { get; set; } + public string listOwner { get; set; } + } +} diff --git a/DataModel/ReducedModels.cs b/DataModel/ReducedModels.cs index b086a61a7..7829cd3eb 100644 --- a/DataModel/ReducedModels.cs +++ b/DataModel/ReducedModels.cs @@ -8,50 +8,23 @@ namespace DataModel { #region ReducedClasses - public class LTSActivityLinkedReduced : LTSActivityLinked - { + public class LTSActivityLinkedReduced : LTSActivityLinked { } - } + public class LTSPoiLinkedReduced : LTSPoiLinked { } - public class LTSPoiLinkedReduced : LTSPoiLinked - { + public class LTSODHActivityPoiReduced : ODHActivityPoiLinked { } - } + public class AccommodationLinkedReduced : AccommodationLinked { } - public class LTSODHActivityPoiReduced : ODHActivityPoiLinked - { + public class EventLinkedReduced : EventLinked { } - } + public class GastronomyLinkedReduced : GastronomyLinked { } - public class AccommodationLinkedReduced : AccommodationLinked - { + public class MeasuringpointLinkedReduced : MeasuringpointLinked { } - } + public class WebcamInfoLinkedReduced : WebcamInfoLinked { } - public class EventLinkedReduced : EventLinked - { - - } - - public class GastronomyLinkedReduced : GastronomyLinked - { - - } - - public class MeasuringpointLinkedReduced : MeasuringpointLinked - { - - } - - public class WebcamInfoLinkedReduced : WebcamInfoLinked - { - - } - - public class DDVenueReduced : DDVenue - { - - } + public class DDVenueReduced : DDVenue { } #endregion } diff --git a/DataModel/SuedtirolDB.cs b/DataModel/SuedtirolDB.cs index db24d2596..186ba28ae 100644 --- a/DataModel/SuedtirolDB.cs +++ b/DataModel/SuedtirolDB.cs @@ -17,7 +17,7 @@ public interface IIdentifiable { string Id { get; set; } string? Shortname { get; set; } - } + } public interface IMetaData { @@ -32,11 +32,11 @@ public interface ILicenseInfo public interface ISource { [SwaggerSchema("Source of the Data")] - string? Source { get; set; } + string? Source { get; set; } } public interface IImportDateassigneable - { + { DateTime? FirstImport { get; set; } DateTime? LastChange { get; set; } } @@ -63,7 +63,7 @@ public interface IHasLanguage public interface IDetailInfosAware { - IDictionary Detail { get; set; } + IDictionary Detail { get; set; } } public interface IDetailInfos @@ -99,12 +99,12 @@ public interface IContactInfos } public interface IContactInfosAware - { + { IDictionary ContactInfos { get; set; } } public interface IImageGallery - { + { string? ImageName { get; set; } string? ImageUrl { get; set; } int? Width { get; set; } @@ -121,7 +121,7 @@ public interface IImageGallery } public interface IImageGalleryAware - { + { ICollection? ImageGallery { get; set; } } @@ -139,7 +139,7 @@ public interface IGpsInfo double Latitude { get; set; } double Longitude { get; set; } double? Altitude { get; set; } - string? AltitudeUnitofMeasure { get; set; } + string? AltitudeUnitofMeasure { get; set; } } public interface IGPSInfoAware @@ -181,7 +181,7 @@ public interface IGpsPolygon } public interface IGpsPolygonAware - { + { ICollection? GpsPolygon { get; set; } } @@ -213,9 +213,11 @@ public interface IWebcamAware public interface IOperationSchedules { IDictionary OperationscheduleName { get; set; } + //string OperationscheduleName { get; set; } DateTime Start { get; set; } DateTime Stop { get; set; } + //bool? ClosedonPublicHolidays { get; set; } ICollection? OperationScheduleTime { get; set; } @@ -238,7 +240,7 @@ public interface IOperationScheduleTime public interface ISmgTags { - ICollection? SmgTags { get; set; } + ICollection? SmgTags { get; set; } } public interface IRatings @@ -264,9 +266,9 @@ public interface ISuedtirolType int Level { get; set; } IDictionary TypeNames { get; set; } } - + public interface ITags - { + { IDictionary> Tags { get; set; } } @@ -276,9 +278,9 @@ public interface IPublishedOn } //ODHActivityPoi - + public interface IAdditionalPoiInfosAware - { + { IDictionary AdditionalPoiInfos { get; set; } } @@ -300,7 +302,7 @@ public interface IActivityStatus bool? IsWithLigth { get; set; } bool? HasRentals { get; set; } } - + //Article public interface IAdditionalArticleInfosAware @@ -341,9 +343,9 @@ public interface IEventDate TimeSpan? End { get; set; } TimeSpan? Entrance { get; set; } } - + #endregion - + #region District Municipality Region public class Region : BaseInfos, IImageGalleryAware, IWebcamAware, IGpsPolygon @@ -352,6 +354,7 @@ public Region() { DetailThemed = new Dictionary(); } + public IDictionary DetailThemed { get; set; } public ICollection? GpsPolygon { get; set; } @@ -379,7 +382,7 @@ public MetaRegion() public ICollection? RelatedContent { get; set; } } - + public class ExperienceArea : BaseInfos, IImageGalleryAware, IGpsPolygon { public ICollection? DistrictIds { get; set; } @@ -435,10 +438,11 @@ public class District : BaseInfos, IImageGalleryAware, IWebcamAware, IGpsPolygon public class Area : IIdentifiable, IActivateable, IImportDateassigneable, IMappingAware, ISource { public Area() - { + { Mapping = new Dictionary>(); Detail = new Dictionary(); } + public LicenseInfo LicenseInfo { get; set; } public string? Id { get; set; } public bool Active { get; set; } @@ -453,16 +457,13 @@ public Area() public string? LtsID { get; set; } public string? AreaType { get; set; } public DateTime? LastChange { get; set; } - public DateTime? FirstImport { get; set; } + public DateTime? FirstImport { get; set; } public IDictionary> Mapping { get; set; } public string Source { get; set; } public IDictionary Detail { get; set; } } - public class GeneralGroup : BaseInfos - { - - } + public class GeneralGroup : BaseInfos { } public class SkiArea : BaseInfos, IImageGalleryAware, IWebcamAware, IContactInfosAware { @@ -474,26 +475,28 @@ public SkiArea() public string? SkiRegionId { get; set; } public string? SkiAreaMapURL { get; set; } public string? TotalSlopeKm { get; set; } - + public string? SlopeKmBlue { get; set; } public string? SlopeKmRed { get; set; } public string? SlopeKmBlack { get; set; } public string? LiftCount { get; set; } - + public Nullable AltitudeFrom { get; set; } public Nullable AltitudeTo { get; set; } - public IDictionary SkiRegionName { get; set; } [SwaggerDeprecated("Deprecated use AreaIds")] public ICollection? AreaId { get; set; } - - public ICollection? AreaIds { get { return AreaId; } } + + public ICollection? AreaIds + { + get { return AreaId; } + } public ICollection? Webcam { get; set; } - + public LocationInfo? LocationInfo { get; set; } public ICollection? OperationSchedule { get; set; } @@ -513,7 +516,7 @@ public class SkiRegion : BaseInfos, IImageGalleryAware, IGpsPolygonAware, IWebca public ICollection? Webcam { get; set; } public ICollection? RelatedContent { get; set; } - } + } public class SmgTags : IIdentifiable, IImportDateassigneable, ILicenseInfo { @@ -528,12 +531,12 @@ public SmgTags() } public string? Id { get; set; } + [SwaggerDeprecated("Deprecated, refer to TagName")] public string? Shortname { get; set; } public IDictionary TagName { get; set; } public ICollection ValidForEntity { get; set; } - public ICollection Source { get; set; } @@ -544,6 +547,7 @@ public SmgTags() [SwaggerDeprecated("Deprecated, use Mapping")] public IDictionary IDMCategoryMapping { get; set; } + [SwaggerDeprecated("Deprecated, use Mapping")] public LTSTaggingInfo LTSTaggingInfo { get; set; } @@ -600,16 +604,13 @@ public class Marketinggroup : IIdentifiable #endregion - #region Activities & POIs + #region Activities & POIs public class LTSPoi : PoiBaseInfos, IGPSPointsAware { public IDictionary GpsPoints { - get - { - return this.GpsInfo.ToGpsPointsDictionary(true); - } + get { return this.GpsInfo.ToGpsPointsDictionary(true); } } } @@ -617,13 +618,10 @@ public class LTSActivity : PoiBaseInfos, IGPSPointsAware { public IDictionary GpsPoints { - get - { - return this.GpsInfo.ToGpsPointsDictionary(true); - } + get { return this.GpsInfo.ToGpsPointsDictionary(true); } } } - + public class ODHActivityPoi : PoiBaseInfos, IWebcamAware, ILicenseInfo, IGPSPointsAware { public ODHActivityPoi() @@ -637,7 +635,7 @@ public ODHActivityPoi() public IDictionary> PoiProperty { get; set; } public ICollection? PoiServices { get; set; } - //Neu + //Neu //public string? Source { get; set; } public string? SyncSourceInterface { get; set; } public string? SyncUpdateMode { get; set; } @@ -656,10 +654,7 @@ public ODHActivityPoi() public IDictionary>? AdditionalContact { get; set; } public IDictionary GpsPoints { - get - { - return this.GpsInfo.ToGpsPointsDictionary(); - } + get { return this.GpsInfo.ToGpsPointsDictionary(); } } } @@ -702,11 +697,15 @@ public string? Link return "ODHActivityPoi/" + this.Id; } } - else return "ODHActivityPoi/" + this.Id; + else + return "ODHActivityPoi/" + this.Id; } } - public string Self { get { return this.Link; } } + public string Self + { + get { return this.Link; } + } } public class RatingSources @@ -719,14 +718,28 @@ public class RatingSources #region Accommodations - public class Accommodation : TrustYouInfos, IIdentifiable, IActivateable, IGpsInfo, IImageGalleryAware, ISmgActive, IHasLanguage, IImportDateassigneable, ILicenseInfo, ISource, IMappingAware, IDistanceInfoAware, IPublishedOn, IGPSPointsAware + public class Accommodation + : TrustYouInfos, + IIdentifiable, + IActivateable, + IGpsInfo, + IImageGalleryAware, + ISmgActive, + IHasLanguage, + IImportDateassigneable, + ILicenseInfo, + ISource, + IMappingAware, + IDistanceInfoAware, + IPublishedOn, + IGPSPointsAware { public LicenseInfo LicenseInfo { get; set; } public Accommodation() { AccoDetail = new Dictionary(); - MssResponseShort = new List(); + MssResponseShort = new List(); Mapping = new Dictionary>(); } @@ -737,6 +750,7 @@ public Accommodation() [SwaggerDeprecated("Accommodation ID on the HGV System, use Mapping instead")] public string? HgvId { get; set; } + [SwaggerDeprecated("Use AccoDetail.lang.Name")] public string? Shortname { get; set; } @@ -763,7 +777,6 @@ public Accommodation() public DistanceInfo? DistanceInfo { get; set; } - public string? AccoCategoryId { get; set; } public string? AccoTypeId { get; set; } public string? DistrictId { get; set; } @@ -779,7 +792,7 @@ public Accommodation() public IDictionary? AccoDetail { get; set; } public ICollection? AccoBookingChannel { get; set; } public ICollection? ImageGallery { get; set; } - + public LocationInfo? LocationInfo { get; set; } public string? GastronomyId { get; set; } @@ -789,11 +802,13 @@ public Accommodation() public ICollection? MssResponseShort { get; set; } - [SwaggerSchema("Independent Data cooperative Independent")] + [SwaggerSchema( + "Independent Data cooperative Independent" + )] public IndependentData? IndependentData { get; set; } public ICollection? AccoRoomInfo { get; set; } - + public IDictionary GpsPoints { get @@ -802,22 +817,30 @@ public IDictionary GpsPoints { return new Dictionary { - { "position", new GpsInfo(){ Gpstype = "position", Altitude = this.Altitude, AltitudeUnitofMeasure = this.AltitudeUnitofMeasure, Latitude = this.Latitude, Longitude = this.Longitude } } + { + "position", + new GpsInfo() + { + Gpstype = "position", + Altitude = this.Altitude, + AltitudeUnitofMeasure = this.AltitudeUnitofMeasure, + Latitude = this.Latitude, + Longitude = this.Longitude + } + } }; } else { - return new Dictionary - { - }; + return new Dictionary { }; } } } - + public ICollection? PublishedOn { get; set; } - + public string? Source { get; set; } - + public IDictionary> Mapping { get; set; } } @@ -887,13 +910,21 @@ public abstract class TrustYouInfos public int TrustYouState { get; set; } } - public class AccoRoom : IIdentifiable, IImageGalleryAware, IHasLanguage, IImportDateassigneable, ILicenseInfo, ISource, IMappingAware, IPublishedOn + public class AccoRoom + : IIdentifiable, + IImageGalleryAware, + IHasLanguage, + IImportDateassigneable, + ILicenseInfo, + ISource, + IMappingAware, + IPublishedOn { public LicenseInfo LicenseInfo { get; set; } public AccoRoom() { - AccoRoomDetail = new Dictionary(); + AccoRoomDetail = new Dictionary(); Mapping = new Dictionary>(); } @@ -909,7 +940,7 @@ public AccoRoom() public ICollection? ImageGallery { get; set; } public ICollection? HasLanguage { get; set; } - + public string? LTSId { get; set; } public string? HGVId { get; set; } public string? Source { get; set; } @@ -926,7 +957,7 @@ public AccoRoom() public Nullable LastChange { get; set; } public Nullable FirstImport { get; set; } - + public ICollection? PublishedOn { get; set; } public IDictionary> Mapping { get; set; } @@ -966,7 +997,7 @@ public class IndependentDescription : ILanguage #region Gastronomy public class Gastronomy : GastronomyBaseInfos, IGPSPointsAware - { + { public IDictionary GpsPoints { get @@ -975,36 +1006,38 @@ public IDictionary GpsPoints { return new Dictionary { - { "position", new GpsInfo(){ Gpstype = "position", Altitude = this.Altitude, AltitudeUnitofMeasure = this.AltitudeUnitofMeasure, Latitude = this.Latitude, Longitude = this.Longitude } } + { + "position", + new GpsInfo() + { + Gpstype = "position", + Altitude = this.Altitude, + AltitudeUnitofMeasure = this.AltitudeUnitofMeasure, + Latitude = this.Latitude, + Longitude = this.Longitude + } + } }; } else { - return new Dictionary - { - }; + return new Dictionary { }; } } } - } + } #endregion #region Events - public class Event : EventBaseInfos - { - - } + public class Event : EventBaseInfos { } #endregion - #region Articles + #region Articles - public class Article : ArticleBaseInfos - { - - } + public class Article : ArticleBaseInfos { } #endregion @@ -1113,7 +1146,10 @@ public class Stationdata public int Maxtemp { get; set; } //Compatibility Reasons - public int MaxTemp { get { return Maxtemp; } } + public int MaxTemp + { + get { return Maxtemp; } + } } public class BezirksWeather @@ -1201,6 +1237,7 @@ public WeatherHistory() { Weather = new Dictionary(); } + public IDictionary Weather { get; set; } public LicenseInfo LicenseInfo { get; set; } @@ -1212,11 +1249,18 @@ public WeatherHistory() public string Id { get; set; } } - #endregion + #endregion #region Packages - public class Package : IIdentifiable, IActivateable, ISmgActive, ISmgTags, IImageGalleryAware, IHasLanguage, ISource + public class Package + : IIdentifiable, + IActivateable, + ISmgActive, + ISmgTags, + IImageGalleryAware, + IHasLanguage, + ISource { public LicenseInfo LicenseInfo { get; set; } @@ -1224,7 +1268,7 @@ public Package() { PackageDetail = new Dictionary(); Inclusive = new Dictionary(); - ChannelInfo = new Dictionary(); + ChannelInfo = new Dictionary(); } //IIdentifiable @@ -1293,11 +1337,11 @@ public Package() //MSS Result public ICollection? MssResponseShort { get; set; } - public EvalancheMapping? EvalancheMapping { get; set; } - + public EvalancheMapping? EvalancheMapping { get; set; } + public List? PublishedOn { get; set; } - public string? Source { get; set; } + public string? Source { get; set; } } public class Season @@ -1363,10 +1407,21 @@ public class ThemeDetail : ILanguage #region Measuringpoints - public class Measuringpoint : IIdentifiable, IActivateable, ISmgActive, IGpsInfo, ILicenseInfo, IImportDateassigneable, ISource, IMappingAware, IDistanceInfoAware, IPublishedOn, IGPSPointsAware + public class Measuringpoint + : IIdentifiable, + IActivateable, + ISmgActive, + IGpsInfo, + ILicenseInfo, + IImportDateassigneable, + ISource, + IMappingAware, + IDistanceInfoAware, + IPublishedOn, + IGPSPointsAware { public Measuringpoint() - { + { Mapping = new Dictionary>(); } @@ -1390,7 +1445,6 @@ public Measuringpoint() public string? AltitudeUnitofMeasure { get; set; } public DistanceInfo? DistanceInfo { get; set; } - //Observation public string? SnowHeight { get; set; } public string? newSnowHeight { get; set; } @@ -1403,7 +1457,7 @@ public Measuringpoint() public string? OwnerId { get; set; } public List? AreaIds { get; set; } - + public IDictionary GpsPoints { get @@ -1412,14 +1466,22 @@ public IDictionary GpsPoints { return new Dictionary { - { "position", new GpsInfo(){ Gpstype = "position", Altitude = this.Altitude, AltitudeUnitofMeasure = this.AltitudeUnitofMeasure, Latitude = this.Latitude, Longitude = this.Longitude } } + { + "position", + new GpsInfo() + { + Gpstype = "position", + Altitude = this.Altitude, + AltitudeUnitofMeasure = this.AltitudeUnitofMeasure, + Latitude = this.Latitude, + Longitude = this.Longitude + } + } }; } else { - return new Dictionary - { - }; + return new Dictionary { }; } } } @@ -1427,7 +1489,7 @@ public IDictionary GpsPoints public ICollection? PublishedOn { get; set; } public string? Source { get; set; } - + public IDictionary> Mapping { get; set; } } @@ -1442,6 +1504,7 @@ public WeatherObservation() public string? Level { get; set; } public string? LevelId { get; set; } public Dictionary WeatherStatus { get; set; } + //New public string? IconID { get; set; } public DateTime? Date { get; set; } @@ -1450,10 +1513,7 @@ public WeatherObservation() //SnowReport Base Data public class SnowReportBaseData { - public SnowReportBaseData() - { - - } + public SnowReportBaseData() { } public int Id { get; set; } public string? RID { get; set; } @@ -1480,7 +1540,7 @@ public SnowReportBaseData() //public string weathercode { get; set; } //public string observationtemperature { get; set; } - //Slopes Lifts + //Slopes Lifts public string? totalskilift { get; set; } public string? openskilift { get; set; } public string? totalskiliftkm { get; set; } @@ -1500,8 +1560,6 @@ public SnowReportBaseData() public string? totaliceskating { get; set; } public string? openiceskating { get; set; } - - //Contact public string? contactadress { get; set; } public string? contacttel { get; set; } @@ -1516,8 +1574,6 @@ public SnowReportBaseData() public string? contactgpsnorth { get; set; } public string? contactgpseast { get; set; } - - //public virtual ICollection Slopes { get; set; } //public virtual ICollection Tracks { get; set; } //public virtual ICollection Lifts { get; set; } @@ -1530,7 +1586,7 @@ public SnowReportBaseData() //Reduced Measuringpoint for Snow Report public class MeasuringpointReduced : ISource - { + { public string? Id { get; set; } public DateTime LastUpdate { get; set; } @@ -1563,7 +1619,14 @@ public class MeasuringpointReduced : ISource #region EventShort - public class EventShort : IIdentifiable, IImportDateassigneable, ISource, IMappingAware, ILicenseInfo, IPublishedOn, IGPSPointsAware + public class EventShort + : IIdentifiable, + IImportDateassigneable, + ISource, + IMappingAware, + ILicenseInfo, + IPublishedOn, + IGPSPointsAware { public EventShort() { @@ -1580,7 +1643,6 @@ public EventShort() public int EventId { get; set; } - public string? EventTextDE { get; set; } public string? EventTextIT { get; set; } public string? EventTextEN { get; set; } @@ -1590,24 +1652,33 @@ public EventShort() //Hauptbeschreibung public string? EventDescription { get; set; } + //Beschreibung DE public string? EventDescriptionDE { get; set; } + //Beschreibung IT public string? EventDescriptionIT { get; set; } + //Beschreibung EN public string? EventDescriptionEN { get; set; } + //Hauptsaal/ort public string? AnchorVenue { get; set; } + //Hauptsaal/ort soll für die Ausgabe verwendet werden public string? AnchorVenueShort { get; set; } + //letzte Änderung public DateTime ChangedOn { get; set; } + //Beginndatum public DateTime StartDate { get; set; } + //Beginnzeit //public string StartTime { get; set; } ////Ende Datum public DateTime EndDate { get; set; } + //Endzeit //public string EndTime { get; set; } @@ -1616,9 +1687,10 @@ public EventShort() //URL für externe Webseite (noch nicht ausgefüllt) public string? WebAddress { get; set; } + //Spezialfelder - + [RegularExpression("Y|N", ErrorMessage = "Only Y and N allowed")] [SwaggerEnum(new[] { "Y", "N" })] [SwaggerSchema("Active")] @@ -1649,7 +1721,7 @@ public EventShort() [SwaggerEnum(new[] { "Y", "N" })] public string? Display9 { get; set; } - + public string? CompanyName { get; set; } public string? CompanyId { get; set; } public string? CompanyAddressLine1 { get; set; } @@ -1681,7 +1753,7 @@ public EventShort() //gebuchten Sääle von spezifischen Event //Space : Code für Raum von DB //SpaceDesc: Beschreibung --> zu nehmen - //SpaceAbbrev: Abgekürzte Beschreibung + //SpaceAbbrev: Abgekürzte Beschreibung //SoaceType : EC = Eurac, NO = Noi //Comnment: entweder x oder leer --> x bedeutet bitte nicht anzeigen!!!!!!! //Subtitle: Untertitel vom Saal (anzeigen) @@ -1697,7 +1769,6 @@ public EventShort() public List? ImageGallery { get; set; } public string? VideoUrl { get; set; } - public List? TechnologyFields { get; set; } public List? CustomTagging { get; set; } @@ -1707,14 +1778,22 @@ public EventShort() public bool? ExternalOrganizer { get; set; } public string? Shortname { get; set; } - + public ICollection? PublishedOn { get; set; } public string? AnchorVenueRoomMapping { get { - return !String.IsNullOrEmpty(this.AnchorVenue) ? (this.AnchorVenue.StartsWith("NOI ") || this.AnchorVenue.StartsWith("Noi ") || this.AnchorVenue.StartsWith("noi ")) ? this.AnchorVenue.Remove(0, 3).Trim() : this.AnchorVenue : this.AnchorVenue; + return !String.IsNullOrEmpty(this.AnchorVenue) + ? ( + this.AnchorVenue.StartsWith("NOI ") + || this.AnchorVenue.StartsWith("Noi ") + || this.AnchorVenue.StartsWith("noi ") + ) + ? this.AnchorVenue.Remove(0, 3).Trim() + : this.AnchorVenue + : this.AnchorVenue; } } @@ -1722,19 +1801,21 @@ public string? AnchorVenueRoomMapping public DateTime? LastChange { get; set; } public bool? SoldOut { get; set; } - - [SwaggerSchema(" ActiveWeb Indicates if Event is shown on the Noi Website Section Events at NOI")] + + [SwaggerSchema( + " ActiveWeb Indicates if Event is shown on the Noi Website Section Events at NOI" + )] public bool? ActiveWeb { get; set; } [SwaggerSchema("ActiveCommunityApp Indicates if Event is shown on the Noi Community App")] public bool? ActiveCommunityApp { get; set; } public ICollection? HasLanguage { get; set; } - + public IDictionary> Mapping { get; set; } public ICollection? GpsInfo { get; set; } - + public IDictionary GpsPoints { get @@ -1745,9 +1826,7 @@ public IDictionary GpsPoints } else { - return new Dictionary - { - }; + return new Dictionary { }; } } } @@ -1771,7 +1850,15 @@ public string? SpaceDescRoomMapping { get { - return !String.IsNullOrEmpty(this.SpaceDesc) ? (this.SpaceDesc.StartsWith("NOI ") || this.SpaceDesc.StartsWith("Noi ") || this.SpaceDesc.StartsWith("noi ")) ? this.SpaceDesc.Remove(0, 3).Trim() : this.SpaceDesc : this.SpaceDesc; + return !String.IsNullOrEmpty(this.SpaceDesc) + ? ( + this.SpaceDesc.StartsWith("NOI ") + || this.SpaceDesc.StartsWith("Noi ") + || this.SpaceDesc.StartsWith("noi ") + ) + ? this.SpaceDesc.Remove(0, 3).Trim() + : this.SpaceDesc + : this.SpaceDesc; } } } @@ -1853,13 +1940,19 @@ public class DocumentPDF #region Wine - public class Wine : IIdentifiable, IImportDateassigneable, ILicenseInfo, ISource, IMappingAware, IPublishedOn + public class Wine + : IIdentifiable, + IImportDateassigneable, + ILicenseInfo, + ISource, + IMappingAware, + IPublishedOn { public LicenseInfo LicenseInfo { get; set; } public Wine() { - Detail = new Dictionary(); + Detail = new Dictionary(); Mapping = new Dictionary>(); } @@ -1870,7 +1963,7 @@ public Wine() public IDictionary Detail { get; set; } //public Dictionary Title { get; set; } - //public Dictionary WineName { get; set; } + //public Dictionary WineName { get; set; } public int Vintage { get; set; } public int Awardyear { get; set; } @@ -1890,13 +1983,12 @@ public Wine() public ICollection? HasLanguage { get; set; } public string? Source { get; set; } - + public IDictionary> Mapping { get; set; } public ICollection PublishedOn { get; set; } } - #endregion #region TypeInfos @@ -1939,12 +2031,9 @@ public AccoTypes() } //For Types Api - public class AccoFeatures : AccoTypes - { - - } + public class AccoFeatures : AccoTypes { } - //For Types Api + //For Types Api public class SmgPoiTypes { public SmgPoiTypes() @@ -1961,7 +2050,7 @@ public SmgPoiTypes() public IDictionary? TypeDesc { get; set; } } - //For Types Api + //For Types Api public class EventTypes { public EventTypes() @@ -1975,28 +2064,17 @@ public EventTypes() public Dictionary TypeDesc { get; set; } } - //For Types Api - public class ActivityTypes : SmgPoiTypes - { - - } - - //For Types Api - public class ArticleTypes : SmgPoiTypes - { - - } + //For Types Api + public class ActivityTypes : SmgPoiTypes { } - //For Types Api - public class PoiTypes : SmgPoiTypes - { + //For Types Api + public class ArticleTypes : SmgPoiTypes { } - } + //For Types Api + public class PoiTypes : SmgPoiTypes { } - //For Types Api - public class ODHActivityPoiTypes : SmgPoiTypes - { - } + //For Types Api + public class ODHActivityPoiTypes : SmgPoiTypes { } #endregion @@ -2018,7 +2096,7 @@ public class LicenseInfo public string? Author { get; set; } public bool ClosedData { get; set; } } - + public class LTSTaggingType { public LTSTaggingType() @@ -2037,7 +2115,21 @@ public LTSTaggingType() } //BaseInfos for Districts / Regions / Municipalities ... - public abstract class BaseInfos : IIdentifiable, IActivateable, IGpsInfo, ISmgTags, ISmgActive, IHasLanguage, IImportDateassigneable, ILicenseInfo, IDetailInfosAware, IContactInfosAware, ISource, IMappingAware, IDistanceInfoAware, IGPSPointsAware + public abstract class BaseInfos + : IIdentifiable, + IActivateable, + IGpsInfo, + ISmgTags, + ISmgActive, + IHasLanguage, + IImportDateassigneable, + ILicenseInfo, + IDetailInfosAware, + IContactInfosAware, + ISource, + IMappingAware, + IDistanceInfoAware, + IGPSPointsAware { public LicenseInfo LicenseInfo { get; set; } @@ -2053,15 +2145,19 @@ public BaseInfos() public bool Active { get; set; } public string? CustomId { get; set; } public string? Shortname { get; set; } - + [SwaggerDeprecated("Deprecated, use GpsPoints")] public string? Gpstype { get; set; } + [SwaggerDeprecated("Deprecated, use GpsPoints")] public double Latitude { get; set; } + [SwaggerDeprecated("Deprecated, use GpsPoints")] public double Longitude { get; set; } + [SwaggerDeprecated("Deprecated, use GpsPoints")] public Nullable Altitude { get; set; } + [SwaggerDeprecated("Deprecated, use GpsPoints")] public string? AltitudeUnitofMeasure { get; set; } @@ -2090,14 +2186,22 @@ public IDictionary GpsPoints { return new Dictionary { - { "position", new GpsInfo(){ Gpstype = "position", Altitude = this.Altitude, AltitudeUnitofMeasure = this.AltitudeUnitofMeasure, Latitude = this.Latitude, Longitude = this.Longitude } } + { + "position", + new GpsInfo() + { + Gpstype = "position", + Altitude = this.Altitude, + AltitudeUnitofMeasure = this.AltitudeUnitofMeasure, + Latitude = this.Latitude, + Longitude = this.Longitude + } + } }; } else { - return new Dictionary - { - }; + return new Dictionary { }; } } } @@ -2111,11 +2215,28 @@ public IDictionary GpsPoints public IDictionary> Mapping { get; set; } public DistanceInfo? DistanceInfo { get; set; } - } //BaseInfos for ODHActivityPois - public class PoiBaseInfos : IIdentifiable, IActivateable, IGeoDataInfoAware, IActivityStatus, IImageGalleryAware, IContactInfosAware, IAdditionalPoiInfosAware, ISmgTags, ISmgActive, IHasLanguage, IImportDateassigneable, ILicenseInfo, IDetailInfosAware, ISource, IMappingAware, IDistanceInfoAware, IGPSInfoAware, IPublishedOn + public class PoiBaseInfos + : IIdentifiable, + IActivateable, + IGeoDataInfoAware, + IActivityStatus, + IImageGalleryAware, + IContactInfosAware, + IAdditionalPoiInfosAware, + ISmgTags, + ISmgActive, + IHasLanguage, + IImportDateassigneable, + ILicenseInfo, + IDetailInfosAware, + ISource, + IMappingAware, + IDistanceInfoAware, + IGPSInfoAware, + IPublishedOn { public LicenseInfo LicenseInfo { get; set; } @@ -2123,7 +2244,7 @@ public PoiBaseInfos() { Detail = new Dictionary(); ContactInfos = new Dictionary(); - AdditionalPoiInfos = new Dictionary(); + AdditionalPoiInfos = new Dictionary(); Mapping = new Dictionary>(); Tags = new Dictionary>(); } @@ -2132,7 +2253,7 @@ public PoiBaseInfos() public string? OutdooractiveID { get; set; } public string? OutdooractiveElevationID { get; set; } - + public bool? CopyrightChecked { get; set; } public bool Active { get; set; } @@ -2142,25 +2263,30 @@ public PoiBaseInfos() [SwaggerDeprecated("Use Ratings.Difficulty")] public string? Difficulty { get; set; } - + [SwaggerDeprecated("Use AdditionalPoiInfos.Categories instead")] public string? Type { get; set; } + [SwaggerDeprecated("Use AdditionalPoiInfos.Categories instead")] public string? SubType { get; set; } + [SwaggerDeprecated("Use AdditionalPoiInfos.Categories instead")] public string? PoiType { get; set; } - - public DateTime? FirstImport { get; set; } + + public DateTime? FirstImport { get; set; } public DateTime? LastChange { get; set; } public bool SmgActive { get; set; } - + public LocationInfo? LocationInfo { get; set; } public string? TourismorganizationId { get; set; } [SwaggerDeprecated("Deprecated use AreaIds")] - public ICollection? AreaId { get; set; } - public ICollection? AreaIds { get { return AreaId; } } + public ICollection? AreaId { get; set; } + public ICollection? AreaIds + { + get { return AreaId; } + } public double? AltitudeDifference { get; set; } public double? AltitudeHighestPoint { get; set; } @@ -2170,7 +2296,6 @@ public PoiBaseInfos() public double? DistanceDuration { get; set; } public double? DistanceLength { get; set; } - public bool? IsOpen { get; set; } public bool? IsPrepared { get; set; } @@ -2180,13 +2305,13 @@ public PoiBaseInfos() public bool? HasFreeEntrance { get; set; } public bool? LiftAvailable { get; set; } public bool? FeetClimb { get; set; } - + public bool? BikeTransport { get; set; } public ICollection? OperationSchedule { get; set; } public ICollection? GpsInfo { get; set; } - public ICollection? GpsTrack { get; set; } + public ICollection? GpsTrack { get; set; } public ICollection? ImageGallery { get; set; } public IDictionary Detail { get; set; } @@ -2195,7 +2320,7 @@ public PoiBaseInfos() public ICollection? SmgTags { get; set; } public ICollection? HasLanguage { get; set; } - + public Ratings? Ratings { get; set; } public ICollection? Exposition { get; set; } @@ -2203,13 +2328,13 @@ public PoiBaseInfos() public List? ChildPoiIds { get; set; } public List? MasterPoiIds { get; set; } - + public int? WayNumber { get; set; } public string? Number { get; set; } public List? LTSTags { get; set; } - + public ICollection? PublishedOn { get; set; } public string? Source { get; set; } @@ -2222,7 +2347,23 @@ public PoiBaseInfos() } //BaseInfo Article - public abstract class ArticleBaseInfos : IIdentifiable, IActivateable, IImageGalleryAware, IContactInfosAware, IAdditionalArticleInfosAware, ISmgTags, ISmgActive, IImportDateassigneable, ILicenseInfo, IDetailInfosAware, ISource, IMappingAware, IGPSInfoAware, IDistanceInfoAware, IPublishedOn, IGPSPointsAware + public abstract class ArticleBaseInfos + : IIdentifiable, + IActivateable, + IImageGalleryAware, + IContactInfosAware, + IAdditionalArticleInfosAware, + ISmgTags, + ISmgActive, + IImportDateassigneable, + ILicenseInfo, + IDetailInfosAware, + ISource, + IMappingAware, + IGPSInfoAware, + IDistanceInfoAware, + IPublishedOn, + IGPSPointsAware { public LicenseInfo? LicenseInfo { get; set; } @@ -2244,6 +2385,7 @@ public ArticleBaseInfos() //Activity SubType public string? Type { get; set; } public string? SubType { get; set; } + //für BaseArticle //public string SubType2 { get; set; } @@ -2280,7 +2422,7 @@ public ArticleBaseInfos() public ICollection? SmgTags { get; set; } public ICollection? HasLanguage { get; set; } - + public IDictionary GpsPoints { get @@ -2291,13 +2433,11 @@ public IDictionary GpsPoints } else { - return new Dictionary - { - }; + return new Dictionary { }; } } } - + public ICollection? PublishedOn { get; set; } public string? Source { get; set; } @@ -2309,7 +2449,20 @@ public IDictionary GpsPoints } //BaseInfo Gastronomy - public abstract class GastronomyBaseInfos : IIdentifiable, IActivateable, IGpsInfo, IImageGalleryAware, IContactInfosAware, ISmgTags, ISmgActive, IImportDateassigneable, IDetailInfosAware, ISource, IMappingAware, IDistanceInfoAware, ILicenseInfo + public abstract class GastronomyBaseInfos + : IIdentifiable, + IActivateable, + IGpsInfo, + IImageGalleryAware, + IContactInfosAware, + ISmgTags, + ISmgActive, + IImportDateassigneable, + IDetailInfosAware, + ISource, + IMappingAware, + IDistanceInfoAware, + ILicenseInfo { public LicenseInfo LicenseInfo { get; set; } @@ -2327,11 +2480,12 @@ public GastronomyBaseInfos() public string? Type { get; set; } - //Region Fraktion + //Region Fraktion public string? DistrictId { get; set; } + //public string MunicipalityId { get; set; } - //public string RegionId { get; set; } - //public string TourismorganizationId { get; set; } + //public string RegionId { get; set; } + //public string TourismorganizationId { get; set; } public DateTime? FirstImport { get; set; } public DateTime? LastChange { get; set; } @@ -2352,7 +2506,6 @@ public GastronomyBaseInfos() //Wenn mearere sein aso public ICollection? OperationSchedule { get; set; } - //CapacityCeremony public int? MaxSeatingCapacity { get; set; } @@ -2393,7 +2546,22 @@ public GastronomyBaseInfos() } //BaseInfo Events - public abstract class EventBaseInfos : IIdentifiable, IActivateable, IImageGalleryAware, IGpsInfo, IContactInfosAware, ISmgTags, ISmgActive, IImportDateassigneable, IDetailInfosAware, ISource, IMappingAware, IDistanceInfoAware, ILicenseInfo, IPublishedOn, IGPSPointsAware + public abstract class EventBaseInfos + : IIdentifiable, + IActivateable, + IImageGalleryAware, + IGpsInfo, + IContactInfosAware, + ISmgTags, + ISmgActive, + IImportDateassigneable, + IDetailInfosAware, + ISource, + IMappingAware, + IDistanceInfoAware, + ILicenseInfo, + IPublishedOn, + IGPSPointsAware { public LicenseInfo LicenseInfo { get; set; } @@ -2417,18 +2585,17 @@ public EventBaseInfos() public Nullable DateBegin { get; set; } public Nullable DateEnd { get; set; } - + public DateTime? FirstImport { get; set; } public DateTime? LastChange { get; set; } - //GPS Info public string? Gpstype { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } public Nullable Altitude { get; set; } public string? AltitudeUnitofMeasure { get; set; } - + public string? OrgRID { get; set; } public int? Ranc { get; set; } public string? Ticket { get; set; } @@ -2437,16 +2604,15 @@ public EventBaseInfos() public string? Type { get; set; } public string Pdf { get; set; } - public string? DistrictId { get; set; } - public ICollection? DistrictIds { get; set; } + public string? DistrictId { get; set; } + public ICollection? DistrictIds { get; set; } public ICollection? ImageGallery { get; set; } - + public IDictionary Detail { get; set; } public ICollection? TopicRIDs { get; set; } public ICollection? Topics { get; set; } - public ICollection? EventPublisher { get; set; } public IDictionary EventAdditionalInfos { get; set; } @@ -2465,7 +2631,7 @@ public EventBaseInfos() public ICollection? HasLanguage { get; set; } public Nullable NextBeginDate { get; set; } - + public string Source { get; set; } public bool? GrpEvent { get; set; } public bool? EventBenefit { get; set; } @@ -2473,14 +2639,14 @@ public EventBaseInfos() public ICollection LTSTags { get; set; } public IDictionary> EventPrices { get; set; } - + //Only for LTS internal use //public IDictionary> EventVariants { get; set; } public IDictionary> Hashtag { get; set; } public EventOperationScheduleOverview EventOperationScheduleOverview { get; set; } - + public IDictionary GpsPoints { get @@ -2489,25 +2655,33 @@ public IDictionary GpsPoints { return new Dictionary { - { "position", new GpsInfo(){ Gpstype = "position", Altitude = this.Altitude, AltitudeUnitofMeasure = this.AltitudeUnitofMeasure, Latitude = this.Latitude, Longitude = this.Longitude } } + { + "position", + new GpsInfo() + { + Gpstype = "position", + Altitude = this.Altitude, + AltitudeUnitofMeasure = this.AltitudeUnitofMeasure, + Latitude = this.Latitude, + Longitude = this.Longitude + } + } }; } else { - return new Dictionary - { - }; + return new Dictionary { }; } } } - + public ICollection? PublishedOn { get; set; } public string ClassificationRID { get; set; } public ICollection EventCrossSelling { get; set; } public IDictionary EventDescAdditional { get; set; } - + public IDictionary> Mapping { get; set; } public DistanceInfo? DistanceInfo { get; set; } @@ -2522,14 +2696,17 @@ public class Topic public class Detail : IDetailInfos, ILanguage { public string? Header { get; set; } - //public string SiteHeader { get; set; } + + //public string SiteHeader { get; set; } public string? SubHeader { get; set; } public string? IntroText { get; set; } public string? BaseText { get; set; } public string? Title { get; set; } + //OLT //public string Alttext { get; set; } public string? AdditionalText { get; set; } + //NEW public string? MetaTitle { get; set; } public string? MetaDesc { get; set; } @@ -2539,7 +2716,7 @@ public class Detail : IDetailInfos, ILanguage public ICollection? Keywords { get; set; } - //New LTS Fields + //New LTS Fields public string? ParkingInfo { get; set; } public string? PublicTransportationInfo { get; set; } public string? AuthorTip { get; set; } @@ -2547,7 +2724,7 @@ public class Detail : IDetailInfos, ILanguage public string? EquipmentInfo { get; set; } } - //Special Element for Themed Content + //Special Element for Themed Content public class DetailThemed : ILanguage { public DetailThemed() @@ -2615,7 +2792,7 @@ public Webcam() [SwaggerDeprecated("Use GpsPoints instead")] public GpsInfo? GpsInfo { get; set; } - public int? ListPosition { get; set; } + public int? ListPosition { get; set; } public string? Streamurl { get; set; } public string? Previewurl { get; set; } @@ -2632,10 +2809,18 @@ public Webcam() //public string Source { get; set; } } - public class WebcamInfo : Webcam, IIdentifiable, IImportDateassigneable, ISource, ILicenseInfo, IMappingAware, IPublishedOn, IGPSPointsAware + public class WebcamInfo + : Webcam, + IIdentifiable, + IImportDateassigneable, + ISource, + ILicenseInfo, + IMappingAware, + IPublishedOn, + IGPSPointsAware { public WebcamInfo() - { + { Mapping = new Dictionary>(); } @@ -2656,7 +2841,7 @@ public WebcamInfo() public ICollection? AreaIds { get; set; } public ICollection? SmgTags { get; set; } - + public IDictionary GpsPoints { get @@ -2670,15 +2855,13 @@ public IDictionary GpsPoints } else { - return new Dictionary - { - }; + return new Dictionary { }; } } } public ICollection? PublishedOn { get; set; } - + public IDictionary> Mapping { get; set; } //Temporary Hack because GpsInfo here is a object instead of object list @@ -2686,7 +2869,9 @@ public ICollection GpsInfos { get { - return this.GpsInfo != null ? new List { this.GpsInfo } : new List(); + return this.GpsInfo != null + ? new List { this.GpsInfo } + : new List(); } } } @@ -2739,6 +2924,7 @@ public class ImageGalleryLocalized public string? ImageTitle { get; set; } public string? ImageDesc { get; set; } + //public string Language { get; set; } public Nullable IsInGallery { get; set; } public Nullable ListPosition { get; set; } @@ -2777,8 +2963,10 @@ public class AdditionalPoiInfos : IAdditionalPoiInfos, ILanguage [SwaggerDeprecated("Use Categories instead")] public string? MainType { get; set; } + [SwaggerDeprecated("Use Categories instead")] public string? SubType { get; set; } + [SwaggerDeprecated("Use Categories instead")] public string? PoiType { get; set; } @@ -2804,7 +2992,7 @@ public LTSTags() LTSTins = new List(); } - public string? Id { get; set; } + public string? Id { get; set; } public int Level { get; set; } public string? LTSRID { get; set; } public IDictionary TagName { get; set; } @@ -2878,22 +3066,28 @@ public class DishRates : IIdentifiable //public string Language { get; set; } } - [SwaggerSchema("Wiki Article on Wiki Article")] + [SwaggerSchema( + "Wiki Article on Wiki Article" + )] public class OperationSchedule : IOperationSchedules { public OperationSchedule() { OperationscheduleName = new Dictionary(); - } - public IDictionary OperationscheduleName { get; set; } - public DateTime Start { get; set; } + } + + public IDictionary OperationscheduleName { get; set; } + public DateTime Start { get; set; } public DateTime Stop { get; set; } + /// /// Type: 1 - Standard, 2 - Only day + month recurring (year not to consider) 3 - only month recurring (season: year and day not to consider) - /// - [SwaggerSchema("1 - Standard, 2 - Only day + month recurring (year not to consider) 3 - only month recurring (season: year and day not to consider), Wiki Article on Wiki Article")] + /// + [SwaggerSchema( + "1 - Standard, 2 - Only day + month recurring (year not to consider) 3 - only month recurring (season: year and day not to consider), Wiki Article on Wiki Article" + )] public string? Type { get; set; } - + public ICollection? OperationScheduleTime { get; set; } } @@ -2904,13 +3098,18 @@ public class OperationScheduleTime : IOperationScheduleTime public bool Monday { get; set; } public bool Tuesday { get; set; } public bool Wednesday { get; set; } + // Here for compatibility reasons [SwaggerDeprecated("Will be removed within 2021-12-31")] public bool Thuresday { get; set; } - public bool Thursday { get { return Thuresday; } } + public bool Thursday + { + get { return Thuresday; } + } public bool Friday { get; set; } public bool Saturday { get; set; } public bool Sunday { get; set; } + /// /// //1 = closed, 2 = open, 0 = undefined /// @@ -3117,6 +3316,5 @@ public class AreaInfo public IDictionary? Name { get; set; } } - #endregion - + #endregion } diff --git a/DataModel/SuedtirolDBDestinationData.cs b/DataModel/SuedtirolDBDestinationData.cs index 4a5c20a31..9807727c6 100644 --- a/DataModel/SuedtirolDBDestinationData.cs +++ b/DataModel/SuedtirolDBDestinationData.cs @@ -6,7 +6,13 @@ namespace DataModel { - public class DDVenue : IIdentifiable, IMetaData, IImportDateassigneable, ILicenseInfo, ISource, IMappingAware + public class DDVenue + : IIdentifiable, + IMetaData, + IImportDateassigneable, + ILicenseInfo, + ISource, + IMappingAware { public DDVenue() { @@ -16,14 +22,12 @@ public DDVenue() public string Self { - get - { - return "Venue/" + Uri.EscapeDataString(this.Id); - } + get { return "Venue/" + Uri.EscapeDataString(this.Id); } } public Metadata? _Meta { get; set; } public string? type { get; set; } + //public string id { get; set; } [JsonProperty("id")] public string? Id { get; set; } @@ -38,10 +42,13 @@ public string Self [JsonIgnore] public string? Shortname { get; set; } + [JsonIgnore] public DateTime? FirstImport { get; set; } - [JsonIgnore] + + [JsonIgnore] public DateTime? LastChange { get; set; } + [JsonIgnore] public LicenseInfo? LicenseInfo { get; set; } @@ -68,13 +75,25 @@ public ODHData() public bool Active { get; set; } public bool ODHActive { get; set; } + //public ICollection ODHTags { get; set; } public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } @@ -112,10 +131,7 @@ public class VenueType public string Self { - get - { - return "VenueTypes/" + Uri.EscapeDataString(this.Id); - } + get { return "VenueTypes/" + Uri.EscapeDataString(this.Id); } } } @@ -127,10 +143,7 @@ public class VenueSetup public string Self { - get - { - return "VenueTypes/" + Uri.EscapeDataString(this.Id); - } + get { return "VenueTypes/" + Uri.EscapeDataString(this.Id); } } } @@ -140,6 +153,7 @@ public class VenueRoomDetails public string Shortname { get; set; } public int? SquareMeters { get; set; } + //public int maxCapacity { get; set; } public bool? Indoor { get; set; } @@ -240,7 +254,10 @@ public class DDGeometry public class DDRelationships { - public IDictionary>? multimediaDescriptions { get; set; } + public IDictionary< + string, + ICollection + >? multimediaDescriptions { get; set; } public ICollection? subVenues { get; set; } } @@ -251,9 +268,9 @@ public class DDMultimediadescriptions public ICollection categories { get; set; } public DDAttributesMultimedia attributes { get; set; } public DDLinks links { get; set; } + //public DDRelationships relationships { get; set; } public DDRelationshipsMultiMedia relationships { get; set; } - } public class DDAttributesMultimedia diff --git a/DataModel/SuedtirolDBLinked.cs b/DataModel/SuedtirolDBLinked.cs index 960deae8d..8bacd1518 100644 --- a/DataModel/SuedtirolDBLinked.cs +++ b/DataModel/SuedtirolDBLinked.cs @@ -14,10 +14,7 @@ public class AccoFeatureLinked : AccoFeature { public string Self { - get - { - return "AccommodationFeatures/" + Uri.EscapeDataString(this.Id); - } + get { return "AccommodationFeatures/" + Uri.EscapeDataString(this.Id); } } } @@ -25,10 +22,7 @@ public class AccoRoomInfoLinked : AccoRoomInfo { public string Self { - get - { - return "AccommodationRoom/" + Uri.EscapeDataString(this.Id); - } + get { return "AccommodationRoom/" + Uri.EscapeDataString(this.Id); } } } @@ -36,10 +30,7 @@ public class TopicLinked : Topic { public string Self { - get - { - return "EventTopics/" + Uri.EscapeDataString(this.TopicRID); - } + get { return "EventTopics/" + Uri.EscapeDataString(this.TopicRID); } } } @@ -49,7 +40,9 @@ public string Self { get { - return String.IsNullOrEmpty(this.Id) ? null : "GastronomyTypes/" + Uri.EscapeDataString(this.Id); + return String.IsNullOrEmpty(this.Id) + ? null + : "GastronomyTypes/" + Uri.EscapeDataString(this.Id); } } } @@ -60,7 +53,9 @@ public string Self { get { - return String.IsNullOrEmpty(this.Id) ? null : "GastronomyTypes/" + Uri.EscapeDataString(this.Id); + return String.IsNullOrEmpty(this.Id) + ? null + : "GastronomyTypes/" + Uri.EscapeDataString(this.Id); } } } @@ -71,7 +66,9 @@ public string Self { get { - return String.IsNullOrEmpty(this.Id) ? null : "GastronomyTypes/" + Uri.EscapeDataString(this.Id); + return String.IsNullOrEmpty(this.Id) + ? null + : "GastronomyTypes/" + Uri.EscapeDataString(this.Id); } } } @@ -82,7 +79,9 @@ public string Self { get { - return String.IsNullOrEmpty(this.Id) ? null : "GastronomyTypes/" + Uri.EscapeDataString(this.Id); + return String.IsNullOrEmpty(this.Id) + ? null + : "GastronomyTypes/" + Uri.EscapeDataString(this.Id); } } } @@ -93,7 +92,9 @@ public string Self { get { - return String.IsNullOrEmpty(this.Id) ? null : "Region/" + Uri.EscapeDataString(this.Id); + return String.IsNullOrEmpty(this.Id) + ? null + : "Region/" + Uri.EscapeDataString(this.Id); } } } @@ -104,7 +105,9 @@ public string Self { get { - return String.IsNullOrEmpty(this.Id) ? null : "TourismAssociation/" + Uri.EscapeDataString(this.Id); + return String.IsNullOrEmpty(this.Id) + ? null + : "TourismAssociation/" + Uri.EscapeDataString(this.Id); } } } @@ -115,7 +118,9 @@ public string Self { get { - return String.IsNullOrEmpty(this.Id) ? null : "Municipality/" + Uri.EscapeDataString(this.Id); + return String.IsNullOrEmpty(this.Id) + ? null + : "Municipality/" + Uri.EscapeDataString(this.Id); } } } @@ -126,7 +131,9 @@ public string Self { get { - return String.IsNullOrEmpty(this.Id) ? null : "District/" + Uri.EscapeDataString(this.Id); + return String.IsNullOrEmpty(this.Id) + ? null + : "District/" + Uri.EscapeDataString(this.Id); } } } @@ -137,7 +144,9 @@ public string Self { get { - return String.IsNullOrEmpty(this.Id) ? null : "Area/" + Uri.EscapeDataString(this.Id); + return String.IsNullOrEmpty(this.Id) + ? null + : "Area/" + Uri.EscapeDataString(this.Id); } } } @@ -157,7 +166,9 @@ public string Self { get { - return String.IsNullOrEmpty(this.Id) ? null : ODHConstant.ApplicationURL + "ODHTag/" + this.Id; + return String.IsNullOrEmpty(this.Id) + ? null + : ODHConstant.ApplicationURL + "ODHTag/" + this.Id; } } } @@ -176,14 +187,10 @@ public class Tags public string Source { get; set; } public string Self { - get - { - return ODHConstant.ApplicationURL + "Tag/" + this.Id; - } + get { return ODHConstant.ApplicationURL + "Tag/" + this.Id; } } } - public class ODHActivityPoiTypesLink { public string Id { get; set; } @@ -281,18 +288,12 @@ public class GastronomyLinked : Gastronomy, IMetaData public string Self { - get - { - return "Gastronomy/" + Uri.EscapeDataString(this.Id); - } + get { return "Gastronomy/" + Uri.EscapeDataString(this.Id); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } //Taglist @@ -300,7 +301,18 @@ public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } @@ -320,18 +332,12 @@ public class AccommodationLinked : Accommodation, IMetaData public string Self { - get - { - return "Accommodation/" + Uri.EscapeDataString(this.Id); - } + get { return "Accommodation/" + Uri.EscapeDataString(this.Id); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } //Taglist @@ -339,7 +345,18 @@ public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } @@ -347,7 +364,16 @@ public AccoType AccoType { get { - return String.IsNullOrEmpty(this.AccoTypeId) ? null : new AccoType() { Id = this.AccoTypeId, Self = ODHConstant.ApplicationURL + "AccommodationTypes/" + Uri.EscapeDataString(this.AccoTypeId) }; + return String.IsNullOrEmpty(this.AccoTypeId) + ? null + : new AccoType() + { + Id = this.AccoTypeId, + Self = + ODHConstant.ApplicationURL + + "AccommodationTypes/" + + Uri.EscapeDataString(this.AccoTypeId) + }; } } @@ -355,7 +381,16 @@ public AccoCategory AccoCategory { get { - return String.IsNullOrEmpty(this.AccoCategoryId) ? null : new AccoCategory() { Id = this.AccoCategoryId, Self = ODHConstant.ApplicationURL + "AccommodationTypes/" + Uri.EscapeDataString(this.AccoCategoryId) }; + return String.IsNullOrEmpty(this.AccoCategoryId) + ? null + : new AccoCategory() + { + Id = this.AccoCategoryId, + Self = + ODHConstant.ApplicationURL + + "AccommodationTypes/" + + Uri.EscapeDataString(this.AccoCategoryId) + }; } } @@ -363,7 +398,18 @@ public ICollection AccoBoards { get { - return this.BoardIds != null ? this.BoardIds.Select(x => new AccoBoards() { Id = x, Self = ODHConstant.ApplicationURL + "AccommodationTypes/" + x }).ToList() : new List(); + return this.BoardIds != null + ? this.BoardIds + .Select( + x => + new AccoBoards() + { + Id = x, + Self = ODHConstant.ApplicationURL + "AccommodationTypes/" + x + } + ) + .ToList() + : new List(); } } @@ -371,7 +417,18 @@ public ICollection AccoBadges { get { - return this.BadgeIds != null ? this.BadgeIds.Select(x => new AccoBadges() { Id = x, Self = ODHConstant.ApplicationURL + "AccommodationTypes/" + x }).ToList() : new List(); + return this.BadgeIds != null + ? this.BadgeIds + .Select( + x => + new AccoBadges() + { + Id = x, + Self = ODHConstant.ApplicationURL + "AccommodationTypes/" + x + } + ) + .ToList() + : new List(); } } @@ -379,7 +436,18 @@ public ICollection AccoThemes { get { - return this.ThemeIds != null ? this.ThemeIds.Select(x => new AccoThemes() { Id = x, Self = ODHConstant.ApplicationURL + "AccommodationTypes/" + x }).ToList() : new List(); + return this.ThemeIds != null + ? this.ThemeIds + .Select( + x => + new AccoThemes() + { + Id = x, + Self = ODHConstant.ApplicationURL + "AccommodationTypes/" + x + } + ) + .ToList() + : new List(); } } @@ -387,7 +455,18 @@ public ICollection AccoSpecialFeatures { get { - return this.SpecialFeaturesIds != null ? this.SpecialFeaturesIds.Select(x => new AccoSpecialFeatures() { Id = x, Self = ODHConstant.ApplicationURL + "AccommodationTypes/" + x }).ToList() : new List(); + return this.SpecialFeaturesIds != null + ? this.SpecialFeaturesIds + .Select( + x => + new AccoSpecialFeatures() + { + Id = x, + Self = ODHConstant.ApplicationURL + "AccommodationTypes/" + x + } + ) + .ToList() + : new List(); } } @@ -407,14 +486,11 @@ public class AccommodationRoomLinked : AccoRoom, IMetaData public string Self { - get - { - return "AccommodationRoom/" + Uri.EscapeDataString(this.Id); - } + get { return "AccommodationRoom/" + Uri.EscapeDataString(this.Id); } } //Overwrites The Features - public new ICollection? Features { get; set; } + public new ICollection? Features { get; set; } } public class EventPG : Event @@ -447,25 +523,30 @@ public List EventDatesEnd public int EventDateCounter { - get - { - return this.EventDate != null ? this.EventDate.Count : 0; - } + get { return this.EventDate != null ? this.EventDate.Count : 0; } } public string Self { - get - { - return "Event/" + Uri.EscapeDataString(this.Id); - } + get { return "Event/" + Uri.EscapeDataString(this.Id); } } public ICollection Districts { get { - return this.DistrictIds != null ? this.DistrictIds.Select(x => new DistrictLink() { Id = x, Self = ODHConstant.ApplicationURL + "District/" + x }).ToList() : new List(); + return this.DistrictIds != null + ? this.DistrictIds + .Select( + x => + new DistrictLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "District/" + x + } + ) + .ToList() + : new List(); } } @@ -474,16 +555,24 @@ public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } //Overwrites The Features @@ -502,10 +591,7 @@ public class PackageLinked : Package, IMetaData public string Self { - get - { - return "Package/" + Uri.EscapeDataString(this.Id); - } + get { return "Package/" + Uri.EscapeDataString(this.Id); } } //Taglist @@ -513,16 +599,24 @@ public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } //Overwrites The LocationInfo @@ -543,17 +637,25 @@ public string? Self public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } @@ -562,10 +664,32 @@ public ICollection? ODHActivityPoiTypes get { var returnlist = new List(); - returnlist.Add(new ODHActivityPoiTypesLink() { Id = this.Type, Self = ODHConstant.ApplicationURL + "OdhActivityPoiTypes/" + this.Type, Type = "Type" }); - returnlist.Add(new ODHActivityPoiTypesLink() { Id = this.SubType, Self = ODHConstant.ApplicationURL + "OdhActivityPoiTypes/" + this.SubType, Type = "SubType" }); + returnlist.Add( + new ODHActivityPoiTypesLink() + { + Id = this.Type, + Self = ODHConstant.ApplicationURL + "OdhActivityPoiTypes/" + this.Type, + Type = "Type" + } + ); + returnlist.Add( + new ODHActivityPoiTypesLink() + { + Id = this.SubType, + Self = ODHConstant.ApplicationURL + "OdhActivityPoiTypes/" + this.SubType, + Type = "SubType" + } + ); if (!String.IsNullOrEmpty(this.PoiType)) - returnlist.Add(new ODHActivityPoiTypesLink() { Id = this.PoiType, Self =ODHConstant.ApplicationURL + "OdhActivityPoiTypes/" + this.PoiType, Type = "PoiType" }); + returnlist.Add( + new ODHActivityPoiTypesLink() + { + Id = this.PoiType, + Self = + ODHConstant.ApplicationURL + "OdhActivityPoiTypes/" + this.PoiType, + Type = "PoiType" + } + ); return returnlist; } @@ -575,7 +699,18 @@ public ICollection? Areas { get { - return this.AreaId != null ? this.AreaId.Select(x => new AreaLink() { Id = x, Self = ODHConstant.ApplicationURL + "Area/" + x }).ToList() : new List(); + return this.AreaId != null + ? this.AreaId + .Select( + x => + new AreaLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "Area/" + x + } + ) + .ToList() + : new List(); } } @@ -589,8 +724,6 @@ public ICollection? Areas //Overwrites LTSTags public new List? LTSTags { get; set; } - - } public class LTSPoiLinked : LTSPoi, IMetaData @@ -599,25 +732,30 @@ public class LTSPoiLinked : LTSPoi, IMetaData public string Self { - get - { - return "Poi/" + Uri.EscapeDataString(this.Id); - } + get { return "Poi/" + Uri.EscapeDataString(this.Id); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "PoiTypes/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "PoiTypes/" + x + } + ) + .ToList() + : new List(); } } @@ -626,11 +764,45 @@ public ICollection PoiTypes get { var returnlist = new List(); - returnlist.Add(new ODHActivityPoiTypesLink() { Id = this.Type, Self = ODHConstant.ApplicationURL + "PoiTypes/" + Uri.EscapeDataString(this.Type), Type = "Type" }); - if (!String.IsNullOrEmpty(this.SubType) && this.SubType != "no Subtype" && this.SubType != "Essen Trinken") - returnlist.Add(new ODHActivityPoiTypesLink() { Id = this.SubType, Self = ODHConstant.ApplicationURL + "PoiTypes/" + Uri.EscapeDataString(this.SubType), Type = "SubType" }); + returnlist.Add( + new ODHActivityPoiTypesLink() + { + Id = this.Type, + Self = + ODHConstant.ApplicationURL + + "PoiTypes/" + + Uri.EscapeDataString(this.Type), + Type = "Type" + } + ); + if ( + !String.IsNullOrEmpty(this.SubType) + && this.SubType != "no Subtype" + && this.SubType != "Essen Trinken" + ) + returnlist.Add( + new ODHActivityPoiTypesLink() + { + Id = this.SubType, + Self = + ODHConstant.ApplicationURL + + "PoiTypes/" + + Uri.EscapeDataString(this.SubType), + Type = "SubType" + } + ); if (!String.IsNullOrEmpty(this.PoiType)) - returnlist.Add(new ODHActivityPoiTypesLink() { Id = this.PoiType, Self = ODHConstant.ApplicationURL + "PoiTypes/" + Uri.EscapeDataString(this.PoiType), Type = "PoiType" }); + returnlist.Add( + new ODHActivityPoiTypesLink() + { + Id = this.PoiType, + Self = + ODHConstant.ApplicationURL + + "PoiTypes/" + + Uri.EscapeDataString(this.PoiType), + Type = "PoiType" + } + ); return returnlist; } @@ -640,7 +812,18 @@ public ICollection Areas { get { - return this.AreaId != null ? this.AreaId.Select(x => new AreaLink() { Id = x, Self = ODHConstant.ApplicationURL + "Area/" + x }).ToList() : new List(); + return this.AreaId != null + ? this.AreaId + .Select( + x => + new AreaLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "Area/" + x + } + ) + .ToList() + : new List(); } } @@ -648,7 +831,7 @@ public ICollection Areas public new LocationInfoLinked? LocationInfo { get; set; } //Overwrites LTSTags - public new List? LTSTags { get; set; } + public new List? LTSTags { get; set; } } public class LTSActivityLinked : LTSActivity, IMetaData @@ -657,25 +840,30 @@ public class LTSActivityLinked : LTSActivity, IMetaData public string Self { - get - { - return ODHConstant.ApplicationURL + "Activity/" + Uri.EscapeDataString(this.Id); - } + get { return ODHConstant.ApplicationURL + "Activity/" + Uri.EscapeDataString(this.Id); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ActivityTypes/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ActivityTypes/" + x + } + ) + .ToList() + : new List(); } } @@ -684,11 +872,45 @@ public ICollection ActivityTypes get { var returnlist = new List(); - returnlist.Add(new ODHActivityPoiTypesLink() { Id = this.Type, Self = ODHConstant.ApplicationURL + "ActivityTypes/" + Uri.EscapeDataString(this.Type), Type = "Type" }); - if (!String.IsNullOrEmpty(this.SubType) && this.SubType != "no Subtype" && this.SubType != "Essen Trinken") - returnlist.Add(new ODHActivityPoiTypesLink() { Id = this.SubType, Self = ODHConstant.ApplicationURL + "ActivityTypes/" + Uri.EscapeDataString(this.SubType), Type = "SubType" }); + returnlist.Add( + new ODHActivityPoiTypesLink() + { + Id = this.Type, + Self = + ODHConstant.ApplicationURL + + "ActivityTypes/" + + Uri.EscapeDataString(this.Type), + Type = "Type" + } + ); + if ( + !String.IsNullOrEmpty(this.SubType) + && this.SubType != "no Subtype" + && this.SubType != "Essen Trinken" + ) + returnlist.Add( + new ODHActivityPoiTypesLink() + { + Id = this.SubType, + Self = + ODHConstant.ApplicationURL + + "ActivityTypes/" + + Uri.EscapeDataString(this.SubType), + Type = "SubType" + } + ); if (!String.IsNullOrEmpty(this.PoiType)) - returnlist.Add(new ODHActivityPoiTypesLink() { Id = this.PoiType, Self = ODHConstant.ApplicationURL + "ActivityTypes/" + Uri.EscapeDataString(this.PoiType), Type = "PoiType" }); + returnlist.Add( + new ODHActivityPoiTypesLink() + { + Id = this.PoiType, + Self = + ODHConstant.ApplicationURL + + "ActivityTypes/" + + Uri.EscapeDataString(this.PoiType), + Type = "PoiType" + } + ); return returnlist; } @@ -698,7 +920,18 @@ public ICollection Areas { get { - return this.AreaId != null ? this.AreaId.Select(x => new AreaLink() { Id = x, Self = ODHConstant.ApplicationURL + "Area/" + x }).ToList() : new List(); + return this.AreaId != null + ? this.AreaId + .Select( + x => + new AreaLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "Area/" + x + } + ) + .ToList() + : new List(); } } @@ -706,7 +939,7 @@ public ICollection Areas public new LocationInfoLinked? LocationInfo { get; set; } //Overwrites LTSTags - public new List? LTSTags { get; set; } + public new List? LTSTags { get; set; } } public class ArticlesLinked : ArticleBaseInfos, IMetaData @@ -715,18 +948,12 @@ public class ArticlesLinked : ArticleBaseInfos, IMetaData public string? Self { - get - { - return this.Id != null ? "Article/" + Uri.EscapeDataString(this.Id) : null; - } + get { return this.Id != null ? "Article/" + Uri.EscapeDataString(this.Id) : null; } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } public ICollection? ArticleTypes @@ -734,9 +961,33 @@ public ICollection? ArticleTypes get { var returnlist = new List(); - returnlist.Add(new ODHActivityPoiTypesLink() { Id = this.Type, Self = ODHConstant.ApplicationURL + "ArticleTypes/" + Uri.EscapeDataString(this.Type), Type = "ArticleType" }); - if (!String.IsNullOrEmpty(this.SubType) && this.SubType != "no Subtype" && this.SubType != "Essen Trinken") - returnlist.Add(new ODHActivityPoiTypesLink() { Id = this.SubType, Self = ODHConstant.ApplicationURL + "ArticleTypes/" + Uri.EscapeDataString(this.SubType), Type = "ArticleSubType" }); + returnlist.Add( + new ODHActivityPoiTypesLink() + { + Id = this.Type, + Self = + ODHConstant.ApplicationURL + + "ArticleTypes/" + + Uri.EscapeDataString(this.Type), + Type = "ArticleType" + } + ); + if ( + !String.IsNullOrEmpty(this.SubType) + && this.SubType != "no Subtype" + && this.SubType != "Essen Trinken" + ) + returnlist.Add( + new ODHActivityPoiTypesLink() + { + Id = this.SubType, + Self = + ODHConstant.ApplicationURL + + "ArticleTypes/" + + Uri.EscapeDataString(this.SubType), + Type = "ArticleSubType" + } + ); return returnlist; } @@ -748,7 +999,11 @@ public ICollection? ArticleTypeList { var returnlist = new List(); returnlist.Add(this.Type); - if (!String.IsNullOrEmpty(this.SubType) && this.SubType != "no Subtype" && this.SubType != "Essen Trinken") + if ( + !String.IsNullOrEmpty(this.SubType) + && this.SubType != "no Subtype" + && this.SubType != "Essen Trinken" + ) returnlist.Add(this.SubType); return returnlist; @@ -759,7 +1014,18 @@ public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } } @@ -770,33 +1036,47 @@ public class DistrictLinked : District, IMetaData public string Self { - get - { - return "District/" + Uri.EscapeDataString(this.Id); - } + get { return "District/" + Uri.EscapeDataString(this.Id); } } public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } public RegionLink Region { get { - return String.IsNullOrEmpty(this.RegionId) ? null : new RegionLink() { Id = this.RegionId, Self = ODHConstant.ApplicationURL + "Region/" + Uri.EscapeDataString(this.RegionId) }; + return String.IsNullOrEmpty(this.RegionId) + ? null + : new RegionLink() + { + Id = this.RegionId, + Self = + ODHConstant.ApplicationURL + + "Region/" + + Uri.EscapeDataString(this.RegionId) + }; } } @@ -804,7 +1084,16 @@ public MunicipalityLink Municipality { get { - return String.IsNullOrEmpty(this.MunicipalityId) ? null : new MunicipalityLink() { Id = this.MunicipalityId, Self = ODHConstant.ApplicationURL + "Municipality/" + Uri.EscapeDataString(this.MunicipalityId) }; + return String.IsNullOrEmpty(this.MunicipalityId) + ? null + : new MunicipalityLink() + { + Id = this.MunicipalityId, + Self = + ODHConstant.ApplicationURL + + "Municipality/" + + Uri.EscapeDataString(this.MunicipalityId) + }; } } @@ -812,7 +1101,16 @@ public TourismAssociationLink Tourismassociation { get { - return String.IsNullOrEmpty(this.TourismvereinId) ? null : new TourismAssociationLink() { Id = this.TourismvereinId, Self = ODHConstant.ApplicationURL + "TourismAssociation/" + Uri.EscapeDataString(this.TourismvereinId) }; + return String.IsNullOrEmpty(this.TourismvereinId) + ? null + : new TourismAssociationLink() + { + Id = this.TourismvereinId, + Self = + ODHConstant.ApplicationURL + + "TourismAssociation/" + + Uri.EscapeDataString(this.TourismvereinId) + }; } } } @@ -823,33 +1121,47 @@ public class MunicipalityLinked : Municipality, IMetaData public string Self { - get - { - return "Municipality/" + Uri.EscapeDataString(this.Id); - } + get { return "Municipality/" + Uri.EscapeDataString(this.Id); } } public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } public RegionLink Region { get { - return String.IsNullOrEmpty(this.RegionId) ? null : new RegionLink() { Id = this.RegionId, Self = ODHConstant.ApplicationURL + "Region/" + Uri.EscapeDataString(this.RegionId) }; + return String.IsNullOrEmpty(this.RegionId) + ? null + : new RegionLink() + { + Id = this.RegionId, + Self = + ODHConstant.ApplicationURL + + "Region/" + + Uri.EscapeDataString(this.RegionId) + }; } } @@ -857,7 +1169,16 @@ public TourismAssociationLink Tourismassociation { get { - return String.IsNullOrEmpty(this.TourismvereinId) ? null : new TourismAssociationLink() { Id = this.TourismvereinId, Self = ODHConstant.ApplicationURL + "TourismAssociation/" + Uri.EscapeDataString(this.TourismvereinId) }; + return String.IsNullOrEmpty(this.TourismvereinId) + ? null + : new TourismAssociationLink() + { + Id = this.TourismvereinId, + Self = + ODHConstant.ApplicationURL + + "TourismAssociation/" + + Uri.EscapeDataString(this.TourismvereinId) + }; } } } @@ -868,33 +1189,47 @@ public class TourismvereinLinked : Tourismverein, IMetaData public string Self { - get - { - return "TourismAssociation/" + Uri.EscapeDataString(this.Id); - } + get { return "TourismAssociation/" + Uri.EscapeDataString(this.Id); } } public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } public RegionLink Region { get { - return String.IsNullOrEmpty(this.RegionId) ? null : new RegionLink() { Id = this.RegionId, Self = ODHConstant.ApplicationURL + "Region/" + Uri.EscapeDataString(this.RegionId) }; + return String.IsNullOrEmpty(this.RegionId) + ? null + : new RegionLink() + { + Id = this.RegionId, + Self = + ODHConstant.ApplicationURL + + "Region/" + + Uri.EscapeDataString(this.RegionId) + }; } } @@ -902,7 +1237,18 @@ public ICollection SkiAreas { get { - return this.SkiareaIds != null ? this.SkiareaIds.Select(x => new SkiAreaLink() { Id = x, Self = ODHConstant.ApplicationURL + "SkiArea/" + x }).ToList() : new List(); + return this.SkiareaIds != null + ? this.SkiareaIds + .Select( + x => + new SkiAreaLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "SkiArea/" + x + } + ) + .ToList() + : new List(); } } } @@ -913,33 +1259,49 @@ public class RegionLinked : Region, IMetaData public string Self { - get - { - return "Region/" + Uri.EscapeDataString(this.Id); - } + get { return "Region/" + Uri.EscapeDataString(this.Id); } } public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } public ICollection SkiAreas { get { - return this.SkiareaIds != null ? this.SkiareaIds.Select(x => new SkiAreaLink() { Id = x, Self = ODHConstant.ApplicationURL + "SkiArea/" + x }).ToList() : new List(); + return this.SkiareaIds != null + ? this.SkiareaIds + .Select( + x => + new SkiAreaLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "SkiArea/" + x + } + ) + .ToList() + : new List(); } } } @@ -950,33 +1312,49 @@ public class MetaRegionLinked : MetaRegion, IMetaData public string Self { - get - { - return "MetaRegion/" + Uri.EscapeDataString(this.Id); - } + get { return "MetaRegion/" + Uri.EscapeDataString(this.Id); } } public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } public ICollection Districts { get { - return this.DistrictIds != null ? this.DistrictIds.Select(x => new DistrictLink() { Id = x, Self = ODHConstant.ApplicationURL + "District/" + x }).ToList() : new List(); + return this.DistrictIds != null + ? this.DistrictIds + .Select( + x => + new DistrictLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "District/" + x + } + ) + .ToList() + : new List(); } } @@ -984,7 +1362,18 @@ public ICollection TourismAssociations { get { - return this.TourismvereinIds != null ? this.TourismvereinIds.Select(x => new TourismAssociationLink() { Id = x, Self = ODHConstant.ApplicationURL + "TourismAssociation/" + x }).ToList() : new List(); + return this.TourismvereinIds != null + ? this.TourismvereinIds + .Select( + x => + new TourismAssociationLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "TourismAssociation/" + x + } + ) + .ToList() + : new List(); } } @@ -992,7 +1381,18 @@ public ICollection Regions { get { - return this.RegionIds != null ? this.RegionIds.Select(x => new RegionLink() { Id = x, Self = ODHConstant.ApplicationURL + "Region/" + x }).ToList() : new List(); + return this.RegionIds != null + ? this.RegionIds + .Select( + x => + new RegionLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "Region/" + x + } + ) + .ToList() + : new List(); } } } @@ -1003,33 +1403,49 @@ public class ExperienceAreaLinked : ExperienceArea, IMetaData public string Self { - get - { - return "ExperienceArea/" + Uri.EscapeDataString(this.Id); - } + get { return "ExperienceArea/" + Uri.EscapeDataString(this.Id); } } public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } public ICollection TourismAssociations { get { - return this.TourismvereinIds != null ? this.TourismvereinIds.Select(x => new TourismAssociationLink() { Id = x, Self = ODHConstant.ApplicationURL + "TourismAssociation/" + x }).ToList() : new List(); + return this.TourismvereinIds != null + ? this.TourismvereinIds + .Select( + x => + new TourismAssociationLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "TourismAssociation/" + x + } + ) + .ToList() + : new List(); } } @@ -1037,7 +1453,18 @@ public ICollection Districts { get { - return this.DistrictIds != null ? this.DistrictIds.Select(x => new DistrictLink() { Id = x, Self = ODHConstant.ApplicationURL + "District/" + x }).ToList() : new List(); + return this.DistrictIds != null + ? this.DistrictIds + .Select( + x => + new DistrictLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "District/" + x + } + ) + .ToList() + : new List(); } } } @@ -1048,25 +1475,28 @@ public class AreaLinked : Area, IMetaData public string Self { - get - { - return "Area/" + Uri.EscapeDataString(this.Id); - } + get { return "Area/" + Uri.EscapeDataString(this.Id); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } public RegionLink Region { get { - return String.IsNullOrEmpty(this.RegionId) ? null : new RegionLink() { Id = this.RegionId, Self = ODHConstant.ApplicationURL + "Region/" + Uri.EscapeDataString(this.RegionId) }; + return String.IsNullOrEmpty(this.RegionId) + ? null + : new RegionLink() + { + Id = this.RegionId, + Self = + ODHConstant.ApplicationURL + + "Region/" + + Uri.EscapeDataString(this.RegionId) + }; } } @@ -1074,7 +1504,16 @@ public MunicipalityLink Municipality { get { - return String.IsNullOrEmpty(this.MunicipalityId) ? null : new MunicipalityLink() { Id = this.MunicipalityId, Self = ODHConstant.ApplicationURL + "Municipality/" + Uri.EscapeDataString(this.MunicipalityId) }; + return String.IsNullOrEmpty(this.MunicipalityId) + ? null + : new MunicipalityLink() + { + Id = this.MunicipalityId, + Self = + ODHConstant.ApplicationURL + + "Municipality/" + + Uri.EscapeDataString(this.MunicipalityId) + }; } } @@ -1082,7 +1521,16 @@ public TourismAssociationLink Tourismassociation { get { - return String.IsNullOrEmpty(this.TourismvereinId) ? null : new TourismAssociationLink() { Id = this.TourismvereinId, Self = ODHConstant.ApplicationURL + "TourismAssociation/" + Uri.EscapeDataString(this.TourismvereinId) }; + return String.IsNullOrEmpty(this.TourismvereinId) + ? null + : new TourismAssociationLink() + { + Id = this.TourismvereinId, + Self = + ODHConstant.ApplicationURL + + "TourismAssociation/" + + Uri.EscapeDataString(this.TourismvereinId) + }; } } @@ -1090,7 +1538,16 @@ public SkiAreaLink SkiArea { get { - return String.IsNullOrEmpty(this.SkiAreaID) ? null : new SkiAreaLink() { Id = this.SkiAreaID, Self = ODHConstant.ApplicationURL + "SkiArea/" + Uri.EscapeDataString(this.SkiAreaID) }; + return String.IsNullOrEmpty(this.SkiAreaID) + ? null + : new SkiAreaLink() + { + Id = this.SkiAreaID, + Self = + ODHConstant.ApplicationURL + + "SkiArea/" + + Uri.EscapeDataString(this.SkiAreaID) + }; } } } @@ -1101,33 +1558,47 @@ public class SkiAreaLinked : SkiArea, IMetaData public string Self { - get - { - return "SkiArea/" + Uri.EscapeDataString(this.Id); - } + get { return "SkiArea/" + Uri.EscapeDataString(this.Id); } } public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } public SkiRegionLink SkiRegion { get { - return String.IsNullOrEmpty(this.SkiRegionId) ? null : new SkiRegionLink() { Id = this.SkiRegionId, Self = ODHConstant.ApplicationURL + "SkiRegion/" + Uri.EscapeDataString(this.SkiRegionId) }; + return String.IsNullOrEmpty(this.SkiRegionId) + ? null + : new SkiRegionLink() + { + Id = this.SkiRegionId, + Self = + ODHConstant.ApplicationURL + + "SkiRegion/" + + Uri.EscapeDataString(this.SkiRegionId) + }; } } @@ -1135,7 +1606,18 @@ public ICollection Areas { get { - return this.AreaId != null ? this.AreaId.Select(x => new AreaLink() { Id = x, Self = ODHConstant.ApplicationURL + "Area/" + x }).ToList() : new List(); + return this.AreaId != null + ? this.AreaId + .Select( + x => + new AreaLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "Area/" + x + } + ) + .ToList() + : new List(); } } @@ -1143,7 +1625,18 @@ public ICollection TourismAssociations { get { - return this.TourismvereinIds != null ? this.TourismvereinIds.Select(x => new TourismAssociationLink() { Id = x, Self = ODHConstant.ApplicationURL + "TourismAssociation/" + x }).ToList() : new List(); + return this.TourismvereinIds != null + ? this.TourismvereinIds + .Select( + x => + new TourismAssociationLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "TourismAssociation/" + x + } + ) + .ToList() + : new List(); } } @@ -1151,7 +1644,18 @@ public ICollection Regions { get { - return this.RegionIds != null ? this.RegionIds.Select(x => new RegionLink() { Id = x, Self = ODHConstant.ApplicationURL + "Region/" + x }).ToList() : new List(); + return this.RegionIds != null + ? this.RegionIds + .Select( + x => + new RegionLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "Region/" + x + } + ) + .ToList() + : new List(); } } @@ -1165,26 +1669,31 @@ public class SkiRegionLinked : SkiRegion, IMetaData public string Self { - get - { - return "SkiRegion/" + Uri.EscapeDataString(this.Id); - } + get { return "SkiRegion/" + Uri.EscapeDataString(this.Id); } } public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } } public bool OdhActive { - get - { - return this.SmgActive; - } + get { return this.SmgActive; } } } @@ -1194,25 +1703,30 @@ public class WebcamInfoLinked : WebcamInfo, IMetaData public string Self { - get - { - return "WebcamInfo/" + Uri.EscapeDataString(this.Id); - } + get { return "WebcamInfo/" + Uri.EscapeDataString(this.Id); } } public bool OdhActive { - get - { - return (bool)this.SmgActive; - } + get { return (bool)this.SmgActive; } } public ICollection Areas { get { - return this.AreaIds != null ? this.AreaIds.Select(x => new AreaLink() { Id = x, Self = ODHConstant.ApplicationURL + "Area/" + x }).ToList() : new List(); + return this.AreaIds != null + ? this.AreaIds + .Select( + x => + new AreaLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "Area/" + x + } + ) + .ToList() + : new List(); } } @@ -1220,9 +1734,20 @@ public ICollection ODHTags { get { - return this.SmgTags != null ? this.SmgTags.Select(x => new ODHTags() { Id = x, Self = ODHConstant.ApplicationURL + "ODHTag/" + x }).ToList() : new List(); + return this.SmgTags != null + ? this.SmgTags + .Select( + x => + new ODHTags() + { + Id = x, + Self = ODHConstant.ApplicationURL + "ODHTag/" + x + } + ) + .ToList() + : new List(); } - } + } } public class MeasuringpointLinked : Measuringpoint, IMetaData @@ -1231,30 +1756,35 @@ public class MeasuringpointLinked : Measuringpoint, IMetaData public string Self { - get - { - return "Weather/Measuringpoint/" + Uri.EscapeDataString(this.Id); - } + get { return "Weather/Measuringpoint/" + Uri.EscapeDataString(this.Id); } } public bool OdhActive { - get - { - return (bool)this.SmgActive; - } + get { return (bool)this.SmgActive; } } public ICollection Areas { get { - return this.AreaIds != null ? this.AreaIds.Select(x => new AreaLink() { Id = x, Self = ODHConstant.ApplicationURL + "Area/" + x }).ToList() : new List(); + return this.AreaIds != null + ? this.AreaIds + .Select( + x => + new AreaLink() + { + Id = x, + Self = ODHConstant.ApplicationURL + "Area/" + x + } + ) + .ToList() + : new List(); } } //Overwrites The LocationInfo - public new LocationInfoLinked? LocationInfo { get; set; } + public new LocationInfoLinked? LocationInfo { get; set; } } public class WineLinked : Wine, IMetaData @@ -1263,25 +1793,25 @@ public class WineLinked : Wine, IMetaData public string Self { - get - { - return ODHConstant.ApplicationURL + "WineAward/" + this.Id; - } + get { return ODHConstant.ApplicationURL + "WineAward/" + this.Id; } } public bool OdhActive { - get - { - return (bool)this.SmgActive; - } + get { return (bool)this.SmgActive; } } public CompanyLink Company { get { - return String.IsNullOrEmpty(this.CompanyId) ? null : new CompanyLink() { Id = this.CompanyId, Self = ODHConstant.ApplicationURL + "ODHActivityPoi/" + this.CompanyId }; + return String.IsNullOrEmpty(this.CompanyId) + ? null + : new CompanyLink() + { + Id = this.CompanyId, + Self = ODHConstant.ApplicationURL + "ODHActivityPoi/" + this.CompanyId + }; } } } @@ -1292,10 +1822,7 @@ public class EventShortLinked : EventShort, IMetaData public string Self { - get - { - return ODHConstant.ApplicationURL + "EventShort/" + this.Id; - } + get { return ODHConstant.ApplicationURL + "EventShort/" + this.Id; } } } @@ -1305,10 +1832,7 @@ public class WeatherLinked : Weather, IMetaData public string Self { - get - { - return ODHConstant.ApplicationURL + "Weather/" + this.Id; - } + get { return ODHConstant.ApplicationURL + "Weather/" + this.Id; } } } @@ -1318,23 +1842,17 @@ public class WeatherHistoryLinked : WeatherHistory, IMetaData public string Self { - get - { - return ODHConstant.ApplicationURL + "WeatherHistory/" + this.Id; - } + get { return ODHConstant.ApplicationURL + "WeatherHistory/" + this.Id; } } } public class ODHTagLinked : SmgTags, IMetaData { - public Metadata _Meta { get; set; } + public Metadata _Meta { get; set; } public string Self { - get - { - return ODHConstant.ApplicationURL + "ODHTag/" + this.Id; - } + get { return ODHConstant.ApplicationURL + "ODHTag/" + this.Id; } } } @@ -1344,15 +1862,12 @@ public class TagLinked : SmgTags, IMetaData public string Self { - get - { - return ODHConstant.ApplicationURL + "Tag/" + this.Id; - } + get { return ODHConstant.ApplicationURL + "Tag/" + this.Id; } } public List ODHTagIds { get; set; } } - //TODO ADD Linked + Meta + //TODO ADD Linked + Meta //EventTopics //ActivityTypes //PoiTypes diff --git a/DataModel/SuedtirolDBMobile.cs b/DataModel/SuedtirolDBMobile.cs index 28d3632b7..d75245c0a 100644 --- a/DataModel/SuedtirolDBMobile.cs +++ b/DataModel/SuedtirolDBMobile.cs @@ -11,7 +11,7 @@ namespace DataModel /// #region Mobile - + public class SmgPoisMobileTypes { public SmgPoisMobileTypes() @@ -20,6 +20,7 @@ public SmgPoisMobileTypes() } public string? Id { get; set; } + //public int Bitmask { get; set; } public string? Key { get; set; } public string? Type { get; set; } @@ -62,25 +63,25 @@ public SmgPoisMobileFilterDetail() EndDesc = new Dictionary(); } - public string? Id { get; set; } //Unique Id + public string? Id { get; set; } //Unique Id + //public string MainTypeId { get; set; } //Reference to Maintype - public int SortOrder { get; set; } //Sort Order of the Filter + public int SortOrder { get; set; } //Sort Order of the Filter public int Bitmask { get; set; } - public string? Filtertype { get; set; } //Type of the Filter (checkbox, scroller, rating) - public IDictionary FilterText { get; set; } //Values of the Filter, Key is intended to use on the Filter Api, Value is what we want to display. + public string? Filtertype { get; set; } //Type of the Filter (checkbox, scroller, rating) + public IDictionary FilterText { get; set; } //Values of the Filter, Key is intended to use on the Filter Api, Value is what we want to display. public string? FilterReference { get; set; } public string? FilterString { get; set; } - public IDictionary StartingDesc { get; set; } //For a scroller Filter, there can be provided a Starting Description (like 1 km) - public string? StartingValue { get; set; } //For a scroller Filter a startingvalue can be defined - public IDictionary EndDesc { get; set; } //For a scroller Filter, there can be provided a Ending Description (like >20 km) - public string? EndValue { get; set; } //For a scroller Filter a endingvalue can be defined - - public int RatingItems { get; set; } //For a rating Filter there can be set a Rating Items (this well be 6) - public string? SelectedValue { get; set; } //For a rating Filter the Initially selected Value can be defined + public IDictionary StartingDesc { get; set; } //For a scroller Filter, there can be provided a Starting Description (like 1 km) + public string? StartingValue { get; set; } //For a scroller Filter a startingvalue can be defined + public IDictionary EndDesc { get; set; } //For a scroller Filter, there can be provided a Ending Description (like >20 km) + public string? EndValue { get; set; } //For a scroller Filter a endingvalue can be defined + public int RatingItems { get; set; } //For a rating Filter there can be set a Rating Items (this well be 6) + public string? SelectedValue { get; set; } //For a rating Filter the Initially selected Value can be defined } public class MobileHtml @@ -110,7 +111,6 @@ public Tutorial() public string? category { get; set; } public int sortorder { get; set; } - } public class AppMessage @@ -123,7 +123,6 @@ public AppMessage() Images = new Dictionary>(); } - public string? Id { get; set; } public string? Type { get; set; } public DateTime ValidFrom { get; set; } @@ -164,7 +163,7 @@ public class AppMessageImage //} //public class SmgPoisMobileFilterDetailLocalized - //{ + //{ // public string Id { get; set; } //Unique Id // public string SubTypeId { get; set; } //Reference to SmgPoisMobileFilterListLocalized ID @@ -199,6 +198,7 @@ public AccoThemesMobile() public string? Key { get; set; } public Dictionary Name { get; set; } public string? ImageURL { get; set; } + //public int AccoCount { get; set; } public int SortOrder { get; set; } public Nullable Active { get; set; } @@ -257,7 +257,7 @@ public AppCustomTips() public class AppCustomTipsSettings { - public int Fixedposition { get; set; } //position 0 is random + public int Fixedposition { get; set; } //position 0 is random public bool Randomposition { get; set; } public DateTime ValidFrom { get; set; } public DateTime ValidTo { get; set; } @@ -276,7 +276,6 @@ public AppSuggestion() public List? Validfor { get; set; } public IDictionary Suggestion { get; set; } - } public class AppSuggestionValidFor @@ -296,6 +295,4 @@ public class Suggestion } #endregion - - } diff --git a/DataModel/SuedtirolDBSpecial.cs b/DataModel/SuedtirolDBSpecial.cs index 0affdd2a7..4c4d2cf66 100644 --- a/DataModel/SuedtirolDBSpecial.cs +++ b/DataModel/SuedtirolDBSpecial.cs @@ -16,6 +16,7 @@ public MetaInfosOdhActivityPoi() { Metainfos = new Dictionary>>(); } + public string? Id { get; set; } public Dictionary>> Metainfos { get; set; } @@ -23,14 +24,14 @@ public MetaInfosOdhActivityPoi() #endregion public class AccoBookList - { + { public string? Id { get; set; } public bool IsBookable { get; set; } public ICollection? AccoBookingChannel { get; set; } } public class AccoBookListRaw - { + { public string? Id { get; set; } public bool IsBookable { get; set; } public JsonRaw AccoBookingChannel { get; set; } @@ -301,8 +302,6 @@ public class CommonReduced public string Name { get; set; } } - - #region Evalanche public class EvalancheMailing @@ -311,6 +310,7 @@ public EvalancheMailing() { ArticleIDs = new Dictionary(); } + public string? Name { get; set; } public DateTime CreationDate { get; set; } public string? Type { get; set; } @@ -328,7 +328,6 @@ public EvalancheMapping() } public IDictionary EvalancheArticleID { get; set; } - } #endregion diff --git a/EBMS/ImportEBMSData.cs b/EBMS/ImportEBMSData.cs index e7a3416fa..3c51a46bc 100644 --- a/EBMS/ImportEBMSData.cs +++ b/EBMS/ImportEBMSData.cs @@ -12,14 +12,19 @@ namespace EBMS { public class ImportEBMSData { - public const string serviceurlebmsrest = @"https://emea-interface.ungerboeck.com/clients/Bozen/PROD/EventExportAPI/api/event/masterdata/?organization=20"; + public const string serviceurlebmsrest = + @"https://emea-interface.ungerboeck.com/clients/Bozen/PROD/EventExportAPI/api/event/masterdata/?organization=20"; public static async Task GetEBMSEventsFromService(string user, string pass) { try { CredentialCache wrCache = new CredentialCache(); - wrCache.Add(new Uri(serviceurlebmsrest), "Basic", new NetworkCredential(user, pass)); + wrCache.Add( + new Uri(serviceurlebmsrest), + "Basic", + new NetworkCredential(user, pass) + ); using (var handler = new HttpClientHandler { Credentials = wrCache }) { @@ -39,13 +44,20 @@ public static async Task GetEBMSEventsFromService(string user, string pa } } - public static List> GetEbmsEvents(string user, string pass) + public static List> GetEbmsEvents( + string user, + string pass + ) { try { - List> myeventshortlist = new List>(); + List> myeventshortlist = + new List>(); - System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; + System.Net.ServicePointManager.SecurityProtocol = System + .Net + .SecurityProtocolType + .Tls12; var response = GetEBMSEventsFromService(user, pass).Result; @@ -61,10 +73,12 @@ public static List> GetEbmsEvents(string eventtosave.Source = "EBMS"; //ADD MAPPING - var ebmsrid = new Dictionary() { { "id", myevent.EventId.ToString() } }; + var ebmsrid = new Dictionary() + { + { "id", myevent.EventId.ToString() } + }; eventtosave.Mapping.TryAddOrUpdate("ebms", ebmsrid); - //Interface Props eventtosave.EventId = myevent.EventId; @@ -87,19 +101,38 @@ public static List> GetEbmsEvents(string eventtosave.ChangedOn = myevent.ChangedOn; eventtosave.LastChange = myevent.ChangedOn; //Beginndatum - eventtosave.StartDate = new DateTime(myevent.StartDate.Year, myevent.StartDate.Month, myevent.StartDate.Day, myevent.StartTime.Hour, myevent.StartTime.Minute, myevent.StartTime.Second); + eventtosave.StartDate = new DateTime( + myevent.StartDate.Year, + myevent.StartDate.Month, + myevent.StartDate.Day, + myevent.StartTime.Hour, + myevent.StartTime.Minute, + myevent.StartTime.Second + ); //Beginnzeit //eventtosave.StartTime = myevent.StartTime; //Ende Datum - eventtosave.EndDate = new DateTime(myevent.EndDate.Year, myevent.EndDate.Month, myevent.EndDate.Day, myevent.EndTime.Hour, myevent.EndTime.Minute, myevent.EndTime.Second); + eventtosave.EndDate = new DateTime( + myevent.EndDate.Year, + myevent.EndDate.Month, + myevent.EndDate.Day, + myevent.EndTime.Hour, + myevent.EndTime.Minute, + myevent.EndTime.Second + ); //Endzeit //UTC //Int32 unixTimestampEStart = (Int32)(DateTime.UtcNow.Subtract(eventtosave.StartDate)).TotalSeconds; //Int32 unixTimestampEEnd = (Int32)(DateTime.UtcNow.Subtract()).TotalSeconds; - eventtosave.EndDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(eventtosave.EndDate); - eventtosave.StartDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(eventtosave.StartDate); - + eventtosave.EndDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + eventtosave.EndDate + ); + eventtosave.StartDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + eventtosave.StartDate + ); //eventtosave.EndTime = myevent.EndTime; //URL für externe Webseite (noch nicht ausgefüllt) @@ -201,7 +234,7 @@ public static List> GetEbmsEvents(string //gebuchten Sääle von spezifischen Event //Space : Code für Raum von DB //SpaceDesc: Beschreibung --> zu nehmen - //SpaceAbbrev: Abgekürzte Beschreibung + //SpaceAbbrev: Abgekürzte Beschreibung //SoaceType : EC = Eurac, NO = Noi //Comnment: entweder x oder leer --> x bedeutet bitte nicht anzeigen!!!!!!! //Subtitle: Untertitel vom Saal (anzeigen) @@ -217,15 +250,34 @@ public static List> GetEbmsEvents(string { RoomBooked myroom = new RoomBooked(); myroom.Comment = bookingroom.Comment ?? ""; - myroom.EndDate = new DateTime(bookingroom.EndDate.Year, bookingroom.EndDate.Month, bookingroom.EndDate.Day, bookingroom.EndTime.Hour, bookingroom.EndTime.Minute, bookingroom.EndTime.Second); - myroom.StartDate = new DateTime(bookingroom.StartDate.Year, bookingroom.StartDate.Month, bookingroom.StartDate.Day, bookingroom.StartTime.Hour, bookingroom.StartTime.Minute, bookingroom.StartTime.Second); + myroom.EndDate = new DateTime( + bookingroom.EndDate.Year, + bookingroom.EndDate.Month, + bookingroom.EndDate.Day, + bookingroom.EndTime.Hour, + bookingroom.EndTime.Minute, + bookingroom.EndTime.Second + ); + myroom.StartDate = new DateTime( + bookingroom.StartDate.Year, + bookingroom.StartDate.Month, + bookingroom.StartDate.Day, + bookingroom.StartTime.Hour, + bookingroom.StartTime.Minute, + bookingroom.StartTime.Second + ); //Int32 unixTimestampStart = (Int32)(DateTime.UtcNow.Subtract(myroom.StartDate)).TotalSeconds; //Int32 unixTimestampEnd = (Int32)(DateTime.UtcNow.Subtract(myroom.EndDate)).TotalSeconds; - myroom.EndDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(myroom.EndDate); - myroom.StartDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(myroom.StartDate); - + myroom.EndDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + myroom.EndDate + ); + myroom.StartDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + myroom.StartDate + ); myroom.Space = bookingroom.Space ?? ""; myroom.SpaceAbbrev = bookingroom.SpaceAbbrev ?? ""; @@ -248,7 +300,6 @@ public static List> GetEbmsEvents(string if (eventlocation == "NOI") eventtosave.Display1 = eventtosave.Display4; - //all das interessiert nicht //eventtosave.AbstractsEN = myevent.AbstractsEN; //eventtosave.AbstractsGER = myevent.AbstractsGER; @@ -256,12 +307,11 @@ public static List> GetEbmsEvents(string ////gehört zu Abstract //eventtosave.Documents = myevent.Documents; - myeventshortlist.Add(Tuple.Create(eventtosave, myevent)); + myeventshortlist.Add(Tuple.Create(eventtosave, myevent)); } } - - return myeventshortlist; + return myeventshortlist; } catch (Exception ex) { diff --git a/Helper/Alpinebits/AlpineBitsHelper.cs b/Helper/Alpinebits/AlpineBitsHelper.cs index 54cf311e2..c70185d4e 100644 --- a/Helper/Alpinebits/AlpineBitsHelper.cs +++ b/Helper/Alpinebits/AlpineBitsHelper.cs @@ -39,6 +39,5 @@ public static List GetRoomTypeAB(string roomtype) return new List { 1 }; } } - } } diff --git a/Helper/Extensions/DictionaryExtensions.cs b/Helper/Extensions/DictionaryExtensions.cs index 1c9f0bbf0..8a8f94b3c 100644 --- a/Helper/Extensions/DictionaryExtensions.cs +++ b/Helper/Extensions/DictionaryExtensions.cs @@ -7,7 +7,11 @@ namespace Helper public static class DictionaryExtensions { //public static Dictionary TryAddOrUpdate(this Dictionary dict, string key, T val) - public static IDictionary TryAddOrUpdate(this IDictionary dict, TKey key, TValue val) + public static IDictionary TryAddOrUpdate( + this IDictionary dict, + TKey key, + TValue val + ) { if (dict.ContainsKey(key)) dict[key] = val; @@ -21,6 +25,5 @@ public static IDictionary TryAddOrUpdate(this IDicti //{ // return (IDictionary)dict.Where(kvp.Key.ToString() == language); //} - } } diff --git a/Helper/Extensions/GpsExtensions.cs b/Helper/Extensions/GpsExtensions.cs index f33594d94..fcb17964f 100644 --- a/Helper/Extensions/GpsExtensions.cs +++ b/Helper/Extensions/GpsExtensions.cs @@ -9,7 +9,9 @@ namespace Helper { public static class GpsExtensions { - public static Dictionary ConvertGpsInfoToGpsPoints(this List gpsinfolist) + public static Dictionary ConvertGpsInfoToGpsPoints( + this List gpsinfolist + ) { Dictionary gpspoints = new Dictionary(); foreach (var gpsinfo in gpsinfolist) @@ -23,7 +25,9 @@ public static Dictionary ConvertGpsInfoToGpsPoints(this List ConvertGpsInfoToGpsPointsLinq(this List gpsinfolist) + public static Dictionary ConvertGpsInfoToGpsPointsLinq( + this List gpsinfolist + ) { if (gpsinfolist != null && gpsinfolist.Count > 0) return gpsinfolist diff --git a/Helper/Extensions/QueryFactoryExtension.cs b/Helper/Extensions/QueryFactoryExtension.cs index d384d2d7d..fe31ef8d4 100644 --- a/Helper/Extensions/QueryFactoryExtension.cs +++ b/Helper/Extensions/QueryFactoryExtension.cs @@ -13,28 +13,43 @@ namespace Helper { public static class QueryFactoryExtension { - public static async Task GetObjectSingleAsync(this Query query, CancellationToken cancellationToken = default) where T : notnull + public static async Task GetObjectSingleAsync( + this Query query, + CancellationToken cancellationToken = default + ) where T : notnull { var result = await query.FirstOrDefaultAsync(); return JsonConvert.DeserializeObject(result.Value) ?? default!; } - public static async Task> GetObjectListAsync(this Query query, CancellationToken cancellationToken = default) where T : notnull + public static async Task> GetObjectListAsync( + this Query query, + CancellationToken cancellationToken = default + ) where T : notnull { var result = await query.GetAsync(); return result.Select(x => JsonConvert.DeserializeObject(x.Value)!) ?? default!; } //Insert also data in Raw table - public static async Task InsertInRawtableAndGetIdAsync(this QueryFactory queryfactory, RawDataStore rawData, CancellationToken cancellationToken = default) + public static async Task InsertInRawtableAndGetIdAsync( + this QueryFactory queryfactory, + RawDataStore rawData, + CancellationToken cancellationToken = default + ) { - return await queryfactory.Query("rawdata") - .InsertGetIdAsync(rawData); + return await queryfactory.Query("rawdata").InsertGetIdAsync(rawData); } #region PG Helpers - public static async Task UpsertData(this QueryFactory QueryFactory, T data, string table, bool errorwhendataexists = false, bool errorwhendataisnew = false) where T : IIdentifiable, IImportDateassigneable, IMetaData + public static async Task UpsertData( + this QueryFactory QueryFactory, + T data, + string table, + bool errorwhendataexists = false, + bool errorwhendataisnew = false + ) where T : IIdentifiable, IImportDateassigneable, IMetaData { //TODO: What if no id is passed? Generate ID //TODO: Id Uppercase or Lowercase depending on table @@ -44,9 +59,7 @@ public static async Task UpsertData(this QueryFactory QueryFact throw new ArgumentNullException(nameof(data), "no data"); //Check if data exists - var query = QueryFactory.Query(table) - .Select("data") - .Where("id", data.Id); + var query = QueryFactory.Query(table).Select("data").Where("id", data.Id); var queryresult = await query.GetAsync(); @@ -68,36 +81,48 @@ public static async Task UpsertData(this QueryFactory QueryFact if (errorwhendataisnew) throw new ArgumentNullException(nameof(data.Id), "Id does not exist"); - createresult = await QueryFactory.Query(table) - .InsertAsync(new JsonBData() { id = data.Id, data = new JsonRaw(data) }); + createresult = await QueryFactory + .Query(table) + .InsertAsync(new JsonBData() { id = data.Id, data = new JsonRaw(data) }); operation = "INSERT"; } else - { - if(errorwhendataexists) + { + if (errorwhendataexists) throw new ArgumentNullException(nameof(data.Id), "Id exists already"); - updateresult = await QueryFactory.Query(table).Where("id", data.Id) - .UpdateAsync(new JsonBData() { id = data.Id, data = new JsonRaw(data) }); + updateresult = await QueryFactory + .Query(table) + .Where("id", data.Id) + .UpdateAsync(new JsonBData() { id = data.Id, data = new JsonRaw(data) }); operation = "UPDATE"; } if (createresult == 0 && updateresult == 0) errorresult = 1; - return new PGCRUDResult() { id = data.Id, created = createresult, updated = updateresult, deleted = 0, error = errorresult, operation = operation }; + return new PGCRUDResult() + { + id = data.Id, + created = createresult, + updated = updateresult, + deleted = 0, + error = errorresult, + operation = operation + }; } - - public static async Task DeleteData(this QueryFactory QueryFactory, string id, string table) + + public static async Task DeleteData( + this QueryFactory QueryFactory, + string id, + string table + ) { if (string.IsNullOrEmpty(id)) throw new ArgumentException(nameof(id), "No data"); //Check if data exists - var query = - QueryFactory.Query(table) - .Select("data") - .Where("id", id); + var query = QueryFactory.Query(table).Select("data").Where("id", id); var deleteresult = 0; var errorresult = 0; @@ -108,29 +133,40 @@ public static async Task DeleteData(this QueryFactory QueryFactory } else { - deleteresult = await QueryFactory.Query(table).Where("id", id) - .DeleteAsync(); + deleteresult = await QueryFactory.Query(table).Where("id", id).DeleteAsync(); } if (deleteresult == 0) errorresult = 1; - return new PGCRUDResult() { id = id, created = 0, updated = 0, deleted = deleteresult, error = errorresult, operation = "DELETE" }; + return new PGCRUDResult() + { + id = id, + created = 0, + updated = 0, + deleted = deleteresult, + error = errorresult, + operation = "DELETE" + }; } #endregion #region RawDataStore - public static async Task UpsertData(this QueryFactory QueryFactory, T data, string table, int rawdataid, bool errorwhendataexists = false) where T : IIdentifiable, IImportDateassigneable, IMetaData + public static async Task UpsertData( + this QueryFactory QueryFactory, + T data, + string table, + int rawdataid, + bool errorwhendataexists = false + ) where T : IIdentifiable, IImportDateassigneable, IMetaData { if (data == null) throw new ArgumentNullException(nameof(data), "no data"); //Check if data exists - var query = QueryFactory.Query(table) - .Select("data") - .Where("id", data.Id); + var query = QueryFactory.Query(table).Select("data").Where("id", data.Id); var queryresult = await query.GetAsync(); @@ -144,34 +180,56 @@ public static async Task UpsertData(this QueryFactory QueryFact //Setting MetaInfo data._Meta = MetadataHelper.GetMetadataobject(data); - if(data.FirstImport == null) + if (data.FirstImport == null) data.FirstImport = DateTime.Now; if (queryresult == null || queryresult.Count() == 0) { - createresult = await QueryFactory.Query(table) - .InsertAsync(new JsonBDataRaw() { id = data.Id, data = new JsonRaw(data), rawdataid = rawdataid }); + createresult = await QueryFactory + .Query(table) + .InsertAsync( + new JsonBDataRaw() + { + id = data.Id, + data = new JsonRaw(data), + rawdataid = rawdataid + } + ); operation = "INSERT"; } else { if (errorwhendataexists) throw new ArgumentNullException(nameof(data), "Id exists already"); - - updateresult = await QueryFactory.Query(table).Where("id", data.Id) - .UpdateAsync(new JsonBDataRaw() { id = data.Id, data = new JsonRaw(data), rawdataid = rawdataid }); + + updateresult = await QueryFactory + .Query(table) + .Where("id", data.Id) + .UpdateAsync( + new JsonBDataRaw() + { + id = data.Id, + data = new JsonRaw(data), + rawdataid = rawdataid + } + ); operation = "UPDATE"; } if (createresult == 0 && updateresult == 0) errorresult = 1; - return new PGCRUDResult() { id = data.Id, created = createresult, updated = updateresult, deleted = 0, error = errorresult, operation = operation }; + return new PGCRUDResult() + { + id = data.Id, + created = createresult, + updated = updateresult, + deleted = 0, + error = errorresult, + operation = operation + }; } #endregion - } - - } diff --git a/Helper/Extensions/String2HashExtensions.cs b/Helper/Extensions/String2HashExtensions.cs index 6e94e8b31..333c8b479 100644 --- a/Helper/Extensions/String2HashExtensions.cs +++ b/Helper/Extensions/String2HashExtensions.cs @@ -11,13 +11,13 @@ public static class String2HashExtensions { public static string ComputeSHA256Hash(this string value) { - // Create a SHA256 + // Create a SHA256 using (SHA256 sha256Hash = SHA256.Create()) { - // ComputeHash - returns byte array + // ComputeHash - returns byte array byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(value)); - // Convert byte array to a string + // Convert byte array to a string StringBuilder builder = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { @@ -43,4 +43,4 @@ public static string ComputeSHA1Hash(this string value) } } } -} \ No newline at end of file +} diff --git a/Helper/Flags/AccoListCreator.cs b/Helper/Flags/AccoListCreator.cs index 0918cf5e5..0f1d6db69 100644 --- a/Helper/Flags/AccoListCreator.cs +++ b/Helper/Flags/AccoListCreator.cs @@ -14,7 +14,6 @@ public static List CreateBoardListPackages(string? boardfilter) { if (boardfilter != "null") { - if (boardfilter.Substring(boardfilter.Length - 1, 1) == ",") boardfilter = boardfilter.Substring(0, boardfilter.Length - 1); @@ -56,14 +55,16 @@ public static Tuple CreateBoardListHGV(string? boardfilter) { if (boardfilter != "null") { - if (boardfilter.Substring(boardfilter.Length - 1, 1) == ",") boardfilter = boardfilter.Substring(0, boardfilter.Length - 1); switch (boardfilter) { case "Board0": - boardidhgv = Tuple.Create(0, "price_ws,price_bb,price_hb,price_fb,price_ai"); + boardidhgv = Tuple.Create( + 0, + "price_ws,price_bb,price_hb,price_fb,price_ai" + ); break; case "Board1": boardidhgv = Tuple.Create(1, "price_ws"); @@ -91,8 +92,9 @@ public static List>> BuildMyRoomInfo(string r { if (!String.IsNullOrEmpty(roominfo) && roominfo != "null") { - //roominfo aufteilen Form 1Z-1P-18 oder 1Z-2P-18.18,1Z-1P-18 - List>> myroominfo = new List>>(); + //roominfo aufteilen Form 1Z-1P-18 oder 1Z-2P-18.18,1Z-1P-18 + List>> myroominfo = + new List>>(); var zimmerinfos = roominfo.Split('|'); int roomseq = 1; @@ -109,7 +111,11 @@ public static List>> BuildMyRoomInfo(string r mypersons.Add(s); } - var myroom = new Tuple>(roomseq.ToString(), myspittetzimmerinfo[0].Substring(0), mypersons); + var myroom = new Tuple>( + roomseq.ToString(), + myspittetzimmerinfo[0].Substring(0), + mypersons + ); myroominfo.Add(myroom); roomseq++; @@ -120,13 +126,17 @@ public static List>> BuildMyRoomInfo(string r else { //Return standard 2 Person 1 Room - List>> myroominfostd = new List>>(); - var myroomstd = new Tuple>("1", "0", new List() { "18", "18" }); + List>> myroominfostd = + new List>>(); + var myroomstd = new Tuple>( + "1", + "0", + new List() { "18", "18" } + ); myroominfostd.Add(myroomstd); return myroominfostd; } - } #region Flags @@ -134,9 +144,9 @@ public static List>> BuildMyRoomInfo(string r public static List CreateAccoTypeListfromFlag(string? accotypefilter) { List typeids = new List(); - + if (!String.IsNullOrEmpty(accotypefilter) && accotypefilter != "null") - { + { if (int.TryParse(accotypefilter, out var accotypefilterint)) { AccommodationTypeFlag myaccotypeflag = (AccommodationTypeFlag)accotypefilterint; @@ -147,7 +157,7 @@ public static List CreateAccoTypeListfromFlag(string? accotypefilter) { typeids.Add(myflag); } - } + } } return typeids; @@ -158,10 +168,11 @@ public static List CreateCategoryListfromFlag(string? categoryfilter) List categoryids = new List(); if (!String.IsNullOrEmpty(categoryfilter) && categoryfilter != "null") - { + { if (int.TryParse(categoryfilter, out var accocatfilterint)) - { - AccommodationCategoryFlag myaccotypeflag = (AccommodationCategoryFlag)accocatfilterint; + { + AccommodationCategoryFlag myaccotypeflag = + (AccommodationCategoryFlag)accocatfilterint; var myflags = myaccotypeflag.GetFlags().GetDescriptionList(); @@ -182,7 +193,7 @@ public static List CreateThemeListfromFlag(string? themefilter) if (!String.IsNullOrEmpty(themefilter) && themefilter != "null") { if (int.TryParse(themefilter, out var themefilterint)) - { + { AccoThemeFlag myaccothemeflag = (AccoThemeFlag)themefilterint; var myflags = myaccothemeflag.GetFlags().GetDescriptionList(); @@ -223,7 +234,7 @@ public static Dictionary CreateThemeListDictfromFlag(string? theme if (!String.IsNullOrEmpty(themefilter) && themefilter != "null") { if (int.TryParse(themefilter, out var themefilterint)) - { + { AccoThemeFlag myaccothemeflag = (AccoThemeFlag)themefilterint; var myflags = myaccothemeflag.GetFlags().GetDescriptionList(); @@ -245,7 +256,7 @@ public static List CreateBadgeListfromFlag(string? badgefilter) if (!String.IsNullOrEmpty(badgefilter) && badgefilter != "null") { if (int.TryParse(badgefilter, out var accobadgefilterint)) - { + { AccoBadgeFlag myaccobadgeflag = (AccoBadgeFlag)accobadgefilterint; var myflags = myaccobadgeflag.GetFlags().GetDescriptionList(); @@ -267,7 +278,7 @@ public static List CreateFeaturesListfromFlag(string? featurefilter) if (!String.IsNullOrEmpty(featurefilter) && featurefilter != "null") { if (int.TryParse(featurefilter, out var accofeatfilterint)) - { + { AccoFeatureFlag myaccofeatflag = (AccoFeatureFlag)accofeatfilterint; var myflags = myaccofeatflag.GetFlags().GetDescriptionList(); @@ -302,7 +313,7 @@ public static Dictionary CreateFeatureListDictfromFlag(string? fea if (!String.IsNullOrEmpty(featurefilter) && featurefilter != "null") { if (int.TryParse(featurefilter, out var accofeatfilterint)) - { + { AccoFeatureFlag myaccofeatflag = (AccoFeatureFlag)accofeatfilterint; var myflags = myaccofeatflag.GetFlags().GetDescriptionList(); @@ -324,7 +335,7 @@ public static List CreateBoardListFromFlag(string? boardfilter) if (!String.IsNullOrEmpty(boardfilter) && boardfilter != "null") { if (int.TryParse(boardfilter, out var boardfilterint)) - { + { AccoBoardFlag myaccoboardflag = (AccoBoardFlag)boardfilterint; var myflags = myaccoboardflag.GetFlags().GetDescriptionList(); @@ -346,7 +357,7 @@ public static List CreateBoardListPackagesfromFlag(string? boardfilter) if (!String.IsNullOrEmpty(boardfilter) && boardfilter != "null") { if (int.TryParse(boardfilter, out var boardfilterint)) - { + { PackageBoardFlag myaccoboardflag = (PackageBoardFlag)boardfilterint; var myflags = myaccoboardflag.GetFlags().GetDescriptionList(); @@ -374,7 +385,10 @@ public static Tuple CreateBoardListHGVfromFlag(string? boardfilter) switch (boardfilter) { case "0": - boardidhgv = Tuple.Create(0, "price_ws,price_bb,price_hb,price_fb,price_ai"); + boardidhgv = Tuple.Create( + 0, + "price_ws,price_bb,price_hb,price_fb,price_ai" + ); break; case "1": boardidhgv = Tuple.Create(1, "price_ws"); @@ -392,12 +406,10 @@ public static Tuple CreateBoardListHGVfromFlag(string? boardfilter) boardidhgv = Tuple.Create(5, "price_ai"); break; } - } return boardidhgv; } - //Board (Mealplans) on LCS Creator public static List CreateBoardListLCSfromFlag(string? boardfilter) { @@ -438,6 +450,5 @@ public static List CreateBoardListLCSfromFlag(string? boardfilter) } #endregion - } } diff --git a/Helper/Flags/ActivityPoiListCreator.cs b/Helper/Flags/ActivityPoiListCreator.cs index 9766678ea..accd65775 100644 --- a/Helper/Flags/ActivityPoiListCreator.cs +++ b/Helper/Flags/ActivityPoiListCreator.cs @@ -46,7 +46,10 @@ public static List CreateActivitySubTypeList(string subtypefilter) return typeids; } - public static List CreateActivitySubTypeList(string activitytype, string subtypefilter) + public static List CreateActivitySubTypeList( + string activitytype, + string subtypefilter + ) { List typeids = new List(); @@ -107,7 +110,6 @@ public static List CreateActivitySubTypeList(string activitytype, string break; - case "Wandern": switch (filter) @@ -270,8 +272,6 @@ public static List CreateActivitySubTypeList(string activitytype, string break; } - - } } @@ -621,8 +621,6 @@ public static List CreatePoiSubTypeList(string poitype, string subtypefi break; } - - } } @@ -832,14 +830,7 @@ public static List CreateSmgPoiSubTypeList(string poitype, string subtyp } break; - - - - - } - - } } @@ -1133,58 +1124,53 @@ public static List CreateSmgPoiPoiTypeList(string subtype, string poityp break; - //case "Restaurants Gasthäuser": - // switch (filter) - // { - // case "one": - // typeids.Add("Restaurants"); - // break; - // case "two": - // typeids.Add("Gasthäuser Gasthöfe "); - // break; - // case "three": - // typeids.Add("Pizzerias"); - // break; - // case "four": - // typeids.Add("Vinotheken"); - // break; - // case "five": - // typeids.Add("Bars Cafés Bistros"); - // break; - // } - - // break; - //case "Hütten Almen": - // switch (filter) - // { - // case "one": - // typeids.Add("Schutzhütten"); - // break; - // case "two": - // typeids.Add("Almen"); - // break; - // case "three": - // typeids.Add("Skihütten"); - // break; - // } - - // break; - //case "Bäuerliche Schankbetriebe": - // switch (filter) - // { - // case "one": - // typeids.Add("Buschen Hofschänke"); - // break; - - // } - - // break; - - - + //case "Restaurants Gasthäuser": + // switch (filter) + // { + // case "one": + // typeids.Add("Restaurants"); + // break; + // case "two": + // typeids.Add("Gasthäuser Gasthöfe "); + // break; + // case "three": + // typeids.Add("Pizzerias"); + // break; + // case "four": + // typeids.Add("Vinotheken"); + // break; + // case "five": + // typeids.Add("Bars Cafés Bistros"); + // break; + // } + + // break; + //case "Hütten Almen": + // switch (filter) + // { + // case "one": + // typeids.Add("Schutzhütten"); + // break; + // case "two": + // typeids.Add("Almen"); + // break; + // case "three": + // typeids.Add("Skihütten"); + // break; + // } + + // break; + //case "Bäuerliche Schankbetriebe": + // switch (filter) + // { + // case "one": + // typeids.Add("Buschen Hofschänke"); + // break; + + // } + + // break; } - - } } @@ -1221,7 +1207,10 @@ public static List CreateActivityTypefromFlag(string typefilter) return typelist; } - public static List CreateActivitySubTypefromFlag(string? typefiltertext, string? subtypefilter) + public static List CreateActivitySubTypefromFlag( + string? typefiltertext, + string? subtypefilter + ) { List subtypelist = new List(); @@ -1229,7 +1218,6 @@ public static List CreateActivitySubTypefromFlag(string? typefiltertext, { if (long.TryParse(subtypefilter, out long typefilterint)) { - switch (typefiltertext) { case "Berg": @@ -1238,12 +1226,14 @@ public static List CreateActivitySubTypefromFlag(string? typefiltertext, break; case "Radfahren": - ActivityTypeRadfahren mypoitypeflag2 = (ActivityTypeRadfahren)typefilterint; + ActivityTypeRadfahren mypoitypeflag2 = + (ActivityTypeRadfahren)typefilterint; subtypelist.AddRange(mypoitypeflag2.GetFlags().GetDescriptionList()); break; case "Stadtrundgang": - ActivityTypeOrtstouren mypoitypeflag3 = (ActivityTypeOrtstouren)typefilterint; + ActivityTypeOrtstouren mypoitypeflag3 = + (ActivityTypeOrtstouren)typefilterint; subtypelist.AddRange(mypoitypeflag3.GetFlags().GetDescriptionList()); break; @@ -1259,7 +1249,8 @@ public static List CreateActivitySubTypefromFlag(string? typefiltertext, break; case "Laufen und Fitness": - ActivityTypeLaufenFitness mypoitypeflag6 = (ActivityTypeLaufenFitness)typefilterint; + ActivityTypeLaufenFitness mypoitypeflag6 = + (ActivityTypeLaufenFitness)typefilterint; subtypelist.AddRange(mypoitypeflag6.GetFlags().GetDescriptionList()); break; @@ -1283,12 +1274,11 @@ public static List CreateActivitySubTypefromFlag(string? typefiltertext, break; case "Aufstiegsanlagen": - ActivityTypeAufstiegsanlagen mypoitypeflag10 = (ActivityTypeAufstiegsanlagen)typefilterint; + ActivityTypeAufstiegsanlagen mypoitypeflag10 = + (ActivityTypeAufstiegsanlagen)typefilterint; subtypelist.AddRange(mypoitypeflag10.GetFlags().GetDescriptionList()); - break; - } } else @@ -1298,8 +1288,6 @@ public static List CreateActivitySubTypefromFlag(string? typefiltertext, return subtypelist; } - - //Poi Data public static List CreatePoiTypefromFlag(string typefilter) @@ -1314,7 +1302,6 @@ public static List CreatePoiTypefromFlag(string typefilter) var myflags = mypoitypeflag.GetFlags().GetDescriptionList(); - foreach (var myflag in myflags) { typelist.Add(myflag); @@ -1327,7 +1314,10 @@ public static List CreatePoiTypefromFlag(string typefilter) return typelist; } - public static List CreatePoiSubTypefromFlag(string? typefiltertext, string? subtypefilter) + public static List CreatePoiSubTypefromFlag( + string? typefiltertext, + string? subtypefilter + ) { List subtypelist = new List(); @@ -1335,43 +1325,49 @@ public static List CreatePoiSubTypefromFlag(string? typefiltertext, stri { if (long.TryParse(subtypefilter, out long typefilterint)) { - switch (typefiltertext) { case "Ärzte, Apotheken": - PoiTypeAerzteApotheken mypoitypeflag1 = (PoiTypeAerzteApotheken)typefilterint; + PoiTypeAerzteApotheken mypoitypeflag1 = + (PoiTypeAerzteApotheken)typefilterint; subtypelist.AddRange(mypoitypeflag1.GetFlags().GetDescriptionList()); break; case "Kultur und Sehenswürdigkeiten": - PoiTypeKulturSehenswuerdigkeiten mypoitypeflag2 = (PoiTypeKulturSehenswuerdigkeiten)typefilterint; + PoiTypeKulturSehenswuerdigkeiten mypoitypeflag2 = + (PoiTypeKulturSehenswuerdigkeiten)typefilterint; subtypelist.AddRange(mypoitypeflag2.GetFlags().GetDescriptionList()); break; case "Nachtleben und Unterhaltung": - PoiTypeNachtlebenUnterhaltung mypoitypeflag3 = (PoiTypeNachtlebenUnterhaltung)typefilterint; + PoiTypeNachtlebenUnterhaltung mypoitypeflag3 = + (PoiTypeNachtlebenUnterhaltung)typefilterint; subtypelist.AddRange(mypoitypeflag3.GetFlags().GetDescriptionList()); break; case "Öffentliche Einrichtungen": - PoiTypeOeffentlicheEinrichtungen mypoitypeflag4 = (PoiTypeOeffentlicheEinrichtungen)typefilterint; + PoiTypeOeffentlicheEinrichtungen mypoitypeflag4 = + (PoiTypeOeffentlicheEinrichtungen)typefilterint; subtypelist.AddRange(mypoitypeflag4.GetFlags().GetDescriptionList()); break; case "Verkehr und Transport": - PoiTypeVerkehrTransport mypoitypeflag5 = (PoiTypeVerkehrTransport)typefilterint; + PoiTypeVerkehrTransport mypoitypeflag5 = + (PoiTypeVerkehrTransport)typefilterint; subtypelist.AddRange(mypoitypeflag5.GetFlags().GetDescriptionList()); break; case "Sport und Freizeit": - PoiTypeSportFreizeit mypoitypeflag6 = (PoiTypeSportFreizeit)typefilterint; + PoiTypeSportFreizeit mypoitypeflag6 = + (PoiTypeSportFreizeit)typefilterint; subtypelist.AddRange(mypoitypeflag6.GetFlags().GetDescriptionList()); break; case "Geschäfte und Dienstleister": - PoiTypeGeschaefteDienstleister mypoitypeflag7 = (PoiTypeGeschaefteDienstleister)typefilterint; + PoiTypeGeschaefteDienstleister mypoitypeflag7 = + (PoiTypeGeschaefteDienstleister)typefilterint; subtypelist.AddRange(mypoitypeflag7.GetFlags().GetDescriptionList()); break; @@ -1383,7 +1379,8 @@ public static List CreatePoiSubTypefromFlag(string? typefiltertext, stri break; case "Dienstleister": - PoiTypeDienstleister mypoitypeflag9 = (PoiTypeDienstleister)typefilterint; + PoiTypeDienstleister mypoitypeflag9 = + (PoiTypeDienstleister)typefilterint; subtypelist.AddRange(mypoitypeflag9.GetFlags().GetDescriptionList()); break; @@ -1414,7 +1411,6 @@ public static List CreatePoiSubTypefromFlag(string? typefiltertext, stri return subtypelist; } - //SmgPois public static List CreateSmgPoiTypefromFlag(string typefilter) @@ -1429,7 +1425,6 @@ public static List CreateSmgPoiTypefromFlag(string typefilter) var myflags = mypoitypeflag.GetFlags().GetDescriptionList(); - foreach (var myflag in myflags) { typelist.Add(myflag); @@ -1442,7 +1437,10 @@ public static List CreateSmgPoiTypefromFlag(string typefilter) return typelist; } - public static List CreateSmgPoiSubTypefromFlag(string? typefiltertext, string? subtypefilter) + public static List CreateSmgPoiSubTypefromFlag( + string? typefiltertext, + string? subtypefilter + ) { List subtypelist = new List(); @@ -1450,53 +1448,59 @@ public static List CreateSmgPoiSubTypefromFlag(string? typefiltertext, s { if (long.TryParse(subtypefilter, out long typefilterint)) { - switch (typefiltertext) { case "Wellness Entspannung": - SmgPoiSubTypeFlagWellness mypoitypeflag1 = (SmgPoiSubTypeFlagWellness)typefilterint; + SmgPoiSubTypeFlagWellness mypoitypeflag1 = + (SmgPoiSubTypeFlagWellness)typefilterint; subtypelist.AddRange(mypoitypeflag1.GetFlags().GetDescriptionList()); break; case "Winter": - SmgPoiSubTypeFlagWinter mypoitypeflag2 = (SmgPoiSubTypeFlagWinter)typefilterint; + SmgPoiSubTypeFlagWinter mypoitypeflag2 = + (SmgPoiSubTypeFlagWinter)typefilterint; subtypelist.AddRange(mypoitypeflag2.GetFlags().GetDescriptionList()); break; case "Sommer": - SmgPoiSubTypeFlagSommer mypoitypeflag3 = (SmgPoiSubTypeFlagSommer)typefilterint; + SmgPoiSubTypeFlagSommer mypoitypeflag3 = + (SmgPoiSubTypeFlagSommer)typefilterint; subtypelist.AddRange(mypoitypeflag3.GetFlags().GetDescriptionList()); break; case "Kultur Sehenswürdigkeiten": - SmgPoiSubTypeFlagKultur mypoitypeflag4 = (SmgPoiSubTypeFlagKultur)typefilterint; + SmgPoiSubTypeFlagKultur mypoitypeflag4 = + (SmgPoiSubTypeFlagKultur)typefilterint; subtypelist.AddRange(mypoitypeflag4.GetFlags().GetDescriptionList()); break; case "Anderes": - SmgPoiSubTypeFlagAnderes mypoitypeflag5 = (SmgPoiSubTypeFlagAnderes)typefilterint; + SmgPoiSubTypeFlagAnderes mypoitypeflag5 = + (SmgPoiSubTypeFlagAnderes)typefilterint; subtypelist.AddRange(mypoitypeflag5.GetFlags().GetDescriptionList()); break; case "Essen Trinken": - SmgPoiSubTypeFlagEssenTrinken mypoitypeflag6 = (SmgPoiSubTypeFlagEssenTrinken)typefilterint; + SmgPoiSubTypeFlagEssenTrinken mypoitypeflag6 = + (SmgPoiSubTypeFlagEssenTrinken)typefilterint; subtypelist.AddRange(mypoitypeflag6.GetFlags().GetDescriptionList()); break; case "Mobilität": - SmgPoiSubTypeFlagMobility mypoitypeflag7 = (SmgPoiSubTypeFlagMobility)typefilterint; + SmgPoiSubTypeFlagMobility mypoitypeflag7 = + (SmgPoiSubTypeFlagMobility)typefilterint; subtypelist.AddRange(mypoitypeflag7.GetFlags().GetDescriptionList()); break; case "Geschäfte und Dienstleister": - SmgPoiSubTypeFlagShopsAndServices mypoitypeflag8 = (SmgPoiSubTypeFlagShopsAndServices)typefilterint; + SmgPoiSubTypeFlagShopsAndServices mypoitypeflag8 = + (SmgPoiSubTypeFlagShopsAndServices)typefilterint; subtypelist.AddRange(mypoitypeflag8.GetFlags().GetDescriptionList()); break; - } } else @@ -1506,7 +1510,10 @@ public static List CreateSmgPoiSubTypefromFlag(string? typefiltertext, s return subtypelist; } - public static List CreateSmgPoiPoiTypefromFlag(string? subtypefilter, string? poitypefilter) + public static List CreateSmgPoiPoiTypefromFlag( + string? subtypefilter, + string? poitypefilter + ) { List subtypelist = new List(); @@ -1514,187 +1521,213 @@ public static List CreateSmgPoiPoiTypefromFlag(string? subtypefilter, st { if (long.TryParse(poitypefilter, out long typefilterint)) { - switch (subtypefilter) { case "Wandern": - SmgPoiPoiTypeFlagWandern mypoitypeflag1 = (SmgPoiPoiTypeFlagWandern)typefilterint; + SmgPoiPoiTypeFlagWandern mypoitypeflag1 = + (SmgPoiPoiTypeFlagWandern)typefilterint; subtypelist.AddRange(mypoitypeflag1.GetFlags().GetDescriptionList()); break; case "Klettern": - SmgPoiPoiTypeFlagKlettern mypoitypeflag2 = (SmgPoiPoiTypeFlagKlettern)typefilterint; + SmgPoiPoiTypeFlagKlettern mypoitypeflag2 = + (SmgPoiPoiTypeFlagKlettern)typefilterint; subtypelist.AddRange(mypoitypeflag2.GetFlags().GetDescriptionList()); break; case "Radfahren Radtouren": - SmgPoiPoiTypeFlagRadfahren mypoitypeflag3 = (SmgPoiPoiTypeFlagRadfahren)typefilterint; + SmgPoiPoiTypeFlagRadfahren mypoitypeflag3 = + (SmgPoiPoiTypeFlagRadfahren)typefilterint; subtypelist.AddRange(mypoitypeflag3.GetFlags().GetDescriptionList()); break; case "Museen": - SmgPoiPoiTypeFlagMuseen mypoitypeflag4 = (SmgPoiPoiTypeFlagMuseen)typefilterint; + SmgPoiPoiTypeFlagMuseen mypoitypeflag4 = + (SmgPoiPoiTypeFlagMuseen)typefilterint; subtypelist.AddRange(mypoitypeflag4.GetFlags().GetDescriptionList()); break; case "Freizeit Erlebnis": - SmgPoiPoiTypeFlagFreizeitErlebnis mypoitypeflag5 = (SmgPoiPoiTypeFlagFreizeitErlebnis)typefilterint; + SmgPoiPoiTypeFlagFreizeitErlebnis mypoitypeflag5 = + (SmgPoiPoiTypeFlagFreizeitErlebnis)typefilterint; subtypelist.AddRange(mypoitypeflag5.GetFlags().GetDescriptionList()); break; case "Kirchen Klöster": - SmgPoiPoiTypeFlagKirchenKloester mypoitypeflag6 = (SmgPoiPoiTypeFlagKirchenKloester)typefilterint; + SmgPoiPoiTypeFlagKirchenKloester mypoitypeflag6 = + (SmgPoiPoiTypeFlagKirchenKloester)typefilterint; subtypelist.AddRange(mypoitypeflag6.GetFlags().GetDescriptionList()); break; case "Laufen Fitness": - SmgPoiPoiTypeFlagLaufenFitness mypoitypeflag7 = (SmgPoiPoiTypeFlagLaufenFitness)typefilterint; + SmgPoiPoiTypeFlagLaufenFitness mypoitypeflag7 = + (SmgPoiPoiTypeFlagLaufenFitness)typefilterint; subtypelist.AddRange(mypoitypeflag7.GetFlags().GetDescriptionList()); break; case "Therme Wasserwelten": - SmgPoiPoiTypeFlagThermeWasserwelten mypoitypeflag9 = (SmgPoiPoiTypeFlagThermeWasserwelten)typefilterint; + SmgPoiPoiTypeFlagThermeWasserwelten mypoitypeflag9 = + (SmgPoiPoiTypeFlagThermeWasserwelten)typefilterint; subtypelist.AddRange(mypoitypeflag9.GetFlags().GetDescriptionList()); break; case "Weihnachtsmärkte": - SmgPoiPoiTypeFlagWeihnachtsmaerkte mypoitypeflag10 = (SmgPoiPoiTypeFlagWeihnachtsmaerkte)typefilterint; + SmgPoiPoiTypeFlagWeihnachtsmaerkte mypoitypeflag10 = + (SmgPoiPoiTypeFlagWeihnachtsmaerkte)typefilterint; subtypelist.AddRange(mypoitypeflag10.GetFlags().GetDescriptionList()); break; case "Langlaufen": - SmgPoiPoiTypeFlagLanglaufen mypoitypeflag11 = (SmgPoiPoiTypeFlagLanglaufen)typefilterint; + SmgPoiPoiTypeFlagLanglaufen mypoitypeflag11 = + (SmgPoiPoiTypeFlagLanglaufen)typefilterint; subtypelist.AddRange(mypoitypeflag11.GetFlags().GetDescriptionList()); break; case "Rodeln": - SmgPoiPoiTypeFlagRodelbahnen mypoitypeflag12 = (SmgPoiPoiTypeFlagRodelbahnen)typefilterint; + SmgPoiPoiTypeFlagRodelbahnen mypoitypeflag12 = + (SmgPoiPoiTypeFlagRodelbahnen)typefilterint; subtypelist.AddRange(mypoitypeflag12.GetFlags().GetDescriptionList()); break; case "Skischulen Skiverleih": - SmgPoiPoiTypeFlagSkischulen mypoitypeflag13 = (SmgPoiPoiTypeFlagSkischulen)typefilterint; + SmgPoiPoiTypeFlagSkischulen mypoitypeflag13 = + (SmgPoiPoiTypeFlagSkischulen)typefilterint; subtypelist.AddRange(mypoitypeflag13.GetFlags().GetDescriptionList()); break; case "Skigebiete": - SmgPoiPoiTypeFlagSkigebiete mypoitypeflag113 = (SmgPoiPoiTypeFlagSkigebiete)typefilterint; + SmgPoiPoiTypeFlagSkigebiete mypoitypeflag113 = + (SmgPoiPoiTypeFlagSkigebiete)typefilterint; subtypelist.AddRange(mypoitypeflag113.GetFlags().GetDescriptionList()); break; case "Burgen Schlösser": - SmgPoiPoiTypeFlagBurgenSchloesser mypoitypeflag14 = (SmgPoiPoiTypeFlagBurgenSchloesser)typefilterint; + SmgPoiPoiTypeFlagBurgenSchloesser mypoitypeflag14 = + (SmgPoiPoiTypeFlagBurgenSchloesser)typefilterint; subtypelist.AddRange(mypoitypeflag14.GetFlags().GetDescriptionList()); break; case "Badeseen Freibäder": - SmgPoiPoiTypeFlagBadeseenFreibaeder mypoitypeflag15 = (SmgPoiPoiTypeFlagBadeseenFreibaeder)typefilterint; + SmgPoiPoiTypeFlagBadeseenFreibaeder mypoitypeflag15 = + (SmgPoiPoiTypeFlagBadeseenFreibaeder)typefilterint; subtypelist.AddRange(mypoitypeflag15.GetFlags().GetDescriptionList()); break; case "Architektur": - SmgPoiPoiTypeFlagArchitektur mypoitypeflag16 = (SmgPoiPoiTypeFlagArchitektur)typefilterint; + SmgPoiPoiTypeFlagArchitektur mypoitypeflag16 = + (SmgPoiPoiTypeFlagArchitektur)typefilterint; subtypelist.AddRange(mypoitypeflag16.GetFlags().GetDescriptionList()); break; case "Restaurants Gasthäuser": - SmgPoiPoiTypeFlagRestaurantsGasthauser mypoitypeflag17 = (SmgPoiPoiTypeFlagRestaurantsGasthauser)typefilterint; + SmgPoiPoiTypeFlagRestaurantsGasthauser mypoitypeflag17 = + (SmgPoiPoiTypeFlagRestaurantsGasthauser)typefilterint; subtypelist.AddRange(mypoitypeflag17.GetFlags().GetDescriptionList()); break; case "Andere Gastronomiebetriebe": - SmgPoiPoiTypeFlagAndereGastronomiebetriebe mypoitypeflag28 = (SmgPoiPoiTypeFlagAndereGastronomiebetriebe)typefilterint; + SmgPoiPoiTypeFlagAndereGastronomiebetriebe mypoitypeflag28 = + (SmgPoiPoiTypeFlagAndereGastronomiebetriebe)typefilterint; subtypelist.AddRange(mypoitypeflag28.GetFlags().GetDescriptionList()); break; case "Hütten Almen": - SmgPoiPoiTypeFlagHuettenAlmen mypoitypeflag18 = (SmgPoiPoiTypeFlagHuettenAlmen)typefilterint; + SmgPoiPoiTypeFlagHuettenAlmen mypoitypeflag18 = + (SmgPoiPoiTypeFlagHuettenAlmen)typefilterint; subtypelist.AddRange(mypoitypeflag18.GetFlags().GetDescriptionList()); break; case "Bäuerliche Schankbetriebe": - SmgPoiPoiTypeFlagBauerlicheSchankbetriebe mypoitypeflag19 = (SmgPoiPoiTypeFlagBauerlicheSchankbetriebe)typefilterint; + SmgPoiPoiTypeFlagBauerlicheSchankbetriebe mypoitypeflag19 = + (SmgPoiPoiTypeFlagBauerlicheSchankbetriebe)typefilterint; subtypelist.AddRange(mypoitypeflag19.GetFlags().GetDescriptionList()); break; case "Aufstiegsanlagen": - SmgPoiPoiTypeFlagAufstiegsanlagen mypoitypeflag27 = (SmgPoiPoiTypeFlagAufstiegsanlagen)typefilterint; + SmgPoiPoiTypeFlagAufstiegsanlagen mypoitypeflag27 = + (SmgPoiPoiTypeFlagAufstiegsanlagen)typefilterint; subtypelist.AddRange(mypoitypeflag27.GetFlags().GetDescriptionList()); break; - case "Gesundheit": - SmgPoiPoiTypeFlagGesundheit mypoitypeflag20 = (SmgPoiPoiTypeFlagGesundheit)typefilterint; + SmgPoiPoiTypeFlagGesundheit mypoitypeflag20 = + (SmgPoiPoiTypeFlagGesundheit)typefilterint; subtypelist.AddRange(mypoitypeflag20.GetFlags().GetDescriptionList()); break; case "Geschäfte": - SmgPoiPoiTypeFlagGeschaefte mypoitypeflag21 = (SmgPoiPoiTypeFlagGeschaefte)typefilterint; + SmgPoiPoiTypeFlagGeschaefte mypoitypeflag21 = + (SmgPoiPoiTypeFlagGeschaefte)typefilterint; subtypelist.AddRange(mypoitypeflag21.GetFlags().GetDescriptionList()); break; case "Dienstleister": - SmgPoiPoiTypeFlagDienstleister mypoitypeflag22 = (SmgPoiPoiTypeFlagDienstleister)typefilterint; + SmgPoiPoiTypeFlagDienstleister mypoitypeflag22 = + (SmgPoiPoiTypeFlagDienstleister)typefilterint; subtypelist.AddRange(mypoitypeflag22.GetFlags().GetDescriptionList()); break; case "Öffentliche Einrichtungen": - SmgPoiPoiTypeFlagOeffentlichEinrichtungen mypoitypeflag23 = (SmgPoiPoiTypeFlagOeffentlichEinrichtungen)typefilterint; + SmgPoiPoiTypeFlagOeffentlichEinrichtungen mypoitypeflag23 = + (SmgPoiPoiTypeFlagOeffentlichEinrichtungen)typefilterint; subtypelist.AddRange(mypoitypeflag23.GetFlags().GetDescriptionList()); break; case "Nachtleben und Unterhaltung": - SmgPoiPoiTypeFlagNachtlebenUnterhaltung mypoitypeflag24 = (SmgPoiPoiTypeFlagNachtlebenUnterhaltung)typefilterint; + SmgPoiPoiTypeFlagNachtlebenUnterhaltung mypoitypeflag24 = + (SmgPoiPoiTypeFlagNachtlebenUnterhaltung)typefilterint; subtypelist.AddRange(mypoitypeflag24.GetFlags().GetDescriptionList()); break; case "Spiel und Sportanlagen": - SmgPoiPoiTypeFlagSpielundSportanlagen mypoitypeflag25 = (SmgPoiPoiTypeFlagSpielundSportanlagen)typefilterint; + SmgPoiPoiTypeFlagSpielundSportanlagen mypoitypeflag25 = + (SmgPoiPoiTypeFlagSpielundSportanlagen)typefilterint; subtypelist.AddRange(mypoitypeflag25.GetFlags().GetDescriptionList()); break; case "Guides Schulen": - SmgPoiPoiTypeFlagGuidesSchulen mypoitypeflag26 = (SmgPoiPoiTypeFlagGuidesSchulen)typefilterint; + SmgPoiPoiTypeFlagGuidesSchulen mypoitypeflag26 = + (SmgPoiPoiTypeFlagGuidesSchulen)typefilterint; subtypelist.AddRange(mypoitypeflag26.GetFlags().GetDescriptionList()); break; case "Vereine": - SmgPoiPoiTypeFlagVereine mypoitypeflag30 = (SmgPoiPoiTypeFlagVereine)typefilterint; + SmgPoiPoiTypeFlagVereine mypoitypeflag30 = + (SmgPoiPoiTypeFlagVereine)typefilterint; subtypelist.AddRange(mypoitypeflag30.GetFlags().GetDescriptionList()); break; case "Unternehmen": - SmgPoiPoiTypeFlagUnternehmen mypoitypeflag29 = (SmgPoiPoiTypeFlagUnternehmen)typefilterint; + SmgPoiPoiTypeFlagUnternehmen mypoitypeflag29 = + (SmgPoiPoiTypeFlagUnternehmen)typefilterint; subtypelist.AddRange(mypoitypeflag29.GetFlags().GetDescriptionList()); break; } - - } else return new List(); @@ -1703,7 +1736,6 @@ public static List CreateSmgPoiPoiTypefromFlag(string? subtypefilter, st return subtypelist; } - #endregion } } diff --git a/Helper/Flags/ArticleListCreator.cs b/Helper/Flags/ArticleListCreator.cs index 744498d6e..3e2e09979 100644 --- a/Helper/Flags/ArticleListCreator.cs +++ b/Helper/Flags/ArticleListCreator.cs @@ -26,7 +26,10 @@ public static List CreateArticleTypeList(string typefilter) return typeids; } - public static List CreateArticleSubTypeList(string? articletype, string? subtypefilter) + public static List CreateArticleSubTypeList( + string? articletype, + string? subtypefilter + ) { List typeids = new List(); @@ -215,10 +218,7 @@ public static List CreateArticleSubTypeList(string? articletype, string? break; } break; - } - - } } @@ -252,7 +252,10 @@ public static List CreateArticleTypefromFlag(string typefilter) return typelist; } - public static List CreateArticleSubTypefromFlag(string? typefiltertext, string? subtypefilter) + public static List CreateArticleSubTypefromFlag( + string? typefiltertext, + string? subtypefilter + ) { List subtypelist = new List(); @@ -261,11 +264,11 @@ public static List CreateArticleSubTypefromFlag(string? typefiltertext, long typefilterint = 0; if (long.TryParse(subtypefilter, out typefilterint)) { - switch (typefiltertext) { case "basisartikel": - ArticleBasisArticleFlag mypoitypeflag1 = (ArticleBasisArticleFlag)typefilterint; + ArticleBasisArticleFlag mypoitypeflag1 = + (ArticleBasisArticleFlag)typefilterint; subtypelist.AddRange(mypoitypeflag1.GetFlags().GetDescriptionList()); break; @@ -275,17 +278,20 @@ public static List CreateArticleSubTypefromFlag(string? typefiltertext, break; case "contentartikel": - ArticleContentArticleFlag mypoitypeflag3 = (ArticleContentArticleFlag)typefilterint; + ArticleContentArticleFlag mypoitypeflag3 = + (ArticleContentArticleFlag)typefilterint; subtypelist.AddRange(mypoitypeflag3.GetFlags().GetDescriptionList()); break; case "veranstaltungsartikel": - ArticleVeranstaltungsArticleFlag mypoitypeflag4 = (ArticleVeranstaltungsArticleFlag)typefilterint; + ArticleVeranstaltungsArticleFlag mypoitypeflag4 = + (ArticleVeranstaltungsArticleFlag)typefilterint; subtypelist.AddRange(mypoitypeflag4.GetFlags().GetDescriptionList()); break; case "presseartikel": - ArticlePresseArticleFlag mypoitypeflag5 = (ArticlePresseArticleFlag)typefilterint; + ArticlePresseArticleFlag mypoitypeflag5 = + (ArticlePresseArticleFlag)typefilterint; subtypelist.AddRange(mypoitypeflag5.GetFlags().GetDescriptionList()); break; @@ -303,11 +309,11 @@ public static List CreateArticleSubTypefromFlag(string? typefiltertext, // break; case "b2bartikel": - ArticleB2BArticleFlag mypoitypeflag8 = (ArticleB2BArticleFlag)typefilterint; + ArticleB2BArticleFlag mypoitypeflag8 = + (ArticleB2BArticleFlag)typefilterint; subtypelist.AddRange(mypoitypeflag8.GetFlags().GetDescriptionList()); break; - } } else @@ -316,6 +322,5 @@ public static List CreateArticleSubTypefromFlag(string? typefiltertext, return subtypelist; } - } } diff --git a/Helper/Flags/CommonListCreator.cs b/Helper/Flags/CommonListCreator.cs index 87fd2e4a0..7bf6a4bab 100644 --- a/Helper/Flags/CommonListCreator.cs +++ b/Helper/Flags/CommonListCreator.cs @@ -104,22 +104,25 @@ public static (int min, int max) CreateRangeString(string? rangetoSplit) public static (double, double) CreateRangeStringDouble(string? rangetoSplit) { - NumberFormatInfo provider = new NumberFormatInfo - { - NumberDecimalSeparator = "." - }; + NumberFormatInfo provider = new NumberFormatInfo { NumberDecimalSeparator = "." }; if (rangetoSplit != null) { var splittedfilter = rangetoSplit.Split(','); - return (Convert.ToDouble(splittedfilter[0], provider), Convert.ToDouble(splittedfilter[1], provider)); + return ( + Convert.ToDouble(splittedfilter[0], provider), + Convert.ToDouble(splittedfilter[1], provider) + ); } else return (0.0, 0.0); } - public static List CreateDifficultyList(string? difficultyfilter, string? activitypoitype) + public static List CreateDifficultyList( + string? difficultyfilter, + string? activitypoitype + ) { List difficultyids = new List(); @@ -212,14 +215,15 @@ public static List CreateDifficultyList(string? difficultyfilter, string break; } - - } return difficultyids; } - public static List CreateDifficultyListfromFlag(string? difficultyfilter, string activitypoitype) + public static List CreateDifficultyListfromFlag( + string? difficultyfilter, + string activitypoitype + ) { List difficultyids = new List(); @@ -321,8 +325,6 @@ public static List CreateDifficultyListfromFlag(string? difficultyfilter break; } - - } return difficultyids; diff --git a/Helper/Flags/EventListCreator.cs b/Helper/Flags/EventListCreator.cs index 5449f8bae..6d3f9d2a3 100644 --- a/Helper/Flags/EventListCreator.cs +++ b/Helper/Flags/EventListCreator.cs @@ -21,7 +21,6 @@ public static List CreateEventTopicRidList(string topicfilter) foreach (var filter in splittedfilter) { - switch (filter) { case "1": @@ -84,7 +83,6 @@ public static List CreateEventTopicRidListfromFlag(string? topicfilter) var myflags = mytopicflag.GetFlags().GetDescriptionList(); - foreach (var myflag in myflags) { topicids.Add(myflag); @@ -94,6 +92,5 @@ public static List CreateEventTopicRidListfromFlag(string? topicfilter) return topicids; } - } } diff --git a/Helper/Flags/Flags.cs b/Helper/Flags/Flags.cs index 2149115c3..fdaa9d6da 100644 --- a/Helper/Flags/Flags.cs +++ b/Helper/Flags/Flags.cs @@ -15,7 +15,8 @@ public static IEnumerable GetValues() } } } - //Pakete Weekday + + //Pakete Weekday [Flags] public enum WeekdayFlag { @@ -36,14 +37,19 @@ public enum AccoBoardFlag { [Description("all boards")] AllBoards = 0, + [Description("without board")] WithoutBoard = 1, + [Description("breakfast")] Breakfast = 2, + [Description("half board")] HalfBoard = 4, + [Description("full board")] FullBoard = 8, + [Description("All Inclusive")] AllInclusive = 16 } @@ -54,14 +60,19 @@ public enum PackageBoardFlag { [Description("0")] AllBoards = 0, + [Description("1")] without = 2, + [Description("2")] breakfast = 4, + [Description("3")] halfboard = 8, + [Description("4")] fullboard = 16, + [Description("5")] allinclusive = 32 } @@ -72,12 +83,16 @@ public enum HgvBoardFlag { [Description("price_ws")] price_ws = 1, + [Description("price_bb")] price_bb = 2, + [Description("price_hb")] price_hb = 4, + [Description("price_fb")] price_fb = 8, + [Description("price_ai")] price_ai = 16 } @@ -88,18 +103,25 @@ public enum AccommodationTypeFlag { [Description("HotelPension")] HotelPension = 1, + [Description("BedBreakfast")] BedBreakfast = 2, + [Description("Farm")] Farm = 4, + [Description("Camping")] Camping = 8, + [Description("Youth")] Youth = 16, + [Description("Mountain")] Mountain = 32, + [Description("Apartment")] Apartment = 64, + [Description("Notdefined")] Notdefined = 128 } @@ -110,38 +132,55 @@ public enum AccommodationCategoryFlag { [Description("Not categorized")] Without = 1, + [Description("1star")] OneStar = 2, + [Description("1flower")] OneFlower = 4, + [Description("1sun")] OneSun = 8, + [Description("2stars")] TwoStars = 16, + [Description("2flowers")] TwoFlowers = 32, + [Description("2suns")] TwoSuns = 64, + [Description("3stars")] ThreeStars = 128, + [Description("3flowers")] ThreeFlowers = 256, + [Description("3suns")] ThreeSuns = 512, + [Description("3sstars")] ThreeSStars = 1024, + [Description("4stars")] FourStars = 2048, + [Description("4flowers")] FourFlowers = 4096, + [Description("4suns")] FourSuns = 8192, + [Description("4sstars")] FourSStars = 16384, + [Description("5stars")] FiveStars = 32768, + [Description("5flowers")] FiveFlowers = 65536, + [Description("5suns")] FiveSuns = 131072 } @@ -152,38 +191,55 @@ public enum AccoThemeFlag { [Description("Gourmet")] Gourmet = 1, + [Description("In der Höhe")] InderHöhe = 1 << 1, + [Description("Regionale Wellness")] RegionaleWellness = 1 << 2, + [Description("Biken")] Biken = 1 << 3, + [Description("Familie")] Familie = 1 << 4, + [Description("Wandern")] Wandern = 1 << 5, + [Description("Wein")] Wein = 1 << 6, + [Description("Städtisches Flair")] StädtischesFlair = 1 << 7, + [Description("Am Skigebiet")] AmSkigebiet = 1 << 8, + [Description("Mediterran")] Mediterran = 1 << 9, + [Description("Dolomiten")] Dolomiten = 1 << 10, + [Description("Alpin")] Alpin = 1 << 11, + [Description("Kleine Betriebe")] KleineBetriebe = 1 << 12, + [Description("Hütten und Berggasthöfe")] HüttenBerggasthöfe = 1 << 13, + [Description("Bäuerliche Welten")] BäuerlicheWelten = 1 << 14, + [Description("Bonus Vacanze")] BonusVacanze = 1 << 15, + [Description("Christkindlmarkt")] Christkindlmarkt = 1 << 16, + [Description("Sustainability")] Sustainability = 1 << 17 } @@ -194,18 +250,25 @@ public enum AccoBadgeFlag { [Description("Wellnesshotel")] Wellnesshotel = 1, + [Description("Familienhotel")] Familienhotel = 1 << 1, + [Description("Bikehotel")] Bikehotel = 1 << 2, + [Description("Bauernhof")] Bauernhof = 1 << 3, + [Description("Behindertengerecht")] Behindertengerecht = 1 << 4, + [Description("Wanderhotel")] Wanderhotel = 1 << 5, + [Description("Südtirol Privat")] SuedtirolPrivat = 1 << 6, + [Description("Vinumhotel")] Vinumhotel = 1 << 7 } @@ -215,57 +278,83 @@ public enum AccoBadgeFlag public enum PackageThemeFlag { [Description("Wandern")] - Wandern = 1, //1, + Wandern = 1, //1, + [Description("Rad & Mountainbike")] RadMountainbike = 1 << 1, // 2, + [Description("Familie")] Familie = 1 << 2, //4, + [Description("Wellness Gesundheit")] WellnessGesundheit = 1 << 3, //8, + [Description("Essen und Trinken")] EssenTrinken = 1 << 4, //16, + [Description("Golf")] Golf = 1 << 5, //32, + [Description("Kultur")] Kultur = 1 << 6, //64, + [Description("Motorsport")] Motorsport = 1 << 7, //128, + [Description("Ohne Auto im Urlaub")] OhneAutoimUrlaub = 1 << 8, //256, + [Description("Ski & Snowboard")] SkiSnowboard = 1 << 9, //512, + [Description("Sommer Aktiv")] SommerAktiv = 1 << 10, //1024, + [Description("Veranstaltungen")] Veranstaltungen = 1 << 11, //2048, + [Description("Weihnachtsmärkte")] Weihnachtsmaerkte = 1 << 12, //4096, + [Description("Winter Aktiv")] WinterAktiv = 1 << 13, //8192, + [Description("Vitalpina")] Vitalpina = 1 << 14, //16384, + [Description("Vitalpina: Durchatmen")] VitalpinaDurchatmen = 1 << 15, //32768, + [Description("Bikehotels: EBike")] BikehotelsEBike = 1 << 16, //65536, + [Description("Bikehotels Freeride")] BikehotelsFreeride = 1 << 17, //131072, + [Description("Bikehotels Mountainbike")] BikehotelsMountainbike = 1 << 18, //524288, + [Description("Bikehotels Radwandern")] BikehotelsRadwandern = 1 << 19, //1048576, + [Description("Bikehotels: Rennrad")] BikehotelsRennrad = 1 << 20, //2097152, + [Description("Familienhotels")] Familienhotels = 1 << 21, //4194304, + [Description("Familienhotels: Naturdetektiv")] FamilienhotelsNaturdetektiv = 1 << 22, //8388608, + [Description("Familienhotel")] Familienhotel = 1 << 23, //33554432, + [Description("Naturdetektiv Sommer")] NaturdetektivSommer = 1 << 24, //67108864, + [Description("Naturdetektiv Winter")] NaturdetektivWinter = 1 << 25, //134217728 + [Description("Südtirol Balance")] SuedtirolBalance = 1 << 26, //134217728 } @@ -276,26 +365,36 @@ public enum AccoFeatureFlag { [Description("Gruppenfreundlich")] Gruppenfreundlich = 1, + [Description("Tagung")] Tagung = 1 << 1, + [Description("Schwimmbad")] Schwimmbad = 1 << 2, + [Description("Sauna")] Sauna = 1 << 3, + [Description("Garage")] Garage = 1 << 4, + [Description("Abholservice")] Abholservice = 1 << 5, + [Description("Wlan")] Wlan = 1 << 6, + [Description("Barrierefrei")] Barrierefrei = 1 << 7, + [Description("Allergikerküche")] Allergikerküche = 1 << 8, + [Description("Kleine Haustiere")] KleineHaustiere = 1 << 9, + [Description("Guestcard")] - Guestcard = 1 << 10 + Guestcard = 1 << 10 } #endregion @@ -308,42 +407,61 @@ public enum GastroCategoryFlag { [Description("B0BDC4C2C5938D9B734D97B09C8A47A4")] Restaurant = 1, + [Description("9095FC003A3E2F393D63A54682359B37")] BarCafeBistro = 1 << 1, + [Description("59FE0B38EB7F4AC3951A5F477A0E1FA2")] PubDisco = 1 << 2, + [Description("43D095A3FE8A450099D33926BBC1ADF8")] ApresSki = 1 << 3, + [Description("8176B5A707E2067708AF18045E068E15")] Jausenstation = 1 << 4, + [Description("AC56B3717C3152A428A1D338A638C570")] Pizzeria = 1 << 5, + [Description("E8883A596A2463A9B3E1586C9E780F17")] BauerlicherSchankbetrieb = 1 << 6, + [Description("700B02F1BE96B01C34CCF7A637DB3054")] Buschenschank = 1 << 7, + [Description("4A14E16888CB07C18C65A6B59C5A19A7")] Hofschank = 1 << 8, + [Description("AB320B063588EA95F45505E940903115")] ToerggeleLokale = 1 << 9, + [Description("33B86F5B91A08A0EFD6854DEB0207205")] Schnellimbiss = 1 << 10, + [Description("29BC7A9AE7CF173FBCCE6A48DD001229")] Mensa = 1 << 11, + [Description("C3CC9C83C32BFA4E9A05133291EA9FFB")] VinothekWeinhausTaverne = 1 << 12, + [Description("6A2A32E2BFEE270083351B0CFD9BA2E3")] Eisdiele = 1 << 13, + [Description("9B158D17F03509C46037C3C7B23F2FE4")] Gasthaus = 1 << 14, + [Description("D8B8ABEDD17A139DEDA2695545C420D6")] Gasthof = 1 << 15, + [Description("902D9BA559B1ED889694284F05CFA41E")] Braugarten = 1 << 16, + [Description("2328C37167BBBC5776831B8A262A6C36")] Schutzhuette = 1 << 17, + [Description("8025DB5CFCBA4FF281DDDE1F2B1D19A2")] Alm = 1 << 18, + [Description("B916489A77C94D8D92B03184EE587A31")] Skihuette = 1 << 19 } @@ -354,20 +472,28 @@ public enum GastroDishcodeFlag { [Description("A130EB1985EC41CFB199528BE038399B")] Speisen = 1, + [Description("B539399E53D348049B9E710A2B22E74D")] Vorspeise = 1 << 1, + [Description("A7601BBA081B4D48A50634E029B3D75A")] Hauptspeise = 1 << 2, + [Description("E7B9475EC5B24B6F830FBD0339D48F9D")] Nachspeise = 1 << 3, + [Description("EB7532946781423D9932121F3D1D7CC4")] Tagesgericht = 1 << 4, + [Description("78A13E3381FA4A71B21118BDDF84BAFB")] Menue = 1 << 5, + [Description("6284265E90D24C909E23A176EEB3B6F7")] Degustationsmenue = 1 << 6, + [Description("AD8426538FCF4D8A81E06BE044088BAA")] Kindermenues = 1 << 7, + [Description("5C84265DA5F84F84A7896808ACCB675A")] Mittagsmenues = 1 << 8 } @@ -378,20 +504,28 @@ public enum GastroCeremonyFlag { [Description("DEC7019ADE6B46CDAE87584821D9B4DB")] Familienfeiern = 1, + [Description("648773AE1BBD4001B85DC88E7592ACE2")] Hochzeiten = 1 << 1, + [Description("085CF94B4F25440AA079E88D8DBA45C2")] Geburtstagsfeiern = 1 << 2, + [Description("0A7DD92FA86B47D18DBFCB5572A93C9F")] Firmenessen = 1 << 3, + [Description("22C75C83F99F4D6FADF6D82F7754B4C1")] Weihnachtsessen = 1 << 4, + [Description("4FBC28A456AA43E6B01D8BD1072D8CE6")] Silvestermenü = 1 << 5, + [Description("94E42C7211B9430B8F096ABB7ED59AC2")] SeminareTagungen = 1 << 6, + [Description("38DCFB491D27408C990654CB64C6339D")] Versammlungen = 1 << 7, + [Description("41543CA256A8433C8CD47109FFCEE1F7")] SitzplatzAussenbereich = 1 << 8 } @@ -402,67 +536,98 @@ public enum GastroFacilityFlag : long { [Description("BBD9085F89BC417B97D986A26CE86F40")] Kreditkarte = 1L, + [Description("9F05BA64D6614894A89FFE23A4A0F20B")] BankomatMaestro = 1L << 1, + [Description("B7E9EE4A91544849B69D5A5564DDCDFB")] Barrierefrei = 1L << 2, + [Description("93BDE34283FF41899CCF530BE80201E2")] Garten = 1L << 3, + [Description("3A89DBB5F633473096C902D2CBFD2FA3")] Raucherraum = 1L << 4, + [Description("36C354DC30F14DD7B1CCFEE78E82132C")] Spielzimmer = 1L << 5, + [Description("188A9BADC0324C10B0013F108CE5EA5C")] Spielplatz = 1L << 6, + [Description("481891DECDAF443E92E9957B5EC8FCAC")] Parkplaetze = 1L << 7, + [Description("D579D1C8EA8445018CA5BB6DABEA0C26")] Garage = 1L << 8, + [Description("D9DCDD52FE444818AAFAB0E02FD92D91")] Hundeerlaubt = 1L << 9, + [Description("452422597831423F9F4E2B1A2BA9177A")] Biergarten = 1L << 10, + [Description("63534DC188314AC68DAB0EF0DE6EE5B0")] Terrasse = 1L << 11, + [Description("B3BC8F4D7BA948369515FBA8075D47DB")] Wintergarten = 1L << 12, + [Description("52281FC851CA11D18F1400A02427D15E")] GeeignetfuerBusse = 1L << 13, + [Description("5228206E51CA11D18F1400A02427D15E")] Bierbar = 1L << 14, + [Description("46AD7938616B4D4882A006BEF3B199A4")] GaultMillauSuedtirol = 1L << 15, + [Description("F0A385D0E8E44944AFCA3893712A1420")] Guidaespresso = 1L << 16, + [Description("2FA54F6F350748AE9CD1A389A5C9EDD9")] Gamberorosso = 1L << 17, + [Description("C0E761D71CC44F4C80D75FF68ED72C55")] Feinschmecker = 1L << 18, + [Description("6797D594C7BF4C7AA6D384B234EC7C44")] AralSchlemmerAtlas = 1L << 19, + [Description("E5775068F5644E92B7CF94BDFCDA5175")] VartaFuehrer = 1L << 20, + [Description("1FFD5352501542BF8BCB24B7BF75CF4F")] Bertelsmann = 1L << 21, + [Description("1641B07E28B9443EAB53E1DB7363F6F3")] PreisfuerSuedtirolerWeinkultur = 1L << 22, + [Description("5060F78090604B2E97A96D86B97D2E0B")] Michelin = 1L << 23, + [Description("ED4028BEE0164BF185B923B3DD4FF9A0")] RoterHahn = 1L << 24, + [Description("0DBA881DD41340FDA76196EBCEFC9ECD")] Tafelspitz = 1L << 25, + [Description("6C72999B96594EC08281DE9CCA00EF75")] SuedtirolerGasthaus = 1L << 26, + //NEU [Description("098EB30324EA492DBD99F323AE20A621")] KostenlosesWlan = 1L << 27, + [Description("79EDF6ABA6F8484583D38DFDE9758B80")] KleintierStreichelzoo = 1L << 28, + [Description("DB1DDC1CC1EF4449BECD341C9DC12611")] SlowFood = 1L << 29, + [Description("B92FFCECB4574BB9BCAE5EAB8917602D")] ilgattiMassobrio = 1L << 30, + [Description("80BA0C6E19524ECA8956BA65294C8E5A")] guidaOsterieItalia = 1L << 31 } @@ -473,56 +638,82 @@ public enum GastroCuisineFlag { [Description("3091F5B92F534F67986C08151E6F4454")] VegetarischesMenu = 1, + [Description("71A7D4A821F7437EA1DC05CEE9655A5A")] GlutenfreieKueche = 1 << 1, + [Description("11A6BEA7EEFC4716BDF8FBD5E15C0CFB")] LaktosefreieKost = 1 << 2, + [Description("A469B187953944A0AF49C5EBE13DCF00")] VeganeKueche = 1 << 3, + [Description("F42DBD202D6E4289AF48D138DA09ECB7")] WarmeKueche = 1 << 4, + [Description("2476B5BBAEB7467C9A0099F06D0ED004")] SuedtirolerSpezialitaeten = 1 << 5, + [Description("30DC854F943D42CF8DB140CF4A90EC7E")] GourmetKueche = 1 << 6, + [Description("D1F124A123554B14AB9600F2313ED051")] ItalienischeKueche = 1 << 7, + [Description("CB8AF7CB80E844758B18E9C4E2D84035")] InternationaleKueche = 1 << 8, + [Description("50FFF83EB75944DE9F6F15CC51E85E7A")] Pizza = 1 << 9, + [Description("6322DE8AFE8E406F886E7C40D0DC1ADD")] Fischspezialitaeten = 1 << 10, + [Description("0E9721E540FB4D84BADC0DFA24F0543B")] AsiatischeKueche = 1 << 11, + [Description("C48E7E7679B04835B6744650E129BABF")] Wildspezialitaeten = 1 << 12, + [Description("167850CF26984D50A59A5F42EB24A0AD")] ProdukteeigenerErzeugung = 1 << 13, + [Description("4F9335FDAB834B11B36CD4C163F990A7")] Diaetkueche = 1 << 14, + [Description("69621AE51DF942A1BBED32D460E65132")] Grillspezialitaeten = 1 << 15, + [Description("22F0D9C42B06423EB63E1F2F27B7CA3A")] LadinischeKueche = 1 << 16, + [Description("BC08B00995564BB28997C55C870120D1")] KleineKarte = 1 << 17, + [Description("0E55D7C2A7BC4866BF8438C522C17254")] Fischwochen = 1 << 18, + [Description("FC627623C6994E37927F6048E32B79C2")] Spargelwochen = 1 << 19, + [Description("21A903DE35654070803DFDDF29C67291")] Lammwochen = 1 << 20, + [Description("8E28215F82BA430EA016BA5D1C776A30")] Wildwochen = 1 << 21, + [Description("D413EF912D18462CA0055A44F55351D1")] Vorspeisenwochen = 1 << 22, + [Description("BC6B57D90AFB496098DD0D059D04EE7C")] Nudelwochen = 1 << 23, + [Description("B36D855D60CB4D79BA78F3FEFEE9F9D3")] Kräuterwochen = 1 << 24, + [Description("AD8426538FCF4D8A81E06BE044088BAA")] Kindermenues = 1 << 25, + [Description("5C84265DA5F84F84A7896808ACCB675A")] Mittagsmenues = 1 << 26 } @@ -536,30 +727,38 @@ public enum SmgPoiMainTypeFlag { [Description("Activity")] Activity = 1, + [Description("Poi")] Poi = 1 << 1, + [Description("Gastronomy")] - Gastronomy = 1 << 2 + Gastronomy = 1 << 2 } - [Flags] public enum SmgPoiTypeFlag { [Description("Wellness Entspannung")] WellnessEntspannung = 1, + [Description("Winter")] Winter = 1 << 1, + [Description("Sommer")] Sommer = 1 << 2, + [Description("Kultur Sehenswürdigkeiten")] KulturSehenswuerdigkeiten = 1 << 3, + [Description("Anderes")] Anderes = 1 << 4, + [Description("Essen Trinken")] EssenTrinken = 1 << 5, + [Description("Mobilität")] Mobility = 1 << 6, + [Description("Geschäfte und Dienstleister")] ShopsAndServices = 1 << 7 } @@ -571,6 +770,7 @@ public enum SmgPoiSubTypeFlagWellness { [Description("Wellnessbehandlungen")] Wellnessbehandlungen = 1, + [Description("Therme Wasserwelten")] ThermeWasserwelten = 1 << 1 } @@ -580,28 +780,40 @@ public enum SmgPoiSubTypeFlagWinter { [Description("Weihnachtsmärkte")] Weihnachtsmaerkte = 1, + [Description("Eisklettern")] Eisklettern = 1 << 1, + [Description("Eislaufen")] Eislaufen = 1 << 2, + [Description("Langlaufen")] Langlaufen = 1 << 3, + [Description("Pferdeschlittenfahrten")] Pferdeschlittenfahrten = 1 << 4, + [Description("Rodeln")] Rodeln = 1 << 5, + [Description("Skirundtouren Pisten")] SkirundtourenPisten = 1 << 6, + [Description("Snowparks")] Snowparks = 1 << 7, + [Description("Skischulen Skiverleih")] SkischulenSkiverleih = 1 << 8, + [Description("Skitouren")] Skitouren = 1 << 9, + [Description("Schneeschuhwandern")] Schneeschuhwandern = 1 << 10, + [Description("Winterwandern")] Winterwandern = 1 << 11, + [Description("Skigebiete")] Skigebiete = 1 << 12 } @@ -611,28 +823,40 @@ public enum SmgPoiSubTypeFlagSommer { [Description("Wandern")] Wandern = 1, + [Description("Bergsteigen")] Bergsteigen = 1 << 1, + [Description("Klettern")] Klettern = 1 << 2, + [Description("Radfahren Radtouren")] RadfahrenRadtouren = 1 << 3, + [Description("Radverleih")] Radverleih = 1 << 4, + [Description("Badeseen Freibäder")] BadeseenFreibaeder = 1 << 5, + [Description("Wassersport")] Wassersport = 1 << 6, + [Description("Reiten")] Reiten = 1 << 7, + [Description("Freizeit Erlebnis")] FreizeitErlebnis = 1 << 8, + [Description("Laufen Fitness")] LaufenFitness = 1 << 9, + [Description("Golf")] Golf = 1 << 10, + [Description("Paragleiten")] Paragleiten = 1 << 11, + [Description("Angeln Fischen")] AngelnFischen = 1 << 12 } @@ -642,16 +866,22 @@ public enum SmgPoiSubTypeFlagKultur { [Description("Architektur")] Architektur = 1, + [Description("Kirchen Klöster")] KirchenKloester = 1 << 1, + [Description("Museen")] Museen = 1 << 2, + [Description("Naturparkhäuser")] Naturparkhaeuser = 1 << 3, + [Description("Burgen Schlösser")] BurgenSchloesser = 1 << 4, + [Description("Bergwerke")] Bergwerke = 1 << 5, + [Description("Sehenswerte Plätze")] SehenswertePlaetze = 1 << 6 } @@ -661,46 +891,63 @@ public enum SmgPoiSubTypeFlagAnderes { [Description("Ohne Zuordnung")] OhneZuordnung = 1, + [Description("Familienurlaub")] Familienurlaub = 1 << 1, + [Description("Sagen")] Sagen = 1 << 2, + [Description("Klettertour")] Klettertour = 1 << 3, + [Description("Aufstiegsanlagen")] Aufstiegsanlagen = 1 << 4, + [Description("Stadtrundgang")] Fitnessparcours = 1 << 5, - //NEW + + //NEW [Description("Guides Schulen")] GuidesSchulen = 1 << 6, + [Description("Spiel und Sportanlagen")] SpielSportAnlagen = 1 << 7, + [Description("Verleihe")] Verleihe = 1 << 8, + [Description("Parks und Grünanlagen")] ParksGruenanlagen = 1 << 9, + [Description("Kulturzentren und Theater")] KulturzentrenundTheater = 1 << 10, + [Description("Weitere Kultur und Sehenswürdigkeiten")] WeitereKultur = 1 << 11, + [Description("Vereine")] Vereine = 1 << 12, + [Description("Unternehmen")] Unternehmen = 1 << 13 } - + [Flags] public enum SmgPoiSubTypeFlagEssenTrinken { [Description("Andere Gastronomiebetriebe")] AndereGastronomiebetriebe = 1, + [Description("Weinkellereien")] Weinkellereien = 1 << 1, + [Description("Restaurants Gasthäuser")] RestaurantsGasthauser = 1 << 2, + [Description("Hütten Almen")] HuettenAlmen = 1 << 3, + [Description("Bäuerliche Schankbetriebe")] BauerlicheSchankbetriebe = 1 << 4 } @@ -710,30 +957,43 @@ public enum SmgPoiSubTypeFlagMobility { [Description("Bushaltestellen")] Bushaltestellen = 1, + [Description("Parkplätze")] Parkplaetze = 1 << 1, + [Description("Tankstellen Benzin Diesel")] TankstellenBenzinDiesel = 1 << 2, + [Description("E-Tankstellen Ladestationen")] ETankstellenLadestationen = 1 << 3, + [Description("Taxi, Mietwagen mit Fahrer, Bus")] TaxiMietwagenmitFahrerBus = 1 << 4, + [Description("Zugbahnhöfe")] Zugbahnhoefe = 1 << 5, + [Description("Carsharing")] Carsharing = 1 << 6, + [Description("Tankstellen Methan")] TankstellenMethan = 1 << 7, + [Description("Tankstellen Autogas")] TankstellenAutogas = 1 << 8, + [Description("Tankstellen Wasserstoff")] TankstellenWasserstoff = 1 << 9, + [Description("Weitere Verkehr und Transport")] WeitereVerkehrundTransport = 1 << 10, + [Description("E-Bike Ladestation")] EBikeLadestation = 1 << 11, + [Description("Fahrradbox")] - Fahrradbox = 1 << 12, + Fahrradbox = 1 << 12, + [Description("Verkaufstellen Ticket Oeffentliche Verkehrsmittel")] VerkaufstellenTicketOeffentlicheVerkehrsmittel = 1 << 13, } @@ -743,12 +1003,16 @@ public enum SmgPoiSubTypeFlagShopsAndServices : long { [Description("Gesundheit")] Gesundheit = 1, + [Description("Geschäfte")] Geschaefte = 1 << 1, + [Description("Dienstleister")] Dienstleister = 1 << 2, + [Description("Öffentliche Einrichtungen")] OeffentlicheEinrichtung = 1 << 3, + [Description("Nachtleben und Unterhaltung")] NachtlebenUnterhaltung = 1 << 4 } @@ -760,20 +1024,28 @@ public enum SmgPoiPoiTypeFlagGesundheit ////Ärzte Apotheken [Description("Apotheken")] Apotheken = 1, + [Description("Ärzte")] Aerzte = 1 << 1, + [Description("Feriendialysen")] Feriendialysen = 1 << 2, + [Description("Kinderärzte")] Kinderaerzte = 1 << 3, + [Description("Tierärzte")] Tieraerzte = 1 << 4, + [Description("Zahnärzte")] Zahnaerzte = 1 << 5, + [Description("Medizinausgabestellen, Medikamentenautomaten")] MedizinausgabestellenMedikamentenautomatn = 1 << 6, + [Description("Privatkliniken, Trauma Zentren, Physiotherapeuten")] PrivatklinikenTraumaZentrenPhysiotherapeuten = 1 << 7, + [Description("Weitere Ärzte, Apotheken")] WeitereAertzeApotheken = 1 << 8 } @@ -782,67 +1054,97 @@ public enum SmgPoiPoiTypeFlagGesundheit [Flags] public enum SmgPoiPoiTypeFlagGeschaefte : long { - //Geschäfte + //Geschäfte [Description("Getränke")] Getraenke = 1L, + [Description("Antiquitäten")] Antiquitaeten = 1L << 1, + [Description("Blumen")] Blumen = 1L << 2, + [Description("Computerzubehör, Technik")] ComputerzubehoerTechnik = 1L << 3, + [Description("Drogerie")] Drogerie = 1L << 4, + [Description("Fahrräder")] Fahrraeder = 1L << 5, + [Description("Farben, Tapeten")] FarbenTapeten = 1L << 6, + [Description("Fleisch und Wurstwaren")] FleischundWurstwaren = 1L << 7, + [Description("Brot und Gebäck")] BrotundGebaeck = 1L << 8, + [Description("Haushaltswaren")] Haushaltswaren = 1L << 9, + [Description("Juweliere, Goldschmiede")] JuweliereGoldschmiede = 1L << 10, + [Description("Kunsthandwerke")] Kunsthandwerke = 1L << 11, + [Description("Landwirtschaftliche Artikel")] LandwirtschaftlicheArtikel = 1L << 12, + [Description("Lebensmittel")] Lebensmittel = 1L << 13, + [Description("Lederwaren, Schuhe")] LederwarenSchuhe = 1L << 14, + [Description("Lokale traditionelle Produkte")] LokaletraditionelleProdukte = 1L << 15, + [Description("Mode, Bekleidung")] ModeBekleidung = 1L << 16, + [Description("Obst- und Gemüse")] ObstundGemuese = 1L << 17, + [Description("Optiker, Foto")] OptikerFoto = 1L << 18, + [Description("Produktionsstätten, Hofläden")] ProduktionsstaettenHoflaeden = 1L << 19, + [Description("Souvenir")] Souvenir = 1L << 20, + [Description("Spielwaren")] Spielwaren = 1L << 21, + [Description("Sportartikel")] Sportartikel = 1 << 22, + [Description("Tierbedarf")] Tierbedarf = 1L << 23, + [Description("Zeitungen, Bücher und Papierwaren")] ZeitungenBuecherundPapierwaren = 1L << 24, + [Description("Kindermode")] Kindermode = 1L << 25, + [Description("Auto und Motor")] AutoundMotor = 1L << 26, + [Description("Bausektor, Handwerk")] BausektorHandwerk = 1L << 27, + [Description("Reinigungen")] Reinigungen = 1L << 28, + [Description("Weitere Geschäfte")] WeitereGeschaefte = 1L << 29, + [Description("Wohnausstattung")] Wohnausstattung = 1L << 30 } @@ -854,46 +1156,65 @@ public enum SmgPoiPoiTypeFlagDienstleister : long //Diensleister [Description("Auto und Motor")] AutoundMotor = 1L, + [Description("Bausektor, Handwerk")] BausektorHandwerk = 1L << 1, + [Description("Kinderbetreuung Animation")] KinderbetreuungAnimation = 1L << 2, + [Description("Werbung und Grafik")] WerbungundGrafik = 1L << 3, + [Description("Reinigung")] Reinigung = 1L << 4, + [Description("Tierpflege")] Tierpflege = 1L << 5, + [Description("Bank, Bankomat")] BankBankomat = 1L << 6, + [Description("Beauty und Wellness")] BeautyundWellness = 1L << 7, + [Description("Friseur")] Friseur = 1L << 8, + [Description("Kosmetik")] Kosmetik = 1L << 9, + [Description("Massage, Heilbäder")] MassageHeilbaeder = 1L << 10, + [Description("Day Spa, Sauna")] DaySpaSauna = 1L << 11, + [Description("Kneippbäder")] Kneippbaeder = 1L << 12, + [Description("Weitere Beauty und Wellness")] WeitereBeautyundWellness = 1L << 13, + [Description("Weitere Dienstleister")] WeitereDienstleister = 1L << 14, //Handwerk [Description("Bildhauer")] Bildhauer = 1L << 15, + [Description("Kunstwebereien")] Kunstwebereien = 1L << 16, + [Description("Federkielstickereien")] Federkielstickereien = 1L << 17, + [Description("Kunstmaler und Vergolder")] KunstmalerundVergolder = 1L << 18, + [Description("Weitere Kunsthandwerker")] WeitereHandwerker = 1L << 19, + [Description("Künstler")] Kuenstler = 1L << 20 } @@ -905,26 +1226,37 @@ public enum SmgPoiPoiTypeFlagOeffentlichEinrichtungen //Öffentliche Einrichtungen [Description("Bibliotheken")] Bibliotheken = 1, + [Description("Gemeinden")] Gemeinden = 1 << 1, + [Description("Öffentliches WLANs")] OeffentlichesWLANs = 1 << 2, + [Description("Polizei, Carabinieri")] PolizeiCarabinieri = 1 << 3, + [Description("Post")] Post = 1 << 4, + [Description("Recyclinghöfe")] Recyclinghoefe = 1 << 5, + [Description("Infobüro")] Infobuero = 1 << 6, + [Description("Infopoint")] Infopoint = 1 << 7, + [Description("WCs")] WCs = 1 << 8, + [Description("Krankenhaus")] Krankenhaus = 1 << 9, + [Description("Weitere öffentliche Einrichtungen")] WeitereoeffentlicheEinrichtungen = 1 << 10, + [Description("Trinkwasserauffüllpunkte")] Trinkwasserauffuellpunkte = 1 << 11 } @@ -936,10 +1268,13 @@ public enum SmgPoiPoiTypeFlagNachtlebenUnterhaltung //Nachtleben Unterhaltung [Description("Biergärten")] Biergaerten = 1, + [Description("Cocktailbars")] Cocktailbars = 1 << 1, + [Description("Diskotheken, Nachtclubs")] DiskothekenNachtclubs = 1 << 2, + [Description("Weitere Nachtleben und Unterhaltungen")] WeitereNachtlebenundUnterhaltungen = 1 << 3 } @@ -951,10 +1286,13 @@ public enum SmgPoiPoiTypeFlagWandern { [Description("Fernwanderwege")] Fernwanderwege = 1, + [Description("Höhenwege")] Hoehenwege = 1 << 1, + [Description("Themenwanderungen")] Themenwanderungen = 1 << 2, + [Description("Waalwege")] Waalwege = 1 << 3 } @@ -964,10 +1302,13 @@ public enum SmgPoiPoiTypeFlagKlettern { [Description("Klettersteige")] Klettersteige = 1, + [Description("Kletterparks")] Kletterparks = 1 << 1, + [Description("Hochseilgärten")] Hochseilgaerten = 1 << 2, + [Description("Kletterhallen")] Kletterhallen = 1 << 3 } @@ -977,14 +1318,19 @@ public enum SmgPoiPoiTypeFlagRadfahren { [Description("Radtouren")] Radtouren = 1, + [Description("Talradwege")] Talradwege = 1 << 1, + [Description("Mountainbike")] Mountainbike = 1 << 2, + [Description("Rennrad")] Rennrad = 1 << 3, + [Description("Freeride")] Freeride = 1 << 4, + [Description("Downhill")] Downhill = 1 << 5 } @@ -994,16 +1340,22 @@ public enum SmgPoiPoiTypeFlagMuseen { [Description("Museen Kultur")] MuseenKultur = 1, + [Description("Museen Natur")] MuseenNatur = 1 << 1, + [Description("Museen Technik")] MuseenTechnik = 1 << 2, + [Description("Museen Kunst")] MuseenKunst = 1 << 3, + [Description("Museen Montags geöffnet")] MuseenMontagsgeoffnet = 1 << 4, + [Description("Museen Eintritt frei")] MuseenEintrittfrei = 1 << 5, + [Description("Museen Ausstellungen")] MuseenAusstellungen = 1 << 6 } @@ -1013,8 +1365,10 @@ public enum SmgPoiPoiTypeFlagFreizeitErlebnis { [Description("Beachvolleyball")] Beachvolleyball = 1, + [Description("Freizeitparks")] Freizeitparks = 1 << 1, + [Description("Minigolf")] Minigolf = 1 << 2 } @@ -1024,6 +1378,7 @@ public enum SmgPoiPoiTypeFlagKirchenKloester { [Description("Kirchen")] Kirchen = 1, + [Description("Klöster")] Kloester = 1 << 1 } @@ -1033,6 +1388,7 @@ public enum SmgPoiPoiTypeFlagLaufenFitness { [Description("Laufstrecken")] Laufstrecken = 1, + [Description("Nordic Walking")] NordicWalking = 1 << 1 } @@ -1042,6 +1398,7 @@ public enum SmgPoiPoiTypeFlagThermeWasserwelten { [Description("Hallenbad")] Hallenbad = 1, + [Description("Therme")] Therme = 1 << 1 } @@ -1051,6 +1408,7 @@ public enum SmgPoiPoiTypeFlagWeihnachtsmaerkte { [Description("Ländliche Christkindlmärkte")] LaendlicheChristkindlmaerkte = 1, + [Description("Original Südtiroler Christkindlmärkte")] OriginalSuedtirolerChristkindlmaerkte = 1 << 1 } @@ -1060,6 +1418,7 @@ public enum SmgPoiPoiTypeFlagLanglaufen { [Description("Klassisch")] Klassisch = 1, + [Description("Freistil")] Freistil = 1 << 1 } @@ -1069,6 +1428,7 @@ public enum SmgPoiPoiTypeFlagRodelbahnen { [Description("Rodelbahn")] Rodelbahn = 1, + [Description("Alpin Bob")] AlpinBob = 1 << 1 } @@ -1078,6 +1438,7 @@ public enum SmgPoiPoiTypeFlagSkischulen { [Description("Skischulen")] Skischulen = 1, + [Description("Skiverleih")] Skiverleih = 1 << 1 } @@ -1094,6 +1455,7 @@ public enum SmgPoiPoiTypeFlagBadeseenFreibaeder { [Description("Schwimmbäder")] Schwimmbaeder = 1, + [Description("Badeseen")] Badeseen = 1 << 1 } @@ -1103,14 +1465,19 @@ public enum SmgPoiPoiTypeFlagArchitektur { [Description("Architektur Kulinarik")] Kulinarik = 1, + [Description("Architektur Kunst Kultur")] KunstKultur = 1 << 1, + [Description("Architektur Freizeit")] Freizeit = 1 << 2, + [Description("Architektur Öffentliche Gebäude")] OeffentlicheGebaeude = 1 << 3, + [Description("Architektur Wohnbauten")] Wohnbauten = 1 << 4, + [Description("Architektur Wohnen Hotels")] WohnenHotels = 1 << 5 } @@ -1120,18 +1487,25 @@ public enum SmgPoiPoiTypeFlagAndereGastronomiebetriebe { [Description("Pub Disco")] PubDisco = 1, + [Description("Apres Ski")] ApresSki = 1 << 1, + [Description("Jausenstation")] Jausenstation = 1 << 2, + [Description("Törggele Lokal")] ToerggeleLokal = 1 << 3, + [Description("Schnellimbiss")] Schnellimbiss = 1 << 4, + [Description("Mensa")] Mensa = 1 << 5, + [Description("Eisdiele")] Eisdiele = 1 << 6, + [Description("Braugarten")] Braugarten = 1 << 7 } @@ -1141,16 +1515,22 @@ public enum SmgPoiPoiTypeFlagRestaurantsGasthauser { [Description("Restaurants")] Restaurants = 1, + [Description("Gasthäuser Gasthöfe")] GasthauserGasthoefe = 1 << 1, + [Description("Pizzerias")] Pizzerias = 1 << 2, + [Description("Vinotheken")] Vinotheken = 1 << 3, + [Description("Bars Cafes Bistros")] BarsCafesBistros = 1 << 4, + [Description("Gasthaus")] Gasthaus = 1 << 5, + [Description("Gasthof")] Gasthof = 1 << 6 } @@ -1160,8 +1540,10 @@ public enum SmgPoiPoiTypeFlagHuettenAlmen { [Description("Schutzhütten")] Schutzhuetten = 1, + [Description("Almen")] Almen = 1 << 1, + [Description("Skihütten")] Skihuetten = 1 << 2 } @@ -1171,8 +1553,10 @@ public enum SmgPoiPoiTypeFlagBauerlicheSchankbetriebe { [Description("Buschen Hofschänke")] BuschenHofschaenke = 1, + [Description("Buschenschank")] Buschenschank = 1 << 1, + [Description("Hofschank")] Hofschank = 1 << 2 } @@ -1182,10 +1566,13 @@ public enum SmgPoiPoiTypeFlagSkigebiete { [Description("Dolomiti Superski")] DolomitiSuperski = 1, + [Description("Ortler Skiarena")] OrtlerSkiarena = 1 << 1, + [Description("Skiregion Tauferer Ahrntal")] TaufererAhrntal = 1 << 2, + [Description("Skiverbund Eisacktal-Wipptal")] SkiverbundEisacktalerWipptal = 1 << 3 } @@ -1195,10 +1582,13 @@ public enum SmgPoiPoiTypeFlagGuidesSchulen { [Description("Ski- und Bergführer")] SkiBergfuehrer = 1, + [Description("Bikeguides")] Bikeguides = 1 << 1, + [Description("Wanderführer")] Wanderfuehrer = 1 << 2, + [Description("Weitere Guides Schulen")] Weitere = 1 << 3 } @@ -1208,26 +1598,37 @@ public enum SmgPoiPoiTypeFlagSpielundSportanlagen { [Description("Bogenschiessanlagen")] Bogenschiessanlagen = 1, + [Description("Fitnesscenter")] Fitnesscenter = 1 << 1, + [Description("Fussballplätze")] Fußballplaetze = 1 << 2, + [Description("Kinderspielplätze")] Kinderspielplaetze = 1 << 3, + [Description("Pferdekutschenfahrten")] Pferdekutschenfahrten = 1 << 4, + [Description("Radraststätten")] Radraststaetten = 1 << 5, + [Description("Tennisplätze")] Tennisplaetze = 1 << 6, + [Description("Zip-lines")] Ziplines = 1 << 7, + [Description("Weitere Spiel und Sportanlagen")] WeitereSpielSportanlagen = 1 << 8, + [Description("Tierpark")] Tierpark = 1 << 9, + [Description("Bikepark")] Bikepark = 1 << 10, + [Description("Pumptracks und mehr")] Pumptracksundmehr = 1 << 11, } @@ -1237,45 +1638,65 @@ public enum SmgPoiPoiTypeFlagAufstiegsanlagen { [Description("nicht definiert")] nichtdefiniert = 1, + [Description("Seilbahn")] Seilbahn = 1 << 1, + [Description("Umlaufbahn")] Umlaufbahn = 1 << 2, + [Description("Kabinenbahn")] Kabinenbahn = 1 << 3, + [Description("Unterirdische Bahn")] UnterirdischeBahn = 1 << 4, + [Description("Sessellift")] Sessellift = 1 << 5, + [Description("Skilift")] Skilift = 1 << 6, + [Description("Schrägaufzug")] Schraegaufzug = 1 << 7, + [Description("Standseilbahn Zahnradbahn")] StandseilbahnZahnradbahn = 1 << 8, + [Description("Telemix")] Telemix = 1 << 9, + [Description("Förderband")] Foerderband = 1 << 10, + [Description("1er Sessellift kuppelbar")] EinserSesselLiftkuppelbar = 1 << 11, + [Description("2er Sessellift kuppelbar")] ZweierSesselliftkuppelbar = 1 << 12, + [Description("3er Sessellift kuppelbar")] DreierSesselliftkuppelbar = 1 << 13, + [Description("4er Sessellift kuppelbar")] ViererSesselliftkuppelbar = 1 << 14, + [Description("6er Sessellift kuppelbar")] SechserSesselliftkuppelbar = 1 << 15, + [Description("8er Sessellift kuppelbar")] AchterSesselliftkuppelbar = 1 << 16, + [Description("Klein-Skilift")] KleinSkilift = 1 << 17, + //NEU [Description("Skibus")] Skibus = 1 << 18, + [Description("Zug")] Zug = 1 << 19, + [Description("Weitere Aufstiegsanlagen")] WeitereAufstiegsanlagen = 1 << 20 } @@ -1285,16 +1706,22 @@ public enum SmgPoiPoiTypeFlagVereine { [Description("Sport")] Sport = 1, + [Description("Kultur, Musik, Theater")] KulturMusikTheater = 1 << 1, + [Description("Tier, Natur, Wissenschaft")] TierNaturWissenschaft = 1 << 2, + [Description("Gesellschaft, Politisch")] GesellschaftPolitisch = 1 << 3, + [Description("Sozial, Rettung, gemeinnützig")] SozialRettungGemeinnuetzig = 1 << 4, + [Description("Freizeitverein")] Freizeitverein = 1 << 5, + [Description("weitere Vereine")] WeitereVereine = 1 << 6 } @@ -1304,14 +1731,19 @@ public enum SmgPoiPoiTypeFlagUnternehmen { [Description("Industrie")] Industrie = 1, + [Description("Produktion")] Produktion = 1 << 1, + [Description("Baugewerbe")] Baugewerbe = 1 << 2, + [Description("Handwerk")] Handwerk = 1 << 3, + [Description("Energie")] Energie = 1 << 4, + [Description("weitere Unternehmen")] WeitereUnternehmen = 1 << 5 } @@ -1324,25 +1756,35 @@ public enum SmgPoiPoiTypeFlagUnternehmen public enum ArticleTypeFlag { [Description("basisartikel")] - basisartikel = 1, //1 + basisartikel = 1, //1 + [Description("buchtippartikel")] buchtippartikel = 1 << 1, //2 + [Description("contentartikel")] contentartikel = 1 << 2, //4 + [Description("veranstaltungsartikel")] veranstaltungsartikel = 1 << 3, //8 + [Description("presseartikel")] - presseartikel = 1 << 4, //16 + presseartikel = 1 << 4, //16 + [Description("rezeptartikel")] - rezeptartikel = 1 << 5, //32 + rezeptartikel = 1 << 5, //32 + [Description("reiseveranstalter")] - reiseveranstalter = 1 << 6, //64 + reiseveranstalter = 1 << 6, //64 + [Description("b2bartikel")] - b2bartikel = 1 << 7, //128 + b2bartikel = 1 << 7, //128 + [Description("idmartikel")] - idmartikel = 1 << 8, //256 + idmartikel = 1 << 8, //256 + [Description("specialannouncement")] - specialannouncement = 1 << 9, //512 + specialannouncement = 1 << 9, //512 + [Description("newsfeednoi")] newsfeednoi = 1 << 10 //1024 } @@ -1352,16 +1794,22 @@ public enum ArticleBasisArticleFlag { [Description("Suggestion")] Suggestion = 1, + [Description("Hotel")] Hotel = 1 << 1, + [Description("Gastronomy")] Gastronomy = 1 << 2, + [Description("General")] General = 1 << 3, + [Description("Tip")] Tip = 1 << 4, + [Description("News")] News = 1 << 5, + [Description("Detail")] Detail = 1 << 6 } @@ -1371,22 +1819,31 @@ public enum ArticleBuchTippFlag { [Description("Accommodation-Restaurants")] AccommodationRestaurants = 1, + [Description("Biking")] Biking = 1 << 1, + [Description("Culture-History")] CultureHistory = 1 << 2, + [Description("Family")] Family = 1 << 3, + [Description("Gastronomy")] Gastronomy = 1 << 4, + [Description("Health")] Health = 1 << 5, + [Description("Novels-Poetry")] NovelsPoetry = 1 << 6, + [Description("Travel-guides")] Travelguides = 1 << 7, + [Description("Trekking-guides")] Trekkingguides = 1 << 8, + [Description("Winter")] Winter = 1 << 9 } @@ -1396,10 +1853,13 @@ public enum ArticlePresseArticleFlag { [Description("allgemeinepresseartikel")] allgemeinepresseartikel = 1, + [Description("pressemeetings")] pressemeetings = 1 << 1, + [Description("pressemitteilungen")] pressemitteilungen = 1 << 2, + [Description("pressethemenserviceartikel")] pressethemenserviceartikel = 1 << 3 } @@ -1409,10 +1869,13 @@ public enum ArticleB2BArticleFlag { [Description("B2BDetail")] allgemeinepresseartikel = 1, + [Description("B2BProgrammTipp")] pressemeetings = 1 << 1, + [Description("B2BNeuigkeiten")] pressemitteilungen = 1 << 2, + [Description("B2BVeranstaltung")] pressethemenserviceartikel = 1 << 3 } @@ -1422,8 +1885,10 @@ public enum ArticleContentArticleFlag { [Description("Site Content")] SiteContent = 1, + [Description("B2B Site Content")] B2BSiteContent = 1 << 1, + [Description("Press Site Content")] PressSiteContent = 1 << 2 } @@ -1433,6 +1898,7 @@ public enum ArticleIDMArticleFlag { [Description("genussbotschafter")] genussbotschafter = 1, + [Description("hersteller")] hersteller = 1 << 1 } @@ -1442,32 +1908,46 @@ public enum ArticleVeranstaltungsArticleFlag { [Description("Gastronomie")] Gastronomie = 1, + [Description("Treffen")] Treffen = 1 << 1, + [Description("Volksfest")] Volksfest = 1 << 2, + [Description("Tradition")] Tradition = 1 << 3, + [Description("Kinder/Familie")] KinderFamilie = 1 << 4, + [Description("Kultur")] Kultur = 1 << 5, + [Description("Kunsthandwerk")] Kunsthandwerk = 1 << 6, + [Description("Theater")] Theater = 1 << 7, + [Description("Wanderungen")] Wanderungen = 1 << 8, + [Description("Ausstellungen/Kunst")] AusstellungenKunst = 1 << 9, + [Description("Sport")] Sport = 1 << 10, + [Description("Messen")] Messen = 1 << 11, + [Description("Musik")] Musik = 1 << 12, + [Description("Geführte Touren")] GefuehrteTouren = 1 << 13, + [Description("Unterhaltung")] Unterhaltung = 1 << 14 } @@ -1481,31 +1961,43 @@ public enum ArticleVeranstaltungsArticleFlag public enum EventTopicFlag { [Description("0D25868CC23242D6AC97AEB2973CB3D6")] - TagungenVortraege = 1, //1, + TagungenVortraege = 1, //1, + [Description("162C0067811B477DA725D2F5F2D98398")] Sport = 1 << 1, // 2, + [Description("252200A028C8449D9A6205369A6D0D36")] GastronomieTypischeProdukte = 1 << 2, //4, + [Description("33BDC54BD39946F4852B3394B00610AE")] HandwerkBrauchtum = 1 << 3, //8, + [Description("4C4961D9FC5B48EEB73067BEB9D4402A")] MessenMaerkte = 1 << 4, //16, + [Description("6884FE362C88434B9F49725E3328112B")] TheaterVorfuehrungen = 1 << 5, //32, + [Description("767F6F43FC394CE9A3C8A9725C6FF134")] KurseBildung = 1 << 6, //64, + [Description("7E048074BA004EC58E29E330A9AA476B")] MusikTanz = 1 << 7, //128, + [Description("9C3449EE278C4D94AA5A7C286729DEA0")] VolksfesteFestivals = 1 << 8, //256, + [Description("ACE8B613F2074A7BB59C0B1DD40A43CD")] WanderungenAusfluege = 1 << 9, //512, + [Description("B5467FEFE5C74FA5AD32B83793A76165")] FuehrungenBesichtigungen = 1 << 10, //1024, + [Description("C72CE969B98947FABC99CBC7B033F28E")] AusstellungenKunst = 1 << 11, //2048, + [Description("D98B49DF24C342D09A8161836435CF86")] - Familie = 1 << 12, //4096, + Familie = 1 << 12, //4096, } #endregion @@ -1516,19 +2008,26 @@ public enum EventTopicFlag public enum VenueCategoryFlag { [Description("VEN03D5630AD1E1438DBA1E998F0F72B626")] - type_nonConventional = 1, //1, + type_nonConventional = 1, //1, + [Description("VEN410C6C89ED0041559B815FFC112870BB")] type_fair = 1 << 1, // 2, + [Description("VEN5B35118C14FF4CB9A5546DDD6461AB62")] type_historicalResidence = 1 << 2, //4, + [Description("VEN7324F5B3E210450C8DAF4AE3C5354ED5")] type_otherConferenceSite = 1 << 3, //8, + [Description("VENA09AA4B479384DFBBB1605E9E8C0A93B")] type_conferenceHotel = 1 << 4, //16, + [Description("VENAF924020EB32412C8F7FC5B0CB7DD8B3")] type_institutionalSite = 1 << 5, //32, + [Description("VENDD2171604D37485582E9475A63198933")] - type_conventionCenter = 1 << 6, //64, + type_conventionCenter = 1 << 6, //64, + [Description("VEN0219B13D32614E84B30221509F95E0C9")] type_other = 1 << 7 } @@ -1537,54 +2036,74 @@ public enum VenueCategoryFlag public enum VenueSeatTypeFlag { [Description("VENE4AA0F13DDF1410489F237FF6B181831")] - seattype_audience = 1, //1, + seattype_audience = 1, //1, + [Description("VEN0536C64E86B44FC2A2FBA77B6948993D")] seattype_class = 1 << 1, // 2, + [Description("VEN3D1C707DCA794BBFBAA76ECA49465865")] seattype_board = 1 << 2, //4, + [Description("VENDF70389DB7C54D57BCA0778AB7AA9C73")] seattype_horseshoe = 1 << 3, //8, + [Description("VEN6E29B13DB4B04860B97DC993E203B1CF")] seattype_cocktail = 1 << 4, //16, + [Description("VENDB7A4015D38543C5B8971362BDE1986A")] - seattype_galaDinner = 1 << 5 //32, + seattype_galaDinner = 1 << 5 //32, } [Flags] public enum VenueFeatureFlag { [Description("VEN24059D25A6FC4FAE936E7CB3E776A646")] - faci_wardrobe = 1, //1, + faci_wardrobe = 1, //1, + [Description("VEN2BF0A6C5BED846E7B35F84BB2CC39145")] faci_barrierFreeAccess = 1 << 1, // 2, + [Description("VEN3BB8A8EA44CC465AAA91F97FA60A2666")] faci_heating = 1 << 2, //4, + [Description("VEN479B65D5C62D44CE935E59F677477FF8")] faci_table = 1 << 3, //8, + [Description("VEN600538A7883A4C74B6E8DE68DA2C7C04")] faci_food = 1 << 4, //16, + [Description("VEN646D4B0F026243BFAF56709424BA53E1")] faci_projector = 1 << 5, //32, + [Description("VEN7B56AA4CA95844B4AFA6E02DA4A234B9")] faci_darkening = 1 << 6, //64, + [Description("VEN7CC12B6F18A5468180DA26EFB8314FFD")] faci_independentAccess = 1 << 7, //128, + [Description("VEN8D08DF7A9A1A4FA6AA7AC3DF8FD76194")] faci_parking = 1 << 8, //256, + [Description("VEN94ED27485E8743539BAA2F5B3A6B8AE2")] faci_receptionRoom = 1 << 9, //512, + [Description("VENAF97953298494A5BBF4DE00DCC2724ED")] faci_microphone = 1 << 10, //1024, + [Description("VENB7363C4DCE004B6FB163779B61577284")] faci_projectorScreen = 1 << 11, //2048, + [Description("VENCE38E6D7EED44B8C898F6CCD53276CEB")] - faci_airConditioning = 1 << 12, //4096, + faci_airConditioning = 1 << 12, //4096, + [Description("VEND6B34DA7BA5847A7B0154998D80FD5FC")] - faci_lan = 1 << 13, //8192, + faci_lan = 1 << 13, //8192, + [Description("VENEC3EE1CABD4C4507B3A6BC6511BDDEC5")] - faci_bar = 1 << 14, //16384, + faci_bar = 1 << 14, //16384, + [Description("VENF5D451A120074F8F8D3BE961BBE9B526")] - faci_wifi = 1 << 15, //32768, + faci_wifi = 1 << 15, //32768, } #endregion @@ -1596,22 +2115,31 @@ public enum ActivityTypeFlag { [Description("Berg")] Berg = 1, + [Description("Radfahren")] Radfahren = 1 << 1, + [Description("Stadtrundgang")] Stadtrundgang = 1 << 2, + [Description("Pferdesport")] Pferdesport = 1 << 3, + [Description("Wandern")] Wandern = 1 << 4, + [Description("Laufen und Fitness")] LaufenundFitness = 1 << 5, + [Description("Loipen")] Loipen = 1 << 6, + [Description("Rodelbahnen")] Rodelbahnen = 1 << 7, + [Description("Piste")] Piste = 1 << 8, + [Description("Aufstiegsanlagen")] Aufstiegsanlagen = 1 << 9 } @@ -1621,14 +2149,17 @@ public enum ActivityTypePisten { [Description("nicht definiert")] nichtdefiniert = 1, + [Description("Ski alpin")] - Skialpin = 1 << 1, //2 + Skialpin = 1 << 1, //2 + //[Description("Halfpipe")] //Halfpipe = 1 << 2, //4 //[Description("Tiefschnee")] //Tiefschnee = 1 << 3, //8 [Description("Snowpark")] Snowpark = 1 << 2, + //[Description("Kids-Funpark")] //KidsFunpark = 1 << 5, // //[Description("Geschwindigkeitspiste")] @@ -1637,6 +2168,7 @@ public enum ActivityTypePisten //Slalompiste = 1 << 7, [Description("Rundkurs")] Rundkurs = 1 << 3, + [Description("Weitere Pisten")] WeiterePisten = 1 << 4 } @@ -1646,45 +2178,65 @@ public enum ActivityTypeAufstiegsanlagen { [Description("nicht definiert")] nichtdefiniert = 1, + [Description("Seilbahn")] Seilbahn = 1 << 1, + [Description("Umlaufbahn")] Umlaufbahn = 1 << 2, + [Description("Kabinenbahn")] Kabinenbahn = 1 << 3, + [Description("Unterirdische Bahn")] UnterirdischeBahn = 1 << 4, + [Description("Sessellift")] Sessellift = 1 << 5, + [Description("Skilift")] Skilift = 1 << 6, + [Description("Schrägaufzug")] Schraegaufzug = 1 << 7, + [Description("Standseilbahn Zahnradbahn")] StandseilbahnZahnradbahn = 1 << 8, + [Description("Telemix")] Telemix = 1 << 9, + [Description("Förderband")] Foerderband = 1 << 10, + [Description("2er Sessellift kuppelbar")] ZweierSesselliftkuppelbar = 1 << 11, + [Description("3er Sessellift kuppelbar")] DreierSesselliftkuppelbar = 1 << 12, + [Description("4er Sessellift kuppelbar")] ViererSesselliftkuppelbar = 1 << 13, + [Description("6er Sessellift kuppelbar")] SechserSesselliftkuppelbar = 1 << 14, + [Description("8er Sessellift kuppelbar")] AchterSesselliftkuppelbar = 1 << 15, + [Description("Klein-Skilift")] KleinSkilift = 1 << 16, + //NEU [Description("Skibus")] Skibus = 1 << 17, + [Description("1er Sessellift kuppelbar")] EinserSesselLiftkuppelbar = 1 << 18, + [Description("Zug")] Zug = 1 << 19, + [Description("Weitere Aufstiegsanlagen")] WeitereAufstiegsanlagen = 1 << 20 } @@ -1694,20 +2246,28 @@ public enum ActivityTypeBerg { [Description("Alpinklettern")] Alpinklettern = 1, + [Description("Bergtouren")] Bergtouren = 1 << 1, + [Description("Hochtouren")] Hochtouren = 1 << 2, + [Description("Klettersteige")] Klettersteige = 1 << 3, + [Description("Schneeschuhtouren")] Schneeschuhtouren = 1 << 4, + [Description("Skitouren")] Skitouren = 1 << 5, + [Description("Weitere Berge")] WeitereBerge = 1 << 6, + [Description("Eisklettern")] Eisklettern = 1 << 7, + [Description("Eistour")] Eistour = 1 << 8 } @@ -1717,16 +2277,22 @@ public enum ActivityTypeLaufenFitness { [Description("Bergläufe")] Berglaeufe = 1, + [Description("Fitnessparcours")] Fitnessparcours = 1 << 1, + [Description("Innline Skating")] InnlineSkating = 1 << 2, + [Description("Laufstrecken")] Laufstrecken = 1 << 3, + [Description("Nordic Walkings")] NordicWalkings = 1 << 4, + [Description("Trail running")] Trailrunning = 1 << 5, + [Description("Weitere Laufen und Fitness")] WeitereLaufenundFitness = 1 << 6 } @@ -1736,8 +2302,10 @@ public enum ActivityTypeLoipen { [Description("Klassisch")] Klassisch = 1, + [Description("Skating")] Skating = 1 << 1, + [Description("Klassisch und Skating")] KlassischundSkating = 1 << 2 } @@ -1747,6 +2315,7 @@ public enum ActivityTypeOrtstouren { [Description("Ortstouren")] Ortstouren = 1, + [Description("Weitere Ortstouren")] WeitereOrtstouren = 1 << 1 } @@ -1756,8 +2325,10 @@ public enum ActivityTypePferde { [Description("Trail für Kutschenfahrten")] Kutschen = 1, + [Description("Trail für Reitpferde")] Reitpferde = 1 << 1, + [Description("Weitere Pferde")] WeiterePferde = 1 << 2 } @@ -1767,24 +2338,34 @@ public enum ActivityTypeRadfahren { [Description("Downhills, Freerides")] DownhillsFreerides = 1, + [Description("E-Bikes")] EBikes = 1 << 1, + [Description("Fernradwege")] Fernradwege = 1 << 2, + [Description("Mountainbikes")] Mountainbikes = 1 << 3, + [Description("Mountainbike Transalps")] MountainbikeTransalps = 1 << 4, + [Description("Radtouren")] Radtouren = 1 << 5, + [Description("Rennräder")] Rennraeder = 1 << 6, + [Description("Weitere Radfahren")] WeitereRadfahren = 1 << 7, + [Description("Pumptrack")] Pumptrack = 1 << 8, + [Description("Singletrail Freeride")] SingleTrailFreeride = 1 << 9, + [Description("E-MTB")] EMtb = 1 << 10 } @@ -1794,12 +2375,16 @@ public enum ActivityTypeRodeln { [Description("Schienenrodelbahn")] Schienenrodelbahn = 1, + [Description("Eisbahnen")] Eisbahnen = 1 << 1, + [Description("Rodelbahnen")] Rodelbahnen = 1 << 2, + [Description("Schneebahnen")] Schneebahnen = 1 << 3, + [Description("Weitere Rodeln")] WeitereRodeln = 1 << 4 } @@ -1809,22 +2394,31 @@ public enum ActivityTypeWandern { [Description("Barrierefrei")] Barrierefrei = 1, + [Description("Familienwanderungen")] Familienwanderungen = 1 << 1, + [Description("Fernwanderwege")] Fernwanderwege = 1 << 2, + [Description("Pilgerwege")] Pilgerwege = 1 << 3, + [Description("Schneeschuhwanderungen")] Schneeschuhwanderungen = 1 << 4, + [Description("Themenwanderungen")] Themenwanderungen = 1 << 5, + [Description("Winterwanderungen")] Winterwanderungen = 1 << 6, + [Description("Kinderwagen tauglich")] Kinderwagentauglich = 1 << 7, + [Description("Waalweg")] Waalweg = 1 << 8, + [Description("Weitere Wandern")] WeitereWandern = 1 << 9 } @@ -1838,24 +2432,34 @@ public enum PoiTypeFlag { [Description("Ärzte, Apotheken")] AertzeApotheken = 1, + [Description("Geschäfte")] GeschaefteDienstleister = 1 << 1, + [Description("Kultur und Sehenswürdigkeiten")] KulturSehenswuerdigkeiten = 1 << 2, + [Description("Nachtleben und Unterhaltung")] NachtlebenUnterhaltung = 1 << 3, + [Description("Öffentliche Einrichtungen")] OeffentlicheEinrichtungen = 1 << 4, + [Description("Sport und Freizeit")] SportFreizeit = 1 << 5, + [Description("Verkehr und Transport")] VerkehrTransport = 1 << 6, + [Description("Dienstleister")] Dienstleister = 1 << 7, + [Description("Kunsthandwerker")] Handwerk = 1 << 8, + [Description("Vereine")] Vereine = 1 << 9, + [Description("Unternehmen")] Unternehmen = 1 << 10 } @@ -1865,20 +2469,28 @@ public enum PoiTypeAerzteApotheken { [Description("Apotheken")] Apotheken = 1, + [Description("Ärzte")] Aerzte = 1 << 1, + [Description("Feriendialysen")] Feriendialysen = 1 << 2, + [Description("Kinderärzte")] Kinderaerzte = 1 << 3, + [Description("Tierärzte")] Tieraerzte = 1 << 4, + [Description("Zahnärzte")] Zahnaerzte = 1 << 5, + [Description("Medizinausgabestellen, Medikamentenautomatn")] MedizinausgabestellenMedikamentenautomatn = 1 << 6, + [Description("Privatkliniken, Trauma Zentren, Physiotherapeuten")] PrivatklinikenTraumaZentrenPhysiotherapeuten = 1 << 7, + [Description("Weitere Ärzte, Apotheken")] WeitereAertzeApotheken = 1 << 8 } @@ -1888,64 +2500,94 @@ public enum PoiTypeGeschaefte : long { [Description("Getränke")] Getraenke = 1L, + [Description("Antiquitäten")] Antiquitaeten = 1L << 1, + [Description("Blumen")] Blumen = 1L << 2, + [Description("Computerzubehör, Technik")] ComputerzubehoerTechnik = 1L << 3, + [Description("Drogerie")] Drogerie = 1L << 4, + [Description("Fahrräder")] Fahrraeder = 1L << 5, + [Description("Farben, Tapeten")] FarbenTapeten = 1L << 6, + [Description("Fleisch und Wurstwaren")] FleischundWurstwaren = 1L << 7, + [Description("Brot und Gebäck")] BrotundGebaeck = 1L << 8, + [Description("Haushaltswaren")] Haushaltswaren = 1L << 9, + [Description("Juweliere, Goldschmiede")] JuweliereGoldschmiede = 1L << 10, + [Description("Kunsthandwerke")] Kunsthandwerke = 1L << 11, + [Description("Landwirtschaftliche Artikel")] LandwirtschaftlicheArtikel = 1L << 12, + [Description("Lebensmittel")] Lebensmittel = 1L << 13, + [Description("Lederwaren, Schuhe")] LederwarenSchuhe = 1L << 14, + [Description("Lokale traditionelle Produkte")] LokaletraditionelleProdukte = 1L << 15, + [Description("Mode, Bekleidung")] ModeBekleidung = 1L << 16, + [Description("Obst- und Gemüse")] ObstundGemuese = 1L << 17, + [Description("Optiker, Foto")] OptikerFoto = 1L << 18, + [Description("Produktionsstätten, Hofläden")] ProduktionsstaettenHoflaeden = 1L << 19, + [Description("Souvenir")] Souvenir = 1L << 20, + [Description("Spielwaren")] Spielwaren = 1L << 21, + [Description("Sportartikel")] Sportartikel = 1 << 22, + [Description("Tierbedarf")] Tierbedarf = 1L << 23, + [Description("Zeitungen, Bücher und Papierwaren")] ZeitungenBuecherundPapierwaren = 1L << 24, + [Description("Kindermode")] Kindermode = 1L << 25, + [Description("Auto und Motor")] AutoundMotor = 1L << 26, + [Description("Bausektor, Handwerk")] BausektorHandwerk = 1L << 27, + [Description("Reinigungen")] Reinigungen = 1L << 28, + [Description("Weitere Geschäfte")] WeitereGeschaefte = 1L << 29, + [Description("Wohnausstattung")] Wohnausstattung = 1L << 30 } @@ -1955,32 +2597,46 @@ public enum PoiTypeDienstleister : long { [Description("Auto und Motor")] AutoundMotor = 1L, + [Description("Bausektor, Handwerk")] BausektorHandwerk = 1L << 1, + [Description("Kinderbetreuung Animation")] KinderbetreuungAnimation = 1L << 2, + [Description("Werbung und Grafik")] WerbungundGrafik = 1L << 3, + [Description("Reinigung")] Reinigung = 1L << 4, + [Description("Tierpflege")] Tierpflege = 1L << 5, + [Description("Bank, Bankomat")] BankBankomat = 1L << 6, + [Description("Beauty und Wellness")] BeautyundWellness = 1L << 7, + [Description("Friseur")] Friseur = 1L << 8, + [Description("Kosmetik")] Kosmetik = 1L << 9, + [Description("Massage, Heilbäder")] MassageHeilbaeder = 1L << 10, + [Description("Day Spa, Sauna")] DaySpaSauna = 1L << 11, + [Description("Kneippbäder")] Kneippbaeder = 1L << 12, + [Description("Weitere Beauty und Wellness")] WeitereBeautyundWellness = 1L << 13, + [Description("Weitere Dienstleister")] WeitereDienstleister = 1L << 14 } @@ -1990,14 +2646,19 @@ public enum PoiTypeHandwerk { [Description("Bildhauer")] Bildhauer = 1, + [Description("Kunstwebereien")] Kunstwebereien = 1 << 1, + [Description("Federkielstickereien")] Federkielstickereien = 1 << 2, + [Description("Kunstmaler und Vergolder")] KunstmalerundVergolder = 1 << 3, + [Description("Weitere Kunsthandwerker")] WeitereHandwerker = 1 << 4, + [Description("Künstler")] Kuenstler = 1 << 5 } @@ -2007,10 +2668,13 @@ public enum PoiTypeNachtlebenUnterhaltung { [Description("Biergärten")] Biergaerten = 1, + [Description("Cocktailbars")] Cocktailbars = 1 << 1, + [Description("Diskotheken, Nachtclubs")] DiskothekenNachtclubs = 1 << 2, + [Description("Weitere Nachtleben und Unterhaltungen")] WeitereNachtlebenundUnterhaltungen = 1 << 3, } @@ -2020,26 +2684,37 @@ public enum PoiTypeOeffentlicheEinrichtungen { [Description("Bibliotheken")] Bibliotheken = 1, + [Description("Gemeinden")] Gemeinden = 1 << 1, + [Description("Öffentliches WLANs")] OeffentlichesWLANs = 1 << 2, + [Description("Polizei, Carabinieri")] PolizeiCarabinieri = 1 << 3, + [Description("Post")] Post = 1 << 4, + [Description("Recyclinghöfe")] Recyclinghoefe = 1 << 5, + [Description("Infobüro")] Infobuero = 1 << 6, + [Description("Infopoint")] Infopoint = 1 << 7, + [Description("WCs")] WCs = 1 << 8, + [Description("Krankenhaus")] Krankenhaus = 1 << 9, + [Description("Weitere öffentliche Einrichtungen")] WeitereoeffentlicheEinrichtungen = 1 << 10, + [Description("Trinkwasserauffüllpunkte")] Trinkwasserauffuellpunkte = 1 << 11 } @@ -2049,28 +2724,40 @@ public enum PoiTypeVerkehrTransport { [Description("Bushaltestellen")] Bushaltestellen = 1, + [Description("Parkplätze")] Parkplaetze = 1 << 1, + [Description("Tankstellen Benzin Diesel")] TankstellenBenzinDiesel = 1 << 2, + [Description("E-Tankstellen Ladestationen")] ETankstellenLadestationen = 1 << 3, + [Description("Taxi, Mietwagen mit Fahrer, Bus")] TaxiMietwagenmitFahrerBus = 1 << 4, + [Description("Zugbahnhöfe")] Zugbahnhoefe = 1 << 5, + [Description("Carsharing")] Carsharing = 1 << 6, + [Description("Tankstellen Methan")] TankstellenMethan = 1 << 7, + [Description("Tankstellen Autogas")] TankstellenAutogas = 1 << 8, + [Description("Tankstellen Wasserstoff")] TankstellenWasserstoff = 1 << 9, + [Description("Weitere Verkehr und Transport")] WeitereVerkehrundTransport = 1 << 10, + [Description("E-Bike Ladestation")] EBikeLadestation = 1 << 11, + [Description("Fahrradbox")] Fahrradbox = 1 << 12 } @@ -2080,50 +2767,73 @@ public enum PoiTypeKulturSehenswuerdigkeiten { [Description("Denkmäler, Naturdenkmäler")] poitype1 = 1, + [Description("Grünanlagen")] poitype2 = 1 << 1, + [Description("Historische Gebäude")] poitype3 = 1 << 2, + [Description("Ansitze")] poitype4 = 1 << 3, + [Description("Schlösser")] poitype5 = 1 << 4, + [Description("Burgen")] poitype6 = 1 << 5, + [Description("Ruinen")] poitype7 = 1 << 6, + [Description("Weitere historische Gebäude")] poitype8 = 1 << 7, + [Description("Kirchen, Kapellen, Religiöse Zentren")] poitype9 = 1 << 8, + [Description("Kulturzentren")] poitype10 = 1 << 9, + [Description("Museen und Ausstellungen")] poitype11 = 1 << 10, + [Description("Naturparkhaus, Nationalparkhaus")] poitype12 = 1 << 11, + [Description("Produktionsstätten")] poitype13 = 1 << 12, + [Description("Bierbrauerei")] poitype14 = 1 << 13, + [Description("Brennereien")] poitype15 = 1 << 14, + [Description("Obstgenossenschaft")] poitype16 = 1 << 15, + [Description("Kellereien und Winzer")] poitype17 = 1 << 16, + [Description("Weitere Produzenten")] poitype18 = 1 << 17, + [Description("Seen, Wasserfälle")] poitype19 = 1 << 18, + [Description("Theater")] poitype20 = 1 << 19, + [Description("Aussichtspunkte")] poitype21 = 1 << 20, + [Description("Mystische Stätten")] poitype22 = 1 << 21, + [Description("Historische Plätze")] poitype23 = 1 << 22, + [Description("Weitere Kultur und Sehenswürdigkeiten")] poitype24 = 1 << 23 } @@ -2133,78 +2843,115 @@ public enum PoiTypeGeschaefteDienstleister : long { [Description("Bank, Bankomat")] BankBankomat = 1L, + [Description("Beauty und Wellness")] BeautyundWellness = 1L << 1, + [Description("Friseur")] Friseur = 1L << 2, + [Description("Kosmetik")] Kosmetik = 1L << 3, + [Description("Massage, Heilbäder")] MassageHeilbaeder = 1L << 4, + [Description("Weitere Beauty und Wellness")] WeitereBeautyundWellness = 1L << 5, + [Description("Geschäfte")] Geschaefte = 1L << 6, + [Description("Getränke")] Getraenke = 1L << 7, + [Description("Antiquitäten")] Antiquitaeten = 1L << 8, + [Description("Blumen")] Blumen = 1L << 9, + [Description("Computerzubehör, Technik")] ComputerzubehoerTechnik = 1L << 10, + [Description("Drogerie")] Drogerie = 1L << 11, + [Description("Fahrräder")] Fahrraeder = 1L << 12, + [Description("Farben, Tapeten")] FarbenTapeten = 1L << 13, + [Description("Fleisch und Wurstwaren")] FleischundWurstwaren = 1L << 14, + [Description("Haushaltswaren")] Haushaltswaren = 1L << 15, + [Description("Juweliere, Goldschmiede")] JuweliereGoldschmiede = 1L << 16, + [Description("Kunsthandwerke")] Kunsthandwerke = 1L << 17, + [Description("Landwirtschaftliche Artikel")] LandwirtschaftlicheArtikel = 1L << 18, + [Description("Lebensmittel")] Lebensmittel = 1L << 19, + [Description("Lederwaren, Schuhe")] LederwarenSchuhe = 1L << 20, + [Description("Lokale traditionelle Produkte")] LokaletraditionelleProdukte = 1L << 21, + [Description("Mode, Bekleidung")] ModeBekleidung = 1L << 22, + [Description("Obst- und Gemüse")] ObstundGemüse = 1L << 23, + [Description("Optiker, Foto")] OptikerFoto = 1L << 24, + [Description("Produktionsstätten")] Produktionsstaetten = 1L << 25, + [Description("Souvenir")] Souvenir = 1L << 26, + [Description("Sportartikel")] Sportartikel = 1L << 27, + [Description("Tierbedarf")] Tierbedarf = 1L << 28, + [Description("Zeitungen, Bücher und Papierwaren")] ZeitungenBuecherundPapierwaren = 1L << 29, + [Description("Weitere Geschäfte")] WeitereGeschaefte = 1L << 30, + [Description("Weitere")] Weitere = 1L << 31, + [Description("Auto und Motor")] AutoundMotor = 1L << 32, + [Description("Bausektor")] Bausektor = 1L << 33, + [Description("Medien")] Medien = 1L << 34, + [Description("Reinigung")] Reinigung = 1L << 35, + [Description("Tierpflege")] Tierpflege = 1L << 36, + [Description("Weitere")] WeitereWeitere = 1L << 37 } @@ -2214,106 +2961,157 @@ public enum PoiTypeSportFreizeit : long { [Description("Guides, Clubs, Schulen")] GuidesClubsSchulen = 1L, + [Description("Ski- und Bergführer")] SkiundBergfuehrer = 1L << 1, + [Description("Bikeguides")] Bikeguides = 1L << 2, + [Description("Canyoning, Hydrospeed")] Canyoning = 1L << 3, + [Description("Kajak")] Kajak = 1L << 4, + [Description("Kitesurfen, Windsurfen")] KitesurfenWindsurfen = 1L << 5, + [Description("Paragleiten, Drachenfliegen")] ParagleitenDrachenfliegen = 1L << 6, + [Description("Rafting")] Rafting = 1L << 7, + [Description("Skischulen")] Skischulen = 1L << 8, + [Description("Wanderführer")] Wanderfuehrer = 1L << 9, + [Description("Langlaufschule")] Langlaufschule = 1L << 10, + [Description("Skiclubs")] Skiclubs = 1L << 11, + [Description("Weitere Guides, Clubs, Schulen")] WeitereGuidesClubsSchulen = 1L << 12, + [Description("Spiel- und Sportanlagen")] SpielundSportanlagen = 1L << 13, + [Description("Badeseen")] Badeseen = 1L << 14, + [Description("Bogenschiessanlagen")] Bogenschiessanlagen = 1L << 15, + [Description("Eisklettern")] Eisklettern = 1L << 16, + [Description("Fischergewässer")] Fischergewaesser = 1L << 17, + [Description("Fitnesscenter")] Fitnesscenter = 1L << 18, + [Description("Freibäder")] Freibaeder = 1L << 19, + [Description("Fussballplätze")] Fußballplaetze = 1L << 20, + [Description("Golfplätze")] Golfplaetze = 1L << 21, + [Description("Hallenbäder")] Hallenbaeder = 1L << 22, + [Description("Kinderspielplätze")] Kinderspielplaetze = 1L << 23, + [Description("Klettergarten")] Klettergarten = 1L << 24, + [Description("Kletterhallen")] Kletterhallen = 1L << 25, + [Description("Kletterparks")] Kletterparks = 1L << 26, + [Description("Minigolfplätze")] Minigolfplaetze = 1L << 27, + [Description("Pferdekutschenfahrten")] Pferdekutschenfahrten = 1L << 28, + [Description("Pferdeschlittenfahrten")] Pferdeschlittenfahrten = 1L << 29, + [Description("Radraststätten")] Radraststaetten = 1L << 30, + [Description("Reitställe")] Reitstaelle = 1L << 31, + [Description("Schlittschuhlaufen")] Schlittschuhlaufen = 1L << 32, + [Description("Tennisplätze")] Tennisplaetze = 1L << 33, + [Description("Volleyball, Beachvolleyball")] VolleyballBeachvolleyball = 1L << 34, + [Description("Zip-lines")] Ziplines = 1L << 35, + [Description("Kneippanlage")] Kneippanlage = 1L << 36, + [Description("Langlaufzentren")] Langlaufzentren = 1L << 37, + [Description("Weitere Spiel- und Sportanlagen")] WeitereSpielundSportanlagen = 1L << 38, + [Description("Verleih, Depot")] VerleihDepot = 1L << 39, + [Description("E-Bike-Verleihe")] EBikeVerleihe = 1L << 40, + [Description("Radverleihe")] Radverleihe = 1L << 41, + [Description("Schlittschuhverleihe")] Schlittschuhverleihe = 1L << 42, + [Description("Skidepots")] Skidepots = 1L << 43, + [Description("Skiverleihe")] Skiverleihe = 1L << 44, + [Description("Verleih von Kinderartikeln")] VerleihvonKinderartikeln = 1L << 45, + [Description("Verleih von Langlaufskiern")] VerleihLanglaufski = 1L << 46, + [Description("Weitere Verleih, Depot")] WeitereVerleihDepot = 1L << 47, + [Description("Schneeschuhverleih")] Schneeschuhverleih = 1L << 48, + [Description("Tierpark")] Tierpark = 1L << 49, + [Description("Bikepark")] Bikepark = 1L << 50, + [Description("Pumptracks und mehr")] Pumptracksundmehr = 1L << 51 } @@ -2323,16 +3121,22 @@ public enum PoiTypeVereine { [Description("Sport")] Sport = 1, + [Description("Kultur, Musik, Theater")] KulturMusikTheater = 1 << 1, + [Description("Tier, Natur, Wissenschaft")] TierNaturWissenschaft = 1 << 2, + [Description("Gesellschaft, Politisch")] GesellschaftPolitisch = 1 << 3, + [Description("Sozial, Rettung, gemeinnützig")] SozialRettungGemeinnuetzig = 1 << 4, + [Description("Freizeitverein")] Freizeitverein = 1 << 5, + [Description("weitere Vereine")] WeitereVereine = 1 << 6 } @@ -2342,14 +3146,19 @@ public enum PoiTypeUnternehmen { [Description("Industrie")] Industrie = 1, + [Description("Produktion")] Produktion = 1 << 1, + [Description("Baugewerbe")] Baugewerbe = 1 << 2, + [Description("Handwerk")] Handwerk = 1 << 3, + [Description("Energie")] Energie = 1 << 4, + [Description("weitere Unternehmen")] WeitereUnternehmen = 1 << 5 } @@ -2363,40 +3172,58 @@ public enum DSSTypeAufstiegsanlagen { [Description("Seilbahn")] Seilbahn = 1, + [Description("Kabinenbahn")] Kabinenbahn = 3, + [Description("Unterirdische Bahn")] UnterirdischeBahn = 4, + [Description("Sessellift")] Sessellift2 = 7, + [Description("Sessellift")] Sessellift3 = 8, + [Description("Skilift")] Skilift = 9, + [Description("Schrägaufzug")] Schraegaufzug = 10, + [Description("Klein-Skilift")] Kleinskilift = 11, + [Description("Telemix")] Telemix = 12, + [Description("Standseilbahn Zahnradbahn")] StandseilbahnZahnradbahn = 13, + [Description("Skibus")] Skibus = 14, + [Description("Zug")] Zug = 15, + [Description("Sessellift")] Sessellift4 = 16, + [Description("Sessellift")] Sessellift6 = 17, + [Description("Sessellift")] Sessellift8 = 18, + [Description("Förderband")] Foerderband = 19, + [Description("4er Sessellift kuppelbar")] ViererSesselliftkuppelbar = 21, + [Description("6er Sessellift kuppelbar")] SechserSesselliftkuppelbar = 22, + [Description("8er Sessellift kuppelbar")] AchtererSesselliftkuppelbar = 23 } @@ -2432,8 +3259,4 @@ public enum DSSTypeAufstiegsanlagen // rot = 4, // schwarz = 8 //} - - } - - diff --git a/Helper/Flags/FlagsHelper.cs b/Helper/Flags/FlagsHelper.cs index fd5dd3bd0..08efb2081 100644 --- a/Helper/Flags/FlagsHelper.cs +++ b/Helper/Flags/FlagsHelper.cs @@ -14,9 +14,15 @@ public static class FlagsHelper private static void CheckIsEnum(bool withFlags) { if (!typeof(T).IsEnum) - throw new ArgumentException($"Type '{typeof(T).FullName}' is not an enum", nameof(withFlags)); + throw new ArgumentException( + $"Type '{typeof(T).FullName}' is not an enum", + nameof(withFlags) + ); if (withFlags && !Attribute.IsDefined(typeof(T), typeof(FlagsAttribute))) - throw new ArgumentException($"Type '{typeof(T).FullName}' doesn't have the 'Flags' attribute", nameof(withFlags)); + throw new ArgumentException( + $"Type '{typeof(T).FullName}' doesn't have the 'Flags' attribute", + nameof(withFlags) + ); } public static bool IsFlagSet(this T value, T flag) where T : struct @@ -84,7 +90,10 @@ public static T CombineFlags(this IEnumerable flags) where T : struct FieldInfo? field = typeof(T).GetField(name); if (field != null) { - if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attr) + if ( + Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) + is DescriptionAttribute attr + ) { return attr.Description; } @@ -103,7 +112,10 @@ public static T CombineFlags(this IEnumerable flags) where T : struct FieldInfo? field = mytype.GetField(name); if (field != null) { - if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attr) + if ( + Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) + is DescriptionAttribute attr + ) { return attr.Description; } @@ -126,7 +138,10 @@ public static int GetFlagofType(string? id) FieldInfo? field = typeof(T).GetField(name); if (field != null) { - if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attr) + if ( + Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) + is DescriptionAttribute attr + ) { description = attr.Description; } @@ -157,7 +172,10 @@ public static long GetFlagofTypeLong(string? id) FieldInfo? field = typeof(T).GetField(name); if (field != null) { - if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attr) + if ( + Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) + is DescriptionAttribute attr + ) { description = attr.Description; } @@ -175,7 +193,8 @@ public static long GetFlagofTypeLong(string? id) } //Des gibmer die Liste zrugg! - public static List GetDescriptionList(this IEnumerable enumlist) where T : struct + public static List GetDescriptionList(this IEnumerable enumlist) + where T : struct { List descriptionList = new List(); foreach (var value in enumlist) @@ -187,7 +206,10 @@ public static List GetDescriptionList(this IEnumerable enumlist) w FieldInfo? field = typeof(T).GetField(name); if (field != null) { - if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attr) + if ( + Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) + is DescriptionAttribute attr + ) { descriptionList.Add(attr.Description); } diff --git a/Helper/Flags/GastronomyListCreator.cs b/Helper/Flags/GastronomyListCreator.cs index 2eb7b9ab9..696a2a685 100644 --- a/Helper/Flags/GastronomyListCreator.cs +++ b/Helper/Flags/GastronomyListCreator.cs @@ -14,14 +14,19 @@ public static List CreateGastroCeremonyCodeList(string capacityceremonyf { if (capacityceremonyfilter != "null") { - if (capacityceremonyfilter.Substring(capacityceremonyfilter.Length - 1, 1) == ",") - capacityceremonyfilter = capacityceremonyfilter.Substring(0, capacityceremonyfilter.Length - 1); + if ( + capacityceremonyfilter.Substring(capacityceremonyfilter.Length - 1, 1) + == "," + ) + capacityceremonyfilter = capacityceremonyfilter.Substring( + 0, + capacityceremonyfilter.Length - 1 + ); var splittedfilter = capacityceremonyfilter.Split(','); foreach (var filter in splittedfilter) { - switch (filter) { case "1": @@ -71,7 +76,6 @@ public static List CreateGastroDishCodeList(string dishcodefilter) foreach (var filter in splittedfilter) { - switch (filter) { case "1": @@ -117,13 +121,15 @@ public static List CreateGastroCategoryCodeList(string categorycodefilte if (categorycodefilter != "null") { if (categorycodefilter.Substring(categorycodefilter.Length - 1, 1) == ",") - categorycodefilter = categorycodefilter.Substring(0, categorycodefilter.Length - 1); + categorycodefilter = categorycodefilter.Substring( + 0, + categorycodefilter.Length - 1 + ); var splittedfilter = categorycodefilter.Split(','); foreach (var filter in splittedfilter) { - switch (filter) { case "1": @@ -203,13 +209,15 @@ public static List CreateGastroFacilityCodeList(string facilitycodefilte if (facilitycodefilter != "null") { if (facilitycodefilter.Substring(facilitycodefilter.Length - 1, 1) == ",") - facilitycodefilter = facilitycodefilter.Substring(0, facilitycodefilter.Length - 1); + facilitycodefilter = facilitycodefilter.Substring( + 0, + facilitycodefilter.Length - 1 + ); var splittedfilter = facilitycodefilter.Split(','); foreach (var filter in splittedfilter) { - switch (filter) { //Credit Card @@ -398,9 +406,7 @@ public static List CreateGastroFacilityCodeList(string facilitycodefilte typeids.Add("5C84265DA5F84F84A7896808ACCB675A"); break; - //Ende Cuisine - - + //Ende Cuisine } } } @@ -410,15 +416,18 @@ public static List CreateGastroFacilityCodeList(string facilitycodefilte #region Flags - public static List CreateGastroCeremonyCodeListfromFlag(string? capacityceremonyfilter) + public static List CreateGastroCeremonyCodeListfromFlag( + string? capacityceremonyfilter + ) { List ceremonycodeids = new List(); if (!String.IsNullOrEmpty(capacityceremonyfilter) && capacityceremonyfilter != "null") { if (int.TryParse(capacityceremonyfilter, out var ceremonycodefilterint)) - { - GastroCeremonyFlag myceremonycodeflag = (GastroCeremonyFlag)ceremonycodefilterint; + { + GastroCeremonyFlag myceremonycodeflag = + (GastroCeremonyFlag)ceremonycodefilterint; var myflags = myceremonycodeflag.GetFlags().GetDescriptionList(); @@ -439,7 +448,7 @@ public static List CreateGastroDishCodeListfromFlag(string? dishcodefilt if (!String.IsNullOrEmpty(dishcodefilter) && dishcodefilter != "null") { if (int.TryParse(dishcodefilter, out var dishcodefilterint)) - { + { GastroDishcodeFlag mydishcodeflag = (GastroDishcodeFlag)dishcodefilterint; var myflags = mydishcodeflag.GetFlags().GetDescriptionList(); @@ -461,8 +470,9 @@ public static List CreateGastroCategoryCodeListfromFlag(string? category if (!String.IsNullOrEmpty(categorycodefilter) && categorycodefilter != "null") { if (int.TryParse(categorycodefilter, out var categorycodefilterint)) - { - GastroCategoryFlag mycategorycodeflag = (GastroCategoryFlag)categorycodefilterint; + { + GastroCategoryFlag mycategorycodeflag = + (GastroCategoryFlag)categorycodefilterint; var myflags = mycategorycodeflag.GetFlags().GetDescriptionList(); @@ -483,8 +493,9 @@ public static List CreateGastroFacilityCodeListfromFlag(string? facility if (!String.IsNullOrEmpty(facilitycodefilter) && facilitycodefilter != "null") { if (long.TryParse(facilitycodefilter, out var facilitycodefilterint)) - { - GastroFacilityFlag myfacilitycodeflag = (GastroFacilityFlag)facilitycodefilterint; + { + GastroFacilityFlag myfacilitycodeflag = + (GastroFacilityFlag)facilitycodefilterint; var myflags = myfacilitycodeflag.GetFlags().GetDescriptionList(); @@ -505,12 +516,11 @@ public static List CreateGastroCusineCodeListfromFlag(string? facilityco if (!String.IsNullOrEmpty(facilitycodefilter) && facilitycodefilter != "null") { if (long.TryParse(facilitycodefilter, out var facilitycodefilterint)) - { + { GastroCuisineFlag myfacilitycodeflag = (GastroCuisineFlag)facilitycodefilterint; var myflags = myfacilitycodeflag.GetFlags().GetDescriptionList(); - foreach (var myflag in myflags) { facilitycodeids.Add(myflag); @@ -522,6 +532,5 @@ public static List CreateGastroCusineCodeListfromFlag(string? facilityco } #endregion - } } diff --git a/Helper/Flags/VenueListCreator.cs b/Helper/Flags/VenueListCreator.cs index 368c25498..3accda62d 100644 --- a/Helper/Flags/VenueListCreator.cs +++ b/Helper/Flags/VenueListCreator.cs @@ -79,7 +79,5 @@ public static List CreateVenueSeatTypeListfromFlag(string? venueseattype return rids; } - } - } diff --git a/Helper/Generic/CopyClassHelper.cs b/Helper/Generic/CopyClassHelper.cs index 8370806ec..01e16af74 100644 --- a/Helper/Generic/CopyClassHelper.cs +++ b/Helper/Generic/CopyClassHelper.cs @@ -21,11 +21,16 @@ public static void CopyPropertyValues(object source, object destination) { foreach (var destProperty in destProperties) { - if (destProperty.Name == sourceProperty.Name && - destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType)) + if ( + destProperty.Name == sourceProperty.Name + && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType) + ) { - destProperty.SetValue(destination, sourceProperty.GetValue( - source, new object[] { }), new object[] { }); + destProperty.SetValue( + destination, + sourceProperty.GetValue(source, new object[] { }), + new object[] { } + ); break; } diff --git a/Helper/Generic/CreateSeed.cs b/Helper/Generic/CreateSeed.cs index 5bc05ec01..0eea14f85 100644 --- a/Helper/Generic/CreateSeed.cs +++ b/Helper/Generic/CreateSeed.cs @@ -35,10 +35,8 @@ public static int GetSeed(int seed) { if (seedstring == null) return null; - else if (int.TryParse(seedstring, out int seed)) { - //Kein Seed es wird ein Seed zwischen 0 und 10 erzeugt if (seed == 0) { diff --git a/Helper/Generic/DateTimeHelper.cs b/Helper/Generic/DateTimeHelper.cs index 022479d26..a0c1ba751 100644 --- a/Helper/Generic/DateTimeHelper.cs +++ b/Helper/Generic/DateTimeHelper.cs @@ -11,23 +11,27 @@ public static double DateTimeToUnixTimestamp(DateTime dateTime) { var tzinfo = TZConvert.GetTimeZoneInfo("W. Europe Standard Time"); - return (TimeZoneInfo.ConvertTimeToUtc(dateTime, tzinfo) - - new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds; + return ( + TimeZoneInfo.ConvertTimeToUtc(dateTime, tzinfo) + - new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc) + ).TotalSeconds; } public static double DateTimeToUnixTimestampMilliseconds(DateTime dateTime) { var tzinfo = TZConvert.GetTimeZoneInfo("W. Europe Standard Time"); - return (TimeZoneInfo.ConvertTimeToUtc(dateTime, tzinfo) - - new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalMilliseconds; + return ( + TimeZoneInfo.ConvertTimeToUtc(dateTime, tzinfo) + - new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc) + ).TotalMilliseconds; } ////TEST without conversion to UTC simply convert to UTC what is passed //public static double DateTimeToUnixTimestampMillisecondsWithoutUTCConvert(DateTime dateTime) //{ // return (dateTime - - // new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalMilliseconds; + // new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalMilliseconds; //} //TODO UnixTimeStampToDateTime @@ -37,7 +41,16 @@ public static DateTime UnixTimeStampToDateTime(double unixTimeStamp) var tzinfo = TZConvert.GetTimeZoneInfo("W. Europe Standard Time"); // Unix timestamp is seconds past epoch - System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); + System.DateTime dtDateTime = new DateTime( + 1970, + 1, + 1, + 0, + 0, + 0, + 0, + System.DateTimeKind.Utc + ); dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToUniversalTime(); return TimeZoneInfo.ConvertTimeFromUtc(dtDateTime, tzinfo); @@ -48,12 +61,18 @@ public static DateTime UnixTimeStampToDateTimeMilliseconds(double unixTimeStamp) var tzinfo = TZConvert.GetTimeZoneInfo("W. Europe Standard Time"); // Unix timestamp is seconds past epoch - System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); + System.DateTime dtDateTime = new DateTime( + 1970, + 1, + 1, + 0, + 0, + 0, + 0, + System.DateTimeKind.Utc + ); dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp).ToUniversalTime(); return TimeZoneInfo.ConvertTimeFromUtc(dtDateTime, tzinfo); } - - - } } diff --git a/Helper/Generic/GeoSearchHelper.cs b/Helper/Generic/GeoSearchHelper.cs index a863a68fd..87c09aa60 100644 --- a/Helper/Generic/GeoSearchHelper.cs +++ b/Helper/Generic/GeoSearchHelper.cs @@ -12,7 +12,11 @@ public double HaversineInKM(double lat1, double long1, double lat2, double long2 { double dlong = (long2 - long1) * _d2r; double dlat = (lat2 - lat1) * _d2r; - double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D); + double a = + Math.Pow(Math.Sin(dlat / 2D), 2D) + + Math.Cos(lat1 * _d2r) + * Math.Cos(lat2 * _d2r) + * Math.Pow(Math.Sin(dlong / 2D), 2D); double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a)); double d = _eQuatorialEarthRadius * c; @@ -27,10 +31,20 @@ public int HaversineInM(double lat1, double long1, double lat2, double long2) public static bool CheckGeoSearch(string latitude, string longitude, string radius) { bool geosearch = false; - //Check of Geosearch durchgeführt werden kann + //Check of Geosearch durchgeführt werden kann CultureInfo culture = CultureInfo.InvariantCulture; - bool isLatDouble = Double.TryParse(latitude, NumberStyles.Any, culture, out double latitudecheck); - bool isLongDouble = Double.TryParse(longitude, NumberStyles.Any, culture, out double longitudecheck); + bool isLatDouble = Double.TryParse( + latitude, + NumberStyles.Any, + culture, + out double latitudecheck + ); + bool isLongDouble = Double.TryParse( + longitude, + NumberStyles.Any, + culture, + out double longitudecheck + ); bool isRadiusInt = Int32.TryParse(radius, out int radiuscheck); if (isLatDouble && isLongDouble && isRadiusInt) @@ -39,19 +53,36 @@ public static bool CheckGeoSearch(string latitude, string longitude, string radi return geosearch; } - public static PGGeoSearchResult GetPGGeoSearchResult(string? latitude, string? longitude, string? radius) + public static PGGeoSearchResult GetPGGeoSearchResult( + string? latitude, + string? longitude, + string? radius + ) { if (latitude == null && longitude == null) - return new PGGeoSearchResult() { geosearch = false, latitude = 0, longitude = 0, radius = 0 }; - - PGGeoSearchResult pggeosearchresult = new PGGeoSearchResult - { - geosearch = false - }; - //Check of Geosearch durchgeführt werden kann + return new PGGeoSearchResult() + { + geosearch = false, + latitude = 0, + longitude = 0, + radius = 0 + }; + + PGGeoSearchResult pggeosearchresult = new PGGeoSearchResult { geosearch = false }; + //Check of Geosearch durchgeführt werden kann CultureInfo culture = CultureInfo.InvariantCulture; - bool isLatDouble = Double.TryParse(latitude, NumberStyles.Any, culture, out double latitudecheck); - bool isLongDouble = Double.TryParse(longitude, NumberStyles.Any, culture, out double longitudecheck); + bool isLatDouble = Double.TryParse( + latitude, + NumberStyles.Any, + culture, + out double latitudecheck + ); + bool isLongDouble = Double.TryParse( + longitude, + NumberStyles.Any, + culture, + out double longitudecheck + ); bool isRadiusInt = Int32.TryParse(radius, out int radiuscheck); if (isLatDouble && isLongDouble) @@ -69,7 +100,6 @@ public static PGGeoSearchResult GetPGGeoSearchResult(string? latitude, string? l //var actualdistance = DistanceCalculator.Distance(pggeosearchresult.latitude, pggeosearchresult.longitude, DistanceCalculator.suedtirolMitteLatitude, DistanceCalculator.suedtirolMitteLongitude, 'K'); //if (actualdistance > 200) // pggeosearchresult.geosearch = false; - } else { @@ -82,16 +112,22 @@ public static PGGeoSearchResult GetPGGeoSearchResult(string? latitude, string? l return pggeosearchresult; } - public static PGGeoSearchResult GetPGGeoSearchResult(double? latitude, double? longitude, int radius) + public static PGGeoSearchResult GetPGGeoSearchResult( + double? latitude, + double? longitude, + int radius + ) { if (latitude == null && longitude == null) - return new PGGeoSearchResult() { geosearch = false, latitude = 0, longitude = 0, radius = 0 }; - - PGGeoSearchResult pggeosearchresult = new PGGeoSearchResult - { - geosearch = false - }; + return new PGGeoSearchResult() + { + geosearch = false, + latitude = 0, + longitude = 0, + radius = 0 + }; + PGGeoSearchResult pggeosearchresult = new PGGeoSearchResult { geosearch = false }; pggeosearchresult.geosearch = true; pggeosearchresult.latitude = latitude ?? 0; @@ -105,20 +141,36 @@ public static PGGeoSearchResult GetPGGeoSearchResult(double? latitude, double? l return pggeosearchresult; } - - public static RavenGeoSearchResult GetRavenGeoSearchResult(string latitude, string longitude, string radius) + public static RavenGeoSearchResult GetRavenGeoSearchResult( + string latitude, + string longitude, + string radius + ) { if (latitude == null && longitude == null) - return new RavenGeoSearchResult() { geosearch = false, latitude = 0, longitude = 0, radius = 0 }; - - RavenGeoSearchResult pggeosearchresult = new RavenGeoSearchResult - { - geosearch = false - }; - //Check of Geosearch durchgeführt werden kann + return new RavenGeoSearchResult() + { + geosearch = false, + latitude = 0, + longitude = 0, + radius = 0 + }; + + RavenGeoSearchResult pggeosearchresult = new RavenGeoSearchResult { geosearch = false }; + //Check of Geosearch durchgeführt werden kann CultureInfo culture = CultureInfo.InvariantCulture; - bool isLatDouble = Double.TryParse(latitude, NumberStyles.Any, culture, out double latitudecheck); - bool isLongDouble = Double.TryParse(longitude, NumberStyles.Any, culture, out double longitudecheck); + bool isLatDouble = Double.TryParse( + latitude, + NumberStyles.Any, + culture, + out double latitudecheck + ); + bool isLongDouble = Double.TryParse( + longitude, + NumberStyles.Any, + culture, + out double longitudecheck + ); bool isRadiusInt = Int32.TryParse(radius, out int radiuscheck); if (isLatDouble && isLongDouble) @@ -133,10 +185,15 @@ public static RavenGeoSearchResult GetRavenGeoSearchResult(string latitude, stri pggeosearchresult.radius = 150; //Check ob das ganze sinn macht - var actualdistance = DistanceCalculator.Distance(pggeosearchresult.latitude, pggeosearchresult.longitude, DistanceCalculator.suedtirolMitteLatitude, DistanceCalculator.suedtirolMitteLongitude, 'K'); + var actualdistance = DistanceCalculator.Distance( + pggeosearchresult.latitude, + pggeosearchresult.longitude, + DistanceCalculator.suedtirolMitteLatitude, + DistanceCalculator.suedtirolMitteLongitude, + 'K' + ); if (actualdistance > 150) pggeosearchresult.geosearch = false; - } else { @@ -148,7 +205,6 @@ public static RavenGeoSearchResult GetRavenGeoSearchResult(string latitude, stri return pggeosearchresult; } - } public class DistanceCalculator @@ -156,7 +212,6 @@ public class DistanceCalculator public const double suedtirolMitteLatitude = 46.655781; public const double suedtirolMitteLongitude = 11.4296877; - //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //::: ::: //::: This routine calculates the distance between two points (given the ::: @@ -188,7 +243,9 @@ public class DistanceCalculator public static double Distance(double lat1, double lon1, double lat2, double lon2, char unit) { double theta = lon1 - lon2; - double dist = Math.Sin(Deg2rad(lat1)) * Math.Sin(Deg2rad(lat2)) + Math.Cos(Deg2rad(lat1)) * Math.Cos(Deg2rad(lat2)) * Math.Cos(Deg2rad(theta)); + double dist = + Math.Sin(Deg2rad(lat1)) * Math.Sin(Deg2rad(lat2)) + + Math.Cos(Deg2rad(lat1)) * Math.Cos(Deg2rad(lat2)) * Math.Cos(Deg2rad(theta)); dist = Math.Acos(dist); dist = Rad2deg(dist); dist = dist * 60 * 1.1515; @@ -218,7 +275,6 @@ private static double Rad2deg(double rad) { return (rad / Math.PI * 180.0); } - } public class PGGeoSearchResult diff --git a/Helper/Generic/HasLanguageHelper.cs b/Helper/Generic/HasLanguageHelper.cs index 49a330ccc..f73f19785 100644 --- a/Helper/Generic/HasLanguageHelper.cs +++ b/Helper/Generic/HasLanguageHelper.cs @@ -8,7 +8,7 @@ namespace Helper { public static class HasLanguageHelper - { + { private static void FixDetailBaseAndIntroText(Detail mydetail) { if (!String.IsNullOrEmpty(mydetail.BaseText)) @@ -28,19 +28,28 @@ private static void FixDetailBaseAndIntroText(Detail mydetail) } //For Articles - public static void CheckMyInsertedLanguages(this ArticleBaseInfos myarticle, List availablelanguages) + public static void CheckMyInsertedLanguages( + this ArticleBaseInfos myarticle, + List availablelanguages + ) { if (myarticle.HasLanguage == null) myarticle.HasLanguage = new List(); - //Detail, ImageGallery, ContactInfos, AdditionalArticleInfos, + //Detail, ImageGallery, ContactInfos, AdditionalArticleInfos, foreach (string language in availablelanguages) { - if (myarticle.Detail.ContainsKey(language) || myarticle.ContactInfos.ContainsKey(language) || myarticle.AdditionalArticleInfos.ContainsKey(language)) + if ( + myarticle.Detail.ContainsKey(language) + || myarticle.ContactInfos.ContainsKey(language) + || myarticle.AdditionalArticleInfos.ContainsKey(language) + ) { bool removelang = true; - - if (myarticle.Detail.ContainsKey(language) && myarticle.Detail[language] != null) + + if ( + myarticle.Detail.ContainsKey(language) && myarticle.Detail[language] != null + ) { var detailvalues = myarticle.Detail[language]; @@ -70,7 +79,10 @@ public static void CheckMyInsertedLanguages(this ArticleBaseInfos myarticle, Lis myarticle.Detail[language].Language = language; } - if (myarticle.ContactInfos.ContainsKey(language) && myarticle.ContactInfos[language] != null) + if ( + myarticle.ContactInfos.ContainsKey(language) + && myarticle.ContactInfos[language] != null + ) { var contactvalues = myarticle.ContactInfos[language]; @@ -116,7 +128,6 @@ public static void CheckMyInsertedLanguages(this ArticleBaseInfos myarticle, Lis if (additionalvalues.Elements.Count > 0) removelang = false; - } //Add Language @@ -138,23 +149,32 @@ public static void CheckMyInsertedLanguages(this ArticleBaseInfos myarticle, Lis myarticle.HasLanguage.Remove(language); } } - } + } } //For Activities, Pois, ODHActivityPois - public static void CheckMyInsertedLanguages(this PoiBaseInfos mypoiactivity, List availablelanguages) + public static void CheckMyInsertedLanguages( + this PoiBaseInfos mypoiactivity, + List availablelanguages + ) { if (mypoiactivity.HasLanguage == null) mypoiactivity.HasLanguage = new List(); - //Detail, ImageGallery, ContactInfos, AdditionalArticleInfos, + //Detail, ImageGallery, ContactInfos, AdditionalArticleInfos, foreach (string language in availablelanguages) { - if (mypoiactivity.Detail.ContainsKey(language) || mypoiactivity.ContactInfos.ContainsKey(language)) // || mypoiactivity.AdditionalPoiInfos.ContainsKey(language)) + if ( + mypoiactivity.Detail.ContainsKey(language) + || mypoiactivity.ContactInfos.ContainsKey(language) + ) // || mypoiactivity.AdditionalPoiInfos.ContainsKey(language)) { bool removelang = true; - if (mypoiactivity.Detail.ContainsKey(language) && mypoiactivity.Detail[language] != null) + if ( + mypoiactivity.Detail.ContainsKey(language) + && mypoiactivity.Detail[language] != null + ) { var detailvalues = mypoiactivity.Detail[language]; FixDetailBaseAndIntroText(detailvalues); @@ -163,20 +183,23 @@ public static void CheckMyInsertedLanguages(this PoiBaseInfos mypoiactivity, Lis removelang = false; if (!String.IsNullOrEmpty(detailvalues.BaseText)) if (!String.IsNullOrEmpty(detailvalues.BaseText.Trim())) - removelang = false; + removelang = false; if (!String.IsNullOrEmpty(detailvalues.GetThereText)) removelang = false; if (!String.IsNullOrEmpty(detailvalues.Header)) removelang = false; if (!String.IsNullOrEmpty(detailvalues.IntroText)) if (!String.IsNullOrEmpty(detailvalues.IntroText.Trim())) - removelang = false; + removelang = false; if (!String.IsNullOrEmpty(detailvalues.SubHeader)) removelang = false; if (!String.IsNullOrEmpty(detailvalues.Title)) removelang = false; } - if (mypoiactivity.ContactInfos.ContainsKey(language) && mypoiactivity.ContactInfos[language] != null) + if ( + mypoiactivity.ContactInfos.ContainsKey(language) + && mypoiactivity.ContactInfos[language] != null + ) { var contactvalues = mypoiactivity.ContactInfos[language]; @@ -233,23 +256,32 @@ public static void CheckMyInsertedLanguages(this PoiBaseInfos mypoiactivity, Lis mypoiactivity.HasLanguage.Remove(language); } } - } + } } //For Events - public static void CheckMyInsertedLanguages(this EventBaseInfos mypoiactivity, List availablelanguages) + public static void CheckMyInsertedLanguages( + this EventBaseInfos mypoiactivity, + List availablelanguages + ) { if (mypoiactivity.HasLanguage == null) mypoiactivity.HasLanguage = new List(); - //Detail, ImageGallery, ContactInfos, AdditionalArticleInfos, + //Detail, ImageGallery, ContactInfos, AdditionalArticleInfos, foreach (string language in availablelanguages) { - if (mypoiactivity.Detail.ContainsKey(language) || mypoiactivity.ContactInfos.ContainsKey(language)) // || mypoiactivity.AdditionalPoiInfos.ContainsKey(language)) + if ( + mypoiactivity.Detail.ContainsKey(language) + || mypoiactivity.ContactInfos.ContainsKey(language) + ) // || mypoiactivity.AdditionalPoiInfos.ContainsKey(language)) { bool removelang = true; - - if (mypoiactivity.Detail.ContainsKey(language) && mypoiactivity.Detail[language] != null) + + if ( + mypoiactivity.Detail.ContainsKey(language) + && mypoiactivity.Detail[language] != null + ) { var detailvalues = mypoiactivity.Detail[language]; FixDetailBaseAndIntroText(detailvalues); @@ -258,20 +290,23 @@ public static void CheckMyInsertedLanguages(this EventBaseInfos mypoiactivity, L removelang = false; if (!String.IsNullOrEmpty(detailvalues.BaseText)) if (!String.IsNullOrEmpty(detailvalues.BaseText.Trim())) - removelang = false; + removelang = false; if (!String.IsNullOrEmpty(detailvalues.GetThereText)) removelang = false; if (!String.IsNullOrEmpty(detailvalues.Header)) removelang = false; if (!String.IsNullOrEmpty(detailvalues.IntroText)) if (!String.IsNullOrEmpty(detailvalues.IntroText.Trim())) - removelang = false; + removelang = false; if (!String.IsNullOrEmpty(detailvalues.SubHeader)) removelang = false; if (!String.IsNullOrEmpty(detailvalues.Title)) removelang = false; } - if (mypoiactivity.ContactInfos.ContainsKey(language) && mypoiactivity.ContactInfos[language] != null) + if ( + mypoiactivity.ContactInfos.ContainsKey(language) + && mypoiactivity.ContactInfos[language] != null + ) { var contactvalues = mypoiactivity.ContactInfos[language]; @@ -327,11 +362,14 @@ public static void CheckMyInsertedLanguages(this EventBaseInfos mypoiactivity, L mypoiactivity.HasLanguage.Remove(language); } } - } + } } //For EventShort - public static void CheckMyInsertedLanguages(this EventShort mydata, List? availablelanguages = null) + public static void CheckMyInsertedLanguages( + this EventShort mydata, + List? availablelanguages = null + ) { if (availablelanguages == null) availablelanguages = new List { "de", "it", "en" }; diff --git a/Helper/Generic/IdGenerator.cs b/Helper/Generic/IdGenerator.cs index 2b9e7a8da..395d7be0c 100644 --- a/Helper/Generic/IdGenerator.cs +++ b/Helper/Generic/IdGenerator.cs @@ -48,11 +48,11 @@ private static string CreateGUID(IDStyle style) if (style == IDStyle.uppercase) id = id.ToUpper(); - else if(style == IDStyle.lowercase) + else if (style == IDStyle.lowercase) id = id.ToLower(); return id; - } + } public static IDStyle GetIDStyle(T odhtype) { @@ -90,30 +90,62 @@ public static IDStyle GetIDStyle(Type odhtype) { return odhtype switch { - Type _ when odhtype == typeof(Accommodation) || odhtype == typeof(AccommodationLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(AccoRoom) || odhtype == typeof(AccommodationRoomLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(LTSActivity) || odhtype == typeof(LTSActivityLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(LTSPoi) || odhtype == typeof(LTSPoiLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(Gastronomy) || odhtype == typeof(GastronomyLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(Event) || odhtype == typeof(EventLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(ODHActivityPoi) || odhtype == typeof(ODHActivityPoiLinked) => IDStyle.lowercase, - Type _ when odhtype == typeof(Package) || odhtype == typeof(PackageLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(Measuringpoint) || odhtype == typeof(MeasuringpointLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(WebcamInfo) || odhtype == typeof(WebcamInfoLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(Article) || odhtype == typeof(ArticlesLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(DDVenue) => IDStyle.uppercase, - Type _ when odhtype == typeof(EventShort) || odhtype == typeof(EventShortLinked) => IDStyle.lowercase, - Type _ when odhtype == typeof(ExperienceArea) || odhtype == typeof(ExperienceAreaLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(MetaRegion) || odhtype == typeof(MetaRegionLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(Region) || odhtype == typeof(RegionLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(Tourismverein) || odhtype == typeof(TourismvereinLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(Municipality) || odhtype == typeof(MunicipalityLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(District) || odhtype == typeof(DistrictLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(SkiArea) || odhtype == typeof(SkiAreaLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(SkiRegion) || odhtype == typeof(SkiRegionLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(Area) || odhtype == typeof(AreaLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(Wine) || odhtype == typeof(WineLinked) => IDStyle.uppercase, - Type _ when odhtype == typeof(SmgTags) || odhtype == typeof(ODHTagLinked) => IDStyle.lowercase, + Type _ + when odhtype == typeof(Accommodation) || odhtype == typeof(AccommodationLinked) + => IDStyle.uppercase, + Type _ + when odhtype == typeof(AccoRoom) || odhtype == typeof(AccommodationRoomLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(LTSActivity) || odhtype == typeof(LTSActivityLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(LTSPoi) || odhtype == typeof(LTSPoiLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(Gastronomy) || odhtype == typeof(GastronomyLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(Event) || odhtype == typeof(EventLinked) + => IDStyle.uppercase, + Type _ + when odhtype == typeof(ODHActivityPoi) + || odhtype == typeof(ODHActivityPoiLinked) + => IDStyle.lowercase, + Type _ when odhtype == typeof(Package) || odhtype == typeof(PackageLinked) + => IDStyle.uppercase, + Type _ + when odhtype == typeof(Measuringpoint) + || odhtype == typeof(MeasuringpointLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(WebcamInfo) || odhtype == typeof(WebcamInfoLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(Article) || odhtype == typeof(ArticlesLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(DDVenue) => IDStyle.uppercase, + Type _ when odhtype == typeof(EventShort) || odhtype == typeof(EventShortLinked) + => IDStyle.lowercase, + Type _ + when odhtype == typeof(ExperienceArea) + || odhtype == typeof(ExperienceAreaLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(MetaRegion) || odhtype == typeof(MetaRegionLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(Region) || odhtype == typeof(RegionLinked) + => IDStyle.uppercase, + Type _ + when odhtype == typeof(Tourismverein) || odhtype == typeof(TourismvereinLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(Municipality) || odhtype == typeof(MunicipalityLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(District) || odhtype == typeof(DistrictLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(SkiArea) || odhtype == typeof(SkiAreaLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(SkiRegion) || odhtype == typeof(SkiRegionLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(Area) || odhtype == typeof(AreaLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(Wine) || odhtype == typeof(WineLinked) + => IDStyle.uppercase, + Type _ when odhtype == typeof(SmgTags) || odhtype == typeof(ODHTagLinked) + => IDStyle.lowercase, _ => throw new Exception("not known odh type") }; } diff --git a/Helper/Generic/LicenseHelper.cs b/Helper/Generic/LicenseHelper.cs index 8b039b2c1..ced3b59e0 100644 --- a/Helper/Generic/LicenseHelper.cs +++ b/Helper/Generic/LicenseHelper.cs @@ -9,13 +9,27 @@ namespace Helper { public class LicenseHelper { - public static LicenseInfo GetLicenseInfoobject(string licensetype, string author, string licenseholder, bool closeddata) + public static LicenseInfo GetLicenseInfoobject( + string licensetype, + string author, + string licenseholder, + bool closeddata + ) { - return new LicenseInfo() { Author = author, License = licensetype, LicenseHolder = licenseholder, ClosedData = closeddata }; + return new LicenseInfo() + { + Author = author, + License = licensetype, + LicenseHolder = licenseholder, + ClosedData = closeddata + }; } //TODO Make a HOF and apply all the rules - public static LicenseInfo GetLicenseInfoobject(T myobject, Func licensegenerator) + public static LicenseInfo GetLicenseInfoobject( + T myobject, + Func licensegenerator + ) { return licensegenerator(myobject); } @@ -30,7 +44,7 @@ public static LicenseInfo GetLicenseforAccommodation(Accommodation data) { isopendata = true; licensetype = "CC0"; - } + } return GetLicenseInfoobject(licensetype, "", licenseholder, !isopendata); } @@ -112,13 +126,14 @@ public static LicenseInfo GetLicenseforEvent(Event data) } //Source DRIN and CentroTrevi - if(data.Source.ToLower() != "lts") + if (data.Source.ToLower() != "lts") { isopendata = true; licensetype = "CC0"; if (data.Source.ToLower() == "trevilab") - licenseholder = @"https://www.provincia.bz.it/arte-cultura/cultura/centro-trevi.asp"; + licenseholder = + @"https://www.provincia.bz.it/arte-cultura/cultura/centro-trevi.asp"; if (data.Source.ToLower() == "drin") licenseholder = @"https://www.provincia.bz.it/arte-cultura/giovani/drin.asp"; else @@ -137,7 +152,11 @@ public static LicenseInfo GetLicenseforOdhActivityPoi(ODHActivityPoi data) if (data.Source == null) data.Source = "Content"; - if (data.Source.ToLower() == "content" || data.Source.ToLower() == "magnolia" || data.Source.ToLower() == "common") + if ( + data.Source.ToLower() == "content" + || data.Source.ToLower() == "magnolia" + || data.Source.ToLower() == "common" + ) licenseholder = @"https://www.idm-suedtirol.com"; if (data.Source.ToLower() == "siag") licenseholder = "http://www.provinz.bz.it/kunst-kultur/museen"; @@ -152,7 +171,22 @@ public static LicenseInfo GetLicenseforOdhActivityPoi(ODHActivityPoi data) if (data.Source.ToLower() == "dss") licenseholder = @"https://www.dolomitisuperski.com/"; - List allowedsources = new List() { "magnolia", "none", "museumdata", "suedtirolwein", "archapp", "activitydata", "poidata", "beacondata", "gastronomicdata", "common","sta", "dssliftbase", "dssslopebase" }; + List allowedsources = new List() + { + "magnolia", + "none", + "museumdata", + "suedtirolwein", + "archapp", + "activitydata", + "poidata", + "beacondata", + "gastronomicdata", + "common", + "sta", + "dssliftbase", + "dssslopebase" + }; if (data.Active) { @@ -202,7 +236,7 @@ public static LicenseInfo GetLicenseforWebcam(WebcamInfo data) licensetype = ""; //licensetype = "CC0"; } - if(data.Source?.ToLower() == "content") + if (data.Source?.ToLower() == "content") { licenseholder = @"https://www.idm-suedtirol.com"; } @@ -231,7 +265,11 @@ public static LicenseInfo GetLicenseforVenue(DDVenue data) var licensetype = "Closed"; var licenseholder = @"https://www.lts.it"; - if (data.attributes.categories is { } && !data.attributes.categories.Contains("lts/visi_unpublishedOnODH") && data.attributes.categories.Contains("lts/visi_publishedOnODH")) + if ( + data.attributes.categories is { } + && !data.attributes.categories.Contains("lts/visi_unpublishedOnODH") + && data.attributes.categories.Contains("lts/visi_publishedOnODH") + ) { isopendata = true; licensetype = "CC0"; @@ -313,7 +351,11 @@ public static LicenseInfo GetLicenseforWeather() return GetLicenseInfoobject(licensetype, "", licenseholder, !isopendata); } - public static void CheckLicenseInfoWithSource(LicenseInfo licenseinfo, string source, bool setcloseddatato) + public static void CheckLicenseInfoWithSource( + LicenseInfo licenseinfo, + string source, + bool setcloseddatato + ) { if (source == "lts") { diff --git a/Helper/Generic/MetaInfoHelper.cs b/Helper/Generic/MetaInfoHelper.cs index a5dd32d2a..9ec482b0f 100644 --- a/Helper/Generic/MetaInfoHelper.cs +++ b/Helper/Generic/MetaInfoHelper.cs @@ -10,22 +10,47 @@ namespace Helper public class MetadataHelper { //Simple Method to reset the Metainfo - public static Metadata GetMetadata(string id, string type, string? source, DateTime? lastupdated = null, bool reduced = false) + public static Metadata GetMetadata( + string id, + string type, + string? source, + DateTime? lastupdated = null, + bool reduced = false + ) { - return new Metadata() { Id = id, Type = type, LastUpdate = lastupdated, Source = source, Reduced = reduced }; + return new Metadata() + { + Id = id, + Type = type, + LastUpdate = lastupdated, + Source = source, + Reduced = reduced + }; } - public static Metadata GetMetadata(T data, string source, DateTime? lastupdated = null, bool reduced = false) where T : IIdentifiable, IMetaData + public static Metadata GetMetadata( + T data, + string source, + DateTime? lastupdated = null, + bool reduced = false + ) where T : IIdentifiable, IMetaData { string type = ODHTypeHelper.TranslateType2TypeString(data); //If source is already set use the old source if (data._Meta != null && !string.IsNullOrEmpty(data._Meta.Source)) - source = data._Meta.Source; + source = data._Meta.Source; - return new Metadata() { Id = data.Id, Type = type, LastUpdate = lastupdated, Source = source, Reduced = reduced }; + return new Metadata() + { + Id = data.Id, + Type = type, + LastUpdate = lastupdated, + Source = source, + Reduced = reduced + }; } - + public static Metadata GetMetadataobject(T myobject, Func metadataganerator) { return metadataganerator(myobject); @@ -62,7 +87,7 @@ public static Metadata GetMetadataobject(T myobject) ODHTagLinked odhtl => GetMetadataforOdhTag(odhtl), WeatherHistoryLinked wh => GetMetaDataForWeatherHistory(wh), _ => throw new Exception("not known odh type") - }; + }; } public static Metadata GetMetadataforAccommodation(AccommodationLinked data) @@ -101,7 +126,7 @@ public static Metadata GetMetadataforActivity(LTSActivityLinked data) reduced = (bool)data._Meta.Reduced; var sourcemeta = "lts"; - if(data.Source != null) + if (data.Source != null) sourcemeta = data.Source.ToLower(); return GetMetadata(data, sourcemeta, data.LastChange, reduced); @@ -189,8 +214,8 @@ public static Metadata GetMetadataforWebcam(WebcamInfoLinked data) public static Metadata GetMetadataforArticle(ArticlesLinked data) { string sourcemeta = "noi"; - - if(!String.IsNullOrEmpty(data.Source)) + + if (!String.IsNullOrEmpty(data.Source)) sourcemeta = data.Source.ToLower(); if (sourcemeta == "content") @@ -212,11 +237,11 @@ public static Metadata GetMetadataforEventShort(EventShortLinked data) { string sourcemeta = data.Source != null ? data.Source.ToLower() : "ebms"; - string sourcestr = sourcemeta switch - { - "content" => "noi", - "ebms" => "eurac", - _ => sourcemeta, + string sourcestr = sourcemeta switch + { + "content" => "noi", + "ebms" => "eurac", + _ => sourcemeta, }; return GetMetadata(data, sourcestr, data.LastChange, false); } @@ -262,17 +287,17 @@ public static Metadata GetMetadataforSkiRegion(SkiRegionLinked data) } public static Metadata GetMetadataforArea(AreaLinked data) - { + { return GetMetadata(data, "lts", data.LastChange, false); } public static Metadata GetMetadataforWineAward(WineLinked data) { - return GetMetadata(data, "suedtirolwein", data.LastChange, false); - } - + return GetMetadata(data, "suedtirolwein", data.LastChange, false); + } + public static Metadata GetMetaDataForWeatherHistory(WeatherHistoryLinked data) - { + { return GetMetadata(data, "siag", data.LastChange, false); } } diff --git a/Helper/Generic/ODHTypeHelper.cs b/Helper/Generic/ODHTypeHelper.cs index f42310297..9fab517b8 100644 --- a/Helper/Generic/ODHTypeHelper.cs +++ b/Helper/Generic/ODHTypeHelper.cs @@ -11,7 +11,7 @@ namespace Helper public class ODHTypeHelper { #region TypeObject2TypeStringANDPGTable - + /// /// Translates a ODH Type Object to the Type (Metadata) as String /// @@ -295,7 +295,8 @@ public static IIdentifiable ConvertJsonRawToObject(string odhtype, JsonRaw raw) return odhtype switch { "accommodation" => JsonConvert.DeserializeObject(raw.Value)!, - "accommodationroom" => JsonConvert.DeserializeObject(raw.Value)!, + "accommodationroom" + => JsonConvert.DeserializeObject(raw.Value)!, "ltsactivity" => JsonConvert.DeserializeObject(raw.Value)!, "ltspoi" => JsonConvert.DeserializeObject(raw.Value)!, "ltsgastronomy" => JsonConvert.DeserializeObject(raw.Value)!, @@ -310,7 +311,8 @@ public static IIdentifiable ConvertJsonRawToObject(string odhtype, JsonRaw raw) "experiencearea" => JsonConvert.DeserializeObject(raw.Value)!, "metaregion" => JsonConvert.DeserializeObject(raw.Value)!, "region" => JsonConvert.DeserializeObject(raw.Value)!, - "tourismassociation" => JsonConvert.DeserializeObject(raw.Value)!, + "tourismassociation" + => JsonConvert.DeserializeObject(raw.Value)!, "municipality" => JsonConvert.DeserializeObject(raw.Value)!, "district" => JsonConvert.DeserializeObject(raw.Value)!, "skiarea" => JsonConvert.DeserializeObject(raw.Value)!, @@ -366,20 +368,31 @@ public static string[] GetAllSearchableODHTypes(bool getall) return odhtypes.ToArray(); } - public static Func TranslateTypeToSearchField(string odhtype) { return odhtype switch { "accommodation" => PostgresSQLWhereBuilder.AccoTitleFieldsToSearchFor, "accommodationroom" => PostgresSQLWhereBuilder.AccoRoomNameFieldsToSearchFor, - "ltsactivity" or "ltspoi" or "ltsgastronomy" or "event" or "odhactivitypoi" or "metaregion" or "region" or "tourismassociation" or "municipality" - or "district" or "skiarea" or "skiregion" or "article" or "experiencearea" - => PostgresSQLWhereBuilder.TitleFieldsToSearchFor, + "ltsactivity" + or "ltspoi" + or "ltsgastronomy" + or "event" + or "odhactivitypoi" + or "metaregion" + or "region" + or "tourismassociation" + or "municipality" + or "district" + or "skiarea" + or "skiregion" + or "article" + or "experiencearea" + => PostgresSQLWhereBuilder.TitleFieldsToSearchFor, //"measuringpoint" => PostgresSQLWhereBuilder., "webcam" => PostgresSQLWhereBuilder.WebcamnameFieldsToSearchFor, "venue" => PostgresSQLWhereBuilder.VenueTitleFieldsToSearchFor, - //"eventshort" => "eventeuracnoi", + //"eventshort" => "eventeuracnoi", //"area" => "areas", //"wineaward" => "wines", _ => throw new Exception("not known odh type") @@ -401,7 +414,7 @@ public static Func TranslateTypeToSearchField(string odhtype) // //"measuringpoint" => PostgresSQLWhereBuilder., // "webcam" => PostgresSQLWhereBuilder.WebcamnameFieldsToSearchFor, // "venue" => PostgresSQLWhereBuilder.VenueTitleFieldsToSearchFor, - // //"eventshort" => "eventeuracnoi", + // //"eventshort" => "eventeuracnoi", // //"area" => "areas", // //"wineaward" => "wines", // _ => throw new Exception("not known odh type") @@ -416,13 +429,26 @@ public static string TranslateTypeToTitleField(string odhtype, string language) { "accommodation" => $"AccoDetail.{language}.Name", "accommodationroom" => $"AccoRoomDetail.{language}.Name", - "ltsactivity" or "ltspoi" or "ltsgastronomy" or "event" or "odhactivitypoi" or "metaregion" or "region" or "tourismassociation" or "municipality" - or "district" or "skiarea" or "skiregion" or "article" or "experiencearea" - => $"Detail.{language}.Title", + "ltsactivity" + or "ltspoi" + or "ltsgastronomy" + or "event" + or "odhactivitypoi" + or "metaregion" + or "region" + or "tourismassociation" + or "municipality" + or "district" + or "skiarea" + or "skiregion" + or "article" + or "experiencearea" + => $"Detail.{language}.Title", "measuringpoint" => $"Shortname", "webcam" => $"Webcamname.{language}", - "venue" => $"attributes.name.{PostgresSQLWhereBuilder.TransformLanguagetoDDStandard(language)}", - //"eventshort" => "eventeuracnoi", + "venue" + => $"attributes.name.{PostgresSQLWhereBuilder.TransformLanguagetoDDStandard(language)}", + //"eventshort" => "eventeuracnoi", //"area" => "areas", //"wineaward" => "wines", _ => throw new Exception("not known odh type") @@ -435,13 +461,25 @@ public static string TranslateTypeToBaseTextField(string odhtype, string languag { "accommodation" => $"AccoDetail.{language}.Longdesc", "accommodationroom" => $"AccoRoomDetail.{language}.Longdesc", - "ltsactivity" or "ltspoi" or "ltsgastronomy" or "event" or "odhactivitypoi" or "metaregion" or "region" or "tourismassociation" or "municipality" - or "district" or "skiarea" or "skiregion" or "article" or "experiencearea" - => $"Detail.{language}.BaseText", + "ltsactivity" + or "ltspoi" + or "ltsgastronomy" + or "event" + or "odhactivitypoi" + or "metaregion" + or "region" + or "tourismassociation" + or "municipality" + or "district" + or "skiarea" + or "skiregion" + or "article" + or "experiencearea" + => $"Detail.{language}.BaseText", "measuringpoint" => "notextfield", "webcam" => "notextfield", "venue" => "notextfield", - //"eventshort" => "eventeuracnoi", + //"eventshort" => "eventeuracnoi", //"area" => "areas", //"wineaward" => "wines", _ => throw new Exception("not known odh type") diff --git a/Helper/Generic/PublishedOnHelper.cs b/Helper/Generic/PublishedOnHelper.cs index d910dda84..21d2e9d13 100644 --- a/Helper/Generic/PublishedOnHelper.cs +++ b/Helper/Generic/PublishedOnHelper.cs @@ -17,7 +17,7 @@ public static List GetPublishenOnList(string type, bool smgactive) if (smgactive) publishedonlist.Add("https://noi.bz.it"); } - else if(type != "package") + else if (type != "package") { if (smgactive) publishedonlist.Add("https://www.suedtirol.info"); diff --git a/Helper/GetAdditionalTypeInfo.cs b/Helper/GetAdditionalTypeInfo.cs index 80a629964..52f9bf215 100644 --- a/Helper/GetAdditionalTypeInfo.cs +++ b/Helper/GetAdditionalTypeInfo.cs @@ -10,33 +10,42 @@ namespace Helper { public class GetAdditionalTypeInfo { - public static async Task> GetAdditionalTypeInfoForPoi(QueryFactory QueryFactory, string? subtype, List? languages) + public static async Task< + Dictionary + > GetAdditionalTypeInfoForPoi( + QueryFactory QueryFactory, + string? subtype, + List? languages + ) { - if(languages == null) - languages = new List() { "de","it","en"}; + if (languages == null) + languages = new List() { "de", "it", "en" }; - Dictionary myadditionalpoinfosdict = new Dictionary(); + Dictionary myadditionalpoinfosdict = + new Dictionary(); //Get SuedtirolType Subtype - var subtypequery = QueryFactory.Query("smgpoitypes") - .Select("data") - .Where("id", subtype?.ToLower()); - //.WhereRaw("data->>'Key' LIKE $$", subtype); - var subtypedata = - await subtypequery - .GetFirstOrDefaultAsObject(); + var subtypequery = QueryFactory + .Query("smgpoitypes") + .Select("data") + .Where("id", subtype?.ToLower()); + //.WhereRaw("data->>'Key' LIKE $$", subtype); + var subtypedata = await subtypequery.GetFirstOrDefaultAsObject(); if (subtypedata != null) { - var maintypequery = QueryFactory.Query("smgpoitypes") - .Select("data") - .Where("id", subtypedata.Parent?.ToLower()); + var maintypequery = QueryFactory + .Query("smgpoitypes") + .Select("data") + .Where("id", subtypedata.Parent?.ToLower()); //.WhereRaw("data->>'Key' LIKE $$", subtypedata.TypeParent); - var maintypedata = - await maintypequery - .GetFirstOrDefaultAsObject(); + var maintypedata = await maintypequery.GetFirstOrDefaultAsObject(); - var validtags = await ODHTagHelper.GetODHTagsValidforTranslations(QueryFactory, new List(), new List() { maintypedata?.Key ?? "", subtypedata.Key }); + var validtags = await ODHTagHelper.GetODHTagsValidforTranslations( + QueryFactory, + new List(), + new List() { maintypedata?.Key ?? "", subtypedata.Key } + ); foreach (var lang in languages) { @@ -53,7 +62,6 @@ await maintypequery } return myadditionalpoinfosdict; - } + } } - } diff --git a/Helper/JsonGeneratorHelper.cs b/Helper/JsonGeneratorHelper.cs index 4287d2360..38616762f 100644 --- a/Helper/JsonGeneratorHelper.cs +++ b/Helper/JsonGeneratorHelper.cs @@ -15,7 +15,12 @@ namespace Helper { public class JsonGeneratorHelper { - public static async Task GenerateJSONAccommodationsForBooklist(QueryFactory queryFactory, string jsondir, bool isbookable, string jsonName) + public static async Task GenerateJSONAccommodationsForBooklist( + QueryFactory queryFactory, + string jsondir, + bool isbookable, + string jsonName + ) { //List languagelist = new List() { "de", "it", "en" }; @@ -26,26 +31,44 @@ public static async Task GenerateJSONAccommodationsForBooklist(QueryFactory quer var seed = Helper.CreateSeed.GetSeed(0); string orderby = $"md5(id || '{seed}')"; - var query = - queryFactory.Query() - .SelectRaw(select) - .From("accommodations") - .AccommodationWhereExpression( - idlist: new List(), accotypelist: new List(), - categorylist: new List(), featurelist: new Dictionary(), featureidlist: new List(), - badgelist: new List(), themelist: new Dictionary(), - boardlist: new List(), smgtaglist: new List(), - districtlist: new List(), municipalitylist: new List(), - tourismvereinlist: new List(), regionlist: new List(), - apartmentfilter: null, bookable: isbookable, altitude: false, - altitudemin: 0, altitudemax: 0, - activefilter: null, smgactivefilter: true, publishedonlist: new List(), sourcelist: new List(), - searchfilter: null, language: null, lastchange: null, languagelist: new List(), - filterClosedData: false, reducedData: false) - .OrderByRaw(orderby); + var query = queryFactory + .Query() + .SelectRaw(select) + .From("accommodations") + .AccommodationWhereExpression( + idlist: new List(), + accotypelist: new List(), + categorylist: new List(), + featurelist: new Dictionary(), + featureidlist: new List(), + badgelist: new List(), + themelist: new Dictionary(), + boardlist: new List(), + smgtaglist: new List(), + districtlist: new List(), + municipalitylist: new List(), + tourismvereinlist: new List(), + regionlist: new List(), + apartmentfilter: null, + bookable: isbookable, + altitude: false, + altitudemin: 0, + altitudemax: 0, + activefilter: null, + smgactivefilter: true, + publishedonlist: new List(), + sourcelist: new List(), + searchfilter: null, + language: null, + lastchange: null, + languagelist: new List(), + filterClosedData: false, + reducedData: false + ) + .OrderByRaw(orderby); var data = await query.GetAsync(); - + //Save json string fileName = Path.Combine(jsondir, $"{jsonName}.json"); using (var writer = File.CreateText(fileName)) @@ -56,14 +79,15 @@ public static async Task GenerateJSONAccommodationsForBooklist(QueryFactory quer //} } - public static async Task GenerateJSONTaglist(QueryFactory queryFactory, string jsondir, string jsonName) + public static async Task GenerateJSONTaglist( + QueryFactory queryFactory, + string jsondir, + string jsonName + ) { - var serializer = new JsonSerializer(); - - var query = - queryFactory.Query() - .SelectRaw("data") - .From("tags"); + var serializer = new JsonSerializer(); + + var query = queryFactory.Query().SelectRaw("data").From("tags"); var data = await query.GetAllAsObject(); @@ -72,7 +96,7 @@ public static async Task GenerateJSONTaglist(QueryFactory queryFactory, string j using (var writer = File.CreateText(fileName)) { serializer.Serialize(writer, data); - } + } } } diff --git a/Helper/JsonPathException.cs b/Helper/JsonPathException.cs index 8ebf2318c..39a3d7000 100644 --- a/Helper/JsonPathException.cs +++ b/Helper/JsonPathException.cs @@ -8,22 +8,20 @@ public class JsonPathException : Exception { public string Path { get; } = ""; - public JsonPathException() - { - } + public JsonPathException() { } public JsonPathException(string? message, string path) : base(message) { Path = path; } - public JsonPathException(string? message, string path, Exception? innerException) : base(message, innerException) + public JsonPathException(string? message, string path, Exception? innerException) + : base(message, innerException) { Path = path; } - protected JsonPathException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } + protected JsonPathException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } -} \ No newline at end of file +} diff --git a/Helper/JsonTransformer/JsonTransformer.cs b/Helper/JsonTransformer/JsonTransformer.cs index a62fbe677..b119e9229 100644 --- a/Helper/JsonTransformer/JsonTransformer.cs +++ b/Helper/JsonTransformer/JsonTransformer.cs @@ -10,22 +10,33 @@ namespace Helper { public static class JsonTransformer - { + { public static JsonRaw? TransformRawData( - this JsonRaw raw, string? language, string[] fields, bool checkCC0, - bool filterClosedData, bool filteroutNullValues, Func urlGenerator, IEnumerable fieldstohide) + this JsonRaw raw, + string? language, + string[] fields, + bool checkCC0, + bool filterClosedData, + bool filteroutNullValues, + Func urlGenerator, + IEnumerable fieldstohide + ) { JToken? token = JToken.Parse(raw.Value); //Filter out not desired langugae fields - if (language != null) token = JsonTransformerMethods.FilterByLanguage(token, language); + if (language != null) + token = JsonTransformerMethods.FilterByLanguage(token, language); //Filter by given fields - if (fields != null && fields.Length > 0) token = JsonTransformerMethods.FilterByFields(token, fields, language); + if (fields != null && fields.Length > 0) + token = JsonTransformerMethods.FilterByFields(token, fields, language); // Filter out all data where the LicenseInfo does not contain `CC0` - if (checkCC0) token = JsonTransformerMethods.FilterImagesByCC0License(token); + if (checkCC0) + token = JsonTransformerMethods.FilterImagesByCC0License(token); // Filter out all data where the LicenseInfo contains `hgv` as source. - if (filterClosedData) token = JsonTransformerMethods.FilterAccoRoomInfoByHGVSource(token); + if (filterClosedData) + token = JsonTransformerMethods.FilterAccoRoomInfoByHGVSource(token); - //Filter out all Data + //Filter out all Data //var rolefilter = FilterOutPropertiesByRole(userroles); //if (rolefilter.Count > 0) // if (checkCC0) token = JsonTransformerMethods.FilterOutProperties(token, rolefilter); @@ -33,38 +44,49 @@ public static class JsonTransformer if (fieldstohide.Count() > 0) token = JsonTransformerMethods.FilterOutProperties(token, fieldstohide.ToList()); - if (filterClosedData) token = token.FilterClosedData(); - + if (filterClosedData) + token = token.FilterClosedData(); + //Ensure Self Link is the right url token = token.TransformSelfLink(urlGenerator); - if(filteroutNullValues) token = JsonTransformerMethods.FilterOutNullProperties(token); + if (filteroutNullValues) + token = JsonTransformerMethods.FilterOutNullProperties(token); //Filter out meta info //token = token.FilterMetaInformations(); - return (token == null) ? - null : - new JsonRaw(token.ToString(Formatting.Indented)); - } + return (token == null) ? null : new JsonRaw(token.ToString(Formatting.Indented)); + } public static List FilterOutPropertiesByRole(IEnumerable userroles) { if (userroles.Contains("IDM")) - return new List() { }; + return new List() { }; - return new List() { "TVMember", "Beds", "Units", "RepresentationRestriction", "TrustYouID", "TrustYouScore", "TrustYouState", "TrustYouResults", "TrustYouActive" }; + return new List() + { + "TVMember", + "Beds", + "Units", + "RepresentationRestriction", + "TrustYouID", + "TrustYouScore", + "TrustYouState", + "TrustYouResults", + "TrustYouActive" + }; } - } + } - sealed class DistinctComparer - : IEqualityComparer<(string name, string path)> + sealed class DistinctComparer : IEqualityComparer<(string name, string path)> { - public bool Equals([AllowNull] (string name, string path) x, [AllowNull] (string name, string path) y) => - x.name == y.name; + public bool Equals( + [AllowNull] (string name, string path) x, + [AllowNull] (string name, string path) y + ) => x.name == y.name; public int GetHashCode([DisallowNull] (string name, string path) obj) => obj.name.GetHashCode(); } - } diff --git a/Helper/JsonTransformer/JsonTransformerMethods.cs b/Helper/JsonTransformer/JsonTransformerMethods.cs index 218d4e5aa..b45e3fe66 100644 --- a/Helper/JsonTransformer/JsonTransformerMethods.cs +++ b/Helper/JsonTransformer/JsonTransformerMethods.cs @@ -10,12 +10,19 @@ namespace Helper { public static class JsonTransformerMethods { - private static readonly HashSet Languages = new HashSet { - "de", "it", "en", "cs", "fr", "nl", "pl", "ru" + private static readonly HashSet Languages = new HashSet + { + "de", + "it", + "en", + "cs", + "fr", + "nl", + "pl", + "ru" }; - private static bool IsLanguageKey(string key) => - Languages.Contains(key); + private static bool IsLanguageKey(string key) => Languages.Contains(key); //Cutting out all not requested Language Dictionary Objects public static JToken? FilterByLanguage(this JToken? token, string language) @@ -25,18 +32,19 @@ private static bool IsLanguageKey(string key) => JToken Walk(JToken token) => token switch { - JObject obj => - new JObject( + JObject obj + => new JObject( obj.Properties() - .Where(x => - // Check if property name is a language identifier - // and if it is the same as the provided language argument - !(IsLanguageKey(x.Name) && x.Name != language)) - .Select(Walk)), - JProperty prop => - new JProperty(prop.Name, Walk(prop.Value)), - JArray arr => - new JArray(arr.Select(Walk)), + .Where( + x => + // Check if property name is a language identifier + // and if it is the same as the provided language argument + !(IsLanguageKey(x.Name) && x.Name != language) + ) + .Select(Walk) + ), + JProperty prop => new JProperty(prop.Name, Walk(prop.Value)), + JArray arr => new JArray(arr.Select(Walk)), _ => token }; return Walk(token); @@ -53,10 +61,19 @@ JToken Walk(JToken token) => var licenseProp = obj.Property("License"); // If License property exists and it's value isn't CC0 return null, // which filters away the whole object - return licenseProp != null && (licenseProp.Value == null || (!licenseProp.Value.Equals(new JValue("CC0")) && !licenseProp.Path.StartsWith("LicenseInfo"))) ? - null : - new JObject(obj.Properties().Select(x => Walk(x)).Where(x => x != null)); - }; + return + licenseProp != null + && ( + licenseProp.Value == null + || ( + !licenseProp.Value.Equals(new JValue("CC0")) + && !licenseProp.Path.StartsWith("LicenseInfo") + ) + ) + ? null + : new JObject(obj.Properties().Select(x => Walk(x)).Where(x => x != null)); + } + ; static JProperty? TransformProp(JProperty prop) { var value = Walk(prop.Value); @@ -65,15 +82,14 @@ JToken Walk(JToken token) => static JToken? Walk(JToken token) => token switch { - JObject obj => - TransformObj(obj), - JProperty prop => - TransformProp(prop), - JArray arr => - new JArray( + JObject obj => TransformObj(obj), + JProperty prop => TransformProp(prop), + JArray arr + => new JArray( arr.Select(x => Walk(x)) - // Filter away empty content - .Where(x => x != null)), + // Filter away empty content + .Where(x => x != null) + ), _ => token }; return Walk(token); @@ -90,24 +106,37 @@ JToken Walk(JToken token) => var accoRoomInfo = obj.Property("AccoRoomInfo"); if (accoRoomInfo is not null && accoRoomInfo.Value is JArray) { - var props = accoRoomInfo.Value.ToArray().Select(prop => - { - // The prop needs to be an object - if (prop is JObject roomInfo) + var props = accoRoomInfo.Value + .ToArray() + .Select(prop => { - // Get the Source property of an object - var sourceProp = roomInfo.Property("Source"); - // If Source property exists and it's value is hgv return null, - // which filters away the whole object - return sourceProp is not null && (sourceProp.Value is null || sourceProp.Value.Equals(new JValue("hgv"))) ? - null : - new JObject(roomInfo.Properties().Select(x => Walk(x)).Where(x => x != null)); - } - else - { - return prop; - } - }).Where(prop => prop is not null); + // The prop needs to be an object + if (prop is JObject roomInfo) + { + // Get the Source property of an object + var sourceProp = roomInfo.Property("Source"); + // If Source property exists and it's value is hgv return null, + // which filters away the whole object + return + sourceProp is not null + && ( + sourceProp.Value is null + || sourceProp.Value.Equals(new JValue("hgv")) + ) + ? null + : new JObject( + roomInfo + .Properties() + .Select(x => Walk(x)) + .Where(x => x != null) + ); + } + else + { + return prop; + } + }) + .Where(prop => prop is not null); obj.TryAddOrUpdate("AccoRoomInfo", new JArray(props)); return obj; } @@ -115,7 +144,8 @@ JToken Walk(JToken token) => { return obj; } - }; + } + ; static JProperty? TransformProp(JProperty prop) { var value = Walk(prop.Value); @@ -124,15 +154,14 @@ JToken Walk(JToken token) => static JToken? Walk(JToken token) => token switch { - JObject obj => - TransformObj(obj), - JProperty prop => - TransformProp(prop), - JArray arr => - new JArray( + JObject obj => TransformObj(obj), + JProperty prop => TransformProp(prop), + JArray arr + => new JArray( arr.Select(x => Walk(x)) - // Filter away empty content - .Where(x => x != null)), + // Filter away empty content + .Where(x => x != null) + ), _ => token }; return Walk(token); @@ -143,18 +172,18 @@ JToken Walk(JToken token) => { if (token == null) return null; - + static JObject TransformByPropList(JObject obj, List propstocut) { // Get the TVMember property of an object which has to be an property //var accoTVMember = obj.Property("TVMember"); - //if (accoTVMember is not null && accoTVMember is JProperty) + //if (accoTVMember is not null && accoTVMember is JProperty) // //Cut out this property - // return new JObject(obj.Properties().Where(x => !propstocut.Contains(x.Name))); + // return new JObject(obj.Properties().Where(x => !propstocut.Contains(x.Name))); //else - // return obj; + // return obj; return new JObject(obj.Properties().Where(x => !propstocut.Contains(x.Name))); - } + } static JToken Walk(JToken token, List propstocut) => token switch { @@ -177,7 +206,7 @@ static JObject RemoveNullProps(JObject obj) obj.Properties() .Where(x => !x.Value.IsNullOrEmpty(true, true)) .Select(x => new JProperty(x.Name, FilterOutNullProperties(x.Value))) - ); + ); } static JToken Walk(JToken token) => token switch @@ -228,7 +257,8 @@ static JToken Walk(JToken token) => } } return new JObject(obj.Properties().Select(x => Walk(x))); - }; + } + ; static JProperty? TransformProp(JProperty prop) { var value = Walk(prop.Value); @@ -237,59 +267,70 @@ static JToken Walk(JToken token) => static JToken? Walk(JToken token) => token switch { - JObject obj => - TransformObj(obj), - JProperty prop => - TransformProp(prop), - JArray arr => - new JArray( + JObject obj => TransformObj(obj), + JProperty prop => TransformProp(prop), + JArray arr + => new JArray( arr.Select(x => Walk(x)) - // Filter away empty content - .Where(x => x != null)), + // Filter away empty content + .Where(x => x != null) + ), _ => token }; return Walk(token); } //Cuts out all fields that are not requested only Id is active by default - public static JToken? FilterByFields(this JToken? token, string[] fieldsFromQueryString, string? languageParam) + public static JToken? FilterByFields( + this JToken? token, + string[] fieldsFromQueryString, + string? languageParam + ) { if (token == null) return null; var language = languageParam ?? "en"; - var fields = new List<(string name, string path)> - { - ("Id", "Id") - }; + var fields = new List<(string name, string path)> { ("Id", "Id") }; fields.AddRange(fieldsFromQueryString.Select(field => (field, field))); if (token is JObject obj) { return new JObject( - fields.Distinct(new DistinctComparer()).Select(x => - { - try + fields + .Distinct(new DistinctComparer()) + .Select(x => { try { - return new JProperty(x.name, token.SelectToken(x.path, errorWhenNoMatch: true)); + try + { + return new JProperty( + x.name, + token.SelectToken(x.path, errorWhenNoMatch: true) + ); + } + catch (JsonException) + { + return new JProperty( + x.name, + token.SelectTokens(x.path, errorWhenNoMatch: true) + ); + } } catch (JsonException) { - return new JProperty(x.name, token.SelectTokens(x.path, errorWhenNoMatch: true)); + return new JProperty(x.name, (object?)null); } - } - catch (JsonException) - { - return new JProperty(x.name, (object?)null); - } - }) + }) ); } return token; } //Transforms URL of the self link to the right domain - public static JToken? TransformSelfLink(this JToken? token, Func urlGenerator) + public static JToken? TransformSelfLink( + this JToken? token, + Func urlGenerator + ) { if (token == null) return null; @@ -320,42 +361,49 @@ static JToken Walk(JToken token) => static JToken? Walk(JToken token, Func urlGenerator) => token switch { - JObject obj => - TransformObj(obj, urlGenerator), - JProperty prop => - TransformProp(prop, urlGenerator), - JArray arr => - new JArray( + JObject obj => TransformObj(obj, urlGenerator), + JProperty prop => TransformProp(prop, urlGenerator), + JArray arr + => new JArray( arr.Select(x => Walk(x, urlGenerator)) - // Filter away empty content - .Where(x => x != null)), + // Filter away empty content + .Where(x => x != null) + ), _ => token }; return Walk(token, urlGenerator); } - } public static class JsonExtensions { - public static bool IsNullOrEmpty(this JToken token, bool filteremptyarrays, bool filteremptyobjects) + public static bool IsNullOrEmpty( + this JToken token, + bool filteremptyarrays, + bool filteremptyobjects + ) { bool result = false; - result = (token == null) || - (token.Type == JTokenType.String && token.ToString() == String.Empty) || - (token.Type == JTokenType.Null); + result = + (token == null) + || (token.Type == JTokenType.String && token.ToString() == String.Empty) + || (token.Type == JTokenType.Null); if (filteremptyarrays) - result = result || (token == null) || - (token.Type == JTokenType.Array && !token.HasValues); //filter out empty array + result = + result + || (token == null) + || (token.Type == JTokenType.Array && !token.HasValues); //filter out empty array if (filteremptyobjects) - result = result || (token == null) || - (token.Type == JTokenType.Object && !token.HasValues); //filter out empty object - - //(token.Type == JTokenType.Undefined) || //not sure if needed - + result = + result + || (token == null) + || (token.Type == JTokenType.Object && !token.HasValues); //filter out empty object + + //(token.Type == JTokenType.Undefined) || //not sure if needed + return result; } } diff --git a/Helper/Location/GetLocationInfo.cs b/Helper/Location/GetLocationInfo.cs index 659d75404..d56412b64 100644 --- a/Helper/Location/GetLocationInfo.cs +++ b/Helper/Location/GetLocationInfo.cs @@ -10,36 +10,47 @@ namespace Helper { public class GetLocationInfo - { - public static async Task> GetNearestDistrict(QueryFactory QueryFactory, PGGeoSearchResult geosearchresult, int limitto) + { + public static async Task> GetNearestDistrict( + QueryFactory QueryFactory, + PGGeoSearchResult geosearchresult, + int limitto + ) { - var districtquery = QueryFactory.Query("districts") - .Select("data") - .ApplyOrdering_GeneratedColumns(geosearchresult, null) - .Limit(limitto); - - var data = - await districtquery - .GetAllAsObject(); + var districtquery = QueryFactory + .Query("districts") + .Select("data") + .ApplyOrdering_GeneratedColumns(geosearchresult, null) + .Limit(limitto); + + var data = await districtquery.GetAllAsObject(); return data; } - public static async Task GetNearestDistrictbyGPS(QueryFactory QueryFactory, double latitude, double longitude, int radius = 30000) + public static async Task GetNearestDistrictbyGPS( + QueryFactory QueryFactory, + double latitude, + double longitude, + int radius = 30000 + ) { string wheregeo = PostgresSQLHelper.GetGeoWhereSimple(latitude, longitude, radius); string orderbygeo = PostgresSQLHelper.GetGeoOrderBySimple(latitude, longitude); - var query = - QueryFactory.Query("districts") - .Select("data") - .WhereRaw(wheregeo) - .OrderByRaw(orderbygeo); + var query = QueryFactory + .Query("districts") + .Select("data") + .WhereRaw(wheregeo) + .OrderByRaw(orderbygeo); return await query.GetFirstOrDefaultAsObject(); } - public static async Task GetTheLocationInfoDistrict(QueryFactory QueryFactory, string? districtid) + public static async Task GetTheLocationInfoDistrict( + QueryFactory QueryFactory, + string? districtid + ) { if (districtid == null) return new LocationInfoLinked(); @@ -47,145 +58,232 @@ public static async Task GetTheLocationInfoDistrict(QueryFac LocationInfoLinked mylocinfo = new LocationInfoLinked(); //Wenn nicht District nicht definiert ist oder Livinallongo/Arabba/Gebiet Pieve - Digonera - Pordoijoch - nicht südtirol ;) - if (districtid != "79CBD63051C911D18F1400A02427D15E" && districtid != "53DF587C2BF74853B9DF3429089587E3" && districtid != "43C0E6789C4046718B70DAA56CF4332C" && districtid != "52B456D784854FB5A77F87C0CF4AFADF" && districtid != "C17DC9768C1A4DC5BA1592ED5C1D591B" && districtid != "79CBAAA0513331D18F1400A02427D15E") + if ( + districtid != "79CBD63051C911D18F1400A02427D15E" + && districtid != "53DF587C2BF74853B9DF3429089587E3" + && districtid != "43C0E6789C4046718B70DAA56CF4332C" + && districtid != "52B456D784854FB5A77F87C0CF4AFADF" + && districtid != "C17DC9768C1A4DC5BA1592ED5C1D591B" + && districtid != "79CBAAA0513331D18F1400A02427D15E" + ) { - var districtquery = QueryFactory.Query("districts") - .Select("data") - .Where("id", districtid.ToUpper()); + var districtquery = QueryFactory + .Query("districts") + .Select("data") + .Where("id", districtid.ToUpper()); var district = await districtquery.GetFirstOrDefaultAsObject(); - var districtnames = (from x in district?.Detail - select x).ToDictionary(x => x.Key, x => x.Value.Title); + var districtnames = (from x in district?.Detail select x).ToDictionary( + x => x.Key, + x => x.Value.Title + ); - var munquery = QueryFactory.Query("municipalities") - .Select("data") - .Where("id", district?.MunicipalityId?.ToUpper()); + var munquery = QueryFactory + .Query("municipalities") + .Select("data") + .Where("id", district?.MunicipalityId?.ToUpper()); var municipality = await munquery.GetFirstOrDefaultAsObject(); - - var municipalitynames = (from x in municipality?.Detail - select x).ToDictionary(x => x.Key, x => x.Value.Title); - var tvquery = QueryFactory.Query("tvs") - .Select("data") - .Where("id", district?.TourismvereinId?.ToUpper()); + var municipalitynames = (from x in municipality?.Detail select x).ToDictionary( + x => x.Key, + x => x.Value.Title + ); + + var tvquery = QueryFactory + .Query("tvs") + .Select("data") + .Where("id", district?.TourismvereinId?.ToUpper()); var tourismverein = await tvquery.GetFirstOrDefaultAsObject(); - - var tourismvereinnames = (from x in tourismverein?.Detail - select x).ToDictionary(x => x.Key, x => x.Value.Title); - var regquery = QueryFactory.Query("regions") - .Select("data") - .Where("id", district?.RegionId?.ToUpper()); + var tourismvereinnames = (from x in tourismverein?.Detail select x).ToDictionary( + x => x.Key, + x => x.Value.Title + ); + + var regquery = QueryFactory + .Query("regions") + .Select("data") + .Where("id", district?.RegionId?.ToUpper()); var region = await regquery.GetFirstOrDefaultAsObject(); - - var regionnames = (from x in region?.Detail - select x).ToDictionary(x => x.Key, x => x.Value.Title); - - mylocinfo.DistrictInfo = new DistrictInfoLinked() { Id = district?.Id, Name = districtnames }; - mylocinfo.MunicipalityInfo = new MunicipalityInfoLinked() { Id = municipality?.Id, Name = municipalitynames }; - mylocinfo.TvInfo = new TvInfoLinked() { Id = tourismverein?.Id, Name = tourismvereinnames }; - mylocinfo.RegionInfo = new RegionInfoLinked() { Id = region?.Id, Name = regionnames }; + + var regionnames = (from x in region?.Detail select x).ToDictionary( + x => x.Key, + x => x.Value.Title + ); + + mylocinfo.DistrictInfo = new DistrictInfoLinked() + { + Id = district?.Id, + Name = districtnames + }; + mylocinfo.MunicipalityInfo = new MunicipalityInfoLinked() + { + Id = municipality?.Id, + Name = municipalitynames + }; + mylocinfo.TvInfo = new TvInfoLinked() + { + Id = tourismverein?.Id, + Name = tourismvereinnames + }; + mylocinfo.RegionInfo = new RegionInfoLinked() + { + Id = region?.Id, + Name = regionnames + }; } return mylocinfo; } - public static async Task GetTheLocationInfoDistrict_Siag(QueryFactory QueryFactory, string? districtid_siag) + public static async Task GetTheLocationInfoDistrict_Siag( + QueryFactory QueryFactory, + string? districtid_siag + ) { if (districtid_siag == null) return new LocationInfoLinked(); LocationInfoLinked mylocinfo = new LocationInfoLinked(); - - var districtquery = QueryFactory.Query("districts") - .Select("data") - .WhereRaw("data->>'SiagId' = $$", districtid_siag); - var district = await districtquery.GetFirstOrDefaultAsObject(); + var districtquery = QueryFactory + .Query("districts") + .Select("data") + .WhereRaw("data->>'SiagId' = $$", districtid_siag); + var district = await districtquery.GetFirstOrDefaultAsObject(); if (district != null) { - - var districtnames = (from x in district?.Detail - select x).ToDictionary(x => x.Key, x => x.Value.Title); - - var munquery = QueryFactory.Query("municipalities") - .Select("data") - .Where("id", district?.MunicipalityId?.ToUpper()); + var districtnames = (from x in district?.Detail select x).ToDictionary( + x => x.Key, + x => x.Value.Title + ); + + var munquery = QueryFactory + .Query("municipalities") + .Select("data") + .Where("id", district?.MunicipalityId?.ToUpper()); var municipality = await munquery.GetFirstOrDefaultAsObject(); - var municipalitynames = (from x in municipality?.Detail - select x).ToDictionary(x => x.Key, x => x.Value.Title); + var municipalitynames = (from x in municipality?.Detail select x).ToDictionary( + x => x.Key, + x => x.Value.Title + ); - var tvquery = QueryFactory.Query("tvs") - .Select("data") - .Where("id", district?.TourismvereinId?.ToUpper()); + var tvquery = QueryFactory + .Query("tvs") + .Select("data") + .Where("id", district?.TourismvereinId?.ToUpper()); var tourismverein = await tvquery.GetFirstOrDefaultAsObject(); - var tourismvereinnames = (from x in tourismverein?.Detail - select x).ToDictionary(x => x.Key, x => x.Value.Title); + var tourismvereinnames = (from x in tourismverein?.Detail select x).ToDictionary( + x => x.Key, + x => x.Value.Title + ); - var regquery = QueryFactory.Query("regions") - .Select("data") - .Where("id", district?.RegionId?.ToUpper()); + var regquery = QueryFactory + .Query("regions") + .Select("data") + .Where("id", district?.RegionId?.ToUpper()); var region = await regquery.GetFirstOrDefaultAsObject(); - var regionnames = (from x in region?.Detail - select x).ToDictionary(x => x.Key, x => x.Value.Title); - - mylocinfo.DistrictInfo = new DistrictInfoLinked() { Id = district?.Id, Name = districtnames }; - mylocinfo.MunicipalityInfo = new MunicipalityInfoLinked() { Id = municipality?.Id, Name = municipalitynames }; - mylocinfo.TvInfo = new TvInfoLinked() { Id = tourismverein?.Id, Name = tourismvereinnames }; - mylocinfo.RegionInfo = new RegionInfoLinked() { Id = region?.Id, Name = regionnames }; + var regionnames = (from x in region?.Detail select x).ToDictionary( + x => x.Key, + x => x.Value.Title + ); + + mylocinfo.DistrictInfo = new DistrictInfoLinked() + { + Id = district?.Id, + Name = districtnames + }; + mylocinfo.MunicipalityInfo = new MunicipalityInfoLinked() + { + Id = municipality?.Id, + Name = municipalitynames + }; + mylocinfo.TvInfo = new TvInfoLinked() + { + Id = tourismverein?.Id, + Name = tourismvereinnames + }; + mylocinfo.RegionInfo = new RegionInfoLinked() + { + Id = region?.Id, + Name = regionnames + }; } return mylocinfo; } - public static async Task GetTheLocationInfoMunicipality_Siag(QueryFactory QueryFactory, string? municipalityid_siag) + public static async Task GetTheLocationInfoMunicipality_Siag( + QueryFactory QueryFactory, + string? municipalityid_siag + ) { if (municipalityid_siag == null) return new LocationInfoLinked(); LocationInfoLinked mylocinfo = new LocationInfoLinked(); - var municipalityquery = QueryFactory.Query("municipalities") - .Select("data") - .WhereRaw("data->>'SiagId' = $$", municipalityid_siag); + var municipalityquery = QueryFactory + .Query("municipalities") + .Select("data") + .WhereRaw("data->>'SiagId' = $$", municipalityid_siag); var municipality = await municipalityquery.GetFirstOrDefaultAsObject(); if (municipality != null) - { - var municipalitynames = (from x in municipality?.Detail - select x).ToDictionary(x => x.Key, x => x.Value.Title); - - var tvquery = QueryFactory.Query("tvs") - .Select("data") - .Where("id", municipality?.TourismvereinId?.ToUpper()); + { + var municipalitynames = (from x in municipality?.Detail select x).ToDictionary( + x => x.Key, + x => x.Value.Title + ); + + var tvquery = QueryFactory + .Query("tvs") + .Select("data") + .Where("id", municipality?.TourismvereinId?.ToUpper()); var tourismverein = await tvquery.GetFirstOrDefaultAsObject(); - var tourismvereinnames = (from x in tourismverein?.Detail - select x).ToDictionary(x => x.Key, x => x.Value.Title); + var tourismvereinnames = (from x in tourismverein?.Detail select x).ToDictionary( + x => x.Key, + x => x.Value.Title + ); - var regquery = QueryFactory.Query("regions") - .Select("data") - .Where("id", municipality?.RegionId?.ToUpper()); + var regquery = QueryFactory + .Query("regions") + .Select("data") + .Where("id", municipality?.RegionId?.ToUpper()); var region = await regquery.GetFirstOrDefaultAsObject(); - var regionnames = (from x in region?.Detail - select x).ToDictionary(x => x.Key, x => x.Value.Title); + var regionnames = (from x in region?.Detail select x).ToDictionary( + x => x.Key, + x => x.Value.Title + ); //mylocinfo.DistrictInfo = new DistrictInfoLinked() { Id = district?.Id, Name = districtnames }; - mylocinfo.MunicipalityInfo = new MunicipalityInfoLinked() { Id = municipality?.Id, Name = municipalitynames }; - mylocinfo.TvInfo = new TvInfoLinked() { Id = tourismverein?.Id, Name = tourismvereinnames }; - mylocinfo.RegionInfo = new RegionInfoLinked() { Id = region?.Id, Name = regionnames }; + mylocinfo.MunicipalityInfo = new MunicipalityInfoLinked() + { + Id = municipality?.Id, + Name = municipalitynames + }; + mylocinfo.TvInfo = new TvInfoLinked() + { + Id = tourismverein?.Id, + Name = tourismvereinnames + }; + mylocinfo.RegionInfo = new RegionInfoLinked() + { + Id = region?.Id, + Name = regionnames + }; } return mylocinfo; } - ////Get Complete Locationinfo for Municipality ID //public static LocationInfo GetTheLocationInfoMunicipality(NpgsqlConnection conn, string municipalityid) //{ diff --git a/Helper/Location/LocHelper.cs b/Helper/Location/LocHelper.cs index 854f8eaf3..f2af0844a 100644 --- a/Helper/Location/LocHelper.cs +++ b/Helper/Location/LocHelper.cs @@ -47,7 +47,7 @@ public class CustomHelperclass } public class LocHelperclassDynamic : LocHelperclass - { - public new dynamic? name { get; set; } + { + public new dynamic? name { get; set; } } } diff --git a/Helper/Location/LocationListCreator.cs b/Helper/Location/LocationListCreator.cs index 773288028..7b19a8723 100644 --- a/Helper/Location/LocationListCreator.cs +++ b/Helper/Location/LocationListCreator.cs @@ -12,13 +12,18 @@ public static class LocationListCreator { #region Locfilter Helper - public static async Task> CreateActivityAreaListPGAsync(QueryFactory queryFactory, string areafilter, CancellationToken cancellationToken) + public static async Task> CreateActivityAreaListPGAsync( + QueryFactory queryFactory, + string areafilter, + CancellationToken cancellationToken + ) { //Klaub asanond - var splittedlocfilter = - areafilter - .Split(',', System.StringSplitOptions.RemoveEmptyEntries) - .Select(areafilter => (type: areafilter.Substring(0, 3), id: areafilter.Substring(3))); + var splittedlocfilter = areafilter + .Split(',', System.StringSplitOptions.RemoveEmptyEntries) + .Select( + areafilter => (type: areafilter.Substring(0, 3), id: areafilter.Substring(3)) + ); var thearealist = new List(); foreach ((string type, string id) in splittedlocfilter) @@ -27,22 +32,38 @@ public static async Task> CreateActivityAreaListPGAsync(Quer { case "reg": //Suche alle zugehörigen Areas für die Region - thearealist.AddRange(await queryFactory.Query().GetAreaforRegionPGAsync(id, cancellationToken)); + thearealist.AddRange( + await queryFactory + .Query() + .GetAreaforRegionPGAsync(id, cancellationToken) + ); break; case "tvs": //Suche alle zugehörigen TVs für die Region - thearealist.AddRange(await queryFactory.Query().GetAreaforTourismvereinPGAsync(id, cancellationToken)); + thearealist.AddRange( + await queryFactory + .Query() + .GetAreaforTourismvereinPGAsync(id, cancellationToken) + ); break; case "skr": //Suche alle zugehörigen TVs für die Region - thearealist.AddRange(await queryFactory.Query().GetAreaforSkiRegionPGAsync(id, cancellationToken)); + thearealist.AddRange( + await queryFactory + .Query() + .GetAreaforSkiRegionPGAsync(id, cancellationToken) + ); break; case "ska": //Suche alle zugehörigen TVs für die Region - thearealist.AddRange(await queryFactory.Query().GetAreaforSkiAreaPGAsync(id, cancellationToken)); + thearealist.AddRange( + await queryFactory + .Query() + .GetAreaforSkiAreaPGAsync(id, cancellationToken) + ); break; case "are": @@ -53,50 +74,63 @@ public static async Task> CreateActivityAreaListPGAsync(Quer return thearealist.Distinct(); } - public static async Task> GetAreaforRegionPGAsync(this Query query, string regionId, CancellationToken cancellationToken) + public static async Task> GetAreaforRegionPGAsync( + this Query query, + string regionId, + CancellationToken cancellationToken + ) { - return await - query.From("areas") - .SelectRaw("data#>>'\\{Id\\}'") - .WhereRaw("data#>>'\\{RegionId\\}' = $$", regionId.ToUpper()) - .GetAsync(); + return await query + .From("areas") + .SelectRaw("data#>>'\\{Id\\}'") + .WhereRaw("data#>>'\\{RegionId\\}' = $$", regionId.ToUpper()) + .GetAsync(); } - public static async Task> GetAreaforTourismvereinPGAsync(this Query query, string tvId, CancellationToken cancellationToken) + public static async Task> GetAreaforTourismvereinPGAsync( + this Query query, + string tvId, + CancellationToken cancellationToken + ) { - return await - query.From("areas") - .SelectRaw("data#>>'\\{Id\\}'") - .WhereRaw("data#>>'\\{TourismvereinId\\}' = $$", tvId.ToUpper()) - .GetAsync(); + return await query + .From("areas") + .SelectRaw("data#>>'\\{Id\\}'") + .WhereRaw("data#>>'\\{TourismvereinId\\}' = $$", tvId.ToUpper()) + .GetAsync(); } private static string[] FromJsonArray(string jsonArray) => Newtonsoft.Json.JsonConvert.DeserializeObject(jsonArray) ?? new string[] { }; - public static async Task> GetAreaforSkiRegionPGAsync(this Query query, string skiregId, CancellationToken cancellationToken) + public static async Task> GetAreaforSkiRegionPGAsync( + this Query query, + string skiregId, + CancellationToken cancellationToken + ) { - var areaIdsJson = await - query.From("skiareas") - .SelectRaw("data#>>'\\{AreaId\\}'") - .WhereRaw("data#>>'\\{SkiRegionId\\}' = $$", skiregId.ToUpper()) - .GetAsync(); - return areaIdsJson.SelectMany(FromJsonArray) - .Distinct(); + var areaIdsJson = await query + .From("skiareas") + .SelectRaw("data#>>'\\{AreaId\\}'") + .WhereRaw("data#>>'\\{SkiRegionId\\}' = $$", skiregId.ToUpper()) + .GetAsync(); + return areaIdsJson.SelectMany(FromJsonArray).Distinct(); } - public static async Task> GetAreaforSkiAreaPGAsync(this Query query, string skiareaId, CancellationToken cancellationToken) + public static async Task> GetAreaforSkiAreaPGAsync( + this Query query, + string skiareaId, + CancellationToken cancellationToken + ) { - var areaIdsJson = await - query.From("skiareas") - .SelectRaw("data#>>'\\{AreaId\\}'") - .WhereRaw("data#>>'\\{Id\\}' = $$", skiareaId.ToUpper()) - .GetAsync(); - return areaIdsJson.SelectMany(FromJsonArray) - .Distinct(); + var areaIdsJson = await query + .From("skiareas") + .SelectRaw("data#>>'\\{AreaId\\}'") + .WhereRaw("data#>>'\\{Id\\}' = $$", skiareaId.ToUpper()) + .GetAsync(); + return areaIdsJson.SelectMany(FromJsonArray).Distinct(); } - #endregion - + #endregion } } diff --git a/Helper/Models/HttpRequestLog.cs b/Helper/Models/HttpRequestLog.cs index c08f36988..93b95d200 100644 --- a/Helper/Models/HttpRequestLog.cs +++ b/Helper/Models/HttpRequestLog.cs @@ -14,6 +14,7 @@ public struct HttpRequestLog public string host { get; init; } public string path { get; init; } public string schema { get; init; } + //public Dictionary? querystring { get; set; } public string urlparams { get; init; } public string useragent { get; init; } diff --git a/Helper/Models/LogOutput.cs b/Helper/Models/LogOutput.cs index 04ff1fab3..6cd9e353d 100644 --- a/Helper/Models/LogOutput.cs +++ b/Helper/Models/LogOutput.cs @@ -12,5 +12,5 @@ public struct LogOutput public string type { get; init; } public string id { get; init; } public T output { get; init; } - } + } } diff --git a/Helper/Models/WriteLog.cs b/Helper/Models/WriteLog.cs index ab15fae8b..33ba0a490 100644 --- a/Helper/Models/WriteLog.cs +++ b/Helper/Models/WriteLog.cs @@ -19,10 +19,14 @@ public static class WriteLog /// HttpRequestLog / ImportLog public static void LogToConsole(string id, string type, string log, T output) { - LogOutput logoutput = new LogOutput() { id = id, type = type, log = log, output = output }; + LogOutput logoutput = new LogOutput() + { + id = id, + type = type, + log = log, + output = output + }; Console.WriteLine(JsonConvert.SerializeObject(logoutput)); } - - } } diff --git a/Helper/Postgres/PostGresSQLHelper.cs b/Helper/Postgres/PostGresSQLHelper.cs index 635aa2f6d..7bc889365 100644 --- a/Helper/Postgres/PostGresSQLHelper.cs +++ b/Helper/Postgres/PostGresSQLHelper.cs @@ -59,7 +59,11 @@ public static string GetGeoOrderByExtended(string latitude, string longitude) return $"earth_distance(ll_to_earth({latitude}, {longitude}),ll_to_earth((data->'GpsPoints'->'position'#>>'\\{{Latitude\\}}')::double precision, (data#>>'\\{{GpsPoints,position,Longitude\\}}')::double precision))"; } - public static string GetGeoWhereBoundingBoxes(string latitude, string longitude, string radius) + public static string GetGeoWhereBoundingBoxes( + string latitude, + string longitude, + string radius + ) { return $"earth_box(ll_to_earth({latitude}, {longitude}), {radius}) @> ll_to_earth((data#>>'\\{{Latitude\\}}')::double precision, (data#>>'\\{{Longitude\\}}')::double precision) and earth_distance(ll_to_earth({latitude}, {longitude}), ll_to_earth((data#>>'\\{{Latitude\\}}')::double precision, (data#>>'\\{{Longitude\\}}')::double precision)) < {radius}"; } @@ -69,19 +73,30 @@ public static string GetGeoWhereBoundingBoxes(double latitude, double longitude, return $"earth_box(ll_to_earth({latitude.ToString(CultureInfo.InvariantCulture)}, {longitude.ToString(CultureInfo.InvariantCulture)}), {radius.ToString()}) @> ll_to_earth((data#>>'\\{{Latitude\\}}')::double precision, (data#>>'\\{{Longitude\\}}')::double precision) and earth_distance(ll_to_earth({latitude.ToString(CultureInfo.InvariantCulture)}, {longitude.ToString(CultureInfo.InvariantCulture)}), ll_to_earth((data#>>'\\{{Latitude\\}}')::double precision, (data#>>'\\{{Longitude\\}}')::double precision)) < {radius.ToString()}"; } - public static string GetGeoWhereBoundingBoxesExtended(string latitude, string longitude, string radius) + public static string GetGeoWhereBoundingBoxesExtended( + string latitude, + string longitude, + string radius + ) { return $"earth_box(ll_to_earth({latitude}, {longitude}), {radius}) @> ll_to_earth((data#>>'\\{{GpsPoints,position,Latitude\\}}')::double precision, (data#>>'\\{{GpsPoints,position,Longitude\\}}')::double precision) and earth_distance(ll_to_earth({latitude}, {longitude}), ll_to_earth((data#>>'\\{{GpsPoints,position,Latitude\\}}')::double precision, (data#>>'\\{{GpsPoints,position,Longitude\\}}')::double precision)) < {radius}"; } - public static string GetGeoWhereBoundingBoxesExtended(double latitude, double longitude, int radius) + public static string GetGeoWhereBoundingBoxesExtended( + double latitude, + double longitude, + int radius + ) { return $"earth_box(ll_to_earth({latitude.ToString(CultureInfo.InvariantCulture)}, {longitude.ToString(CultureInfo.InvariantCulture)}), {radius.ToString()}) @> ll_to_earth((data#>>'\\{{GpsPoints,position,Latitude\\}}')::double precision, (data#>>'\\{{GpsPoints,position,Longitude\\}}')::double precision) and earth_distance(ll_to_earth({latitude.ToString(CultureInfo.InvariantCulture)}, {longitude.ToString(CultureInfo.InvariantCulture)}), ll_to_earth((data#>>'\\{{GpsPoints,position,Latitude\\}}')::double precision, (data#>>'\\{{GpsPoints,position,Longitude\\}}')::double precision)) < {radius.ToString()}"; } //For Accommodations public static void ApplyGeoSearchWhereOrderbySimple( - ref string where, ref string orderby, PGGeoSearchResult geosearchresult) + ref string where, + ref string orderby, + PGGeoSearchResult geosearchresult + ) { if (geosearchresult != null) { @@ -93,39 +108,43 @@ public static void ApplyGeoSearchWhereOrderbySimple( where += PostgresSQLHelper.GetGeoWhereSimple( geosearchresult.latitude, geosearchresult.longitude, - geosearchresult.radius); + geosearchresult.radius + ); orderby = PostgresSQLHelper.GetGeoOrderBySimple( geosearchresult.latitude, - geosearchresult.longitude); + geosearchresult.longitude + ); } } } public static Query GeoSearchFilterAndOrderby( this Query query, - PGGeoSearchResult? geosearchresult) + PGGeoSearchResult? geosearchresult + ) { if (geosearchresult == null || !geosearchresult.geosearch) return query; - return - query.WhereRaw( - GetGeoWhereExtended( - geosearchresult.latitude, - geosearchresult.longitude, - geosearchresult.radius) - ).OrderByRaw( - GetGeoOrderByExtended( - geosearchresult.latitude, - geosearchresult.longitude) - ); + return query + .WhereRaw( + GetGeoWhereExtended( + geosearchresult.latitude, + geosearchresult.longitude, + geosearchresult.radius + ) + ) + .OrderByRaw( + GetGeoOrderByExtended(geosearchresult.latitude, geosearchresult.longitude) + ); } //For Activities Pois and GBActivityPoi public static void ApplyGeoSearchWhereOrderby( ref string where, ref string orderby, - PGGeoSearchResult geosearchresult) + PGGeoSearchResult geosearchresult + ) { if (geosearchresult != null) { @@ -137,10 +156,12 @@ public static void ApplyGeoSearchWhereOrderby( where += PostgresSQLHelper.GetGeoWhereExtended( geosearchresult.latitude, geosearchresult.longitude, - geosearchresult.radius); + geosearchresult.radius + ); orderby = PostgresSQLHelper.GetGeoOrderByExtended( geosearchresult.latitude, - geosearchresult.longitude); + geosearchresult.longitude + ); } } } @@ -151,7 +172,11 @@ public static void ApplyGeoSearchWhereOrderby( //For Activities Pois and Smgpois - public static string GetGeoWhereSimple_GeneratedColumns(double latitude, double longitude, int radius) + public static string GetGeoWhereSimple_GeneratedColumns( + double latitude, + double longitude, + int radius + ) { return $"earth_distance(ll_to_earth({latitude.ToString(CultureInfo.InvariantCulture)}, {longitude.ToString(CultureInfo.InvariantCulture)}),ll_to_earth((gen_latitude)::double precision, (gen_longitude)::double precision)) < {radius.ToString()}"; } @@ -170,8 +195,12 @@ public static string GetGeoOrderBySimple_GeneratedColumns(double latitude, doubl //{ // return "earth_distance(ll_to_earth(" + latitude + ", " + longitude + "),ll_to_earth((data->>'Latitude')::double precision, (data->>'Longitude')::double precision))"; //} - - public static string GetGeoWhereExtended_GeneratedColumns(double latitude, double longitude, int radius) + + public static string GetGeoWhereExtended_GeneratedColumns( + double latitude, + double longitude, + int radius + ) { return $"earth_distance(ll_to_earth({latitude.ToString(CultureInfo.InvariantCulture)}, {longitude.ToString(CultureInfo.InvariantCulture)}),ll_to_earth((gen_latitude)::double precision, (gen_longitude)::double precision)) < {radius.ToString()}"; } @@ -181,39 +210,64 @@ public static string GetGeoWhereExtended_GeneratedColumns(double latitude, doubl // return "earth_distance(ll_to_earth(" + latitude + ", " + longitude + "),ll_to_earth((data->'GpsPoints'->'position'->>'Latitude')::double precision, (data->'GpsPoints'->'position'->>'Longitude')::double precision)) < " + radius; //} - public static string GetGeoOrderByExtended_GeneratedColumns(double latitude, double longitude) + public static string GetGeoOrderByExtended_GeneratedColumns( + double latitude, + double longitude + ) { return $"earth_distance(ll_to_earth({latitude.ToString(CultureInfo.InvariantCulture)}, {longitude.ToString(CultureInfo.InvariantCulture)}),ll_to_earth((gen_latitude)::double precision, (gen_longitude)::double precision))"; } - public static string GetGeoOrderByExtended_GeneratedColumns(string latitude, string longitude) + public static string GetGeoOrderByExtended_GeneratedColumns( + string latitude, + string longitude + ) { return $"earth_distance(ll_to_earth({latitude}, {longitude}),ll_to_earth((gen_latitude)::double precision, (gen_longitude)::double precision))"; } - public static string GetGeoWhereBoundingBoxes_GeneratedColumns(string latitude, string longitude, string radius) + public static string GetGeoWhereBoundingBoxes_GeneratedColumns( + string latitude, + string longitude, + string radius + ) { return $"earth_box(ll_to_earth({latitude}, {longitude}), {radius}) @> ll_to_earth((gen_latitude)::double precision, (gen_longitude)::double precision) and earth_distance(ll_to_earth({latitude}, {longitude}), ll_to_earth((gen_latitude)::double precision, (gen_longitude)::double precision)) < {radius}"; } - public static string GetGeoWhereBoundingBoxes_GeneratedColumns(double latitude, double longitude, int radius) + public static string GetGeoWhereBoundingBoxes_GeneratedColumns( + double latitude, + double longitude, + int radius + ) { return $"earth_box(ll_to_earth({latitude.ToString(CultureInfo.InvariantCulture)}, {longitude.ToString(CultureInfo.InvariantCulture)}), {radius.ToString()}) @> ll_to_earth((gen_latitude)::double precision, (gen_longitude)::double precision) and earth_distance(ll_to_earth({latitude.ToString(CultureInfo.InvariantCulture)}, {longitude.ToString(CultureInfo.InvariantCulture)}), ll_to_earth((gen_latitude)::double precision, (gen_longitude)::double precision)) < {radius.ToString()}"; } - public static string GetGeoWhereBoundingBoxesExtended_GeneratedColumns(string latitude, string longitude, string radius) + public static string GetGeoWhereBoundingBoxesExtended_GeneratedColumns( + string latitude, + string longitude, + string radius + ) { return $"earth_box(ll_to_earth({latitude}, {longitude}), {radius}) @> ll_to_earth((gen_latitude)::double precision, (gen_longitude)::double precision) and earth_distance(ll_to_earth({latitude}, {longitude}), ll_to_earth((gen_latitude)::double precision, (gen_longitude)::double precision)) < {radius}"; } - public static string GetGeoWhereBoundingBoxesExtended_GeneratedColumns(double latitude, double longitude, int radius) + public static string GetGeoWhereBoundingBoxesExtended_GeneratedColumns( + double latitude, + double longitude, + int radius + ) { return $"earth_box(ll_to_earth({latitude.ToString(CultureInfo.InvariantCulture)}, {longitude.ToString(CultureInfo.InvariantCulture)}), {radius.ToString()}) @> ll_to_earth((gen_latitude)::double precision, (gen_longitude)::double precision) and earth_distance(ll_to_earth({latitude.ToString(CultureInfo.InvariantCulture)}, {longitude.ToString(CultureInfo.InvariantCulture)}), ll_to_earth((gen_latitude)::double precision, (gen_longitude)::double precision)) < {radius.ToString()}"; } //For Accommodations public static void ApplyGeoSearchWhereOrderbySimple_GeneratedColumns( - ref string where, ref string orderby, PGGeoSearchResult geosearchresult) + ref string where, + ref string orderby, + PGGeoSearchResult geosearchresult + ) { if (geosearchresult != null) { @@ -225,39 +279,46 @@ public static void ApplyGeoSearchWhereOrderbySimple_GeneratedColumns( where += PostgresSQLHelper.GetGeoWhereSimple_GeneratedColumns( geosearchresult.latitude, geosearchresult.longitude, - geosearchresult.radius); + geosearchresult.radius + ); orderby = PostgresSQLHelper.GetGeoOrderBySimple_GeneratedColumns( geosearchresult.latitude, - geosearchresult.longitude); + geosearchresult.longitude + ); } } } public static Query GeoSearchFilterAndOrderby_GeneratedColumns( this Query query, - PGGeoSearchResult? geosearchresult) + PGGeoSearchResult? geosearchresult + ) { if (geosearchresult == null || !geosearchresult.geosearch) return query; - return - query.WhereRaw( - GetGeoWhereExtended_GeneratedColumns( - geosearchresult.latitude, - geosearchresult.longitude, - geosearchresult.radius) - ).OrderByRaw( - GetGeoOrderByExtended_GeneratedColumns( - geosearchresult.latitude, - geosearchresult.longitude) - ); + return query + .WhereRaw( + GetGeoWhereExtended_GeneratedColumns( + geosearchresult.latitude, + geosearchresult.longitude, + geosearchresult.radius + ) + ) + .OrderByRaw( + GetGeoOrderByExtended_GeneratedColumns( + geosearchresult.latitude, + geosearchresult.longitude + ) + ); } //For Activities Pois and GBActivityPoi public static void ApplyGeoSearchWhereOrderby_GeneratedColumns( ref string where, ref string orderby, - PGGeoSearchResult geosearchresult) + PGGeoSearchResult geosearchresult + ) { if (geosearchresult != null) { @@ -269,10 +330,12 @@ public static void ApplyGeoSearchWhereOrderby_GeneratedColumns( where += PostgresSQLHelper.GetGeoWhereExtended_GeneratedColumns( geosearchresult.latitude, geosearchresult.longitude, - geosearchresult.radius); + geosearchresult.radius + ); orderby = PostgresSQLHelper.GetGeoOrderByExtended_GeneratedColumns( geosearchresult.latitude, - geosearchresult.longitude); + geosearchresult.longitude + ); } } } @@ -289,7 +352,6 @@ public static uint PGPagingHelper(uint totalcount, uint pagesize) return totalpages; } - } public class PGParameters diff --git a/Helper/Postgres/PostGresSQLHelperException.cs b/Helper/Postgres/PostGresSQLHelperException.cs index b1c7ea511..1c04eb21b 100644 --- a/Helper/Postgres/PostGresSQLHelperException.cs +++ b/Helper/Postgres/PostGresSQLHelperException.cs @@ -5,24 +5,17 @@ namespace Helper { public class PostGresSQLHelperException : Exception { - public PostGresSQLHelperException() - { - } + public PostGresSQLHelperException() { } - public PostGresSQLHelperException(string message) : base(message) - { - } + public PostGresSQLHelperException(string message) : base(message) { } - public PostGresSQLHelperException(Exception innerException) : base("Error executing SQL query.", innerException) - { - } + public PostGresSQLHelperException(Exception innerException) + : base("Error executing SQL query.", innerException) { } - public PostGresSQLHelperException(string message, Exception innerException) : base(message, innerException) - { - } + public PostGresSQLHelperException(string message, Exception innerException) + : base(message, innerException) { } - protected PostGresSQLHelperException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } + protected PostGresSQLHelperException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } } diff --git a/Helper/Postgres/PostgresSQLOrderByBuilder.cs b/Helper/Postgres/PostgresSQLOrderByBuilder.cs index da32dadb0..224cb8530 100644 --- a/Helper/Postgres/PostgresSQLOrderByBuilder.cs +++ b/Helper/Postgres/PostgresSQLOrderByBuilder.cs @@ -13,7 +13,11 @@ public static class PostgresSQLOrderByBuilder /// /// /// - public static void BuildSeedOrderBy(ref string orderby, ref string? seed, string sortifseednull) + public static void BuildSeedOrderBy( + ref string orderby, + ref string? seed, + string sortifseednull + ) { //string? myseed = seed; @@ -51,54 +55,95 @@ public static Query OrderOnlyByRawSortIfNotNull(this Query query, string? rawsor return query; } - public static Query ApplyOrdering(this Query query, ref string? seed, PGGeoSearchResult geosearchresult, string? rawsort, string? overwritestandardorder = null) => + public static Query ApplyOrdering( + this Query query, + ref string? seed, + PGGeoSearchResult geosearchresult, + string? rawsort, + string? overwritestandardorder = null + ) => (geosearchresult, rawsort) switch { - (PGGeoSearchResult geosr, _) when geosr.geosearch => - query.GeoSearchFilterAndOrderby(geosr), - (_, string raw) => - query.OrderByRaw(RawQueryParser.Transformer.TransformSort(raw)), - _ => - query.OrderBySeed(ref seed, overwritestandardorder != null ? overwritestandardorder : "data#>>'\\{Shortname\\}' ASC") + (PGGeoSearchResult geosr, _) when geosr.geosearch + => query.GeoSearchFilterAndOrderby(geosr), + (_, string raw) => query.OrderByRaw(RawQueryParser.Transformer.TransformSort(raw)), + _ + => query.OrderBySeed( + ref seed, + overwritestandardorder != null + ? overwritestandardorder + : "data#>>'\\{Shortname\\}' ASC" + ) }; - public static Query ApplyOrdering_GeneratedColumns(this Query query, ref string? seed, PGGeoSearchResult geosearchresult, string? rawsort, string? overwritestandardorder = null) => + public static Query ApplyOrdering_GeneratedColumns( + this Query query, + ref string? seed, + PGGeoSearchResult geosearchresult, + string? rawsort, + string? overwritestandardorder = null + ) => (geosearchresult, rawsort) switch { - (PGGeoSearchResult geosr, _) when geosr.geosearch => - query.GeoSearchFilterAndOrderby_GeneratedColumns(geosr), - (_, string raw) => - query.OrderByRaw(RawQueryParser.Transformer.TransformSort(raw)), - _ => - query.OrderBySeed(ref seed, overwritestandardorder != null ? overwritestandardorder : "gen_shortname ASC") + (PGGeoSearchResult geosr, _) when geosr.geosearch + => query.GeoSearchFilterAndOrderby_GeneratedColumns(geosr), + (_, string raw) => query.OrderByRaw(RawQueryParser.Transformer.TransformSort(raw)), + _ + => query.OrderBySeed( + ref seed, + overwritestandardorder != null + ? overwritestandardorder + : "gen_shortname ASC" + ) }; - public static Query ApplyOrdering(this Query query, PGGeoSearchResult geosearchresult, string? rawsort, string? overwritestandardorder = null) => + public static Query ApplyOrdering( + this Query query, + PGGeoSearchResult geosearchresult, + string? rawsort, + string? overwritestandardorder = null + ) => (geosearchresult, rawsort) switch { - (PGGeoSearchResult geosr, _) when geosr.geosearch => - query.GeoSearchFilterAndOrderby(geosr), - (_, string raw) => - query.OrderByRaw(RawQueryParser.Transformer.TransformSort(raw)), - _ => - query.OrderByRaw(overwritestandardorder != null ? overwritestandardorder : "data#>>'\\{Shortname\\}' ASC") + (PGGeoSearchResult geosr, _) when geosr.geosearch + => query.GeoSearchFilterAndOrderby(geosr), + (_, string raw) => query.OrderByRaw(RawQueryParser.Transformer.TransformSort(raw)), + _ + => query.OrderByRaw( + overwritestandardorder != null + ? overwritestandardorder + : "data#>>'\\{Shortname\\}' ASC" + ) }; - public static Query ApplyOrdering_GeneratedColumns(this Query query, PGGeoSearchResult geosearchresult, string? rawsort, string? overwritestandardorder = null) => + public static Query ApplyOrdering_GeneratedColumns( + this Query query, + PGGeoSearchResult geosearchresult, + string? rawsort, + string? overwritestandardorder = null + ) => (geosearchresult, rawsort) switch { - (PGGeoSearchResult geosr, _) when geosr.geosearch => - query.GeoSearchFilterAndOrderby_GeneratedColumns(geosr), - (_, string raw) => - query.OrderByRaw(RawQueryParser.Transformer.TransformSort(raw)), - _ => - query.OrderByRaw(overwritestandardorder != null ? overwritestandardorder : "data#>>'\\{Shortname\\}' ASC") + (PGGeoSearchResult geosr, _) when geosr.geosearch + => query.GeoSearchFilterAndOrderby_GeneratedColumns(geosr), + (_, string raw) => query.OrderByRaw(RawQueryParser.Transformer.TransformSort(raw)), + _ + => query.OrderByRaw( + overwritestandardorder != null + ? overwritestandardorder + : "data#>>'\\{Shortname\\}' ASC" + ) }; public static Query ApplyRawFilter(this Query query, string? rawFilter) { - static string jsonSerializer(object value) => Newtonsoft.Json.JsonConvert.SerializeObject(value); - return rawFilter != null ? query.WhereRaw(RawQueryParser.Transformer.TransformFilter(jsonSerializer, rawFilter)) : query; + static string jsonSerializer(object value) => + Newtonsoft.Json.JsonConvert.SerializeObject(value); + return rawFilter != null + ? query.WhereRaw( + RawQueryParser.Transformer.TransformFilter(jsonSerializer, rawFilter) + ) + : query; } } } diff --git a/Helper/Postgres/PostgresSQLQueryExtensions.cs b/Helper/Postgres/PostgresSQLQueryExtensions.cs index 7a8bef74f..dbe78039e 100644 --- a/Helper/Postgres/PostgresSQLQueryExtensions.cs +++ b/Helper/Postgres/PostgresSQLQueryExtensions.cs @@ -17,133 +17,107 @@ public static class PostgresSQLQueryExtensions /// which can be used in the #>> operator.
/// E.g. Detail.de.Title => Detail,de,Title /// - public static string JsonPathToPostgresArray(string field) => - field.Replace('.', ','); + public static string JsonPathToPostgresArray(string field) => field.Replace('.', ','); public static Query WhereJsonb( this Query query, string jsonPath, string comparisonOperator, - string value) => - query.WhereRaw( - $"data#>>'\\{{{JsonPathToPostgresArray(jsonPath)}\\}}' {comparisonOperator} $$", - value - ); + string value + ) => + query.WhereRaw( + $"data#>>'\\{{{JsonPathToPostgresArray(jsonPath)}\\}}' {comparisonOperator} $$", + value + ); - public static Query WhereJsonb( - this Query query, - string jsonPath, - string value) => + public static Query WhereJsonb(this Query query, string jsonPath, string value) => query.WhereJsonb(jsonPath, "=", value); - public static Query WhereJsonb( - this Query query, - string jsonPath, - int value) => - query.WhereRaw( - $"data#>>'\\{{{JsonPathToPostgresArray(jsonPath)}\\}}' = $$", - value.ToString() - ); + public static Query WhereJsonb(this Query query, string jsonPath, int value) => + query.WhereRaw( + $"data#>>'\\{{{JsonPathToPostgresArray(jsonPath)}\\}}' = $$", + value.ToString() + ); - public static Query WhereJsonb( - this Query query, - string jsonPath, - bool value) => - query.WhereRaw( - $"data#>>'\\{{{JsonPathToPostgresArray(jsonPath)}\\}}' = $$", - value ? "true" : "false" - ); + public static Query WhereJsonb(this Query query, string jsonPath, bool value) => + query.WhereRaw( + $"data#>>'\\{{{JsonPathToPostgresArray(jsonPath)}\\}}' = $$", + value ? "true" : "false" + ); - public static Query OrWhereJsonb( - this Query query, - string jsonPath, - string value) => - query.OrWhereRaw( - $"data#>>'\\{{{JsonPathToPostgresArray(jsonPath)}\\}}' = $$", - value - ); + public static Query OrWhereJsonb(this Query query, string jsonPath, string value) => + query.OrWhereRaw($"data#>>'\\{{{JsonPathToPostgresArray(jsonPath)}\\}}' = $$", value); - public static Query OrWhereJsonb( - this Query query, - string jsonPath, - int value) => - query.OrWhereRaw( - $"data#>>'\\{{{JsonPathToPostgresArray(jsonPath)}\\}}' = $$", - value.ToString() - ); + public static Query OrWhereJsonb(this Query query, string jsonPath, int value) => + query.OrWhereRaw( + $"data#>>'\\{{{JsonPathToPostgresArray(jsonPath)}\\}}' = $$", + value.ToString() + ); - public static Query OrWhereJsonb( - this Query query, - string jsonPath, - bool value) => - query.OrWhereRaw( - $"data#>>'\\{{{JsonPathToPostgresArray(jsonPath)}\\}}' = $$", - value ? "true" : "false" - ); + public static Query OrWhereJsonb(this Query query, string jsonPath, bool value) => + query.OrWhereRaw( + $"data#>>'\\{{{JsonPathToPostgresArray(jsonPath)}\\}}' = $$", + value ? "true" : "false" + ); [Obsolete] public static Query WhereJsonb( this Query query, T value, - Func jsonObjectConstructor) => - query.WhereRaw( - "data @> jsonb($$)", - JsonConvert.SerializeObject( - jsonObjectConstructor(value) - ) - ); + Func jsonObjectConstructor + ) => + query.WhereRaw( + "data @> jsonb($$)", + JsonConvert.SerializeObject(jsonObjectConstructor(value)) + ); //[Obsolete] public static Query OrWhereJsonb( this Query query, T value, - Func jsonObjectConstructor) => - query.OrWhereRaw( - "data @> jsonb($$)", - JsonConvert.SerializeObject( - jsonObjectConstructor(value) - ) - ); + Func jsonObjectConstructor + ) => + query.OrWhereRaw( + "data @> jsonb($$)", + JsonConvert.SerializeObject(jsonObjectConstructor(value)) + ); //[Obsolete] //https://github.com/sqlkata/querybuilder/issues/356 public static Query WhereInJsonb( this Query query, IReadOnlyCollection list, - Func jsonObjectConstructor) => - query.Where(q => + Func jsonObjectConstructor + ) => + query.Where(q => + { + foreach (var item in list) { - foreach (var item in list) - { - q = q.OrWhereJsonb( - value: item, - jsonObjectConstructor - ); - } - return q; - }); + q = q.OrWhereJsonb(value: item, jsonObjectConstructor); + } + return q; + }); public static Query WhereInJsonb( this Query query, IReadOnlyCollection list, string jsonPath, - Func jsonObjectConstructor) => - query.Where(q => + Func jsonObjectConstructor + ) => + query.Where(q => + { + foreach (var item in list) { - foreach (var item in list) - { - q = q.OrWhereJsonb( - jsonPath, - jsonObjectConstructor(item) - ); - } - return q; - }); + q = q.OrWhereJsonb(jsonPath, jsonObjectConstructor(item)); + } + return q; + }); public static Query WhereInJsonb( this Query query, IReadOnlyCollection list, - string jsonPath) + string jsonPath + ) { if (list.Count == 0) { @@ -160,27 +134,23 @@ public static Query WhereInJsonb( [Obsolete] public static Query WhereAllInJsonb( - this Query query, - IReadOnlyCollection list, - Func jsonObjectConstructor) => - query.Where(q => - { - foreach (var item in list) - { - q = q.WhereJsonb( - value: item, - jsonObjectConstructor - ); - } - return q; - }); - - public static Query DistrictFilter(this Query query, IReadOnlyCollection districtlist) => - query.WhereInJsonb( - list: districtlist, - "DistrictId", - id => id.ToUpper() - ); + this Query query, + IReadOnlyCollection list, + Func jsonObjectConstructor + ) => + query.Where(q => + { + foreach (var item in list) + { + q = q.WhereJsonb(value: item, jsonObjectConstructor); + } + return q; + }); + + public static Query DistrictFilter( + this Query query, + IReadOnlyCollection districtlist + ) => query.WhereInJsonb(list: districtlist, "DistrictId", id => id.ToUpper()); public static Query IdUpperFilter(this Query query, IReadOnlyCollection idlist) => query.Where(q => @@ -203,122 +173,124 @@ public static Query IdLowerFilter(this Query query, IReadOnlyCollection }); public static Query IdIlikeFilter(this Query query, IReadOnlyCollection idlist) => - query.Where(q => - { - foreach (var id in idlist) - { - q = q.OrWhere("id", "ILIKE", id); - } - return q; - }); + query.Where(q => + { + foreach (var id in idlist) + { + q = q.OrWhere("id", "ILIKE", id); + } + return q; + }); public static Query LastChangedFilter(this Query query, string? updatefrom) => query.When( updatefrom != null, - query => query.WhereRaw( - "to_date(data#>>'\\{LastChange\\}', 'YYYY-MM-DD') > date($$)", - updatefrom - ) + query => + query.WhereRaw( + "to_date(data#>>'\\{LastChange\\}', 'YYYY-MM-DD') > date($$)", + updatefrom + ) ); - public static Query LocFilterDistrictFilter(this Query query, IReadOnlyCollection districtlist) => - query.WhereInJsonb( - list: districtlist, - jsonPath: "LocationInfo.DistrictInfo.Id" - ); + public static Query LocFilterDistrictFilter( + this Query query, + IReadOnlyCollection districtlist + ) => query.WhereInJsonb(list: districtlist, jsonPath: "LocationInfo.DistrictInfo.Id"); - public static Query LocFilterMunicipalityFilter(this Query query, IReadOnlyCollection municipalitylist) => + public static Query LocFilterMunicipalityFilter( + this Query query, + IReadOnlyCollection municipalitylist + ) => query.WhereInJsonb( list: municipalitylist, jsonPath: "LocationInfo.MunicipalityInfo.Id" ); - public static Query LocFilterTvsFilter(this Query query, IReadOnlyCollection tourismvereinlist) => - query.WhereInJsonb( - list: tourismvereinlist, - jsonPath: "LocationInfo.TvInfo.Id" - ); + public static Query LocFilterTvsFilter( + this Query query, + IReadOnlyCollection tourismvereinlist + ) => query.WhereInJsonb(list: tourismvereinlist, jsonPath: "LocationInfo.TvInfo.Id"); - public static Query LocFilterRegionFilter(this Query query, IReadOnlyCollection regionlist) => - query.WhereInJsonb( - list: regionlist, - jsonPath: "LocationInfo.RegionInfo.Id" - ); + public static Query LocFilterRegionFilter( + this Query query, + IReadOnlyCollection regionlist + ) => query.WhereInJsonb(list: regionlist, jsonPath: "LocationInfo.RegionInfo.Id"); public static Query AreaFilter(this Query query, IReadOnlyCollection arealist) => - query.WhereInJsonb( - arealist, - areaid => new { AreaId = new[] { areaid } } - ); + query.WhereInJsonb(arealist, areaid => new { AreaId = new[] { areaid } }); - public static Query AreaFilterMeasuringpoints(this Query query, IReadOnlyCollection arealist) => - query.WhereInJsonb( - arealist, - areaid => new { AreaIds = new[] { areaid } } - ); + public static Query AreaFilterMeasuringpoints( + this Query query, + IReadOnlyCollection arealist + ) => query.WhereInJsonb(arealist, areaid => new { AreaIds = new[] { areaid } }); public static Query HighlightFilter(this Query query, bool? highlight) => query.When( highlight != null, - query => query.WhereJsonb( - "Highlight", - highlight ?? false - ) + query => query.WhereJsonb("Highlight", highlight ?? false) ); public static Query ActiveFilter(this Query query, bool? active) => - query.When( - active != null, - query => query.WhereJsonb( - "Active", - active ?? false - ) - ); + query.When(active != null, query => query.WhereJsonb("Active", active ?? false)); public static Query SmgActiveFilter(this Query query, bool? smgactive) => query.When( smgactive != null, - query => query.WhereJsonb( - "SmgActive", - smgactive ?? false - ) + query => query.WhereJsonb("SmgActive", smgactive ?? false) ); - public static Query DistanceFilter(this Query query, bool distance, int distancemin, int distancemax) => + public static Query DistanceFilter( + this Query query, + bool distance, + int distancemin, + int distancemax + ) => query.When( distance, - query => query.WhereRaw( - "(data#>>'\\{DistanceLength\\}')::numeric > $$ AND (data#>>'\\{DistanceLength\\}')::numeric < $$", - distancemin, - distancemax - ) + query => + query.WhereRaw( + "(data#>>'\\{DistanceLength\\}')::numeric > $$ AND (data#>>'\\{DistanceLength\\}')::numeric < $$", + distancemin, + distancemax + ) ); - public static Query DurationFilter(this Query query, bool duration, double durationmin, double durationmax) => + public static Query DurationFilter( + this Query query, + bool duration, + double durationmin, + double durationmax + ) => query.When( duration, - query => query.WhereRaw( - "(data#>>'\\{DistanceDuration\\}')::numeric > $$ AND (data#>>'\\{DistanceDuration\\}')::numeric < $$", - durationmin, - durationmax - ) + query => + query.WhereRaw( + "(data#>>'\\{DistanceDuration\\}')::numeric > $$ AND (data#>>'\\{DistanceDuration\\}')::numeric < $$", + durationmin, + durationmax + ) ); - public static Query AltitudeFilter(this Query query, bool altitude, int altitudemin, int altitudemax) => + public static Query AltitudeFilter( + this Query query, + bool altitude, + int altitudemin, + int altitudemax + ) => query.When( altitude, - query => query.WhereRaw( - "(data#>>'\\{AltitudeDifference\\}')::numeric > $$ AND (data#>>'\\{AltitudeDifference\\}')::numeric < $$", - altitudemin, - altitudemax - ) + query => + query.WhereRaw( + "(data#>>'\\{AltitudeDifference\\}')::numeric > $$ AND (data#>>'\\{AltitudeDifference\\}')::numeric < $$", + altitudemin, + altitudemax + ) ); - public static Query SmgTagFilter(this Query query, IReadOnlyCollection smgtaglist) => - query.WhereInJsonb( - smgtaglist, - tag => new { SmgTags = new[] { tag.ToLower() } } - ); + public static Query SmgTagFilter( + this Query query, + IReadOnlyCollection smgtaglist + ) => query.WhereInJsonb(smgtaglist, tag => new { SmgTags = new[] { tag.ToLower() } }); //NOT WORKING //public static Query SmgTagFilter(this Query query, IReadOnlyCollection smgtaglist) => @@ -331,115 +303,125 @@ public static Query SmgTagFilter(this Query query, IReadOnlyCollection s public static Query SearchFilter(this Query query, string[] fields, string? searchfilter) => query.When( searchfilter != null && fields.Length > 0, - query => query.Where(q => - { - foreach (var field in fields) + query => + query.Where(q => { - q = q.OrWhereRaw( + foreach (var field in fields) + { + q = q.OrWhereRaw( $"data#>>'\\{{{JsonPathToPostgresArray(field)}\\}}' ILIKE $$", - $"%{searchfilter}%"); - } - return q; - }) + $"%{searchfilter}%" + ); + } + return q; + }) ); - public static Query ActivityTypeFilter(this Query query, IReadOnlyCollection activitytypelist) => - query.WhereInJsonb( - list: activitytypelist, - "Type", - type => type - ); + public static Query ActivityTypeFilter( + this Query query, + IReadOnlyCollection activitytypelist + ) => query.WhereInJsonb(list: activitytypelist, "Type", type => type); - public static Query ActivityTypeFilterOnTags(this Query query, IReadOnlyCollection activitytypelist) => + public static Query ActivityTypeFilterOnTags( + this Query query, + IReadOnlyCollection activitytypelist + ) => query.WhereInJsonb( list: activitytypelist, tag => new { SmgTags = new[] { tag.ToLower() } } ); - public static Query ActivitySubTypeFilterOnTags(this Query query, IReadOnlyCollection subtypelist) => - query.WhereInJsonb( - list: subtypelist, - tag => new { SmgTags = new[] { tag.ToLower() } } - ); + public static Query ActivitySubTypeFilterOnTags( + this Query query, + IReadOnlyCollection subtypelist + ) => + query.WhereInJsonb(list: subtypelist, tag => new { SmgTags = new[] { tag.ToLower() } }); - public static Query DifficultyFilter(this Query query, IReadOnlyCollection difficultylist) => - query.WhereInJsonb( - list: difficultylist, - jsonPath: "Difficulty" - ); + public static Query DifficultyFilter( + this Query query, + IReadOnlyCollection difficultylist + ) => query.WhereInJsonb(list: difficultylist, jsonPath: "Difficulty"); - public static Query PoiTypeFilterOnTags(this Query query, IReadOnlyCollection poitypelist) => + public static Query PoiTypeFilterOnTags( + this Query query, + IReadOnlyCollection poitypelist + ) => query.WhereInJsonb( poitypelist, poitype => new { SmgTags = new[] { poitype.ToLower() } } ); - public static Query PoiSubTypeFilterOnTags(this Query query, IReadOnlyCollection subtypelist) => + public static Query PoiSubTypeFilterOnTags( + this Query query, + IReadOnlyCollection subtypelist + ) => query.WhereInJsonb( subtypelist, poitype => new { SmgTags = new[] { poitype.ToLower() } } ); - public static Query MetaRegionFilter(this Query query, IReadOnlyCollection metaregionlist) => - query.WhereInJsonb( - metaregionlist, - "Id", - id => id.ToUpper() - ); + public static Query MetaRegionFilter( + this Query query, + IReadOnlyCollection metaregionlist + ) => query.WhereInJsonb(metaregionlist, "Id", id => id.ToUpper()); // TODO Add correct filters - public static Query CuisineCodeFilter(this Query query, IReadOnlyCollection cuisinecodelist) => + public static Query CuisineCodeFilter( + this Query query, + IReadOnlyCollection cuisinecodelist + ) => query.WhereInJsonb( cuisinecodelist, tag => new { Facilities = new[] { new { Id = tag.ToUpper() } } } ); - public static Query CeremonyCodeFilter(this Query query, IReadOnlyCollection ceremonycodelist) => + public static Query CeremonyCodeFilter( + this Query query, + IReadOnlyCollection ceremonycodelist + ) => query.WhereInJsonb( ceremonycodelist, tag => new { CapacityCeremony = new[] { new { Id = tag.ToUpper() } } } ); - public static Query CategoryCodeFilter(this Query query, IReadOnlyCollection categorycodelist) => + public static Query CategoryCodeFilter( + this Query query, + IReadOnlyCollection categorycodelist + ) => query.WhereInJsonb( categorycodelist, tag => new { CategoryCodes = new[] { new { Id = tag.ToUpper() } } } ); - public static Query DishCodeFilter(this Query query, IReadOnlyCollection dishcodelist) => + public static Query DishCodeFilter( + this Query query, + IReadOnlyCollection dishcodelist + ) => query.WhereInJsonb( dishcodelist, tag => new { DishRates = new[] { new { Id = tag.ToUpper() } } } ); - public static Query SourceFilter(this Query query, IReadOnlyCollection sourcelist) => - query.WhereInJsonb( - list: sourcelist, - "Source", - id => id.ToUpper() - ); + public static Query SourceFilter( + this Query query, + IReadOnlyCollection sourcelist + ) => query.WhereInJsonb(list: sourcelist, "Source", id => id.ToUpper()); //For Alpinebits - public static Query SourceFilterAlpineBits(this Query query, IReadOnlyCollection sourcelist) => - query.WhereInJsonb( - list: sourcelist, - "Source", - id => id.ToLower() - ); + public static Query SourceFilterAlpineBits( + this Query query, + IReadOnlyCollection sourcelist + ) => query.WhereInJsonb(list: sourcelist, "Source", id => id.ToLower()); - public static Query SyncSourceInterfaceFilter(this Query query, IReadOnlyCollection sourcelist) => - query.WhereInJsonb( - list: sourcelist, - "SyncSourceInterface", - id => id.ToUpper() - ); + public static Query SyncSourceInterfaceFilter( + this Query query, + IReadOnlyCollection sourcelist + ) => query.WhereInJsonb(list: sourcelist, "SyncSourceInterface", id => id.ToUpper()); - public static Query SourceFilterMeta(this Query query, IReadOnlyCollection sourcelist) => - query.WhereInJsonb( - list: sourcelist, - "_Meta.Source", - id => id.ToLower() - ); + public static Query SourceFilterMeta( + this Query query, + IReadOnlyCollection sourcelist + ) => query.WhereInJsonb(list: sourcelist, "_Meta.Source", id => id.ToLower()); //not working //public static Query HasLanguageFilter(this Query query, IReadOnlyCollection languagelist) => @@ -449,466 +431,584 @@ public static Query SourceFilterMeta(this Query query, IReadOnlyCollection id.ToUpper() // ); - public static Query HasLanguageFilter(this Query query, IReadOnlyCollection languagelist) => - query.WhereInJsonb( + public static Query HasLanguageFilter( + this Query query, + IReadOnlyCollection languagelist + ) => + query.WhereInJsonb( languagelist, lang => new { HasLanguage = new[] { lang.ToLower() } } ); + public static Query ODHActivityPoiTypeFilter( + this Query query, + IReadOnlyCollection typelist + ) => query.WhereInJsonb(list: typelist, "Type", type => type); - public static Query ODHActivityPoiTypeFilter(this Query query, IReadOnlyCollection typelist) => - query.WhereInJsonb( - list: typelist, - "Type", - type => type - ); + public static Query ODHActivityPoiSubTypeFilter( + this Query query, + IReadOnlyCollection subtypelist + ) => query.WhereInJsonb(list: subtypelist, "SubType", type => type); - public static Query ODHActivityPoiSubTypeFilter(this Query query, IReadOnlyCollection subtypelist) => - query.WhereInJsonb( - list: subtypelist, - "SubType", - type => type - ); + public static Query ODHActivityPoiPoiTypeFilter( + this Query query, + IReadOnlyCollection poitypelist + ) => query.WhereInJsonb(list: poitypelist, "PoiType", type => type); - public static Query ODHActivityPoiPoiTypeFilter(this Query query, IReadOnlyCollection poitypelist) => - query.WhereInJsonb( - list: poitypelist, - "PoiType", - type => type - ); + //To change, ODH Type Filtering based on + public static Query ODHActivityPoiTypeFilterOnTags( + this Query query, + IReadOnlyCollection typelist + ) => query.WhereInJsonb(typelist, type => new { SmgTags = new[] { type.ToLower() } }); - //To change, ODH Type Filtering based on - public static Query ODHActivityPoiTypeFilterOnTags(this Query query, IReadOnlyCollection typelist) => + public static Query ODHActivityPoiSubTypeFilterOnTags( + this Query query, + IReadOnlyCollection subtypelist + ) => query.WhereInJsonb( - typelist, - type => new { SmgTags = new[] { type.ToLower() } } + subtypelist, + subtype => new { SmgTags = new[] { subtype.ToLower() } } ); - public static Query ODHActivityPoiSubTypeFilterOnTags(this Query query, IReadOnlyCollection subtypelist) => - query.WhereInJsonb( - subtypelist, - subtype => new { SmgTags = new[] { subtype.ToLower() } } - ); - - public static Query ODHActivityPoiPoiTypeFilterOnTags(this Query query, IReadOnlyCollection poitypelist) => - query.WhereInJsonb( - poitypelist, - poitype => new { SmgTags = new[] { poitype.ToLower() } } - ); - - - public static Query EventTopicFilter(this Query query, IReadOnlyCollection eventtopiclist) => - query.WhereInJsonb( - eventtopiclist, - topic => new { TopicRIDs = new[] { topic.ToUpper() } } - ); - - public static Query EventTypeFilter(this Query query, IReadOnlyCollection eventtypelist) => - query.WhereInJsonb( - list: eventtypelist, - "Type", - type => type + public static Query ODHActivityPoiPoiTypeFilterOnTags( + this Query query, + IReadOnlyCollection poitypelist + ) => + query.WhereInJsonb( + poitypelist, + poitype => new { SmgTags = new[] { poitype.ToLower() } } ); - public static Query EventRancFilter(this Query query, IReadOnlyCollection eventrancfilterlist) => - query.WhereInJsonb( - list: eventrancfilterlist, - "Ranc", - ranc => ranc + public static Query EventTopicFilter( + this Query query, + IReadOnlyCollection eventtopiclist + ) => + query.WhereInJsonb( + eventtopiclist, + topic => new { TopicRIDs = new[] { topic.ToUpper() } } ); - public static Query EventOrgFilter(this Query query, IReadOnlyCollection eventorgfilter) => - query.WhereInJsonb( - list: eventorgfilter, - "OrgRID", - org => org - ); + public static Query EventTypeFilter( + this Query query, + IReadOnlyCollection eventtypelist + ) => query.WhereInJsonb(list: eventtypelist, "Type", type => type); + + public static Query EventRancFilter( + this Query query, + IReadOnlyCollection eventrancfilterlist + ) => query.WhereInJsonb(list: eventrancfilterlist, "Ranc", ranc => ranc); + public static Query EventOrgFilter( + this Query query, + IReadOnlyCollection eventorgfilter + ) => query.WhereInJsonb(list: eventorgfilter, "OrgRID", org => org); //Only Begindate given - public static Query EventDateFilterBegin(this Query query, DateTime? begin, DateTime? end) => + public static Query EventDateFilterBegin( + this Query query, + DateTime? begin, + DateTime? end + ) => query.When( begin != DateTime.MinValue && end == DateTime.MaxValue, - query => query.WhereRaw( - "((begindate >= '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND begindate < '" + String.Format("{0:yyyy-MM-dd}", end) + "') OR(enddate >= '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND enddate < '" + String.Format("{0:yyyy-MM-dd}", end) + "'))" - ) + query => + query.WhereRaw( + "((begindate >= '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND begindate < '" + + String.Format("{0:yyyy-MM-dd}", end) + + "') OR(enddate >= '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND enddate < '" + + String.Format("{0:yyyy-MM-dd}", end) + + "'))" + ) ); //Only Enddate given public static Query EventDateFilterEnd(this Query query, DateTime? begin, DateTime? end) => query.When( begin == DateTime.MinValue && end != DateTime.MaxValue, - query => query.WhereRaw( - "((begindate > '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND begindate < '" + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + "') OR (enddate > '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND enddate < '" + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + "'))" - ) + query => + query.WhereRaw( + "((begindate > '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND begindate < '" + + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + + "') OR (enddate > '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND enddate < '" + + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + + "'))" + ) ); //Both Begin and Enddate given - public static Query EventDateFilterBeginEnd(this Query query, DateTime? begin, DateTime? end) => + public static Query EventDateFilterBeginEnd( + this Query query, + DateTime? begin, + DateTime? end + ) => query.When( begin != DateTime.MinValue && end != DateTime.MaxValue, - query => query.WhereRaw( - "((begindate >= '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND begindate < '" + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + "') OR (enddate >= '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND enddate < '" + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + "'))" - ) + query => + query.WhereRaw( + "((begindate >= '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND begindate < '" + + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + + "') OR (enddate >= '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND enddate < '" + + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + + "'))" + ) ); public static Query VisibleInSearchFilter(this Query query, bool? visibleinsearch) => query.When( visibleinsearch != null, - query => query.WhereJsonb( - "VisibleInSearch", - visibleinsearch ?? false - ) + query => query.WhereJsonb("VisibleInSearch", visibleinsearch ?? false) ); - public static Query CompanyIdFilter(this Query query, IReadOnlyCollection companyidfilter) => - query.WhereInJsonb( - list: companyidfilter, - "CompanyId", - compid => compid - ); + public static Query CompanyIdFilter( + this Query query, + IReadOnlyCollection companyidfilter + ) => query.WhereInJsonb(list: companyidfilter, "CompanyId", compid => compid); - public static Query WineIdFilter(this Query query, IReadOnlyCollection wineidfilter) => - query.WhereInJsonb( - list: wineidfilter, - "CustomId", - wineid => wineid - ); + public static Query WineIdFilter( + this Query query, + IReadOnlyCollection wineidfilter + ) => query.WhereInJsonb(list: wineidfilter, "CustomId", wineid => wineid); - public static Query AccoAltitudeFilter(this Query query, bool altitude, int altitudemin, int altitudemax) => + public static Query AccoAltitudeFilter( + this Query query, + bool altitude, + int altitudemin, + int altitudemax + ) => query.When( altitude, - query => query.WhereRaw( - "(data#>>'\\{Altitude\\}')::numeric > $$ AND (data#>>'\\{Altitude\\}')::numeric < $$", - altitudemin, - altitudemax - ) - ); - - public static Query AccoTypeFilter(this Query query, IReadOnlyCollection accotypefilter) => - query.WhereInJsonb( - list: accotypefilter, - "AccoTypeId", - wineid => wineid - ); - - public static Query AccoBoardFilter(this Query query, IReadOnlyCollection boardlist) => - query.WhereInJsonb( - boardlist, - board => new { BoardIds = new[] { board.ToLower() } } - ); - - public static Query AccoBadgeFilter(this Query query, IReadOnlyCollection badgelist) => - query.WhereInJsonb( - badgelist, - badge => new { BadgeIds = new[] { badge.ToLower() } } - ); - - public static Query AccoLTSFeatureFilter(this Query query, IReadOnlyCollection ltsfeaturelist) => - query.WhereInJsonb( - ltsfeaturelist, - feature => new { Features = new[] { new { Id = feature.ToUpper() } } } - ); - - public static Query AccoMarketinggroupFilter(this Query query, IReadOnlyCollection marketinggrouplist) => - query.WhereInJsonb( - marketinggrouplist, - marketinggroup => new { MarketingGroupIds = new[] { marketinggroup } } - ); - - public static Query AccoBookingPortalFeatureFilter(this Query query, IReadOnlyCollection bookingportallist) => - query.WhereInJsonb( - bookingportallist, - bookingportal => new { AccoBookingChannel = new[] { new { Id = bookingportal } } } - ); + query => + query.WhereRaw( + "(data#>>'\\{Altitude\\}')::numeric > $$ AND (data#>>'\\{Altitude\\}')::numeric < $$", + altitudemin, + altitudemax + ) + ); + + public static Query AccoTypeFilter( + this Query query, + IReadOnlyCollection accotypefilter + ) => query.WhereInJsonb(list: accotypefilter, "AccoTypeId", wineid => wineid); + + public static Query AccoBoardFilter( + this Query query, + IReadOnlyCollection boardlist + ) => query.WhereInJsonb(boardlist, board => new { BoardIds = new[] { board.ToLower() } }); + + public static Query AccoBadgeFilter( + this Query query, + IReadOnlyCollection badgelist + ) => query.WhereInJsonb(badgelist, badge => new { BadgeIds = new[] { badge.ToLower() } }); + + public static Query AccoLTSFeatureFilter( + this Query query, + IReadOnlyCollection ltsfeaturelist + ) => + query.WhereInJsonb( + ltsfeaturelist, + feature => new { Features = new[] { new { Id = feature.ToUpper() } } } + ); + + public static Query AccoMarketinggroupFilter( + this Query query, + IReadOnlyCollection marketinggrouplist + ) => + query.WhereInJsonb( + marketinggrouplist, + marketinggroup => new { MarketingGroupIds = new[] { marketinggroup } } + ); + + public static Query AccoBookingPortalFeatureFilter( + this Query query, + IReadOnlyCollection bookingportallist + ) => + query.WhereInJsonb( + bookingportallist, + bookingportal => new { AccoBookingChannel = new[] { new { Id = bookingportal } } } + ); //THEMEFILTER is AND connected - public static Query AccoThemeFilter(this Query query, IReadOnlyCollection themelist) => - query.WhereAllInJsonb( - themelist, - theme => new { ThemeIds = new[] { theme } } - ); + public static Query AccoThemeFilter( + this Query query, + IReadOnlyCollection themelist + ) => query.WhereAllInJsonb(themelist, theme => new { ThemeIds = new[] { theme } }); //TODO THEMEFILTER is AND connected - public static Query AccoFeatureFilter(this Query query, IReadOnlyCollection featurelist) => + public static Query AccoFeatureFilter( + this Query query, + IReadOnlyCollection featurelist + ) => query.WhereAllInJsonb( - featurelist, - feature => new { SpecialFeaturesIds = new[] { feature } } - ); - - public static Query AccoCategoryFilter(this Query query, IReadOnlyCollection categorylist) => - query.WhereInJsonb( - list: categorylist, - "AccoCategoryId", - category => category + featurelist, + feature => new { SpecialFeaturesIds = new[] { feature } } ); - public static Query AccoFeatureIdFilter(this Query query, IReadOnlyCollection featureidlist) => - query.WhereInJsonb( + public static Query AccoCategoryFilter( + this Query query, + IReadOnlyCollection categorylist + ) => query.WhereInJsonb(list: categorylist, "AccoCategoryId", category => category); + + public static Query AccoFeatureIdFilter( + this Query query, + IReadOnlyCollection featureidlist + ) => + query.WhereInJsonb( featureidlist, tag => new { Features = new[] { new { Id = tag.ToUpper() } } } ); - public static Query AccoApartmentFilter(this Query query, bool? apartment) => query.When( apartment != null, - query => query.WhereJsonb( - "HasApartment", - apartment ?? false - ) + query => query.WhereJsonb("HasApartment", apartment ?? false) ); public static Query AccoBookableFilter(this Query query, bool? bookable) => query.When( bookable != null, - query => query.WhereJsonb( - "IsBookable", - bookable ?? false - ) - ); - - public static Query EventShortLocationFilter(this Query query, IReadOnlyCollection eventlocationlist) => - query.WhereInJsonb( - list: eventlocationlist, - "EventLocation", - id => id.ToUpper() - ); - - public static Query EventShortWebaddressFilter(this Query query, IReadOnlyCollection webaddresslist) => - query.WhereInJsonb( - list: webaddresslist, - "WebAddress", - id => id - ); + query => query.WhereJsonb("IsBookable", bookable ?? false) + ); + + public static Query EventShortLocationFilter( + this Query query, + IReadOnlyCollection eventlocationlist + ) => query.WhereInJsonb(list: eventlocationlist, "EventLocation", id => id.ToUpper()); + + public static Query EventShortWebaddressFilter( + this Query query, + IReadOnlyCollection webaddresslist + ) => query.WhereInJsonb(list: webaddresslist, "WebAddress", id => id); public static Query EventShortActiveFilter(this Query query, string? active) => - query.When( - active != null, - query => query.WhereJsonb( - "Display1", - active ?? "" - ) - ); + query.When(active != null, query => query.WhereJsonb("Display1", active ?? "")); public static Query EventShortWebsiteActiveFilter(this Query query, bool? websiteactive) => query.When( websiteactive != null, - query => query.WhereJsonb( - "ActiveWeb", - websiteactive ?? false - ) + query => query.WhereJsonb("ActiveWeb", websiteactive ?? false) ); - public static Query EventShortCommunityActiveFilter(this Query query, bool? communityactive) => - query.When( - communityactive != null, - query => query.WhereJsonb( - "ActiveCommunityApp", - communityactive ?? false - ) - ); + public static Query EventShortCommunityActiveFilter( + this Query query, + bool? communityactive + ) => + query.When( + communityactive != null, + query => query.WhereJsonb("ActiveCommunityApp", communityactive ?? false) + ); //Only Begindate given - public static Query EventShortDateFilterBegin(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterBegin( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start != DateTime.MinValue && end == DateTime.MaxValue && active, - query => query.WhereRaw( - "((to_timestamp(data ->> 'EndDate', 'YYYY-MM-DD T HH24:MI:SS') >= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", start) + "'))" - ) + query => + query.WhereRaw( + "((to_timestamp(data ->> 'EndDate', 'YYYY-MM-DD T HH24:MI:SS') >= '" + + String.Format("{0:yyyy-MM-dd HH:mm:ss}", start) + + "'))" + ) ); //Only Enddate given - public static Query EventShortDateFilterEnd(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterEnd( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start == DateTime.MinValue && end != DateTime.MaxValue && active, - query => query.WhereRaw( - "((to_timestamp(data->> 'EndDate', 'YYYY-MM-DD T HH24:MI:SS') <= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", end) + "'))" - ) + query => + query.WhereRaw( + "((to_timestamp(data->> 'EndDate', 'YYYY-MM-DD T HH24:MI:SS') <= '" + + String.Format("{0:yyyy-MM-dd HH:mm:ss}", end) + + "'))" + ) ); //Both Begin and Enddate given - public static Query EventShortDateFilterBeginEnd(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterBeginEnd( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start != DateTime.MinValue && end != DateTime.MaxValue && active, - query => query.WhereRaw( - "(((to_timestamp(data ->> 'StartDate', 'YYYY-MM-DD T HH24:MI:SS') >= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", start) + "') AND (to_timestamp(data->> 'EndDate', 'YYYY-MM-DD T HH24:MI:SS') <= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", end) + "')))" - ) + query => + query.WhereRaw( + "(((to_timestamp(data ->> 'StartDate', 'YYYY-MM-DD T HH24:MI:SS') >= '" + + String.Format("{0:yyyy-MM-dd HH:mm:ss}", start) + + "') AND (to_timestamp(data->> 'EndDate', 'YYYY-MM-DD T HH24:MI:SS') <= '" + + String.Format("{0:yyyy-MM-dd HH:mm:ss}", end) + + "')))" + ) ); //Both Begin and Enddate given which allows Today Query (In behaviour) - public static Query EventShortDateFilterBeginEndWithInBehaviour(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterBeginEndWithInBehaviour( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start != DateTime.MinValue && end != DateTime.MaxValue && active, - query => query.WhereRaw( - "(((to_timestamp(data ->> 'EndDate', 'YYYY-MM-DD T HH24:MI:SS') >= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", start) + "') AND (to_timestamp(data->> 'StartDate', 'YYYY-MM-DD T HH24:MI:SS') <= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", end) + "')))" - ) + query => + query.WhereRaw( + "(((to_timestamp(data ->> 'EndDate', 'YYYY-MM-DD T HH24:MI:SS') >= '" + + String.Format("{0:yyyy-MM-dd HH:mm:ss}", start) + + "') AND (to_timestamp(data->> 'StartDate', 'YYYY-MM-DD T HH24:MI:SS') <= '" + + String.Format("{0:yyyy-MM-dd HH:mm:ss}", end) + + "')))" + ) ); //Only Begindate given - public static Query EventShortDateFilterBeginByRoom(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterBeginByRoom( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start != DateTime.MinValue && end == DateTime.MaxValue && active, - query => query.WhereRaw( - "((to_date(data ->> 'EndDate', 'YYYY-MM-DD') >= '" + String.Format("{0:yyyy-MM-dd}", start) + "'))" - ) + query => + query.WhereRaw( + "((to_date(data ->> 'EndDate', 'YYYY-MM-DD') >= '" + + String.Format("{0:yyyy-MM-dd}", start) + + "'))" + ) ); //Only Enddate given - public static Query EventShortDateFilterEndByRoom(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterEndByRoom( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start == DateTime.MinValue && end != DateTime.MaxValue && active, - query => query.WhereRaw( - "((to_date(data->> 'EndDate', 'YYYY-MM-DD') <= '" + String.Format("{0:yyyy-MM-dd}", end) + "'))" - ) + query => + query.WhereRaw( + "((to_date(data->> 'EndDate', 'YYYY-MM-DD') <= '" + + String.Format("{0:yyyy-MM-dd}", end) + + "'))" + ) ); //Both Begin and Enddate given - public static Query EventShortDateFilterBeginEndByRoom(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterBeginEndByRoom( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start != DateTime.MinValue && end != DateTime.MaxValue && active, - query => query.WhereRaw( - "(((to_date(data ->> 'EndDate', 'YYYY-MM-DD') >= '" + String.Format("{0:yyyy-MM-dd}", start) + "') AND (to_date(data->> 'StartDate', 'YYYY-MM-DD') <= '" + String.Format("{0:yyyy-MM-dd}", end) + "')))" - ) - ); - - public static Query ODHTagMainEntityFilter(this Query query, IReadOnlyCollection mainentitylist) => - query.WhereInJsonb( - list: mainentitylist, - "MainEntity", - id => id.ToLower() - ); - - public static Query ODHTagValidForEntityFilter(this Query query, IReadOnlyCollection validforentitylist) => - query.WhereInJsonb( - validforentitylist, - validforentity => new { ValidForEntity = new[] { validforentity.ToLower() } } - ); - - public static Query ODHTagDisplayAsCategoryFilter(this Query query, bool? displayascategory) => - query.When( - displayascategory != null, - query => query.WhereJsonb( - "DisplayAsCategory", - displayascategory ?? false - ) + query => + query.WhereRaw( + "(((to_date(data ->> 'EndDate', 'YYYY-MM-DD') >= '" + + String.Format("{0:yyyy-MM-dd}", start) + + "') AND (to_date(data->> 'StartDate', 'YYYY-MM-DD') <= '" + + String.Format("{0:yyyy-MM-dd}", end) + + "')))" + ) ); - //AlpineBits - public static Query AlpineBitsAccommodationIdFilter(this Query query, IReadOnlyCollection accommodationids) => + public static Query ODHTagMainEntityFilter( + this Query query, + IReadOnlyCollection mainentitylist + ) => query.WhereInJsonb(list: mainentitylist, "MainEntity", id => id.ToLower()); + + public static Query ODHTagValidForEntityFilter( + this Query query, + IReadOnlyCollection validforentitylist + ) => query.WhereInJsonb( - list: accommodationids, - "AccommodationId", - id => id + validforentitylist, + validforentity => new { ValidForEntity = new[] { validforentity.ToLower() } } ); - //AlpineBits - public static Query AlpineBitsMessageFilter(this Query query, IReadOnlyCollection messagetypelist) => - query.WhereInJsonb( - list: messagetypelist, - "MessageType", - id => id + public static Query ODHTagDisplayAsCategoryFilter( + this Query query, + bool? displayascategory + ) => + query.When( + displayascategory != null, + query => query.WhereJsonb("DisplayAsCategory", displayascategory ?? false) ); + //AlpineBits + public static Query AlpineBitsAccommodationIdFilter( + this Query query, + IReadOnlyCollection accommodationids + ) => query.WhereInJsonb(list: accommodationids, "AccommodationId", id => id); + + //AlpineBits + public static Query AlpineBitsMessageFilter( + this Query query, + IReadOnlyCollection messagetypelist + ) => query.WhereInJsonb(list: messagetypelist, "MessageType", id => id); + //Venue Filters (Special case) - public static Query VenueLocFilterDistrictFilter(this Query query, IReadOnlyCollection districtlist) => - query.WhereInJsonb( - list: districtlist, - jsonPath: "odhdata.LocationInfo.DistrictInfo.Id" - ); + public static Query VenueLocFilterDistrictFilter( + this Query query, + IReadOnlyCollection districtlist + ) => + query.WhereInJsonb( + list: districtlist, + jsonPath: "odhdata.LocationInfo.DistrictInfo.Id" + ); - public static Query VenueLocFilterMunicipalityFilter(this Query query, IReadOnlyCollection municipalitylist) => + public static Query VenueLocFilterMunicipalityFilter( + this Query query, + IReadOnlyCollection municipalitylist + ) => query.WhereInJsonb( list: municipalitylist, jsonPath: "odhdata.LocationInfo.MunicipalityInfo.Id" ); - public static Query VenueLocFilterTvsFilter(this Query query, IReadOnlyCollection tourismvereinlist) => - query.WhereInJsonb( - list: tourismvereinlist, - jsonPath: "odhdata.LocationInfo.TvInfo.Id" - ); + public static Query VenueLocFilterTvsFilter( + this Query query, + IReadOnlyCollection tourismvereinlist + ) => + query.WhereInJsonb(list: tourismvereinlist, jsonPath: "odhdata.LocationInfo.TvInfo.Id"); - public static Query VenueLocFilterRegionFilter(this Query query, IReadOnlyCollection regionlist) => - query.WhereInJsonb( - list: regionlist, - jsonPath: "odhdata.LocationInfo.RegionInfo.Id" - ); + public static Query VenueLocFilterRegionFilter( + this Query query, + IReadOnlyCollection regionlist + ) => query.WhereInJsonb(list: regionlist, jsonPath: "odhdata.LocationInfo.RegionInfo.Id"); public static Query VenueActiveFilter(this Query query, bool? active) => query.When( active != null, - query => query.WhereJsonb( - "odhdata.Active", - active ?? false - ) + query => query.WhereJsonb("odhdata.Active", active ?? false) ); public static Query VenueODHActiveFilter(this Query query, bool? odhactive) => query.When( odhactive != null, - query => query.WhereJsonb( - "odhdata.ODHActive", - odhactive ?? false - ) - ); - - public static Query VenueCategoryFilter(this Query query, IReadOnlyCollection categorylist) => - query.WhereInJsonb( - categorylist, - tag => new { odhdata = new { VenueCategory = new[] { new { Id = tag.ToUpper() } } } } - ); - - public static Query VenueFeatureFilter(this Query query, IReadOnlyCollection featurelist) => - query.WhereInJsonb( - featurelist, - tag => new { odhdata = new { RoomDetails = new[] { new { VenueFeatures = new[] { new { Id = tag.ToUpper() } } } } } } - ); - - public static Query VenueSetupTypeFilter(this Query query, IReadOnlyCollection setuptypelist) => - query.WhereInJsonb( - setuptypelist, - tag => new { odhdata = new { RoomDetails = new[] { new { VenueSetup = new[] { new { Id = tag.ToUpper() } } } } } } - ); - - public static Query VenueRoomCountFilter(this Query query, bool roomcount, int roomcountmin, int roomcountmax) => + query => query.WhereJsonb("odhdata.ODHActive", odhactive ?? false) + ); + + public static Query VenueCategoryFilter( + this Query query, + IReadOnlyCollection categorylist + ) => + query.WhereInJsonb( + categorylist, + tag => + new { odhdata = new { VenueCategory = new[] { new { Id = tag.ToUpper() } } } } + ); + + public static Query VenueFeatureFilter( + this Query query, + IReadOnlyCollection featurelist + ) => + query.WhereInJsonb( + featurelist, + tag => + new + { + odhdata = new + { + RoomDetails = new[] + { + new { VenueFeatures = new[] { new { Id = tag.ToUpper() } } } + } + } + } + ); + + public static Query VenueSetupTypeFilter( + this Query query, + IReadOnlyCollection setuptypelist + ) => + query.WhereInJsonb( + setuptypelist, + tag => + new + { + odhdata = new + { + RoomDetails = new[] + { + new { VenueSetup = new[] { new { Id = tag.ToUpper() } } } + } + } + } + ); + + public static Query VenueRoomCountFilter( + this Query query, + bool roomcount, + int roomcountmin, + int roomcountmax + ) => query.When( roomcount, - query => query.WhereRaw( - "(data#>>'\\{odhdata,RoomCount\\}')::numeric > ? AND (data#>>'\\{odhdata,RoomCount\\}')::numeric < ?", - roomcountmin, - roomcountmax - ) + query => + query.WhereRaw( + "(data#>>'\\{odhdata,RoomCount\\}')::numeric > ? AND (data#>>'\\{odhdata,RoomCount\\}')::numeric < ?", + roomcountmin, + roomcountmax + ) ); - public static Query VenueODHTagFilter(this Query query, IReadOnlyCollection smgtaglist) => - query.WhereInJsonb( - smgtaglist, - tag => new { odhdata = new { ODHTags = new[] { tag.ToLower() } } } - ); + public static Query VenueODHTagFilter( + this Query query, + IReadOnlyCollection smgtaglist + ) => + query.WhereInJsonb( + smgtaglist, + tag => new { odhdata = new { ODHTags = new[] { tag.ToLower() } } } + ); public static Query VenueLastChangedFilter(this Query query, string? updatefrom) => - query.When( - updatefrom != null, - query => query.WhereRaw( - "to_date(data#>>'\\{meta,lastUpdate\\}', 'YYYY-MM-DD') > date($$)", - updatefrom - ) - ); - - public static Query VenueSourceFilter(this Query query, IReadOnlyCollection sourcelist) => - query.WhereInJsonb( - list: sourcelist, - "odhdata.SyncSourceInterface", - id => id.ToUpper() + query.When( + updatefrom != null, + query => + query.WhereRaw( + "to_date(data#>>'\\{meta,lastUpdate\\}', 'YYYY-MM-DD') > date($$)", + updatefrom + ) ); - public static Query VenueHasLanguageFilter(this Query query, IReadOnlyCollection languagelist) => + public static Query VenueSourceFilter( + this Query query, + IReadOnlyCollection sourcelist + ) => + query.WhereInJsonb(list: sourcelist, "odhdata.SyncSourceInterface", id => id.ToUpper()); + + public static Query VenueHasLanguageFilter( + this Query query, + IReadOnlyCollection languagelist + ) => query.WhereInJsonb( - languagelist, - lang => new { odhdata = new { HasLanguage = new[] { lang.ToLower() } } } - ); + languagelist, + lang => new { odhdata = new { HasLanguage = new[] { lang.ToLower() } } } + ); //private static Query VenueCapacityFilterWhere(bool capacity, int capacitymin, int capacitymax) //{ @@ -925,89 +1025,135 @@ public static Query VenueHasLanguageFilter(this Query query, IReadOnlyCollection //} - public static Query PublishedOnFilter(this Query query, IReadOnlyCollection publishedonlist) => - query.WhereInJsonb( - publishedonlist, - publishedon => new { PublishedOn = new[] { publishedon.ToLower() } } - ); - + public static Query PublishedOnFilter( + this Query query, + IReadOnlyCollection publishedonlist + ) => + query.WhereInJsonb( + publishedonlist, + publishedon => new { PublishedOn = new[] { publishedon.ToLower() } } + ); //Standard JSON Filter public static Query FilterClosedData(this Query query) => - query.Where(q => - q.WhereRaw( - "data#>>'\\{LicenseInfo,ClosedData\\}' IS NULL" - ).OrWhereRaw( - "data#>>'\\{LicenseInfo,ClosedData\\}' = 'false'" - ) + query.Where( + q => + q.WhereRaw("data#>>'\\{LicenseInfo,ClosedData\\}' IS NULL") + .OrWhereRaw("data#>>'\\{LicenseInfo,ClosedData\\}' = 'false'") ); public static Query FilterClosedDataVenues(this Query query) => - query.Where(q => - q.WhereRaw( - "data#>>'\\{odhdata,LicenseInfo,ClosedData\\}' IS NULL" - ).OrWhereRaw( - "data#>>'\\{odhdata,LicenseInfo,ClosedData\\}' = 'false'" - ) + query.Where( + q => + q.WhereRaw("data#>>'\\{odhdata,LicenseInfo,ClosedData\\}' IS NULL") + .OrWhereRaw("data#>>'\\{odhdata,LicenseInfo,ClosedData\\}' = 'false'") ); #region Tagging - public static Query TaggingFilter_OR(this Query query, string tagkey, IReadOnlyCollection taglist) => - query.Where(q => - taglist.Aggregate(q, (q, tag) => - q.OrWhereRaw(@$"(data->>'Tags')::jsonb @? '$.{tagkey}\[*\] ? (@.Id == ""{tag}"")'"))); + public static Query TaggingFilter_OR( + this Query query, + string tagkey, + IReadOnlyCollection taglist + ) => + query.Where( + q => + taglist.Aggregate( + q, + (q, tag) => + q.OrWhereRaw( + @$"(data->>'Tags')::jsonb @? '$.{tagkey}\[*\] ? (@.Id == ""{tag}"")'" + ) + ) + ); + + public static Query TaggingFilter_AND( + this Query query, + string tagkey, + IReadOnlyCollection taglist + ) => + query.Where( + q => + taglist.Aggregate( + q, + (q, tag) => + q.WhereRaw( + @$"(data->>'Tags')::jsonb @? '$.{tagkey}\[*\] ? (@.Id == ""{tag}"")'" + ) + ) + ); - public static Query TaggingFilter_AND(this Query query, string tagkey, IReadOnlyCollection taglist) => - query.Where(q => - taglist.Aggregate(q, (q, tag) => - q.WhereRaw(@$"(data->>'Tags')::jsonb @? '$.{tagkey}\[*\] ? (@.Id == ""{tag}"")'"))); - - public static Query TaggingFilter_OR(this Query query, IDictionary tagdict) => - query.Where(q => - tagdict.Aggregate(q, (q, tag) => - q.OrWhereRaw(@$"(data->>'Tags')::jsonb @? '$.{tag.Value}\[*\] ? (@.Id == ""{tag.Key}"")'"))); - - public static Query TaggingFilter_AND(this Query query, IDictionary tagdict) => - query.Where(q => - tagdict.Aggregate(q, (q, tag) => - q.WhereRaw(@$"(data->>'Tags')::jsonb @? '$.{tag.Value}\[*\] ? (@.Id == ""{tag.Key}"")'"))); + public static Query TaggingFilter_OR( + this Query query, + IDictionary tagdict + ) => + query.Where( + q => + tagdict.Aggregate( + q, + (q, tag) => + q.OrWhereRaw( + @$"(data->>'Tags')::jsonb @? '$.{tag.Value}\[*\] ? (@.Id == ""{tag.Key}"")'" + ) + ) + ); + + public static Query TaggingFilter_AND( + this Query query, + IDictionary tagdict + ) => + query.Where( + q => + tagdict.Aggregate( + q, + (q, tag) => + q.WhereRaw( + @$"(data->>'Tags')::jsonb @? '$.{tag.Value}\[*\] ? (@.Id == ""{tag.Key}"")'" + ) + ) + ); #endregion #region Generated Columns Basic - public static Query WhereArrayInListOr(this Query query, IReadOnlyCollection list, string generatedcolumn) => - query.Where(q => + public static Query WhereArrayInListOr( + this Query query, + IReadOnlyCollection list, + string generatedcolumn + ) => + query.Where(q => + { + foreach (var item in list) { - foreach (var item in list) - { - q = q.OrWhereRaw( - generatedcolumn + " @> array\\[$$\\]", item.ToLower() - ); - } - return q; - }); + q = q.OrWhereRaw(generatedcolumn + " @> array\\[$$\\]", item.ToLower()); + } + return q; + }); - public static Query WhereArrayInListAnd(this Query query, IReadOnlyCollection list, string generatedcolumn) => - query.Where(q => - q.WhereRaw( - generatedcolumn + " @> array\\[$$\\]", list.Select(x => x.ToLower()) - ) - ); - - public static Query WhereStringInListOr(this Query query, IReadOnlyCollection list, string generatedcolumn) => - query.Where(q => - { - foreach (var item in list) - { - q = q.OrWhereRaw( - generatedcolumn + " = $$", item.ToLower() - ); - } - return q; - }); + public static Query WhereArrayInListAnd( + this Query query, + IReadOnlyCollection list, + string generatedcolumn + ) => + query.Where( + q => + q.WhereRaw(generatedcolumn + " @> array\\[$$\\]", list.Select(x => x.ToLower())) + ); + public static Query WhereStringInListOr( + this Query query, + IReadOnlyCollection list, + string generatedcolumn + ) => + query.Where(q => + { + foreach (var item in list) + { + q = q.OrWhereRaw(generatedcolumn + " = $$", item.ToLower()); + } + return q; + }); #endregion @@ -1015,254 +1161,277 @@ public static Query WhereStringInListOr(this Query query, IReadOnlyCollection - query.Where(q => - q.WhereRaw( - "gen_licenseinfo_closeddata IS NULL" - ).OrWhereRaw( - "gen_licenseinfo_closeddata = false" - ) + query.Where( + q => + q.WhereRaw("gen_licenseinfo_closeddata IS NULL") + .OrWhereRaw("gen_licenseinfo_closeddata = false") ); //Filter on Generated Field gen_haslanguage AND - public static Query HasLanguageFilterAnd_GeneratedColumn(this Query query, IReadOnlyCollection languagelist) => - query.Where(q => q.WhereRaw( - "gen_haslanguage @> array\\[$$\\]", - languagelist.Select(x => x.ToLower()) - ) - ); + public static Query HasLanguageFilterAnd_GeneratedColumn( + this Query query, + IReadOnlyCollection languagelist + ) => + query.Where( + q => + q.WhereRaw( + "gen_haslanguage @> array\\[$$\\]", + languagelist.Select(x => x.ToLower()) + ) + ); //Filter on Generated Field gen_haslanguage AND - public static Query HasLanguageFilterOr_GeneratedColumn(this Query query, IReadOnlyCollection languagelist) => - query.Where(q => - { - foreach (var item in languagelist) - { - q = q.OrWhereRaw( - "gen_haslanguage @> array\\[$$\\]", item.ToLower() - ); - } - return q; - }); + public static Query HasLanguageFilterOr_GeneratedColumn( + this Query query, + IReadOnlyCollection languagelist + ) => + query.Where(q => + { + foreach (var item in languagelist) + { + q = q.OrWhereRaw("gen_haslanguage @> array\\[$$\\]", item.ToLower()); + } + return q; + }); //Filter on Generated Field gen_smgtags AND - public static Query SmgTagFilterAnd_GeneratedColumn(this Query query, IReadOnlyCollection list) => - query.Where(q => q.WhereRaw( - "gen_smgtags @> array\\[$$\\]", - list.Select(x => x.ToLower()) - ) - ); + public static Query SmgTagFilterAnd_GeneratedColumn( + this Query query, + IReadOnlyCollection list + ) => + query.Where( + q => q.WhereRaw("gen_smgtags @> array\\[$$\\]", list.Select(x => x.ToLower())) + ); //Filter on Generated Field gen_smgtags OR - public static Query SmgTagFilterOr_GeneratedColumn(this Query query, IReadOnlyCollection list) => - query.Where(q => - { - foreach (var item in list) + public static Query SmgTagFilterOr_GeneratedColumn( + this Query query, + IReadOnlyCollection list + ) => + query.Where(q => { - q = q.OrWhereRaw( - "gen_smgtags @> array\\[$$\\]", item.ToLower() - ); - } - return q; - }); + foreach (var item in list) + { + q = q.OrWhereRaw("gen_smgtags @> array\\[$$\\]", item.ToLower()); + } + return q; + }); //Filter on Generated Field gen_articletype OR - public static Query ArticleTypeFilterOr_GeneratedColumn(this Query query, IReadOnlyCollection list) => - query.Where(q => - { - foreach (var item in list) + public static Query ArticleTypeFilterOr_GeneratedColumn( + this Query query, + IReadOnlyCollection list + ) => + query.Where(q => { - q = q.OrWhereRaw( - "gen_articletype @> array\\[$$\\]", item.ToLower() - ); - } - return q; - }); + foreach (var item in list) + { + q = q.OrWhereRaw("gen_articletype @> array\\[$$\\]", item.ToLower()); + } + return q; + }); - //Filter on Generated Field gen_active + //Filter on Generated Field gen_active public static Query ActiveFilter_GeneratedColumn(this Query query, bool? active) => - query.When( - active != null, - query => query.WhereRaw( - "gen_active = $$", - active ?? false - ) - ); + query.When(active != null, query => query.WhereRaw("gen_active = $$", active ?? false)); - //Filter on Generated Field gen_odhactive + //Filter on Generated Field gen_odhactive public static Query OdhActiveFilter_GeneratedColumn(this Query query, bool? odhactive) => query.When( odhactive != null, - query => query.WhereRaw( - "gen_odhactive = $$", - odhactive ?? false - ) - ); - + query => query.WhereRaw("gen_odhactive = $$", odhactive ?? false) + ); + //Filter on Generated Field gen_eventtopic OR - public static Query EventTopicFilter_GeneratedColumn(this Query query, IReadOnlyCollection eventtopiclist) => - query.Where(q => - { - foreach (var item in eventtopiclist) + public static Query EventTopicFilter_GeneratedColumn( + this Query query, + IReadOnlyCollection eventtopiclist + ) => + query.Where(q => { - q = q.OrWhereRaw( - "gen_eventtopic @> array\\[$$\\]", item.ToUpper() - ); - } - return q; - }); + foreach (var item in eventtopiclist) + { + q = q.OrWhereRaw("gen_eventtopic @> array\\[$$\\]", item.ToUpper()); + } + return q; + }); //Filter on Generated Field gen_boardids - public static Query AccoBoardIdsFilterOr_GeneratedColumn(this Query query, IReadOnlyCollection boardids) => - query.Where(q => - { - foreach (var item in boardids) + public static Query AccoBoardIdsFilterOr_GeneratedColumn( + this Query query, + IReadOnlyCollection boardids + ) => + query.Where(q => { - q = q.OrWhereRaw( - "gen_boardids @> array\\[$$\\]", item - ); - } - return q; - }); + foreach (var item in boardids) + { + q = q.OrWhereRaw("gen_boardids @> array\\[$$\\]", item); + } + return q; + }); //Filter on Generated Field gen_featureids - public static Query AccoFeatureIdsFilterOr_GeneratedColumn(this Query query, IReadOnlyCollection featureids) => - query.Where(q => - { - foreach (var item in featureids) + public static Query AccoFeatureIdsFilterOr_GeneratedColumn( + this Query query, + IReadOnlyCollection featureids + ) => + query.Where(q => { - q = q.OrWhereRaw( - "gen_featureids @> array\\[$$\\]", item - ); - } - return q; - }); + foreach (var item in featureids) + { + q = q.OrWhereRaw("gen_featureids @> array\\[$$\\]", item); + } + return q; + }); //Filter on Generated Field gen_specialfeatureids - public static Query AccoSpecialFeatureIdsFilterOr_GeneratedColumn(this Query query, IReadOnlyCollection specialfeatureids) => - query.Where(q => - { - foreach (var item in specialfeatureids) + public static Query AccoSpecialFeatureIdsFilterOr_GeneratedColumn( + this Query query, + IReadOnlyCollection specialfeatureids + ) => + query.Where(q => { - q = q.OrWhereRaw( - "gen_specialfeatureids @> array\\[$$\\]", item - ); - } - return q; - }); + foreach (var item in specialfeatureids) + { + q = q.OrWhereRaw("gen_specialfeatureids @> array\\[$$\\]", item); + } + return q; + }); //Filter on Generated Field gen_badgeids - public static Query AccoBadgeIdsFilterOr_GeneratedColumn(this Query query, IReadOnlyCollection boardids) => - query.Where(q => - { - foreach (var item in boardids) + public static Query AccoBadgeIdsFilterOr_GeneratedColumn( + this Query query, + IReadOnlyCollection boardids + ) => + query.Where(q => { - q = q.OrWhereRaw( - "gen_badgeids @> array\\[$$\\]", item - ); - } - return q; - }); + foreach (var item in boardids) + { + q = q.OrWhereRaw("gen_badgeids @> array\\[$$\\]", item); + } + return q; + }); //Filter on Generated Field gen_themeids - public static Query AccoThemeIdsFilterOr_GeneratedColumn(this Query query, IReadOnlyCollection boardids) => - query.Where(q => - { - foreach (var item in boardids) + public static Query AccoThemeIdsFilterOr_GeneratedColumn( + this Query query, + IReadOnlyCollection boardids + ) => + query.Where(q => { - q = q.OrWhereRaw( - "gen_themeids @> array\\[$$\\]", item - ); - } - return q; - }); + foreach (var item in boardids) + { + q = q.OrWhereRaw("gen_themeids @> array\\[$$\\]", item); + } + return q; + }); - //Filter on Generated Field gen_accotype - public static Query AccoTypeFilter_GeneratedColumn(this Query query, IReadOnlyCollection accotype) => + //Filter on Generated Field gen_accotype + public static Query AccoTypeFilter_GeneratedColumn( + this Query query, + IReadOnlyCollection accotype + ) => query.Where(q => { foreach (var item in accotype) { - q = q.OrWhereRaw( - "gen_accotype = $$", item - ); + q = q.OrWhereRaw("gen_accotype = $$", item); } return q; }); - //Filter on Generated Field gen_accocategory - public static Query AccoCategoryFilter_GeneratedColumn(this Query query, IReadOnlyCollection accocategory) => - query.Where(q => - { - foreach (var item in accocategory) - { - q = q.OrWhereRaw( - "gen_accocategory = $$", item - ); - } - return q; - }); - - //Filter on Generated Field gen_hasapartment - public static Query AccoApartmentFilter_GeneratedColumn(this Query query, bool? hasapartment) => + //Filter on Generated Field gen_accocategory + public static Query AccoCategoryFilter_GeneratedColumn( + this Query query, + IReadOnlyCollection accocategory + ) => + query.Where(q => + { + foreach (var item in accocategory) + { + q = q.OrWhereRaw("gen_accocategory = $$", item); + } + return q; + }); + + //Filter on Generated Field gen_hasapartment + public static Query AccoApartmentFilter_GeneratedColumn( + this Query query, + bool? hasapartment + ) => query.When( hasapartment != null, - query => query.WhereRaw( - "gen_hasapartment = $$", - hasapartment ?? false - ) + query => query.WhereRaw("gen_hasapartment = $$", hasapartment ?? false) ); - //Filter on Generated Field gen_isbookable - public static Query AccoIsBookableFilter_GeneratedColumn(this Query query, bool? isbookable) => + //Filter on Generated Field gen_isbookable + public static Query AccoIsBookableFilter_GeneratedColumn( + this Query query, + bool? isbookable + ) => query.When( isbookable != null, - query => query.WhereRaw( - "gen_isbookable = $$", - isbookable ?? false - ) - ); - - //Filter on Generated Field gen_altitude - public static Query AccoAltitudeFilter_GeneratedColumn(this Query query, bool altitude, int altitudemin, int altitudemax) => - query.When( - altitude, - query => query.WhereRaw( - "(gen_altitude)::numeric > $$ AND (gen_altitude)::numeric < $$", - altitudemin, - altitudemax - ) - ); - - //Filter on Generated Field gen_lastchange - public static Query LastChangedFilter_GeneratedColumn(this Query query, string? updatefrom) => + query => query.WhereRaw("gen_isbookable = $$", isbookable ?? false) + ); + + //Filter on Generated Field gen_altitude + public static Query AccoAltitudeFilter_GeneratedColumn( + this Query query, + bool altitude, + int altitudemin, + int altitudemax + ) => + query.When( + altitude, + query => + query.WhereRaw( + "(gen_altitude)::numeric > $$ AND (gen_altitude)::numeric < $$", + altitudemin, + altitudemax + ) + ); + + //Filter on Generated Field gen_lastchange + public static Query LastChangedFilter_GeneratedColumn( + this Query query, + string? updatefrom + ) => query.When( //DISPLAY ERRROR OR IGNORE DATE? //updatefrom != null && DateTime.TryParseExact(updatefrom, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime updatefromparsed), //updatefrom != null && DateTime.TryParse(updatefrom, out DateTime updatefromparsed), updatefrom != null, - query => query.WhereRaw( - //"to_date(gen_lastchange, 'YYYY-MM-DD') > date($$)", - "gen_lastchange > date($$)", - updatefrom - ) + query => + query.WhereRaw( + //"to_date(gen_lastchange, 'YYYY-MM-DD') > date($$)", + "gen_lastchange > date($$)", + updatefrom + ) ); - //Weatherhistory lastchangedBetween - //Filter on Generated Field gen_lastchange - public static Query LastChangedFilter_GeneratedColumn(this Query query, DateTime? updatefrom, DateTime? updateto) => + //Filter on Generated Field gen_lastchange + public static Query LastChangedFilter_GeneratedColumn( + this Query query, + DateTime? updatefrom, + DateTime? updateto + ) => query.When( updatefrom != null && updateto != null, - query => query.WhereRaw( - //"to_date(gen_lastchange, 'YYYY-MM-DD') > date($$)", - "gen_lastchange > date($$) AND gen_lastchange < date($$)", - updatefrom, - updateto - ) + query => + query.WhereRaw( + //"to_date(gen_lastchange, 'YYYY-MM-DD') > date($$)", + "gen_lastchange > date($$) AND gen_lastchange < date($$)", + updatefrom, + updateto + ) ); //Source Filter (SyncSourceInterface) - public static Query SyncSourceInterfaceFilter_GeneratedColumn(this Query query, IReadOnlyCollection sourcelist) => + public static Query SyncSourceInterfaceFilter_GeneratedColumn( + this Query query, + IReadOnlyCollection sourcelist + ) => query.Where(q => { foreach (var source in sourcelist) @@ -1270,10 +1439,13 @@ public static Query SyncSourceInterfaceFilter_GeneratedColumn(this Query query, q = q.OrWhere("gen_syncsourceinterface", "ILIKE", source); } return q; - }); - - //Source Filter (SyncSourceInterface) - public static Query SourceFilter_GeneratedColumn(this Query query, IReadOnlyCollection sourcelist) => + }); + + //Source Filter (SyncSourceInterface) + public static Query SourceFilter_GeneratedColumn( + this Query query, + IReadOnlyCollection sourcelist + ) => query.Where(q => { foreach (var source in sourcelist) @@ -1283,9 +1455,11 @@ public static Query SourceFilter_GeneratedColumn(this Query query, IReadOnlyColl return q; }); - //Source Filter for Alpinebits - public static Query SourceFilterAlpineBits_GeneratedColumn(this Query query, IReadOnlyCollection sourcelist) => + public static Query SourceFilterAlpineBits_GeneratedColumn( + this Query query, + IReadOnlyCollection sourcelist + ) => query.Where(q => { foreach (var source in sourcelist) @@ -1296,33 +1470,36 @@ public static Query SourceFilterAlpineBits_GeneratedColumn(this Query query, IRe }); //AlpineBits - public static Query AlpineBitsAccommodationIdFilter_GeneratedColumn(this Query query, IReadOnlyCollection accommodationids) => - query.Where(q => - { - foreach (var item in accommodationids) - { - q = q.OrWhere("gen_accommodation_id", "=", item); - } - return q; - }); + public static Query AlpineBitsAccommodationIdFilter_GeneratedColumn( + this Query query, + IReadOnlyCollection accommodationids + ) => + query.Where(q => + { + foreach (var item in accommodationids) + { + q = q.OrWhere("gen_accommodation_id", "=", item); + } + return q; + }); //AlpineBits - public static Query AlpineBitsMessageFilter_GeneratedColumn(this Query query, IReadOnlyCollection messagetypelist) => + public static Query AlpineBitsMessageFilter_GeneratedColumn( + this Query query, + IReadOnlyCollection messagetypelist + ) => query.Where(q => { foreach (var item in messagetypelist) { - q = q.OrWhereRaw( - "gen_messagetype = $$", item - ); + q = q.OrWhereRaw("gen_messagetype = $$", item); } return q; - }); - - - //public static Query TaggingFilter_OR_GeneratedColumn(this Query query, IDictionary tagdict) => - // query.Where(q => - // tagdict.Aggregate(q, (q, tag) => + }); + + //public static Query TaggingFilter_OR_GeneratedColumn(this Query query, IDictionary tagdict) => + // query.Where(q => + // tagdict.Aggregate(q, (q, tag) => // q.OrWhereRaw(@$"(data->>'Tags')::jsonb @? '$.{tag.Value}\[*\] ? (@.Id == ""{tag.Key}"")'"))); //public static Query TaggingFilter_AND_GeneratedColumn(this Query query, IDictionary tagdict) => @@ -1338,60 +1515,124 @@ public static Query AlpineBitsMessageFilter_GeneratedColumn(this Query query, IR //EVENTS Usecase to check //Only Begindate given - public static Query EventDateFilterBegin_GeneratedColumn(this Query query, DateTime? begin, DateTime? end) => + public static Query EventDateFilterBegin_GeneratedColumn( + this Query query, + DateTime? begin, + DateTime? end + ) => query.When( begin != DateTime.MinValue && end == DateTime.MaxValue, - query => query.WhereRaw( - "((gen_begindate >= '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND gen_begindate < '" + String.Format("{0:yyyy-MM-dd}", end) + "') OR(gen_enddate >= '" + String.Format("{0:yyyy-MM-dd}", begin) + "'))" - ) + query => + query.WhereRaw( + "((gen_begindate >= '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND gen_begindate < '" + + String.Format("{0:yyyy-MM-dd}", end) + + "') OR(gen_enddate >= '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "'))" + ) ); //Only Enddate given - public static Query EventDateFilterEnd_GeneratedColumn(this Query query, DateTime? begin, DateTime? end) => + public static Query EventDateFilterEnd_GeneratedColumn( + this Query query, + DateTime? begin, + DateTime? end + ) => query.When( begin == DateTime.MinValue && end != DateTime.MaxValue, - query => query.WhereRaw( - "((gen_begindate > '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND gen_begindate < '" + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + "') OR (gen_enddate > '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND gen_enddate < '" + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + "'))" - ) + query => + query.WhereRaw( + "((gen_begindate > '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND gen_begindate < '" + + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + + "') OR (gen_enddate > '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND gen_enddate < '" + + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + + "'))" + ) ); //Both Begin and Enddate given - public static Query EventDateFilterBeginEnd_GeneratedColumn(this Query query, DateTime? begin, DateTime? end) => + public static Query EventDateFilterBeginEnd_GeneratedColumn( + this Query query, + DateTime? begin, + DateTime? end + ) => query.When( begin != DateTime.MinValue && end != DateTime.MaxValue, - query => query.WhereRaw( - "((gen_begindate >= '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND gen_begindate < '" + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + "') OR (gen_enddate >= '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND gen_enddate < '" + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + "'))" - ) + query => + query.WhereRaw( + "((gen_begindate >= '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND gen_begindate < '" + + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + + "') OR (gen_enddate >= '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND gen_enddate < '" + + String.Format("{0:yyyy-MM-dd}", end?.AddDays(1)) + + "'))" + ) ); //Article - //NEWS Usecase: Begindate filter shows all News that ends after requested date, and all News which begin before the requested date + //NEWS Usecase: Begindate filter shows all News that ends after requested date, and all News which begin before the requested date //Only Begindate given - public static Query ArticleDateNewsFilterBeginWithIN_GeneratedColumn(this Query query, DateTime? begin, DateTime? end) => + public static Query ArticleDateNewsFilterBeginWithIN_GeneratedColumn( + this Query query, + DateTime? begin, + DateTime? end + ) => query.When( begin != DateTime.MinValue && end == DateTime.MaxValue, - query => query.WhereRaw( - "(gen_enddate >= '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND gen_begindate <= '" + String.Format("{0:yyyy-MM-dd}", begin) + "')" - ) + query => + query.WhereRaw( + "(gen_enddate >= '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND gen_begindate <= '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "')" + ) ); //Only Enddate given - public static Query ArticleDateNewsFilterEndWithIN_GeneratedColumn(this Query query, DateTime? begin, DateTime? end) => + public static Query ArticleDateNewsFilterEndWithIN_GeneratedColumn( + this Query query, + DateTime? begin, + DateTime? end + ) => query.When( begin == DateTime.MinValue && end != DateTime.MaxValue, - query => query.WhereRaw( - "(gen_enddate >= '" + String.Format("{0:yyyy-MM-dd}", end) + "' AND gen_begindate <= '" + String.Format("{0:yyyy-MM-dd}", end) + "')" - ) + query => + query.WhereRaw( + "(gen_enddate >= '" + + String.Format("{0:yyyy-MM-dd}", end) + + "' AND gen_begindate <= '" + + String.Format("{0:yyyy-MM-dd}", end) + + "')" + ) ); //Both Begindate and Enddate given - public static Query ArticleDateNewsFilterBeginEndWithIN_GeneratedColumn(this Query query, DateTime? begin, DateTime? end) => + public static Query ArticleDateNewsFilterBeginEndWithIN_GeneratedColumn( + this Query query, + DateTime? begin, + DateTime? end + ) => query.When( begin != DateTime.MinValue && end != DateTime.MaxValue, - query => query.WhereRaw( - "(gen_enddate >= '" + String.Format("{0:yyyy-MM-dd}", begin) + "' AND gen_begindate <= '" + String.Format("{0:yyyy-MM-dd}", end) + "')" - ) + query => + query.WhereRaw( + "(gen_enddate >= '" + + String.Format("{0:yyyy-MM-dd}", begin) + + "' AND gen_begindate <= '" + + String.Format("{0:yyyy-MM-dd}", end) + + "')" + ) ); //EventShort @@ -1400,69 +1641,124 @@ public static Query ArticleDateNewsFilterBeginEndWithIN_GeneratedColumn(this Que //IN Behaviour = all events that ends after the startdate and begins before enddate (All events that are NOW) //Only Begindate given - public static Query EventShortDateFilterBegin_GeneratedColumn(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterBegin_GeneratedColumn( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start != DateTime.MinValue && end == DateTime.MaxValue && active, - query => query.WhereRaw( - "(gen_enddate >= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", start) + "'))" - ) + query => + query.WhereRaw( + "(gen_enddate >= '" + + String.Format("{0:yyyy-MM-dd HH:mm:ss}", start) + + "'))" + ) ); //Only Enddate given - public static Query EventShortDateFilterEnd_GeneratedColumn(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterEnd_GeneratedColumn( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start == DateTime.MinValue && end != DateTime.MaxValue && active, - query => query.WhereRaw( - "(gen_enddate <= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", end) + "'))" - ) + query => + query.WhereRaw( + "(gen_enddate <= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", end) + "'))" + ) ); //Both Begin and Enddate given - public static Query EventShortDateFilterBeginEnd_GeneratedColumn(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterBeginEnd_GeneratedColumn( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start != DateTime.MinValue && end != DateTime.MaxValue && active, - query => query.WhereRaw( - "((gen_begindate >= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", start) + "') AND (gen_enddate <= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", end) + "'))" - ) + query => + query.WhereRaw( + "((gen_begindate >= '" + + String.Format("{0:yyyy-MM-dd HH:mm:ss}", start) + + "') AND (gen_enddate <= '" + + String.Format("{0:yyyy-MM-dd HH:mm:ss}", end) + + "'))" + ) ); //Both Begin and Enddate given which allows Today Query (In behaviour) - public static Query EventShortDateFilterBeginEndWithInBehaviour_GeneratedColumn(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterBeginEndWithInBehaviour_GeneratedColumn( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start != DateTime.MinValue && end != DateTime.MaxValue && active, - query => query.WhereRaw( - "((gen_enddate >= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", start) + "') AND (gen_begindate <= '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", end) + "'))" - ) + query => + query.WhereRaw( + "((gen_enddate >= '" + + String.Format("{0:yyyy-MM-dd HH:mm:ss}", start) + + "') AND (gen_begindate <= '" + + String.Format("{0:yyyy-MM-dd HH:mm:ss}", end) + + "'))" + ) ); //Only Begindate given - public static Query EventShortDateFilterBeginByRoom_GeneratedColumn(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterBeginByRoom_GeneratedColumn( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start != DateTime.MinValue && end == DateTime.MaxValue && active, - query => query.WhereRaw( - "(gen_enddate >= '" + String.Format("{0:yyyy-MM-dd}", start) + "'))" - ) + query => + query.WhereRaw( + "(gen_enddate >= '" + String.Format("{0:yyyy-MM-dd}", start) + "'))" + ) ); //Only Enddate given - public static Query EventShortDateFilterEndByRoom_GeneratedColumn(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterEndByRoom_GeneratedColumn( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start == DateTime.MinValue && end != DateTime.MaxValue && active, - query => query.WhereRaw( - "(gen_enddate <= '" + String.Format("{0:yyyy-MM-dd}", end) + "'))" - ) + query => + query.WhereRaw( + "(gen_enddate <= '" + String.Format("{0:yyyy-MM-dd}", end) + "'))" + ) ); //Both Begin and Enddate given - public static Query EventShortDateFilterBeginEndByRoom_GeneratedColumn(this Query query, DateTime? start, DateTime? end, bool active) => + public static Query EventShortDateFilterBeginEndByRoom_GeneratedColumn( + this Query query, + DateTime? start, + DateTime? end, + bool active + ) => query.When( start != DateTime.MinValue && end != DateTime.MaxValue && active, - query => query.WhereRaw( - "((gen_enddate >= '" + String.Format("{0:yyyy-MM-dd}", start) + "') AND (gen_begindate <= '" + String.Format("{0:yyyy-MM-dd}", end) + "'))" - ) + query => + query.WhereRaw( + "((gen_enddate >= '" + + String.Format("{0:yyyy-MM-dd}", start) + + "') AND (gen_begindate <= '" + + String.Format("{0:yyyy-MM-dd}", end) + + "'))" + ) ); - #endregion #region Opendata_LTS_Rules @@ -1470,35 +1766,45 @@ public static Query EventShortDateFilterBeginEndByRoom_GeneratedColumn(this Quer //anonymous -> where (closeddata = false and source != lts) OR (reduced = true and source = lts and cc0 = true) //logged -> where (source != lts) OR (reduced = true and source = lts) //idmuser -> where (source != lts) OR (reduced = false and source = lts) - public static Query Anonymous_Logged_UserRule_GeneratedColumn(this Query query, bool closeddatafilter, bool idmuser) => - idmuser ? query.FilterSourceReducedLogged(false) : closeddatafilter ? query.FilterSourceReducedAnonymous() : query.FilterSourceReducedLogged(true); + public static Query Anonymous_Logged_UserRule_GeneratedColumn( + this Query query, + bool closeddatafilter, + bool idmuser + ) => + idmuser + ? query.FilterSourceReducedLogged(false) + : closeddatafilter + ? query.FilterSourceReducedAnonymous() + : query.FilterSourceReducedLogged(true); public static Query FilterSourceReducedLogged(this Query query, bool reduced) => - query.Where(q => - q.WhereRaw( - "(gen_source <> 'lts')" - ).OrWhereRaw( - "(gen_source = 'lts' AND gen_reduced = $$)", reduced - ) + query.Where( + q => + q.WhereRaw("(gen_source <> 'lts')") + .OrWhereRaw("(gen_source = 'lts' AND gen_reduced = $$)", reduced) ); public static Query FilterSourceReducedAnonymous(this Query query) => - query.Where(q => - q.WhereRaw( - "(gen_source <> 'lts' AND (gen_licenseinfo_closeddata IS NULL OR gen_licenseinfo_closeddata = $$))", false - ).OrWhereRaw( - "(gen_source = 'lts' AND gen_reduced = true AND ((gen_licenseinfo_closeddata IS NULL OR gen_licenseinfo_closeddata = $$)))", false - ) + query.Where( + q => + q.WhereRaw( + "(gen_source <> 'lts' AND (gen_licenseinfo_closeddata IS NULL OR gen_licenseinfo_closeddata = $$))", + false + ) + .OrWhereRaw( + "(gen_source = 'lts' AND gen_reduced = true AND ((gen_licenseinfo_closeddata IS NULL OR gen_licenseinfo_closeddata = $$)))", + false + ) ); #endregion #region Query Extension Methods Common used - public static async Task GetFirstOrDefaultAsObject(this Query query) { - + public static async Task GetFirstOrDefaultAsObject(this Query query) + { var rawdata = await query.FirstOrDefaultAsync(); - return rawdata != null ? JsonConvert.DeserializeObject(rawdata.Value) : default(T); + return rawdata != null ? JsonConvert.DeserializeObject(rawdata.Value) : default(T); } public static async Task> GetAllAsObject(this Query query) @@ -1516,6 +1822,5 @@ public static async Task> GetAllAsObject(this Query query) } #endregion - } } diff --git a/Helper/Postgres/PostgresSQLWhereBuilder.cs b/Helper/Postgres/PostgresSQLWhereBuilder.cs index 32e2673b1..a54ed7013 100644 --- a/Helper/Postgres/PostgresSQLWhereBuilder.cs +++ b/Helper/Postgres/PostgresSQLWhereBuilder.cs @@ -7,8 +7,7 @@ namespace Helper { public static class PostgresSQLWhereBuilder { - private static readonly string[] _languagesToSearchFor = - new[] { "de", "it", "en" }; + private static readonly string[] _languagesToSearchFor = new[] { "de", "it", "en" }; /// /// Provide title fields as JsonPath @@ -18,51 +17,45 @@ public static class PostgresSQLWhereBuilder /// specified language get returned /// public static string[] TitleFieldsToSearchFor(string? language) => - _languagesToSearchFor.Where(lang => - language != null ? lang == language : true - ).Select(lang => - $"Detail.{lang}.Title" - ).ToArray(); + _languagesToSearchFor + .Where(lang => language != null ? lang == language : true) + .Select(lang => $"Detail.{lang}.Title") + .ToArray(); public static string[] AccoTitleFieldsToSearchFor(string? language) => - _languagesToSearchFor.Where(lang => - language != null ? lang == language : true - ).Select(lang => - $"AccoDetail.{lang}.Name" - ).ToArray(); - + _languagesToSearchFor + .Where(lang => language != null ? lang == language : true) + .Select(lang => $"AccoDetail.{lang}.Name") + .ToArray(); //Public for use in Controllers directly public static string[] TypeDescFieldsToSearchFor(string? language) => - _languagesToSearchFor.Where(lang => - language != null ? lang == language : true - ).Select(lang => - $"TypeDesc.{lang}" - ).ToArray(); + _languagesToSearchFor + .Where(lang => language != null ? lang == language : true) + .Select(lang => $"TypeDesc.{lang}") + .ToArray(); public static string[] AccoRoomNameFieldsToSearchFor(string? language) => - _languagesToSearchFor.Where(lang => - language != null ? lang == language : true - ).Select(lang => - $"AccoRoomDetail.{lang}.Name" - ).ToArray(); + _languagesToSearchFor + .Where(lang => language != null ? lang == language : true) + .Select(lang => $"AccoRoomDetail.{lang}.Name") + .ToArray(); //TODO TRANSFORM LANGUAGE to deu,eng,ita public static string[] VenueTitleFieldsToSearchFor(string? language) => - _languagesToSearchFor.Where(lang => - language != null ? lang == language : true - ).Select(lang => - $"attributes.name.{TransformLanguagetoDDStandard(lang)}" - ).ToArray(); - - public static string TransformLanguagetoDDStandard(string language) => language switch - { - "de" => "deu", - "it" => "ita", - "en" => "eng", - _ => language - }; + _languagesToSearchFor + .Where(lang => language != null ? lang == language : true) + .Select(lang => $"attributes.name.{TransformLanguagetoDDStandard(lang)}") + .ToArray(); + public static string TransformLanguagetoDDStandard(string language) => + language switch + { + "de" => "deu", + "it" => "ita", + "en" => "eng", + _ => language + }; //TODO search name example //name: { @@ -78,27 +71,27 @@ public static string[] VenueTitleFieldsToSearchFor(string? language) => // ).ToArray(); public static string[] TagNameFieldsToSearchFor(string? language) => - _languagesToSearchFor.Where(lang => - language != null ? lang == language : true - ).Select(lang => - $"TagName.{lang}" - ).ToArray(); + _languagesToSearchFor + .Where(lang => language != null ? lang == language : true) + .Select(lang => $"TagName.{lang}") + .ToArray(); public static string[] WebcamnameFieldsToSearchFor(string? language) => - _languagesToSearchFor.Where(lang => - language != null ? lang == language : true - ).Select(lang => - $"Webcamname.{lang}" - ).ToArray(); + _languagesToSearchFor + .Where(lang => language != null ? lang == language : true) + .Select(lang => $"Webcamname.{lang}") + .ToArray(); public static string[] WeatherHistoryFieldsToSearchFor(string? language) => - _languagesToSearchFor.Where(lang => - language != null ? lang == language : true - ).Select(lang => - $"Weather.{lang}.evolutiontitle" - ).ToArray(); + _languagesToSearchFor + .Where(lang => language != null ? lang == language : true) + .Select(lang => $"Weather.{lang}.evolutiontitle") + .ToArray(); - public static void CheckPassedLanguage(ref string language, IEnumerable availablelanguages) + public static void CheckPassedLanguage( + ref string language, + IEnumerable availablelanguages + ) { language = language.ToLower(); @@ -108,40 +101,78 @@ public static void CheckPassedLanguage(ref string language, IEnumerable //Return where and Parameters [System.Diagnostics.Conditional("TRACE")] - private static void LogMethodInfo(System.Reflection.MethodBase m, params object?[] parameters) + private static void LogMethodInfo( + System.Reflection.MethodBase m, + params object?[] parameters + ) { - var parameterInfo = - m.GetParameters() - .Zip(parameters) - .Select((x, _) => (x.First.Name, x.Second)); + var parameterInfo = m.GetParameters() + .Zip(parameters) + .Select((x, _) => (x.First.Name, x.Second)); Serilog.Log.Debug("{method}({@parameters})", m.Name, parameterInfo); } //Return Where and Parameters for Activity public static Query ActivityWhereExpression( - this Query query, IReadOnlyCollection languagelist, - IReadOnlyCollection idlist, IReadOnlyCollection activitytypelist, - IReadOnlyCollection subtypelist, IReadOnlyCollection difficultylist, - IReadOnlyCollection smgtaglist, IReadOnlyCollection districtlist, - IReadOnlyCollection municipalitylist, IReadOnlyCollection tourismvereinlist, - IReadOnlyCollection regionlist, IReadOnlyCollection arealist, bool distance, int distancemin, - int distancemax, bool duration, int durationmin, int durationmax, bool altitude, int altitudemin, - int altitudemax, bool? highlight, bool? activefilter, bool? smgactivefilter, string? searchfilter, - string? language, string? lastchange, bool filterClosedData, bool reducedData) + this Query query, + IReadOnlyCollection languagelist, + IReadOnlyCollection idlist, + IReadOnlyCollection activitytypelist, + IReadOnlyCollection subtypelist, + IReadOnlyCollection difficultylist, + IReadOnlyCollection smgtaglist, + IReadOnlyCollection districtlist, + IReadOnlyCollection municipalitylist, + IReadOnlyCollection tourismvereinlist, + IReadOnlyCollection regionlist, + IReadOnlyCollection arealist, + bool distance, + int distancemin, + int distancemax, + bool duration, + int durationmin, + int durationmax, + bool altitude, + int altitudemin, + int altitudemax, + bool? highlight, + bool? activefilter, + bool? smgactivefilter, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData, + bool reducedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - idlist, activitytypelist, - subtypelist, difficultylist, - smgtaglist, districtlist, - municipalitylist, tourismvereinlist, - regionlist, arealist, distance, distancemin, - distancemax, duration, durationmin, - durationmax, altitude, altitudemin, - altitudemax, highlight, activefilter, - smgactivefilter, searchfilter, - language, lastchange + "", // not interested in query + idlist, + activitytypelist, + subtypelist, + difficultylist, + smgtaglist, + districtlist, + municipalitylist, + tourismvereinlist, + regionlist, + arealist, + distance, + distancemin, + distancemax, + duration, + durationmin, + durationmax, + altitude, + altitudemin, + altitudemax, + highlight, + activefilter, + smgactivefilter, + searchfilter, + language, + lastchange ); return query @@ -150,88 +181,136 @@ public static Query ActivityWhereExpression( .LocFilterMunicipalityFilter(municipalitylist) .LocFilterTvsFilter(tourismvereinlist) .LocFilterRegionFilter(regionlist) - .AreaFilter(arealist) - .When(activitytypelist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(activitytypelist)) //.ActivityTypeFilterOnTags(activitytypelist) + .AreaFilter(arealist) + .When( + activitytypelist.Count > 0, + q => q.SmgTagFilterOr_GeneratedColumn(activitytypelist) + ) //.ActivityTypeFilterOnTags(activitytypelist) .When(subtypelist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(subtypelist)) //.ActivitySubTypeFilterOnTags(subtypelist) .DifficultyFilter(difficultylist) .DistanceFilter(distance, distancemin, distancemax) .DurationFilter(duration, durationmin, durationmax) .AltitudeFilter(altitude, altitudemin, altitudemax) - .HighlightFilter(highlight) + .HighlightFilter(highlight) .ActiveFilter_GeneratedColumn(activefilter) //.ActiveFilter(activefilter) - .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) - .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) + .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) + .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) .SearchFilter(TitleFieldsToSearchFor(language), searchfilter) .LastChangedFilter_GeneratedColumn(lastchange) //.LastChangedFilter(lastchange) - .When(languagelist.Count > 0, q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist)) //OK GENERATED COLUMNS + .When( + languagelist.Count > 0, + q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist) + ) //OK GENERATED COLUMNS //.When(filterClosedData, q => q.FilterClosedData_GeneratedColumn()); .Anonymous_Logged_UserRule_GeneratedColumn(filterClosedData, !reducedData); } //Return Where and Parameters for Poi public static Query PoiWhereExpression( - this Query query, IReadOnlyCollection languagelist, - IReadOnlyCollection idlist, IReadOnlyCollection poitypelist, - IReadOnlyCollection subtypelist, IReadOnlyCollection smgtaglist, - IReadOnlyCollection districtlist, IReadOnlyCollection municipalitylist, - IReadOnlyCollection tourismvereinlist, IReadOnlyCollection regionlist, - IReadOnlyCollection arealist, bool? highlight, bool? activefilter, - bool? smgactivefilter, string? searchfilter, string? language, string? lastchange, - bool filterClosedData, bool reducedData) + this Query query, + IReadOnlyCollection languagelist, + IReadOnlyCollection idlist, + IReadOnlyCollection poitypelist, + IReadOnlyCollection subtypelist, + IReadOnlyCollection smgtaglist, + IReadOnlyCollection districtlist, + IReadOnlyCollection municipalitylist, + IReadOnlyCollection tourismvereinlist, + IReadOnlyCollection regionlist, + IReadOnlyCollection arealist, + bool? highlight, + bool? activefilter, + bool? smgactivefilter, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData, + bool reducedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", - idlist, poitypelist, - subtypelist, smgtaglist, - districtlist, municipalitylist, - tourismvereinlist, regionlist, - arealist, highlight, activefilter, - smgactivefilter, searchfilter, - language, lastchange + "", + idlist, + poitypelist, + subtypelist, + smgtaglist, + districtlist, + municipalitylist, + tourismvereinlist, + regionlist, + arealist, + highlight, + activefilter, + smgactivefilter, + searchfilter, + language, + lastchange ); return query .IdUpperFilter(idlist) - .DistrictFilter(districtlist) //Use generated columns also here? - .LocFilterMunicipalityFilter(municipalitylist) //Use generated columns also here? - .LocFilterTvsFilter(tourismvereinlist) //Use generated columns also here? - .LocFilterRegionFilter(regionlist) //Use generated columns also here? - .AreaFilter(arealist) //Use generated columns also here? - .When(poitypelist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(poitypelist)) //OK GENERATED COLUMNS //.PoiTypeFilterOnTags(poitypelist) - .When(subtypelist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(subtypelist)) //OK GENERATED COLUMNS //.PoiSubTypeFilterOnTags(subtypelist) - .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) + .DistrictFilter(districtlist) //Use generated columns also here? + .LocFilterMunicipalityFilter(municipalitylist) //Use generated columns also here? + .LocFilterTvsFilter(tourismvereinlist) //Use generated columns also here? + .LocFilterRegionFilter(regionlist) //Use generated columns also here? + .AreaFilter(arealist) //Use generated columns also here? + .When(poitypelist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(poitypelist)) //OK GENERATED COLUMNS //.PoiTypeFilterOnTags(poitypelist) + .When(subtypelist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(subtypelist)) //OK GENERATED COLUMNS //.PoiSubTypeFilterOnTags(subtypelist) + .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) .HighlightFilter(highlight) - .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) - .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) + .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) + .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) .SearchFilter(TitleFieldsToSearchFor(language), searchfilter) .LastChangedFilter_GeneratedColumn(lastchange) - .When(languagelist.Count > 0, q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist)) //OK GENERATED COLUMNS - //.When(filterClosedData, q => q.FilterClosedData_GeneratedColumn()); //OK GENERATED COLUMNS + .When( + languagelist.Count > 0, + q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist) + ) //OK GENERATED COLUMNS + //.When(filterClosedData, q => q.FilterClosedData_GeneratedColumn()); //OK GENERATED COLUMNS .Anonymous_Logged_UserRule_GeneratedColumn(filterClosedData, !reducedData); } //Return Where and Parameters for Gastronomy public static Query GastronomyWhereExpression( - this Query query, IReadOnlyCollection languagelist, - IReadOnlyCollection idlist, IReadOnlyCollection dishcodeslist, - IReadOnlyCollection ceremonycodeslist, IReadOnlyCollection categorycodeslist, - IReadOnlyCollection facilitycodeslist, IReadOnlyCollection smgtaglist, - IReadOnlyCollection districtlist, IReadOnlyCollection municipalitylist, - IReadOnlyCollection tourismvereinlist, IReadOnlyCollection regionlist, bool? activefilter, - bool? smgactivefilter, string? searchfilter, string? language, string? lastchange, - bool filterClosedData, bool reducedData) + this Query query, + IReadOnlyCollection languagelist, + IReadOnlyCollection idlist, + IReadOnlyCollection dishcodeslist, + IReadOnlyCollection ceremonycodeslist, + IReadOnlyCollection categorycodeslist, + IReadOnlyCollection facilitycodeslist, + IReadOnlyCollection smgtaglist, + IReadOnlyCollection districtlist, + IReadOnlyCollection municipalitylist, + IReadOnlyCollection tourismvereinlist, + IReadOnlyCollection regionlist, + bool? activefilter, + bool? smgactivefilter, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData, + bool reducedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - idlist, dishcodeslist, - ceremonycodeslist, categorycodeslist, - facilitycodeslist, smgtaglist, - districtlist, municipalitylist, - tourismvereinlist, regionlist, + idlist, + dishcodeslist, + ceremonycodeslist, + categorycodeslist, + facilitycodeslist, + smgtaglist, + districtlist, + municipalitylist, + tourismvereinlist, + regionlist, activefilter, - smgactivefilter, searchfilter, - language, lastchange + smgactivefilter, + searchfilter, + language, + lastchange ); return query @@ -244,40 +323,86 @@ public static Query GastronomyWhereExpression( .CategoryCodeFilter(categorycodeslist) .CuisineCodeFilter(facilitycodeslist) .DishCodeFilter(dishcodeslist) - .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) - .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) - .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) + .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) + .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) + .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) .SearchFilter(TitleFieldsToSearchFor(language), searchfilter) .LastChangedFilter(lastchange) - .When(languagelist.Count > 0, q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist)) //.HasLanguageFilter(languagelist) + .When( + languagelist.Count > 0, + q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist) + ) //.HasLanguageFilter(languagelist) //.When(filterClosedData, q => q.FilterClosedData_GeneratedColumn()); .Anonymous_Logged_UserRule_GeneratedColumn(filterClosedData, !reducedData); } //Return Where and Parameters for Activity public static Query ODHActivityPoiWhereExpression( - this Query query, IReadOnlyCollection languagelist, - IReadOnlyCollection idlist, IReadOnlyCollection typelist, IReadOnlyCollection subtypelist, - IReadOnlyCollection level3typelist, IReadOnlyCollection sourcelist, - IReadOnlyCollection smgtaglist, IReadOnlyCollection smgtaglistand, IReadOnlyCollection districtlist, - IReadOnlyCollection municipalitylist, IReadOnlyCollection tourismvereinlist, - IReadOnlyCollection regionlist, IReadOnlyCollection arealist, bool? highlight, bool? activefilter, bool? smgactivefilter, - IReadOnlyCollection categorycodeslist, IReadOnlyCollection dishcodeslist, IReadOnlyCollection ceremonycodeslist, IReadOnlyCollection facilitycodeslist, - IReadOnlyCollection activitytypelist, IReadOnlyCollection poitypelist, IReadOnlyCollection difficultylist, - bool distance, int distancemin, int distancemax, bool duration, int durationmin, int durationmax, bool altitude, int altitudemin, int altitudemax, - string tagbehaviour, IDictionary>? tagdict, - IReadOnlyCollection publishedonlist, string? searchfilter, string? language, string? lastchange, bool filterClosedData, bool reducedData) + this Query query, + IReadOnlyCollection languagelist, + IReadOnlyCollection idlist, + IReadOnlyCollection typelist, + IReadOnlyCollection subtypelist, + IReadOnlyCollection level3typelist, + IReadOnlyCollection sourcelist, + IReadOnlyCollection smgtaglist, + IReadOnlyCollection smgtaglistand, + IReadOnlyCollection districtlist, + IReadOnlyCollection municipalitylist, + IReadOnlyCollection tourismvereinlist, + IReadOnlyCollection regionlist, + IReadOnlyCollection arealist, + bool? highlight, + bool? activefilter, + bool? smgactivefilter, + IReadOnlyCollection categorycodeslist, + IReadOnlyCollection dishcodeslist, + IReadOnlyCollection ceremonycodeslist, + IReadOnlyCollection facilitycodeslist, + IReadOnlyCollection activitytypelist, + IReadOnlyCollection poitypelist, + IReadOnlyCollection difficultylist, + bool distance, + int distancemin, + int distancemax, + bool duration, + int durationmin, + int durationmax, + bool altitude, + int altitudemin, + int altitudemax, + string tagbehaviour, + IDictionary>? tagdict, + IReadOnlyCollection publishedonlist, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData, + bool reducedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - idlist, typelist, - subtypelist, level3typelist, poitypelist, languagelist, sourcelist, - smgtaglist, districtlist, - municipalitylist, tourismvereinlist, - regionlist, arealist, highlight, activefilter, - smgactivefilter, searchfilter, - language, lastchange + "", // not interested in query + idlist, + typelist, + subtypelist, + level3typelist, + poitypelist, + languagelist, + sourcelist, + smgtaglist, + districtlist, + municipalitylist, + tourismvereinlist, + regionlist, + arealist, + highlight, + activefilter, + smgactivefilter, + searchfilter, + language, + lastchange ); return query @@ -289,29 +414,47 @@ public static Query ODHActivityPoiWhereExpression( .AreaFilter(arealist) .When(typelist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(typelist)) //.ODHActivityPoiTypeFilterOnTags(typelist) .When(subtypelist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(subtypelist)) //.ODHActivityPoiSubTypeFilterOnTags(subtypelist) - .When(level3typelist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(level3typelist)) //.ODHActivityPoiSubTypeFilterOnTags(subtypelist) + .When( + level3typelist.Count > 0, + q => q.SmgTagFilterOr_GeneratedColumn(level3typelist) + ) //.ODHActivityPoiSubTypeFilterOnTags(subtypelist) .SyncSourceInterfaceFilter_GeneratedColumn(sourcelist) //.SourceFilter(sourcelist) - .When(languagelist.Count > 0, q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist)) //.HasLanguageFilter(languagelist) + .When( + languagelist.Count > 0, + q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist) + ) //.HasLanguageFilter(languagelist) .HighlightFilter(highlight) - .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) - .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) - .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) - .When(smgtaglistand.Count > 0, q => q.SmgTagFilterAnd_GeneratedColumn(smgtaglistand)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) //New GastronomyFilters + .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) + .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) + .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) + .When( + smgtaglistand.Count > 0, + q => q.SmgTagFilterAnd_GeneratedColumn(smgtaglistand) + ) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) //New GastronomyFilters .CeremonyCodeFilter(ceremonycodeslist) .CategoryCodeFilter(categorycodeslist) .CuisineCodeFilter(facilitycodeslist) .DishCodeFilter(dishcodeslist) //New ActivityFilters - .When(activitytypelist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(activitytypelist)) //.ActivityTypeFilterOnTags(activitytypelist) + .When( + activitytypelist.Count > 0, + q => q.SmgTagFilterOr_GeneratedColumn(activitytypelist) + ) //.ActivityTypeFilterOnTags(activitytypelist) //Changed PoiTypeFilter .When(poitypelist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(poitypelist)) //.ODHActivityPoiPoiTypeFilterOnTags(poitypelist) .DifficultyFilter(difficultylist) .DistanceFilter(distance, distancemin, distancemax) .DurationFilter(duration, durationmin, durationmax) .AltitudeFilter(altitude, altitudemin, altitudemax) - .PublishedOnFilter(publishedonlist) - .When(tagdict != null && tagdict.ContainsKey("and") && tagdict["and"].Any(), q => q.TaggingFilter_AND(tagdict!["and"])) - .When(tagdict != null && tagdict.ContainsKey("or") && tagdict["or"].Any(), q => q.TaggingFilter_OR(tagdict!["or"])) + .PublishedOnFilter(publishedonlist) + .When( + tagdict != null && tagdict.ContainsKey("and") && tagdict["and"].Any(), + q => q.TaggingFilter_AND(tagdict!["and"]) + ) + .When( + tagdict != null && tagdict.ContainsKey("or") && tagdict["or"].Any(), + q => q.TaggingFilter_OR(tagdict!["or"]) + ) .SearchFilter(TitleFieldsToSearchFor(language), searchfilter) .LastChangedFilter_GeneratedColumn(lastchange) //.When(filterClosedData, q => q.FilterClosedData_GeneratedColumn()); @@ -320,19 +463,44 @@ public static Query ODHActivityPoiWhereExpression( //Return Where and Parameters for Article public static Query ArticleWhereExpression( - this Query query, IReadOnlyCollection languagelist, - IReadOnlyCollection idlist, IReadOnlyCollection typelist, IReadOnlyCollection subtypelist, - IReadOnlyCollection smgtaglist, bool? highlight, bool? activefilter, bool? smgactivefilter, DateTime? articledate, DateTime? articledateto, IReadOnlyCollection sourcelist, - IReadOnlyCollection publishedonlist, string? searchfilter, string? language, string? lastchange, bool filterClosedData, bool reducedData) + this Query query, + IReadOnlyCollection languagelist, + IReadOnlyCollection idlist, + IReadOnlyCollection typelist, + IReadOnlyCollection subtypelist, + IReadOnlyCollection smgtaglist, + bool? highlight, + bool? activefilter, + bool? smgactivefilter, + DateTime? articledate, + DateTime? articledateto, + IReadOnlyCollection sourcelist, + IReadOnlyCollection publishedonlist, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData, + bool reducedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - idlist, typelist, subtypelist, languagelist, smgtaglist, - highlight, activefilter, smgactivefilter, - articledate, articledateto, sourcelist, publishedonlist, + "", // not interested in query + idlist, + typelist, + subtypelist, + languagelist, + smgtaglist, + highlight, + activefilter, + smgactivefilter, + articledate, + articledateto, + sourcelist, + publishedonlist, searchfilter, - language, lastchange + language, + lastchange ); return query @@ -340,12 +508,18 @@ public static Query ArticleWhereExpression( //.ODHActivityPoiTypeFilter(typelist) //.ODHActivityPoiSubTypeFilter(subtypelist) .When(typelist.Count > 0, q => q.ArticleTypeFilterOr_GeneratedColumn(typelist)) - .When(subtypelist.Count > 0, q => q.ArticleTypeFilterOr_GeneratedColumn(subtypelist)) - .When(languagelist.Count > 0, q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist)) //.HasLanguageFilter(languagelist) + .When( + subtypelist.Count > 0, + q => q.ArticleTypeFilterOr_GeneratedColumn(subtypelist) + ) + .When( + languagelist.Count > 0, + q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist) + ) //.HasLanguageFilter(languagelist) .HighlightFilter(highlight) - .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) - .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) - .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) + .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) + .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) + .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) .SearchFilter(TitleFieldsToSearchFor(language), searchfilter) //Articledate+ Articledatetofilter //.EventDateFilterEnd_GeneratedColumn(articledate, articledateto) @@ -362,28 +536,53 @@ public static Query ArticleWhereExpression( //Return Where and Parameters for Event public static Query EventWhereExpression( - this Query query, IReadOnlyCollection languagelist, - IReadOnlyCollection idlist, IReadOnlyCollection topiclist, - IReadOnlyCollection typelist, IReadOnlyCollection ranclist, - IReadOnlyCollection smgtaglist, IReadOnlyCollection districtlist, - IReadOnlyCollection municipalitylist, IReadOnlyCollection tourismvereinlist, - IReadOnlyCollection regionlist, IReadOnlyCollection orglist, - IReadOnlyCollection sourcelist, - DateTime? begindate, DateTime? enddate, - bool? activefilter, bool? smgactivefilter, - IReadOnlyCollection publishedonlist, - string? searchfilter, string? language, string? lastchange, bool filterClosedData, bool reducedData) + this Query query, + IReadOnlyCollection languagelist, + IReadOnlyCollection idlist, + IReadOnlyCollection topiclist, + IReadOnlyCollection typelist, + IReadOnlyCollection ranclist, + IReadOnlyCollection smgtaglist, + IReadOnlyCollection districtlist, + IReadOnlyCollection municipalitylist, + IReadOnlyCollection tourismvereinlist, + IReadOnlyCollection regionlist, + IReadOnlyCollection orglist, + IReadOnlyCollection sourcelist, + DateTime? begindate, + DateTime? enddate, + bool? activefilter, + bool? smgactivefilter, + IReadOnlyCollection publishedonlist, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData, + bool reducedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - idlist, topiclist, - typelist, ranclist, - smgtaglist, districtlist, - municipalitylist, tourismvereinlist, - regionlist, orglist, sourcelist, languagelist, begindate, enddate, - activefilter, smgactivefilter, searchfilter, - language, lastchange + "", // not interested in query + idlist, + topiclist, + typelist, + ranclist, + smgtaglist, + districtlist, + municipalitylist, + tourismvereinlist, + regionlist, + orglist, + sourcelist, + languagelist, + begindate, + enddate, + activefilter, + smgactivefilter, + searchfilter, + language, + lastchange ); return query @@ -399,11 +598,14 @@ public static Query EventWhereExpression( .EventDateFilterEnd_GeneratedColumn(begindate, enddate) .EventDateFilterBegin_GeneratedColumn(begindate, enddate) .EventDateFilterBeginEnd_GeneratedColumn(begindate, enddate) - .When(languagelist.Count > 0, q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist)) //.HasLanguageFilter(languagelist) + .When( + languagelist.Count > 0, + q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist) + ) //.HasLanguageFilter(languagelist) .SyncSourceInterfaceFilter_GeneratedColumn(sourcelist) - .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) - .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) - .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) + .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) + .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) + .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) .PublishedOnFilter(publishedonlist) .SearchFilter(TitleFieldsToSearchFor(language), searchfilter) .LastChangedFilter_GeneratedColumn(lastchange) @@ -413,25 +615,65 @@ public static Query EventWhereExpression( //Return Where and Parameters for Accommodation public static Query AccommodationWhereExpression( - this Query query, IReadOnlyCollection languagelist, - IReadOnlyCollection idlist, IReadOnlyCollection accotypelist, IReadOnlyCollection categorylist, - Dictionary featurelist, IReadOnlyCollection featureidlist, IReadOnlyCollection badgelist, Dictionary themelist, - IReadOnlyCollection boardlist, IReadOnlyCollection smgtaglist, IReadOnlyCollection districtlist, - IReadOnlyCollection municipalitylist, IReadOnlyCollection tourismvereinlist, - IReadOnlyCollection regionlist, bool? apartmentfilter, bool? bookable, - bool altitude, int altitudemin, int altitudemax, bool? activefilter, bool? smgactivefilter, - IReadOnlyCollection publishedonlist, IReadOnlyCollection sourcelist, - string? searchfilter, string? language, string? lastchange, bool filterClosedData, bool reducedData) + this Query query, + IReadOnlyCollection languagelist, + IReadOnlyCollection idlist, + IReadOnlyCollection accotypelist, + IReadOnlyCollection categorylist, + Dictionary featurelist, + IReadOnlyCollection featureidlist, + IReadOnlyCollection badgelist, + Dictionary themelist, + IReadOnlyCollection boardlist, + IReadOnlyCollection smgtaglist, + IReadOnlyCollection districtlist, + IReadOnlyCollection municipalitylist, + IReadOnlyCollection tourismvereinlist, + IReadOnlyCollection regionlist, + bool? apartmentfilter, + bool? bookable, + bool altitude, + int altitudemin, + int altitudemax, + bool? activefilter, + bool? smgactivefilter, + IReadOnlyCollection publishedonlist, + IReadOnlyCollection sourcelist, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData, + bool reducedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - idlist, accotypelist, categorylist, - featurelist, featureidlist, badgelist, languagelist, themelist, boardlist, - smgtaglist, districtlist, municipalitylist, tourismvereinlist, - regionlist, altitude, altitudemin, altitudemax, activefilter, - smgactivefilter, searchfilter, apartmentfilter, bookable, - language, lastchange, sourcelist + "", // not interested in query + idlist, + accotypelist, + categorylist, + featurelist, + featureidlist, + badgelist, + languagelist, + themelist, + boardlist, + smgtaglist, + districtlist, + municipalitylist, + tourismvereinlist, + regionlist, + altitude, + altitudemin, + altitudemax, + activefilter, + smgactivefilter, + searchfilter, + apartmentfilter, + bookable, + language, + lastchange, + sourcelist ); return query @@ -443,18 +685,25 @@ public static Query AccommodationWhereExpression( .AccoAltitudeFilter(altitude, altitudemin, altitudemax) .AccoTypeFilter_GeneratedColumn(accotypelist) .AccoCategoryFilter_GeneratedColumn(categorylist) //.AccoCategoryFilter(categorylist) - .AccoSpecialFeatureIdsFilterOr_GeneratedColumn(featurelist.Where(x => x.Value == true).Select(x => x.Key).ToList()) //.AccoFeatureFilter(featurelist.Where(x => x.Value == true).Select(x => x.Key).ToList()) + .AccoSpecialFeatureIdsFilterOr_GeneratedColumn( + featurelist.Where(x => x.Value == true).Select(x => x.Key).ToList() + ) //.AccoFeatureFilter(featurelist.Where(x => x.Value == true).Select(x => x.Key).ToList()) .AccoFeatureIdsFilterOr_GeneratedColumn(featureidlist) //.AccoFeatureIdFilter(featureidlist) .AccoBadgeIdsFilterOr_GeneratedColumn(badgelist) //.AccoBadgeFilter(badgelist) - .AccoThemeIdsFilterOr_GeneratedColumn(themelist.Where(x => x.Value == true).Select(x => x.Key).ToList()) // .AccoThemeFilter(themelist.Where(x => x.Value == true).Select(x => x.Key).ToList()) + .AccoThemeIdsFilterOr_GeneratedColumn( + themelist.Where(x => x.Value == true).Select(x => x.Key).ToList() + ) // .AccoThemeFilter(themelist.Where(x => x.Value == true).Select(x => x.Key).ToList()) .AccoBoardIdsFilterOr_GeneratedColumn(boardlist) //.AccoBoardFilter(boardlist) - .AccoApartmentFilter_GeneratedColumn(apartmentfilter) //.AccoApartmentFilter(apartmentfilter) + .AccoApartmentFilter_GeneratedColumn(apartmentfilter) //.AccoApartmentFilter(apartmentfilter) .AccoIsBookableFilter_GeneratedColumn(bookable) - // FILTERS Available Marketinggroup, LTSFeature, BookingPortal - .When(languagelist.Count > 0, q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist)) //.HasLanguageFilter(languagelist) - .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) - .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) - .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) + // FILTERS Available Marketinggroup, LTSFeature, BookingPortal + .When( + languagelist.Count > 0, + q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist) + ) //.HasLanguageFilter(languagelist) + .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) + .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) + .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) .PublishedOnFilter(publishedonlist) .SearchFilter(AccoTitleFieldsToSearchFor(language), searchfilter) .LastChangedFilter_GeneratedColumn(lastchange) @@ -465,15 +714,33 @@ public static Query AccommodationWhereExpression( //Return Where and Parameters for Common public static Query CommonWhereExpression( - this Query query, IReadOnlyCollection idlist, IReadOnlyCollection languagelist, - bool? visibleinsearch, IReadOnlyCollection smgtaglist, bool? activefilter, bool? odhactivefilter, - IReadOnlyCollection publishedonlist, IReadOnlyCollection sourcelist, - string? searchfilter, string? language, string? lastchange, bool filterClosedData) + this Query query, + IReadOnlyCollection idlist, + IReadOnlyCollection languagelist, + bool? visibleinsearch, + IReadOnlyCollection smgtaglist, + bool? activefilter, + bool? odhactivefilter, + IReadOnlyCollection publishedonlist, + IReadOnlyCollection sourcelist, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - idlist, languagelist, searchfilter, language, lastchange, activefilter, odhactivefilter, lastchange, sourcelist + "", // not interested in query + idlist, + languagelist, + searchfilter, + language, + lastchange, + activefilter, + odhactivefilter, + lastchange, + sourcelist ); return query @@ -482,24 +749,39 @@ public static Query CommonWhereExpression( .PublishedOnFilter(publishedonlist) .LastChangedFilter_GeneratedColumn(lastchange) .VisibleInSearchFilter(visibleinsearch) - .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) - .OdhActiveFilter_GeneratedColumn(odhactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) - .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) - .When(languagelist.Count > 0, q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist)) //.HasLanguageFilter(languagelist) + .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) + .OdhActiveFilter_GeneratedColumn(odhactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) + .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.SmgTagFilter(smgtaglist) + .When( + languagelist.Count > 0, + q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist) + ) //.HasLanguageFilter(languagelist) .SourceFilter_GeneratedColumn(sourcelist) .When(filterClosedData, q => q.FilterClosedData_GeneratedColumn()); } //Return Where and Parameters for Wine public static Query WineWhereExpression( - this Query query, IReadOnlyCollection languagelist, IReadOnlyCollection companyid, IReadOnlyCollection wineid, - bool? activefilter, bool? odhactivefilter, IReadOnlyCollection sourcelist, - string? searchfilter, string? language, string? lastchange, bool filterClosedData) + this Query query, + IReadOnlyCollection languagelist, + IReadOnlyCollection companyid, + IReadOnlyCollection wineid, + bool? activefilter, + bool? odhactivefilter, + IReadOnlyCollection sourcelist, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - searchfilter, language, lastchange, sourcelist + "", // not interested in query + searchfilter, + language, + lastchange, + sourcelist ); return query @@ -507,34 +789,45 @@ public static Query WineWhereExpression( .LastChangedFilter(lastchange) .CompanyIdFilter(companyid) .WineIdFilter(wineid) - .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) - .OdhActiveFilter_GeneratedColumn(odhactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) + .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) + .OdhActiveFilter_GeneratedColumn(odhactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) .SourceFilter_GeneratedColumn(sourcelist) .When(filterClosedData, q => q.FilterClosedData_GeneratedColumn()); } //Return Where and Parameters for WebCamInfo public static Query WebCamInfoWhereExpression( - this Query query, IReadOnlyCollection languagelist, - IReadOnlyCollection idlist, IReadOnlyCollection sourcelist, - bool? activefilter, bool? smgactivefilter, - IReadOnlyCollection publishedonlist, - string? searchfilter, string? language, string? lastchange, bool filterClosedData, bool reducedData) + this Query query, + IReadOnlyCollection languagelist, + IReadOnlyCollection idlist, + IReadOnlyCollection sourcelist, + bool? activefilter, + bool? smgactivefilter, + IReadOnlyCollection publishedonlist, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData, + bool reducedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - idlist, sourcelist, + "", // not interested in query + idlist, + sourcelist, activefilter, - smgactivefilter, searchfilter, - language, lastchange + smgactivefilter, + searchfilter, + language, + lastchange ); return query .IdUpperFilter(idlist) .SyncSourceInterfaceFilter_GeneratedColumn(sourcelist) - .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) - .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) + .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) + .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) .PublishedOnFilter(publishedonlist) .SearchFilter(WebcamnameFieldsToSearchFor(language), searchfilter) .LastChangedFilter_GeneratedColumn(lastchange) @@ -543,24 +836,37 @@ public static Query WebCamInfoWhereExpression( } public static Query WeatherHistoryWhereExpression( - this Query query, IReadOnlyCollection languagelist, - IReadOnlyCollection idlist, IReadOnlyCollection sourcelist, - DateTime? begindate, DateTime? enddate, string? searchfilter, - string? language, string? lastchange, bool filterClosedData) + this Query query, + IReadOnlyCollection languagelist, + IReadOnlyCollection idlist, + IReadOnlyCollection sourcelist, + DateTime? begindate, + DateTime? enddate, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - idlist, sourcelist, + "", // not interested in query + idlist, + sourcelist, begindate, - enddate, searchfilter, - language, lastchange + enddate, + searchfilter, + language, + lastchange ); return query .IdUpperFilter(idlist) .SyncSourceInterfaceFilter_GeneratedColumn(sourcelist) - .When(languagelist.Count > 0, q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist)) + .When( + languagelist.Count > 0, + q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist) + ) .SearchFilter(WeatherHistoryFieldsToSearchFor(language), searchfilter) .LastChangedFilter_GeneratedColumn(begindate, enddate) .LastChangedFilter_GeneratedColumn(lastchange) @@ -569,21 +875,38 @@ public static Query WeatherHistoryWhereExpression( //Return Where and Parameters for Measuringpoint public static Query MeasuringpointWhereExpression( - this Query query, - IReadOnlyCollection idlist, IReadOnlyCollection districtlist, - IReadOnlyCollection municipalitylist, IReadOnlyCollection tourismvereinlist, - IReadOnlyCollection regionlist, IReadOnlyCollection arealist, - bool? activefilter, bool? smgactivefilter, - IReadOnlyCollection publishedonlist, IReadOnlyCollection sourcelist, - string? searchfilter, string? language, string? lastchange, bool filterClosedData, bool reducedData) + this Query query, + IReadOnlyCollection idlist, + IReadOnlyCollection districtlist, + IReadOnlyCollection municipalitylist, + IReadOnlyCollection tourismvereinlist, + IReadOnlyCollection regionlist, + IReadOnlyCollection arealist, + bool? activefilter, + bool? smgactivefilter, + IReadOnlyCollection publishedonlist, + IReadOnlyCollection sourcelist, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData, + bool reducedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - idlist, districtlist, municipalitylist, tourismvereinlist, regionlist, - arealist, activefilter, - smgactivefilter, searchfilter, - language, lastchange + "", // not interested in query + idlist, + districtlist, + municipalitylist, + tourismvereinlist, + regionlist, + arealist, + activefilter, + smgactivefilter, + searchfilter, + language, + lastchange ); return query @@ -593,11 +916,11 @@ public static Query MeasuringpointWhereExpression( .LocFilterTvsFilter(tourismvereinlist) .LocFilterRegionFilter(regionlist) .AreaFilterMeasuringpoints(arealist) - .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) - .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) + .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.ActiveFilter(activefilter) + .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) .PublishedOnFilter(publishedonlist) - .SearchFilter(new string[1]{ $"Shortname" }, searchfilter) //Search only Shortname Field - .LastChangedFilter_GeneratedColumn(lastchange) //.LastChangedFilter(lastchange) + .SearchFilter(new string[1] { $"Shortname" }, searchfilter) //Search only Shortname Field + .LastChangedFilter_GeneratedColumn(lastchange) //.LastChangedFilter(lastchange) .SourceFilter_GeneratedColumn(sourcelist) //.When(filterClosedData, q => q.FilterClosedData_GeneratedColumn()); .Anonymous_Logged_UserRule_GeneratedColumn(filterClosedData, !reducedData); @@ -605,22 +928,37 @@ public static Query MeasuringpointWhereExpression( //Return Where and Parameters for Eventshort public static Query EventShortWhereExpression( - this Query query, - IReadOnlyCollection idlist, IReadOnlyCollection sourcelist, - IReadOnlyCollection eventlocationlist, IReadOnlyCollection webaddresslist, - string? activefilter, bool? websiteactivefilter, bool? communityactivefilter, - DateTime? start, DateTime? end, + this Query query, + IReadOnlyCollection idlist, + IReadOnlyCollection sourcelist, + IReadOnlyCollection eventlocationlist, + IReadOnlyCollection webaddresslist, + string? activefilter, + bool? websiteactivefilter, + bool? communityactivefilter, + DateTime? start, + DateTime? end, IReadOnlyCollection publishedonlist, string? searchfilter, - string? language, string? lastchange, bool filterClosedData, bool getbyrooms = false) + string? language, + string? lastchange, + bool filterClosedData, + bool getbyrooms = false + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - idlist, sourcelist, eventlocationlist, webaddresslist, - activefilter, start, end, + "", // not interested in query + idlist, + sourcelist, + eventlocationlist, + webaddresslist, + activefilter, + start, + end, searchfilter, - language, lastchange + language, + lastchange ); return query @@ -629,7 +967,7 @@ public static Query EventShortWhereExpression( .EventShortLocationFilter(eventlocationlist) .EventShortWebaddressFilter(webaddresslist) //.ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.EventShortActiveFilter(activefilter) - //.OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) + //.OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.SmgActiveFilter(smgactivefilter) .EventShortActiveFilter(activefilter) .EventShortWebsiteActiveFilter(websiteactivefilter) .EventShortCommunityActiveFilter(communityactivefilter) @@ -647,29 +985,59 @@ public static Query EventShortWhereExpression( //Return Where and Parameters for Venue public static Query VenueWhereExpression( - this Query query, IReadOnlyCollection languagelist, - IReadOnlyCollection idlist, IReadOnlyCollection categorylist, - IReadOnlyCollection featurelist, IReadOnlyCollection setuptypelist, - IReadOnlyCollection smgtaglist, IReadOnlyCollection districtlist, - IReadOnlyCollection municipalitylist, IReadOnlyCollection tourismvereinlist, - IReadOnlyCollection regionlist, IReadOnlyCollection sourcelist, - bool capacity, int capacitymin, int capacitymax, bool roomcount, int roomcountmin, int roomcountmax, - bool? activefilter, bool? smgactivefilter, - IReadOnlyCollection publishedonlist, - string? searchfilter, string? language, string? lastchange, bool filterClosedData, bool reducedData) + this Query query, + IReadOnlyCollection languagelist, + IReadOnlyCollection idlist, + IReadOnlyCollection categorylist, + IReadOnlyCollection featurelist, + IReadOnlyCollection setuptypelist, + IReadOnlyCollection smgtaglist, + IReadOnlyCollection districtlist, + IReadOnlyCollection municipalitylist, + IReadOnlyCollection tourismvereinlist, + IReadOnlyCollection regionlist, + IReadOnlyCollection sourcelist, + bool capacity, + int capacitymin, + int capacitymax, + bool roomcount, + int roomcountmin, + int roomcountmax, + bool? activefilter, + bool? smgactivefilter, + IReadOnlyCollection publishedonlist, + string? searchfilter, + string? language, + string? lastchange, + bool filterClosedData, + bool reducedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - idlist, categorylist, - featurelist, setuptypelist, - smgtaglist, districtlist, - municipalitylist, tourismvereinlist, - regionlist, sourcelist, languagelist, capacity, - capacitymin, capacitymax, roomcount, - roomcountmin, roomcountmax, activefilter, - smgactivefilter, searchfilter, - language, lastchange + "", // not interested in query + idlist, + categorylist, + featurelist, + setuptypelist, + smgtaglist, + districtlist, + municipalitylist, + tourismvereinlist, + regionlist, + sourcelist, + languagelist, + capacity, + capacitymin, + capacitymax, + roomcount, + roomcountmin, + roomcountmax, + activefilter, + smgactivefilter, + searchfilter, + language, + lastchange ); //TODO @@ -679,16 +1047,19 @@ public static Query VenueWhereExpression( .VenueLocFilterMunicipalityFilter(municipalitylist) .VenueLocFilterTvsFilter(tourismvereinlist) .VenueLocFilterRegionFilter(regionlist) - .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.VenueActiveFilter(activefilter) - .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.VenueODHActiveFilter(smgactivefilter) + .ActiveFilter_GeneratedColumn(activefilter) //OK GENERATED COLUMNS //.VenueActiveFilter(activefilter) + .OdhActiveFilter_GeneratedColumn(smgactivefilter) //OK GENERATED COLUMNS //.VenueODHActiveFilter(smgactivefilter) .VenueCategoryFilter(categorylist) .VenueFeatureFilter(featurelist) .VenueSetupTypeFilter(setuptypelist) .VenueRoomCountFilter(roomcount, roomcountmin, roomcountmax) - .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.VenueODHTagFilter(smgtaglist) - .LastChangedFilter_GeneratedColumn(lastchange) //.VenueLastChangedFilter(lastchange) + .When(smgtaglist.Count > 0, q => q.SmgTagFilterOr_GeneratedColumn(smgtaglist)) //OK GENERATED COLUMNS //.VenueODHTagFilter(smgtaglist) + .LastChangedFilter_GeneratedColumn(lastchange) //.VenueLastChangedFilter(lastchange) .VenueSourceFilter(sourcelist) - .When(languagelist.Count > 0, q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist)) //.VenueHasLanguageFilter(languagelist) + .When( + languagelist.Count > 0, + q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist) + ) //.VenueHasLanguageFilter(languagelist) //TODO //.VenueCapacityFilter(capacity, capacitymin, capacitymax) .PublishedOnFilter(publishedonlist) @@ -698,18 +1069,24 @@ public static Query VenueWhereExpression( .Anonymous_Logged_UserRule_GeneratedColumn(filterClosedData, !reducedData); } - //Return Where and Parameters for AlpineBits public static Query AlpineBitsWhereExpression( this Query query, - IReadOnlyCollection idlist, IReadOnlyCollection sourcelist, - IReadOnlyCollection accommodationIds, IReadOnlyCollection messagetypelist, - string? requestdate) + IReadOnlyCollection idlist, + IReadOnlyCollection sourcelist, + IReadOnlyCollection accommodationIds, + IReadOnlyCollection messagetypelist, + string? requestdate + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - idlist, sourcelist, accommodationIds, messagetypelist, requestdate + "", // not interested in query + idlist, + sourcelist, + accommodationIds, + messagetypelist, + requestdate ); return query @@ -721,14 +1098,25 @@ public static Query AlpineBitsWhereExpression( //Return Where and Parameters for Wine public static Query ODHTagWhereExpression( - this Query query, IReadOnlyCollection languagelist, IReadOnlyCollection mainentitylist, IReadOnlyCollection validforentitylist, IReadOnlyCollection sourcelist, bool? displayascategory, - string? searchfilter, string? language, bool filterClosedData) + this Query query, + IReadOnlyCollection languagelist, + IReadOnlyCollection mainentitylist, + IReadOnlyCollection validforentitylist, + IReadOnlyCollection sourcelist, + bool? displayascategory, + string? searchfilter, + string? language, + bool filterClosedData + ) { LogMethodInfo( System.Reflection.MethodBase.GetCurrentMethod()!, - "", // not interested in query - searchfilter, language, validforentitylist, - mainentitylist, displayascategory + "", // not interested in query + searchfilter, + language, + validforentitylist, + mainentitylist, + displayascategory ); return query @@ -741,6 +1129,5 @@ public static Query ODHTagWhereExpression( .SourceFilter_GeneratedColumn(sourcelist) .When(filterClosedData, q => q.FilterClosedData_GeneratedColumn()); } - } } diff --git a/Helper/PostgresLicenseCountHelper.cs b/Helper/PostgresLicenseCountHelper.cs index 1364681f0..bf59d9a7a 100644 --- a/Helper/PostgresLicenseCountHelper.cs +++ b/Helper/PostgresLicenseCountHelper.cs @@ -12,16 +12,18 @@ public class PostgresLicenseCountHelper { public static async Task GetTotalCount(QueryFactory QueryFactory, string tablename) { - var query = QueryFactory.Query() - .SelectRaw("id") - .From(tablename); + var query = QueryFactory.Query().SelectRaw("id").From(tablename); return await query.CountAsync(); } - public static async Task GetTotalCountOpendata(QueryFactory QueryFactory, string tablename) + public static async Task GetTotalCountOpendata( + QueryFactory QueryFactory, + string tablename + ) { - var query = QueryFactory.Query() + var query = QueryFactory + .Query() .SelectRaw("id") .From(tablename) .WhereRaw("gen_licenseinfo_closeddata IS NULL") @@ -34,27 +36,34 @@ public static async Task GetTotalCountCC0(QueryFactory QueryFactory, strin { //string whereexpression = "data @> '{\"LicenseInfo\": { \"License\": \"CC0\" } }'"; - var query = QueryFactory.Query() + var query = QueryFactory + .Query() .SelectRaw("id") .From(tablename) .WhereInJsonb( new List() { "CC0" }, - tag => new { LicenseInfo = new[] { new { License = tag } } }); + tag => new { LicenseInfo = new[] { new { License = tag } } } + ); return await query.CountAsync(); } - public static async Task GetAllDataWithCC0Image(QueryFactory QueryFactory, string tablename) + public static async Task GetAllDataWithCC0Image( + QueryFactory QueryFactory, + string tablename + ) { //string whereexpression = "data @> {\"ImageGallery\": [{ \"License\": \"CC0\" }] }"; //Works but obsolete - var query = QueryFactory.Query() + var query = QueryFactory + .Query() .SelectRaw("id") .From(tablename) .WhereInJsonb( new List() { "CC0" }, - tag => new { ImageGallery = new[] { new { License = tag } } }); + tag => new { ImageGallery = new[] { new { License = tag } } } + ); //always returning 0 //var query = QueryFactory.Query() @@ -68,9 +77,11 @@ public static async Task GetAllDataWithCC0Image(QueryFactory QueryFactory, return await query.CountAsync(); } - public static async Task GetAllImagesWithCC0License(QueryFactory QueryFactory, string tablename) + public static async Task GetAllImagesWithCC0License( + QueryFactory QueryFactory, + string tablename + ) { - //select count(result1) from(select jsonb_array_elements(data-> 'ImageGallery') as result1 from accommodations where //data @> '{ "ImageGallery": [{ "License": "CC0" }] }') as subsel where result1 ->> 'License' like 'CC0' @@ -78,30 +89,37 @@ public static async Task GetAllImagesWithCC0License(QueryFactory QueryFact // .Select("Id") // .Select(q => q.From("Visits").Where("UserId", 10).Count(), "VisitsCount"); - var subquery = QueryFactory.Query() + var subquery = QueryFactory + .Query() .SelectRaw("jsonb_array_elements(data -> 'ImageGallery') as result1") .From(tablename) .WhereInJsonb( new List() { "CC0" }, - tag => new { ImageGallery = new[] { new { License = tag } } }); + tag => new { ImageGallery = new[] { new { License = tag } } } + ); - var query = QueryFactory.Query() + var query = QueryFactory + .Query() .Select(subquery, "result1") .From(subquery, "subsel") .WhereRaw("result1 ->> 'License' like 'CC0'"); - return await query.CountAsync(); } - public static async Task GetAllImagesWithNONCC0License(QueryFactory QueryFactory, string tablename) + public static async Task GetAllImagesWithNONCC0License( + QueryFactory QueryFactory, + string tablename + ) { - var subquery = QueryFactory.Query() + var subquery = QueryFactory + .Query() .SelectRaw("jsonb_array_elements(data -> 'ImageGallery') as result1") .From(tablename) .WhereRaw("data ->> 'ImageGallery' is not null AND data -> 'ImageGallery' != '[]'"); - var query = QueryFactory.Query() + var query = QueryFactory + .Query() .Select(subquery, "result1") .From(subquery, "subsel") .WhereRaw("result1 ->> 'License' not like 'CC0' OR result1 ->> 'License' is null"); diff --git a/Helper/PushServer/PushServerMessageHelper.cs b/Helper/PushServer/PushServerMessageHelper.cs index 6f6d8b0f7..9a6984469 100644 --- a/Helper/PushServer/PushServerMessageHelper.cs +++ b/Helper/PushServer/PushServerMessageHelper.cs @@ -9,7 +9,14 @@ namespace Helper { public class PushServerMessageHelper { - public static PushServerMessage GetPuhServerMessage(string title, string text, string language, string group, string? image = null, string? video = null) + public static PushServerMessage GetPuhServerMessage( + string title, + string text, + string language, + string group, + string? image = null, + string? video = null + ) { var message = new PushServerMessage(); message.text = text; diff --git a/Helper/Reduced/ReduceDataHelper.cs b/Helper/Reduced/ReduceDataHelper.cs index 510c936ab..77fb6e435 100644 --- a/Helper/Reduced/ReduceDataHelper.cs +++ b/Helper/Reduced/ReduceDataHelper.cs @@ -19,22 +19,76 @@ public static bool ReduceDataCheck(T myobject) where T : ISource, ILicenseInf { return myobject switch { - Accommodation or AccommodationLinked => myobject.Source != null ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData ? true : false : false, - LTSActivity or LTSActivityLinked => myobject.Source != null ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData ? true : false : false, - LTSPoi or LTSPoiLinked => myobject.Source != null ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData ? true : false : false, - Gastronomy or GastronomyLinked => myobject.Source != null ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData ? true : false : false, - Event or EventLinked => myobject.Source != null ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData ? true : false : false, - ODHActivityPoi or ODHActivityPoiLinked => myobject.Source != null ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData ? true : false : false, - Measuringpoint or MeasuringpointLinked => myobject.Source != null ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData ? true : false : false, - WebcamInfo or WebcamInfoLinked => myobject.Source != null ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData ? true : false : false, - DDVenue => myobject.Source != null ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData ? true : false : false, + Accommodation + or AccommodationLinked + => myobject.Source != null + ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData + ? true + : false + : false, + LTSActivity + or LTSActivityLinked + => myobject.Source != null + ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData + ? true + : false + : false, + LTSPoi + or LTSPoiLinked + => myobject.Source != null + ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData + ? true + : false + : false, + Gastronomy + or GastronomyLinked + => myobject.Source != null + ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData + ? true + : false + : false, + Event + or EventLinked + => myobject.Source != null + ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData + ? true + : false + : false, + ODHActivityPoi + or ODHActivityPoiLinked + => myobject.Source != null + ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData + ? true + : false + : false, + Measuringpoint + or MeasuringpointLinked + => myobject.Source != null + ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData + ? true + : false + : false, + WebcamInfo + or WebcamInfoLinked + => myobject.Source != null + ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData + ? true + : false + : false, + DDVenue + => myobject.Source != null + ? myobject.Source.ToLower() == "lts" && !myobject.LicenseInfo.ClosedData + ? true + : false + : false, _ => false }; } - //LTS ActivityData - public static LTSActivityLinkedReduced CopyLTSActivityToReducedObject(LTSActivityLinked myactivity) + public static LTSActivityLinkedReduced CopyLTSActivityToReducedObject( + LTSActivityLinked myactivity + ) { var reduced = new LTSActivityLinkedReduced(); @@ -61,11 +115,16 @@ public static LTSActivityLinkedReduced CopyLTSActivityToReducedObject(LTSActivit //Name reduced.Detail = ReducedDataHelper.ReduceDetailInfo(myactivity.Detail); //ContactInfo/URL - reduced.ContactInfos = ReducedDataHelper.ReduceContactInfoForActivity(myactivity.ContactInfos); + reduced.ContactInfos = ReducedDataHelper.ReduceContactInfoForActivity( + myactivity.ContactInfos + ); //Tag reduced.SmgTags = myactivity.SmgTags; - reduced.LTSTags = myactivity.LTSTags != null ? ReducedDataHelper.ReduceLtsTags(myactivity.LTSTags).ToList() : null; + reduced.LTSTags = + myactivity.LTSTags != null + ? ReducedDataHelper.ReduceLtsTags(myactivity.LTSTags).ToList() + : null; //ODH Fields reduced.Shortname = myactivity.Shortname; @@ -83,11 +142,19 @@ public static LTSActivityLinkedReduced CopyLTSActivityToReducedObject(LTSActivit reduced.HasLanguage = myactivity.HasLanguage; ///LocationInfo, ODH Object calculated with - reduced.LocationInfo = ReducedDataHelper.RemoveAreafromLocationInfo(myactivity.LocationInfo); + reduced.LocationInfo = ReducedDataHelper.RemoveAreafromLocationInfo( + myactivity.LocationInfo + ); //License + Meta reduced.LicenseInfo = myactivity.LicenseInfo; - reduced._Meta = MetadataHelper.GetMetadata(reduced.Id, "ltsactivity", "lts", reduced.LastChange, true); + reduced._Meta = MetadataHelper.GetMetadata( + reduced.Id, + "ltsactivity", + "lts", + reduced.LastChange, + true + ); //reduced.PublishedOn = HelperClass.GetPublishenOnList("ltsactivity", reduced.SmgActive); return reduced; @@ -103,14 +170,17 @@ public static LTSPoiLinkedReduced CopyLTSPoiToReducedObject(LTSPoiLinked mypoi) reduced.HasFreeEntrance = mypoi.HasFreeEntrance; //Features/HasFreeEntrance //Position/Longitude,Latitude,Altitude reduced.GpsInfo = mypoi.GpsInfo; - //reduced.GpsPoints = mypoi.GpsPoints; + //reduced.GpsPoints = mypoi.GpsPoints; reduced.Detail = ReducedDataHelper.ReduceDetailInfo(mypoi.Detail); reduced.ContactInfos = ReducedDataHelper.ReduceContactInfoForPoi(mypoi.ContactInfos); //Tag reduced.SmgTags = mypoi.SmgTags; - reduced.LTSTags = mypoi.LTSTags != null ? ReducedDataHelper.ReduceLtsTags(mypoi.LTSTags).ToList() : null; + reduced.LTSTags = + mypoi.LTSTags != null + ? ReducedDataHelper.ReduceLtsTags(mypoi.LTSTags).ToList() + : null; //ODH Fields reduced.Active = mypoi.Active; @@ -130,14 +200,22 @@ public static LTSPoiLinkedReduced CopyLTSPoiToReducedObject(LTSPoiLinked mypoi) //License + Meta reduced.LicenseInfo = mypoi.LicenseInfo; - reduced._Meta = MetadataHelper.GetMetadata(reduced.Id, "ltspoi", "lts", reduced.LastChange, true); + reduced._Meta = MetadataHelper.GetMetadata( + reduced.Id, + "ltspoi", + "lts", + reduced.LastChange, + true + ); //reduced.PublishedOn = HelperClass.GetPublishenOnList("ltspoi", reduced.SmgActive); return reduced; } //LTS Gastronomic Data ACTIVE: (IsEnabled=1 and RepresentationRestricition=1) - public static GastronomyLinkedReduced CopyLTSGastronomyToReducedObject(GastronomyLinked mypoi) + public static GastronomyLinkedReduced CopyLTSGastronomyToReducedObject( + GastronomyLinked mypoi + ) { var reduced = new GastronomyLinkedReduced(); @@ -152,9 +230,11 @@ public static GastronomyLinkedReduced CopyLTSGastronomyToReducedObject(Gastronom //ContactInfo/CompanyName reduced.Detail = ReducedDataHelper.ReduceDetailInfo(mypoi.Detail); //ContactInfo/CompanyName - reduced.ContactInfos = ReducedDataHelper.ReduceContactInfoForGastronomy(mypoi.ContactInfos); + reduced.ContactInfos = ReducedDataHelper.ReduceContactInfoForGastronomy( + mypoi.ContactInfos + ); - //CategoryCodes/GastronomicCategory + //CategoryCodes/GastronomicCategory reduced.CategoryCodes = mypoi.CategoryCodes; //ODH Fields @@ -171,14 +251,22 @@ public static GastronomyLinkedReduced CopyLTSGastronomyToReducedObject(Gastronom //License + Meta reduced.LicenseInfo = mypoi.LicenseInfo; - reduced._Meta = MetadataHelper.GetMetadata(reduced.Id, "ltsgastronomy", "lts", reduced.LastChange, true); + reduced._Meta = MetadataHelper.GetMetadata( + reduced.Id, + "ltsgastronomy", + "lts", + reduced.LastChange, + true + ); //reduced.PublishedOn = HelperClass.GetPublishenOnList("ltsgastronomy", reduced.SmgActive); return reduced; } //LTS PoiData ActivityData - public static LTSODHActivityPoiReduced CopyLTSODHActivtyPoiToReducedObject(ODHActivityPoiLinked mypoi) + public static LTSODHActivityPoiReduced CopyLTSODHActivtyPoiToReducedObject( + ODHActivityPoiLinked mypoi + ) { var reduced = new LTSODHActivityPoiReduced(); @@ -217,13 +305,19 @@ public static LTSODHActivityPoiReduced CopyLTSODHActivtyPoiToReducedObject(ODHAc //Tag reduced.SmgTags = mypoi.SmgTags; - reduced.LTSTags = mypoi.LTSTags != null ? ReducedDataHelper.ReduceLtsTags(mypoi.LTSTags).ToList() : null; + reduced.LTSTags = + mypoi.LTSTags != null + ? ReducedDataHelper.ReduceLtsTags(mypoi.LTSTags).ToList() + : null; //Tagging reduced.Tags = mypoi.Tags; reduced.Detail = ReducedDataHelper.ReduceDetailInfo(mypoi.Detail); - reduced.ContactInfos = ReducedDataHelper.ReduceContactInfoForODHActivityPoi(mypoi.ContactInfos, mypoi.SyncSourceInterface); + reduced.ContactInfos = ReducedDataHelper.ReduceContactInfoForODHActivityPoi( + mypoi.ContactInfos, + mypoi.SyncSourceInterface + ); //Position/Longitude,Latitude,Altitude //reduced.GpsPoints = mypoi.GpsPoints; @@ -251,20 +345,30 @@ public static LTSODHActivityPoiReduced CopyLTSODHActivtyPoiToReducedObject(ODHAc //License + Meta reduced.LicenseInfo = mypoi.LicenseInfo; - reduced._Meta = MetadataHelper.GetMetadata(reduced.Id, "odhactivitypoi", reduced.Source?.ToLower(), reduced.LastChange, true); + reduced._Meta = MetadataHelper.GetMetadata( + reduced.Id, + "odhactivitypoi", + reduced.Source?.ToLower(), + reduced.LastChange, + true + ); reduced.PublishedOn = mypoi.PublishedOn; return reduced; } //LTS Accommodation OK ACTIVE (IDMActive=1) - public static AccommodationLinkedReduced CopyLTSAccommodationToReducedObject(AccommodationLinked myacco) + public static AccommodationLinkedReduced CopyLTSAccommodationToReducedObject( + AccommodationLinked myacco + ) { var reduced = new AccommodationLinkedReduced(); reduced.Id = myacco.Id + "_REDUCED"; - reduced.AccoDetail = ReducedDataHelper.ReduceAccoDetail(myacco.AccoDetail ?? new Dictionary()); + reduced.AccoDetail = ReducedDataHelper.ReduceAccoDetail( + myacco.AccoDetail ?? new Dictionary() + ); //A1GEP, A1GNP, A0Alt reduced.Gpstype = myacco.Gpstype; @@ -279,7 +383,7 @@ public static AccommodationLinkedReduced CopyLTSAccommodationToReducedObject(Acc //A0App reduced.HasApartment = myacco.HasApartment; - //fix + //fix reduced.IsBookable = false; //T6RID @@ -297,11 +401,19 @@ public static AccommodationLinkedReduced CopyLTSAccommodationToReducedObject(Acc reduced.Source = myacco.Source; ///LocationInfo, ODH Object calculated with - reduced.LocationInfo = ReducedDataHelper.RemoveAreafromLocationInfo(myacco.LocationInfo); + reduced.LocationInfo = ReducedDataHelper.RemoveAreafromLocationInfo( + myacco.LocationInfo + ); //License + Meta reduced.LicenseInfo = myacco.LicenseInfo; - reduced._Meta = MetadataHelper.GetMetadata(reduced.Id, "accommodation", "lts", reduced.LastChange, true); + reduced._Meta = MetadataHelper.GetMetadata( + reduced.Id, + "accommodation", + "lts", + reduced.LastChange, + true + ); reduced.PublishedOn = myacco.PublishedOn; return reduced; @@ -325,7 +437,9 @@ public static EventLinkedReduced CopyLTSEventToReducedObject(EventLinked myevent //DefinitionLng/Title reduced.Detail = ReducedDataHelper.ReduceDetailInfo(myevent.Detail); - reduced.ContactInfos = ReducedDataHelper.ReduceContactInfoForEvent(myevent.ContactInfos); + reduced.ContactInfos = ReducedDataHelper.ReduceContactInfoForEvent( + myevent.ContactInfos + ); //Day/Date, DateTo, SingleDays, Begin, End reduced.DateBegin = myevent.DateBegin; @@ -336,10 +450,15 @@ public static EventLinkedReduced CopyLTSEventToReducedObject(EventLinked myevent reduced.Ticket = reduced.Ticket; //BookingData/BookingUrl - reduced.EventBooking = myevent.EventBooking != null ? ReducedDataHelper.ReduceEventBooking(myevent.EventBooking) : null; + reduced.EventBooking = + myevent.EventBooking != null + ? ReducedDataHelper.ReduceEventBooking(myevent.EventBooking) + : null; //Evendate - reduced.EventDate = ReducedDataHelper.ReduceEventDateCollection(myevent.EventDate ?? new List()); + reduced.EventDate = ReducedDataHelper.ReduceEventDateCollection( + myevent.EventDate ?? new List() + ); //ODH Fields reduced.Active = myevent.Active; @@ -351,18 +470,28 @@ public static EventLinkedReduced CopyLTSEventToReducedObject(EventLinked myevent reduced.Source = myevent.Source; ///LocationInfo, ODH Object calculated with - reduced.LocationInfo = ReducedDataHelper.RemoveAreafromLocationInfo(myevent.LocationInfo); + reduced.LocationInfo = ReducedDataHelper.RemoveAreafromLocationInfo( + myevent.LocationInfo + ); //License + Meta reduced.LicenseInfo = myevent.LicenseInfo; - reduced._Meta = MetadataHelper.GetMetadata(reduced.Id, "event", "lts", reduced.LastChange, true); + reduced._Meta = MetadataHelper.GetMetadata( + reduced.Id, + "event", + "lts", + reduced.LastChange, + true + ); reduced.PublishedOn = myevent.PublishedOn; return reduced; } //LTS Measuringpoint (Status/IsEnabled=1) - public static MeasuringpointLinkedReduced CopyLTSMeasuringpointToReducedObject(MeasuringpointLinked measuringpoint) + public static MeasuringpointLinkedReduced CopyLTSMeasuringpointToReducedObject( + MeasuringpointLinked measuringpoint + ) { var reduced = new MeasuringpointLinkedReduced(); @@ -390,18 +519,25 @@ public static MeasuringpointLinkedReduced CopyLTSMeasuringpointToReducedObject(M //Snow / DateLastSnow reduced.LastSnowDate = measuringpoint.LastSnowDate; - //ODH Fields reduced.Active = measuringpoint.Active; reduced.SmgActive = measuringpoint.SmgActive; reduced.LastChange = measuringpoint.LastChange; reduced.FirstImport = measuringpoint.FirstImport; - reduced.LocationInfo = ReducedDataHelper.RemoveAreafromLocationInfo(measuringpoint.LocationInfo); + reduced.LocationInfo = ReducedDataHelper.RemoveAreafromLocationInfo( + measuringpoint.LocationInfo + ); reduced.Source = measuringpoint.Source; //License + Meta reduced.LicenseInfo = measuringpoint.LicenseInfo; - reduced._Meta = MetadataHelper.GetMetadata(reduced.Id, "measuringpoint", "lts", reduced.LastChange, true); + reduced._Meta = MetadataHelper.GetMetadata( + reduced.Id, + "measuringpoint", + "lts", + reduced.LastChange, + true + ); reduced.PublishedOn = measuringpoint.PublishedOn; return reduced; @@ -424,41 +560,56 @@ public static DDVenueReduced CopyLTSVenueToReducedObject(DDVenue venue) if (reduced.relationships != null) { reduced.relationships.multimediaDescriptions = null; - reduced.relationships.subVenues = venue.relationships?.subVenues != null ? ReducedDataHelper.ReduceSubVenues(venue.relationships.subVenues) : null; + reduced.relationships.subVenues = + venue.relationships?.subVenues != null + ? ReducedDataHelper.ReduceSubVenues(venue.relationships.subVenues) + : null; } reduced.odhdata = new ODHData(); - if (venue.odhdata is { }) - { - //ODH Fields TODO - reduced.odhdata.Active = venue.odhdata.Active; - reduced.odhdata.ODHActive = venue.odhdata.ODHActive; - reduced.odhdata.Shortname = venue.odhdata.Shortname; - reduced.odhdata.SmgTags = venue.odhdata.SmgTags; - reduced.odhdata.HasLanguage = venue.odhdata.HasLanguage; - reduced.odhdata.Source = venue.odhdata.Source; - reduced.odhdata.GpsInfo = ReducedDataHelper.ReduceGpsInfo(venue.odhdata.GpsInfo); - reduced.odhdata.GpsPoints = venue.odhdata.GpsPoints; - reduced.odhdata.RoomCount = venue.odhdata.RoomCount; - reduced.odhdata.SyncSourceInterface = venue.odhdata.SyncSourceInterface; - reduced.odhdata.VenueCategory = venue.odhdata.VenueCategory; - reduced.odhdata.RoomDetails = ReducedDataHelper.ReduceVenueRoomDetails(venue.odhdata.RoomDetails); + if (venue.odhdata is { }) + { + //ODH Fields TODO + reduced.odhdata.Active = venue.odhdata.Active; + reduced.odhdata.ODHActive = venue.odhdata.ODHActive; + reduced.odhdata.Shortname = venue.odhdata.Shortname; + reduced.odhdata.SmgTags = venue.odhdata.SmgTags; + reduced.odhdata.HasLanguage = venue.odhdata.HasLanguage; + reduced.odhdata.Source = venue.odhdata.Source; + reduced.odhdata.GpsInfo = ReducedDataHelper.ReduceGpsInfo(venue.odhdata.GpsInfo); + reduced.odhdata.GpsPoints = venue.odhdata.GpsPoints; + reduced.odhdata.RoomCount = venue.odhdata.RoomCount; + reduced.odhdata.SyncSourceInterface = venue.odhdata.SyncSourceInterface; + reduced.odhdata.VenueCategory = venue.odhdata.VenueCategory; + reduced.odhdata.RoomDetails = ReducedDataHelper.ReduceVenueRoomDetails( + venue.odhdata.RoomDetails + ); } ///LocationInfo, ODH Object calculated with - reduced.odhdata.LocationInfo = ReducedDataHelper.RemoveAreafromLocationInfo(reduced.odhdata.LocationInfo); + reduced.odhdata.LocationInfo = ReducedDataHelper.RemoveAreafromLocationInfo( + reduced.odhdata.LocationInfo + ); //License + Meta reduced.odhdata.LicenseInfo = venue.odhdata?.LicenseInfo; - reduced._Meta = MetadataHelper.GetMetadata(reduced.Id, "venue", "lts", reduced.LastChange, true); + reduced._Meta = MetadataHelper.GetMetadata( + reduced.Id, + "venue", + "lts", + reduced.LastChange, + true + ); reduced.odhdata.PublishedOn = venue.odhdata?.PublishedOn; return reduced; } //LTS WebcamInfo - public static WebcamInfoLinkedReduced CopyLTSWebcamInfoToReducedObject(WebcamInfoLinked webcam) + public static WebcamInfoLinkedReduced CopyLTSWebcamInfoToReducedObject( + WebcamInfoLinked webcam + ) { var reduced = new WebcamInfoLinkedReduced(); @@ -469,7 +620,7 @@ public static WebcamInfoLinkedReduced CopyLTSWebcamInfoToReducedObject(WebcamInf reduced.Webcamurl = webcam.Webcamurl; reduced.Streamurl = webcam.Streamurl; - //ODH Fields + //ODH Fields reduced.Active = webcam.Active; reduced.SmgActive = webcam.SmgActive; reduced.LastChange = webcam.LastChange; @@ -479,18 +630,24 @@ public static WebcamInfoLinkedReduced CopyLTSWebcamInfoToReducedObject(WebcamInf //License + Meta reduced.LicenseInfo = webcam.LicenseInfo; - reduced._Meta = MetadataHelper.GetMetadata(reduced.Id, "webcam", "lts", reduced.LastChange, true); + reduced._Meta = MetadataHelper.GetMetadata( + reduced.Id, + "webcam", + "lts", + reduced.LastChange, + true + ); reduced.PublishedOn = webcam.PublishedOn; return reduced; } - - } public class ReducedDataHelper { - public static IDictionary ReduceDetailInfo(IDictionary mydetail) + public static IDictionary ReduceDetailInfo( + IDictionary mydetail + ) { foreach (var value in mydetail.Values) { @@ -517,7 +674,9 @@ public static IDictionary ReduceDetailInfo(IDictionary ReduceContactInfoForActivity(IDictionary mycontactinfo) + public static IDictionary ReduceContactInfoForActivity( + IDictionary mycontactinfo + ) { foreach (var value in mycontactinfo.Values) { @@ -542,7 +701,9 @@ public static IDictionary ReduceContactInfoForActivity(IDi return mycontactinfo; } - public static IDictionary ReduceContactInfoForPoi(IDictionary mycontactinfo) + public static IDictionary ReduceContactInfoForPoi( + IDictionary mycontactinfo + ) { foreach (var value in mycontactinfo.Values) { @@ -567,7 +728,10 @@ public static IDictionary ReduceContactInfoForPoi(IDiction return mycontactinfo; } - public static IDictionary ReduceContactInfoForODHActivityPoi(IDictionary mycontactinfo, string? source) + public static IDictionary ReduceContactInfoForODHActivityPoi( + IDictionary mycontactinfo, + string? source + ) { foreach (var value in mycontactinfo.Values) { @@ -594,8 +758,9 @@ public static IDictionary ReduceContactInfoForODHActivityP return mycontactinfo; } - - public static IDictionary ReduceContactInfoForEvent(IDictionary mycontactinfo) + public static IDictionary ReduceContactInfoForEvent( + IDictionary mycontactinfo + ) { foreach (var value in mycontactinfo.Values) { @@ -603,7 +768,7 @@ public static IDictionary ReduceContactInfoForEvent(IDicti //value.City = null; DefinitionLng/City value.CompanyName = null; //value.CountryCode = null; Definition / NatID - //value.CountryName = null; + //value.CountryName = null; value.Email = null; value.Faxnumber = null; value.Givenname = null; @@ -620,7 +785,9 @@ public static IDictionary ReduceContactInfoForEvent(IDicti return mycontactinfo; } - public static IDictionary ReduceContactInfoForGastronomy(IDictionary mycontactinfo) + public static IDictionary ReduceContactInfoForGastronomy( + IDictionary mycontactinfo + ) { foreach (var value in mycontactinfo.Values) { @@ -645,8 +812,9 @@ public static IDictionary ReduceContactInfoForGastronomy(I return mycontactinfo; } - - public static IDictionary ReduceAccoDetail(IDictionary mydetail) + public static IDictionary ReduceAccoDetail( + IDictionary mydetail + ) { foreach (var value in mydetail.Values) { @@ -708,9 +876,10 @@ public static EventBooking ReduceEventBooking(EventBooking eventBooking) return eventBooking; } - public static ICollection ReduceEventDateCollection(ICollection eventdates) + public static ICollection ReduceEventDateCollection( + ICollection eventdates + ) { - foreach (var eventdate in eventdates) { //eventdate.From = null; Day/Date @@ -737,11 +906,15 @@ public static ICollection ReduceEventDateCollection(ICollection()); + attributes.address = ReduceVenueAttributesAddress( + attributes.address ?? new List() + ); attributes.beds = null; //attributes.categories = null; //attributes.categories attributes.description = null; - attributes.geometries = ReduceVenueAttributesGeometries(attributes.geometries ?? new List()); + attributes.geometries = ReduceVenueAttributesGeometries( + attributes.geometries ?? new List() + ); attributes.howToArrive = null; //attributes.name = null; attributes.name @@ -752,7 +925,9 @@ public static DDAttributes ReduceVenueAttributes(DDAttributes attributes) return attributes; } - public static ICollection ReduceVenueAttributesAddress(ICollection addresses) + public static ICollection ReduceVenueAttributesAddress( + ICollection addresses + ) { foreach (var address in addresses) { @@ -763,13 +938,15 @@ public static ICollection ReduceVenueAttributesAddress(ICollection
ReduceVenueAttributesGeometries(ICollection geometries) + public static ICollection ReduceVenueAttributesGeometries( + ICollection geometries + ) { List allowedgeometries = new List(); @@ -817,7 +994,9 @@ public static ICollection ReduceSubVenues(ICollection su return subvenues; } - public static ICollection ReduceVenueRoomDetails(ICollection roomdetails) + public static ICollection ReduceVenueRoomDetails( + ICollection roomdetails + ) { foreach (var roomdetail in roomdetails) { @@ -826,11 +1005,10 @@ public static ICollection ReduceVenueRoomDetails(ICollection cheapestofferlist, int rooms, string service) + public static CheapestRoomCombination CalculateCheapestRooms( + IEnumerable cheapestofferlist, + int rooms, + string service + ) { - if (cheapestofferlist != null && cheapestofferlist.Count() > 0 && cheapestofferlist.Count() >= rooms) + if ( + cheapestofferlist != null + && cheapestofferlist.Count() > 0 + && cheapestofferlist.Count() >= rooms + ) { if (rooms == 1) { - var cheapestorffersingle = cheapestofferlist.OrderBy(x => x.Price).Take(1).FirstOrDefault(); - CheapestRoomCombination cheapestroomcombinationresult = new CheapestRoomCombination(); + var cheapestorffersingle = cheapestofferlist + .OrderBy(x => x.Price) + .Take(1) + .FirstOrDefault(); + CheapestRoomCombination cheapestroomcombinationresult = + new CheapestRoomCombination(); if (cheapestorffersingle is { }) - cheapestroomcombinationresult.CheapestRoomCombinationDetail = new List() { cheapestorffersingle }; + cheapestroomcombinationresult.CheapestRoomCombinationDetail = + new List() { cheapestorffersingle }; cheapestroomcombinationresult.Service = service; return cheapestroomcombinationresult; - } + } else return CalculateCheapestRoomCombinations(cheapestofferlist, rooms, service); //else @@ -39,16 +52,27 @@ public static CheapestRoomCombination CalculateCheapestRooms(IEnumerable() }; + return new CheapestRoomCombination() + { + Service = service, + CheapestRoomCombinationDetail = new List() + }; } } - private static CheapestRoomCombination CalculateCheapestRoomCombinations(IEnumerable cheapestofferlist, int rooms, string service) + private static CheapestRoomCombination CalculateCheapestRoomCombinations( + IEnumerable cheapestofferlist, + int rooms, + string service + ) { List mycombinationresult = new List(); //Create combinations TO verify use variations?? - Combinations combinations = new Combinations(cheapestofferlist, rooms); + Combinations combinations = new Combinations( + cheapestofferlist, + rooms + ); foreach (IList c in combinations) { @@ -67,7 +91,7 @@ private static CheapestRoomCombination CalculateCheapestRoomCombinations(IEnumer break; } - //Remove all combinations where more rooms are used than roomfree + //Remove all combinations where more rooms are used than roomfree if (addcombination) { for (int i = 0; i < rooms; i++) @@ -86,30 +110,51 @@ private static CheapestRoomCombination CalculateCheapestRoomCombinations(IEnumer if (addcombination) { - mycombinationresult.Add(new CheapestRoomCombination() { CheapestRoomCombinationDetail = c, Service = service }); + mycombinationresult.Add( + new CheapestRoomCombination() + { + CheapestRoomCombinationDetail = c, + Service = service + } + ); } } //Return Cheapestroomcombination - var cheapestcombination = mycombinationresult.OrderBy(x => x.Price).Take(1).FirstOrDefault(); + var cheapestcombination = mycombinationresult + .OrderBy(x => x.Price) + .Take(1) + .FirstOrDefault(); return cheapestcombination ?? new(); } //Hack because of CPU always over 90% - private static CheapestRoomCombination CalculateCheapestRoomCombinationsTemp(IEnumerable cheapestofferlist, int rooms, string service) + private static CheapestRoomCombination CalculateCheapestRoomCombinationsTemp( + IEnumerable cheapestofferlist, + int rooms, + string service + ) { CheapestRoomCombination cheapestroomcombinationresult = new CheapestRoomCombination(); cheapestroomcombinationresult.Service = service; - cheapestroomcombinationresult.CheapestRoomCombinationDetail = new List() { }; + cheapestroomcombinationresult.CheapestRoomCombinationDetail = new List() + { + }; //Get always the cheapest for (int i = 1; i <= rooms; i++) { - var cheapestorffersingle = cheapestofferlist.Where(x => x.RoomSeq == i).OrderBy(x => x.Price).Take(1).FirstOrDefault(); + var cheapestorffersingle = cheapestofferlist + .Where(x => x.RoomSeq == i) + .OrderBy(x => x.Price) + .Take(1) + .FirstOrDefault(); if (cheapestorffersingle != null) - cheapestroomcombinationresult.CheapestRoomCombinationDetail.Add(cheapestorffersingle); + cheapestroomcombinationresult.CheapestRoomCombinationDetail.Add( + cheapestorffersingle + ); } return cheapestroomcombinationresult; diff --git a/Helper/StringHelpers.cs b/Helper/StringHelpers.cs index a19084ac1..167750749 100644 --- a/Helper/StringHelpers.cs +++ b/Helper/StringHelpers.cs @@ -21,13 +21,13 @@ public static string RemoveSpecialCharacters(string value, char[] specialCharact { Dictionary? myvaluedict = new Dictionary(); - string valuenew = value.Replace("?",""); + string valuenew = value.Replace("?", ""); var splitted = valuenew.Split('&'); if (splitted.Count() > 0) { - foreach(var splittedfield in splitted) + foreach (var splittedfield in splitted) { var splittedobj = splittedfield.Split('='); if (splittedobj.Count() == 2) @@ -39,9 +39,13 @@ public static string RemoveSpecialCharacters(string value, char[] specialCharact else return null; } - } + } - public static string JoinStringListForPG(string separator, IEnumerable list, string escapechar) + public static string JoinStringListForPG( + string separator, + IEnumerable list, + string escapechar + ) { var newlist = list.Select(x => (escapechar + x + escapechar)).ToList(); @@ -63,7 +67,9 @@ public static bool ConvertStringToBoolean(this string returnValue) } else { - throw new FormatException("The string is not a recognized as a valid boolean value."); + throw new FormatException( + "The string is not a recognized as a valid boolean value." + ); } } @@ -72,13 +78,13 @@ public static string[] AddToStringArray(this string[] strarr, string value) var strlist = strarr.ToList(); strlist.Add(value); - return strlist.ToArray(); + return strlist.ToArray(); } public static string[] AddToStringArray(this string[] strarr, string[] values) { var strlist = strarr.ToList(); - + foreach (var value in values) { strlist.Add(value); @@ -87,6 +93,4 @@ public static string[] AddToStringArray(this string[] strarr, string[] values) return strlist.ToArray(); } } - - } diff --git a/Helper/Tagging/GenericTaggingHelper.cs b/Helper/Tagging/GenericTaggingHelper.cs index fae804db7..569c18933 100644 --- a/Helper/Tagging/GenericTaggingHelper.cs +++ b/Helper/Tagging/GenericTaggingHelper.cs @@ -19,27 +19,33 @@ public static async Task AddMappingToODHActivityPoi(IIdentifiable mypgdata, stri //Special get all Taglist and traduce it on import var myalltaglist = await GetAllGenericTagsfromJson(jsondir); if (myalltaglist != null && ((ODHActivityPoiLinked)mypgdata).SmgTags != null) - ((ODHActivityPoiLinked)mypgdata).Tags = GenerateNewTags(((ODHActivityPoiLinked)mypgdata).SmgTags ?? new List(), myalltaglist); + ((ODHActivityPoiLinked)mypgdata).Tags = GenerateNewTags( + ((ODHActivityPoiLinked)mypgdata).SmgTags ?? new List(), + myalltaglist + ); } - catch(Exception ex) - { - Console.WriteLine(JsonConvert.SerializeObject(new UpdateResult - { - operation = "Tagging object creation", - updatetype = "single", - otherinfo = "", - id = mypgdata.Id, - message = "Tagging conversion failed: " + ex.Message, - recordsmodified = 0, - created = 0, - updated = 0, - deleted = 0, - success = false - })); + catch (Exception ex) + { + Console.WriteLine( + JsonConvert.SerializeObject( + new UpdateResult + { + operation = "Tagging object creation", + updatetype = "single", + otherinfo = "", + id = mypgdata.Id, + message = "Tagging conversion failed: " + ex.Message, + recordsmodified = 0, + created = 0, + updated = 0, + deleted = 0, + success = false + } + ) + ); } } - //GETS all generic tags from json as object to avoid DB call on each Tag update public static async Task> GetAllGenericTagsfromJson(string jsondir) { @@ -52,7 +58,10 @@ public static async Task> GetAllGenericTagsfromJson(string jsond } //Translates OLD Tags with german keys to new English Tags - public static IDictionary> GenerateNewTags(ICollection currenttags, List alltaglist) + public static IDictionary> GenerateNewTags( + ICollection currenttags, + List alltaglist + ) { var returnDict = new Dictionary>(); @@ -79,11 +88,16 @@ public static IDictionary> GenerateNewTags(ICollection TranslateMappingKey(string germankey, List alltaglist) + private static IDictionary TranslateMappingKey( + string germankey, + List alltaglist + ) { var returnDict = new Dictionary(); - var tagen = alltaglist.Where(x => x.ODHTagIds.Any(y => y == germankey)).FirstOrDefault(); + var tagen = alltaglist + .Where(x => x.ODHTagIds.Any(y => y == germankey)) + .FirstOrDefault(); if (tagen?.Id != null) { @@ -146,6 +160,5 @@ private static string RemoveSpecialCharsRegex(string id) // return toreturn.Trim(); //} - } } diff --git a/Helper/Tagging/LTSTaggingHelper.cs b/Helper/Tagging/LTSTaggingHelper.cs index 435036a35..a20f8add0 100644 --- a/Helper/Tagging/LTSTaggingHelper.cs +++ b/Helper/Tagging/LTSTaggingHelper.cs @@ -157,7 +157,9 @@ public static string CheckActivityPoi(string type) => }; public static async Task> GetPoiTypeDescAsync( - string? key, IAsyncEnumerable ltstaggingtypes) + string? key, + IAsyncEnumerable ltstaggingtypes + ) { IDictionary maintypedict = new Dictionary(); @@ -170,7 +172,9 @@ public static async Task> GetPoiTypeDescAsync( } public static async Task> GetActivityTypeDescAsync( - string? key, IAsyncEnumerable ltstaggingtypes) + string? key, + IAsyncEnumerable ltstaggingtypes + ) { IDictionary maintypedict = new Dictionary(); diff --git a/Helper/Tagging/ODHTagHelper.cs b/Helper/Tagging/ODHTagHelper.cs index c42e22e7b..611eb40dd 100644 --- a/Helper/Tagging/ODHTagHelper.cs +++ b/Helper/Tagging/ODHTagHelper.cs @@ -8,27 +8,40 @@ namespace Helper { - public class ODHTagHelper { - public static async Task> GetODHTagsValidforTranslations(QueryFactory QueryFactory, List validforentity, List? idlist = null) + public static async Task> GetODHTagsValidforTranslations( + QueryFactory QueryFactory, + List validforentity, + List? idlist = null + ) { try { List validtags = new List(); - var validtagquery = QueryFactory.Query("smgtags") - .Select("data") - .When(validforentity.Count > 0, q => q.WhereInJsonb( - validforentity, - tag => new { ValidForEntity = new[] { tag.ToLower() } } - )) - .When(idlist != null, w => w.WhereIn("id", idlist?.Select(x => x.ToLower()) ?? Enumerable.Empty())) - .WhereRaw("data->>'DisplayAsCategory' = $$", "true"); + var validtagquery = QueryFactory + .Query("smgtags") + .Select("data") + .When( + validforentity.Count > 0, + q => + q.WhereInJsonb( + validforentity, + tag => new { ValidForEntity = new[] { tag.ToLower() } } + ) + ) + .When( + idlist != null, + w => + w.WhereIn( + "id", + idlist?.Select(x => x.ToLower()) ?? Enumerable.Empty() + ) + ) + .WhereRaw("data->>'DisplayAsCategory' = $$", "true"); - var validtagdata = - await validtagquery - .GetAllAsObject(); + var validtagdata = await validtagquery.GetAllAsObject(); return validtagdata; } @@ -42,10 +55,7 @@ await validtagquery { try { - var query = - QueryFactory.Query("smgtags") - .Select("data") - .Where("id", id.ToLower()); + var query = QueryFactory.Query("smgtags").Select("data").Where("id", id.ToLower()); var result = await query.GetFirstOrDefaultAsObject(); @@ -62,39 +72,82 @@ public static string SetMainCategorizationForODHActivityPoi(ODHActivityPoiLinked //Add LTS Id as Mapping var maintype = "poi"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "activitydata") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "activitydata" + ) maintype = "activity"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "poidata") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "poidata" + ) maintype = "poi"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "gastronomicdata") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "gastronomicdata" + ) maintype = "gastronomy"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "beacondata") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "beacondata" + ) maintype = "poi"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "archapp") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "archapp" + ) maintype = "poi"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "museumdata") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "museumdata" + ) maintype = "poi"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "suedtirolwein") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "suedtirolwein" + ) maintype = "gastronomy"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "common") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "common" + ) maintype = "activity"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "none") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "none" + ) maintype = "poi"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "magnolia") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "magnolia" + ) maintype = "poi"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "sta") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "sta" + ) maintype = "poi"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "dssliftbase") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "dssliftbase" + ) maintype = "activity"; - if (!String.IsNullOrEmpty(smgpoi.SyncSourceInterface) && smgpoi.SyncSourceInterface.ToLower() == "dssslopebase") + if ( + !String.IsNullOrEmpty(smgpoi.SyncSourceInterface) + && smgpoi.SyncSourceInterface.ToLower() == "dssslopebase" + ) maintype = "activity"; - if(smgpoi.SmgTags == null) + if (smgpoi.SmgTags == null) { smgpoi.SmgTags = new List(); smgpoi.SmgTags.Add(maintype); } - else if(!smgpoi.SmgTags.Contains("activity") && !smgpoi.SmgTags.Contains("poi") && !smgpoi.SmgTags.Contains("gastronomy")) + else if ( + !smgpoi.SmgTags.Contains("activity") + && !smgpoi.SmgTags.Contains("poi") + && !smgpoi.SmgTags.Contains("gastronomy") + ) { //Assign to SMGTags if not there if (!smgpoi.SmgTags.Contains(maintype)) @@ -103,6 +156,5 @@ public static string SetMainCategorizationForODHActivityPoi(ODHActivityPoiLinked return maintype; } - } } diff --git a/Helper/Tagging/SmgTagTransformer.cs b/Helper/Tagging/SmgTagTransformer.cs index b547c83cc..9674a0288 100644 --- a/Helper/Tagging/SmgTagTransformer.cs +++ b/Helper/Tagging/SmgTagTransformer.cs @@ -6,30 +6,44 @@ namespace Helper { public static class SmgTagTransformer { - public static IEnumerable TransformToLocalizedSmgTag(this IEnumerable smgtaglist, string language) + public static IEnumerable TransformToLocalizedSmgTag( + this IEnumerable smgtaglist, + string language + ) { - return (from smgtag in smgtaglist - select new SmgTags - { - Id = smgtag.Id, - Shortname = smgtag.Shortname, - MainEntity = smgtag.MainEntity, - ValidForEntity = smgtag.ValidForEntity, - TagName = smgtag.TagName.Where(x => x.Key == language).ToDictionary(x => x.Key, x => x.Value) - }); + return ( + from smgtag in smgtaglist + select new SmgTags + { + Id = smgtag.Id, + Shortname = smgtag.Shortname, + MainEntity = smgtag.MainEntity, + ValidForEntity = smgtag.ValidForEntity, + TagName = smgtag.TagName + .Where(x => x.Key == language) + .ToDictionary(x => x.Key, x => x.Value) + } + ); } - public static IEnumerable TransformToLocalizedSmgTag(this List smgtaglist, string language) + public static IEnumerable TransformToLocalizedSmgTag( + this List smgtaglist, + string language + ) { - return (from smgtag in smgtaglist - select new SmgTags - { - Id = smgtag.Id, - Shortname = smgtag.Shortname, - MainEntity = smgtag.MainEntity, - ValidForEntity = smgtag.ValidForEntity, - TagName = smgtag.TagName.Where(x => x.Key == language).ToDictionary(x => x.Key, x => x.Value) - }); + return ( + from smgtag in smgtaglist + select new SmgTags + { + Id = smgtag.Id, + Shortname = smgtag.Shortname, + MainEntity = smgtag.MainEntity, + ValidForEntity = smgtag.ValidForEntity, + TagName = smgtag.TagName + .Where(x => x.Key == language) + .ToDictionary(x => x.Key, x => x.Value) + } + ); } public static SmgTags TransformToLocalizedSmgTag(this SmgTags smgtag, string language) @@ -40,18 +54,21 @@ public static SmgTags TransformToLocalizedSmgTag(this SmgTags smgtag, string lan Shortname = smgtag.Shortname, MainEntity = smgtag.MainEntity, ValidForEntity = smgtag.ValidForEntity, - TagName = smgtag.TagName.Where(x => x.Key == language).ToDictionary(x => x.Key, x => x.Value) + TagName = smgtag.TagName + .Where(x => x.Key == language) + .ToDictionary(x => x.Key, x => x.Value) }; } - public static IEnumerable TransformToReducedSmgTag(this IEnumerable smgtaglist, string language) + public static IEnumerable TransformToReducedSmgTag( + this IEnumerable smgtaglist, + string language + ) { - return (from smgtag in smgtaglist - select new SmgTagReduced - { - Id = smgtag.Id, - Name = smgtag.TagName[language] - }); + return ( + from smgtag in smgtaglist + select new SmgTagReduced { Id = smgtag.Id, Name = smgtag.TagName[language] } + ); } } } diff --git a/JsonLDTransformer/Objects/LDDataTypes.cs b/JsonLDTransformer/Objects/LDDataTypes.cs index 2459df3a2..e680ba80e 100644 --- a/JsonLDTransformer/Objects/LDDataTypes.cs +++ b/JsonLDTransformer/Objects/LDDataTypes.cs @@ -19,10 +19,7 @@ public class ObjectLD public string id { get; set; } } - - public class RecipeLD : ObjectLD - { - } + public class RecipeLD : ObjectLD { } public class EventLD : ObjectLD { @@ -42,7 +39,7 @@ public class EventLD : ObjectLD public string endDate { get; set; } [JsonProperty(Order = 8)] - public string url { get; set; } + public string url { get; set; } [JsonProperty(Order = 9)] public PlaceLD location { get; set; } @@ -52,7 +49,6 @@ public class EventLD : ObjectLD [JsonProperty(Order = 11)] public OrganizationLD organizer { get; set; } - } public class RestaurantLD : ObjectLD @@ -89,21 +85,13 @@ public class RestaurantLD : ObjectLD [JsonProperty(Order = 8)] public personLD founder { get; set; } - - } - public class TouristAttractionLD : ObjectLD - { - } + public class TouristAttractionLD : ObjectLD { } - public class ArticleLD : ObjectLD - { - } + public class ArticleLD : ObjectLD { } - public class SkiResortLD : ObjectLD - { - } + public class SkiResortLD : ObjectLD { } public class OrganizationLD : ObjectLD { @@ -121,10 +109,9 @@ public class OrganizationLD : ObjectLD [JsonProperty(Order = 7)] public addressLD address { get; set; } - } - public class PlaceLD + public class PlaceLD { [JsonProperty(PropertyName = "@type", Order = 0)] public string type { get; set; } @@ -133,7 +120,7 @@ public class PlaceLD public string name { get; set; } [JsonProperty(Order = 2)] - public addressLD address { get; set; } + public addressLD address { get; set; } } public class OfferLD @@ -163,21 +150,13 @@ public class OfferLD public string priceCurrency { get; set; } } - public class LodgingBusinessLD : ObjectLD - { - } + public class LodgingBusinessLD : ObjectLD { } - public class BookLD : ObjectLD - { - } + public class BookLD : ObjectLD { } - public class StoreLD : ObjectLD - { - } + public class StoreLD : ObjectLD { } - public class LocalBusinessLD : ObjectLD - { - } + public class LocalBusinessLD : ObjectLD { } public class HotelLD : ObjectLD { @@ -198,7 +177,7 @@ public class HotelLD : ObjectLD [JsonProperty(Order = 5)] public string description { get; set; } - + [JsonProperty(Order = 6)] public string telephone { get; set; } @@ -224,12 +203,16 @@ public class addressLD [JsonProperty(Order = 1)] public string streetAddress { get; set; } + [JsonProperty(Order = 2)] public string postalCode { get; set; } + [JsonProperty(Order = 3)] public string addressLocality { get; set; } + [JsonProperty(Order = 4)] public string addressRegion { get; set; } + [JsonProperty(Order = 5)] public string addressCountry { get; set; } } @@ -241,6 +224,7 @@ public class geoLD [JsonProperty(Order = 1)] public double latitude { get; set; } + [JsonProperty(Order = 2)] public double longitude { get; set; } } @@ -252,5 +236,4 @@ public class personLD [JsonProperty(Order = 1)] public string name { get; set; } - -} \ No newline at end of file +} diff --git a/JsonLDTransformer/TransformToLD.cs b/JsonLDTransformer/TransformToLD.cs index c95f684e5..6f8abe627 100644 --- a/JsonLDTransformer/TransformToLD.cs +++ b/JsonLDTransformer/TransformToLD.cs @@ -13,14 +13,16 @@ public static class TransformToLD [Obsolete] public static List TransformDataToLD(T data, string language, string idtoshow) { - var objectlist = new List(); + var objectlist = new List(); var z = data.GetType(); - switch(z.Name) + switch (z.Name) { case "Accommodation": - objectlist.Add(TransformAccommodationToLD((Accommodation)(object)data, language)); + objectlist.Add( + TransformAccommodationToLD((Accommodation)(object)data, language) + ); break; case "Gastronomy": objectlist.Add(TransformGastronomyToLD((Gastronomy)(object)data, language)); @@ -35,11 +37,9 @@ public static List TransformDataToLD(T data, string language, string break; } - return objectlist; } - public static HotelLD TransformAccommodationToLD(Accommodation acco, string language) { HotelLD myhotel = new HotelLD(); @@ -48,7 +48,6 @@ public static HotelLD TransformAccommodationToLD(Accommodation acco, string lang myhotel.id = acco.Id; myhotel.type = "Hotel"; - myhotel.description = acco.AccoDetail[language].Shortdesc; myhotel.email = acco.AccoDetail[language].Email; var image = acco.ImageGallery.FirstOrDefault(); @@ -86,7 +85,6 @@ public static RestaurantLD TransformGastronomyToLD(Gastronomy gastro, string lan mygastro.id = gastro.Id; mygastro.type = "Restaurant"; - mygastro.description = gastro.Detail[language].BaseText; mygastro.email = gastro.ContactInfos[language].Email; var image = gastro.ImageGallery.FirstOrDefault(); @@ -115,7 +113,8 @@ public static RestaurantLD TransformGastronomyToLD(Gastronomy gastro, string lan personLD founder = new personLD(); founder.type = "http://schema.org/Person"; - founder.name = gastro.ContactInfos["de"].Givenname + " " + gastro.ContactInfos[language].Surname; + founder.name = + gastro.ContactInfos["de"].Givenname + " " + gastro.ContactInfos[language].Surname; mygastro.founder = founder; @@ -130,7 +129,10 @@ private static List GetCuisine(ICollection facilities) { var validcuisine = ValidCuisineCodes(); - return facilities.Where(x => validcuisine.Contains(x.Id)).Select(x => x.Shortname).ToList(); + return facilities + .Where(x => validcuisine.Contains(x.Id)) + .Select(x => x.Shortname) + .ToList(); } private static List ValidCuisineCodes() @@ -167,13 +169,19 @@ private static List ValidCuisineCodes() }; } - private static List GetOpeningDates(ICollection operationschedules) + private static List GetOpeningDates( + ICollection operationschedules + ) { List openingtime = new List(); //openingtime.Add("Mo-Sa 11:00-14:30"); //openingtime.Add("Mo-Th 17:00-21:30"); - foreach(var operationschedule in operationschedules.Where(x => x.Start <= DateTime.Now && x.Stop >= DateTime.Now)) + foreach ( + var operationschedule in operationschedules.Where( + x => x.Start <= DateTime.Now && x.Stop >= DateTime.Now + ) + ) { //Zersch schaugn obs ollaweil offen isch! @@ -183,32 +191,48 @@ private static List GetOpeningDates(ICollection opera //Achtung do muassi die richtigen fir heint finden sischt sein mearere! - if(operationschedule.OperationScheduleTime != null) + if (operationschedule.OperationScheduleTime != null) { - foreach(var operationtime in operationschedule.OperationScheduleTime.Where(x => x.State == 2 && x.Timecode == 1)) + foreach ( + var operationtime in operationschedule.OperationScheduleTime.Where( + x => x.State == 2 && x.Timecode == 1 + ) + ) { if (operationtime.Monday) - openingtime.Add("Mo " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Mo " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Tuesday) - openingtime.Add("Tu " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Tu " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Wednesday) - openingtime.Add("We " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "We " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Thuresday) - openingtime.Add("Th " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Th " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Friday) - openingtime.Add("Fr " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Fr " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Saturday) - openingtime.Add("Sa " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Sa " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Sunday) - openingtime.Add("Su " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Su " + operationtime.Start + " - " + operationtime.End + ); } - } //Keine Zeiten drinn } - return openingtime; } @@ -216,7 +240,7 @@ public static List TransformEventToLD(Event theevent, string language) { List myeventlist = new List(); - foreach(var theeventsingle in theevent.EventDate) + foreach (var theeventsingle in theevent.EventDate) { EventLD myevent = new EventLD(); @@ -242,8 +266,6 @@ public static List TransformEventToLD(Event theevent, string language) myaddress.addressRegion = "Südtirol"; myaddress.addressCountry = theevent.ContactInfos["de"].CountryName; - - PlaceLD location = new PlaceLD(); location.address = myaddress; location.type = "Place"; @@ -284,15 +306,27 @@ public static List TransformEventToLD(Event theevent, string language) myoffer.name = theevent.EventPrice[language].ShortDesc; myoffer.description = theevent.EventPrice[language].Description; - myoffer.validFrom = String.Format("{0:yyyy-MM-dd}", theeventsingle.From) + "T" + theeventsingle.Begin.Value.ToString("hh\\:mm"); - myoffer.validTrough = String.Format("{0:yyyy-MM-dd}", theeventsingle.To) + "T" + theeventsingle.End.Value.ToString("hh\\:mm"); + myoffer.validFrom = + String.Format("{0:yyyy-MM-dd}", theeventsingle.From) + + "T" + + theeventsingle.Begin.Value.ToString("hh\\:mm"); + myoffer.validTrough = + String.Format("{0:yyyy-MM-dd}", theeventsingle.To) + + "T" + + theeventsingle.End.Value.ToString("hh\\:mm"); myevent.offers = myoffer; } } - myevent.startDate = String.Format("{0:yyyy-MM-dd}", theeventsingle.From) + "T" + theeventsingle.Begin.Value.ToString("hh\\:mm"); - myevent.endDate = String.Format("{0:yyyy-MM-dd}", theeventsingle.To) + "T" + theeventsingle.End.Value.ToString("hh\\:mm"); + myevent.startDate = + String.Format("{0:yyyy-MM-dd}", theeventsingle.From) + + "T" + + theeventsingle.Begin.Value.ToString("hh\\:mm"); + myevent.endDate = + String.Format("{0:yyyy-MM-dd}", theeventsingle.To) + + "T" + + theeventsingle.End.Value.ToString("hh\\:mm"); myeventlist.Add(myevent); @@ -329,13 +363,9 @@ public static List TransformEventToLD(Event theevent, string language) //mygastro.servesCuisine = GetCuisine(gastro.Facilities); //mygastro.openingHours = GetOpeningDates(gastro.OperationSchedule); - } - - return myeventlist; } - } } diff --git a/JsonLDTransformer/TransformToSchemaNet.cs b/JsonLDTransformer/TransformToSchemaNet.cs index ab7c16fcd..0f3c4bf29 100644 --- a/JsonLDTransformer/TransformToSchemaNet.cs +++ b/JsonLDTransformer/TransformToSchemaNet.cs @@ -13,55 +13,161 @@ namespace JsonLDTransformer { public class TransformToSchemaNet { - public static List TransformDataToSchemaNet(T data, string type, string language, object parentobject = null, string idtoshow = "", string urltoshow = "", string imageurltoshow = "", bool showid = true) + public static List TransformDataToSchemaNet( + T data, + string type, + string language, + object parentobject = null, + string idtoshow = "", + string urltoshow = "", + string imageurltoshow = "", + bool showid = true + ) { var objectlist = new List(); switch (type) { case "accommodation": - objectlist.Add(TransformAccommodationToLD((DataModel.Accommodation)(object)data, language, idtoshow, urltoshow, imageurltoshow, showid)); + objectlist.Add( + TransformAccommodationToLD( + (DataModel.Accommodation)(object)data, + language, + idtoshow, + urltoshow, + imageurltoshow, + showid + ) + ); break; case "gastronomy": - objectlist.Add(TransformGastronomyToLD((DataModel.ODHActivityPoi)(object)data, language, idtoshow, urltoshow, imageurltoshow, showid)); + objectlist.Add( + TransformGastronomyToLD( + (DataModel.ODHActivityPoi)(object)data, + language, + idtoshow, + urltoshow, + imageurltoshow, + showid + ) + ); break; case "poi": - objectlist.Add(TransformActivityPoiToLD((DataModel.ODHActivityPoi)(object)data, language, idtoshow, urltoshow, imageurltoshow, showid)); + objectlist.Add( + TransformActivityPoiToLD( + (DataModel.ODHActivityPoi)(object)data, + language, + idtoshow, + urltoshow, + imageurltoshow, + showid + ) + ); break; case "skiarea": - objectlist.Add(TransformSkiResortToLD((DataModel.SkiArea)(object)data, (DataModel.SkiRegion)(object)parentobject, language, idtoshow, urltoshow, imageurltoshow, showid)); + objectlist.Add( + TransformSkiResortToLD( + (DataModel.SkiArea)(object)data, + (DataModel.SkiRegion)(object)parentobject, + language, + idtoshow, + urltoshow, + imageurltoshow, + showid + ) + ); break; case "region": - objectlist.Add(TransformPlaceToLD((DataModel.Region)(object)data, language, idtoshow, urltoshow, imageurltoshow, showid)); + objectlist.Add( + TransformPlaceToLD( + (DataModel.Region)(object)data, + language, + idtoshow, + urltoshow, + imageurltoshow, + showid + ) + ); break; case "tv": - objectlist.Add(TransformPlaceToLD((DataModel.Tourismverein)(object)data, language, idtoshow, urltoshow, imageurltoshow, showid)); + objectlist.Add( + TransformPlaceToLD( + (DataModel.Tourismverein)(object)data, + language, + idtoshow, + urltoshow, + imageurltoshow, + showid + ) + ); break; case "municipality": - objectlist.Add(TransformPlaceToLD((DataModel.Municipality)(object)data, language, idtoshow, urltoshow, imageurltoshow, showid)); + objectlist.Add( + TransformPlaceToLD( + (DataModel.Municipality)(object)data, + language, + idtoshow, + urltoshow, + imageurltoshow, + showid + ) + ); break; case "district": - objectlist.Add(TransformPlaceToLD((DataModel.District)(object)data, language, idtoshow, urltoshow, imageurltoshow, showid)); + objectlist.Add( + TransformPlaceToLD( + (DataModel.District)(object)data, + language, + idtoshow, + urltoshow, + imageurltoshow, + showid + ) + ); break; case "recipe": - objectlist.Add(TransformRecipeToLD((DataModel.Article)(object)data, language, idtoshow, urltoshow, imageurltoshow, showid)); + objectlist.Add( + TransformRecipeToLD( + (DataModel.Article)(object)data, + language, + idtoshow, + urltoshow, + imageurltoshow, + showid + ) + ); break; case "event": //Achtung pro EventDate Eintrag 1 Event anlegen //des hoasst i muass a listen zruggeben - objectlist.AddRange(TransformEventToLD((DataModel.Event)(object)data, language, idtoshow, urltoshow, imageurltoshow, showid)); + objectlist.AddRange( + TransformEventToLD( + (DataModel.Event)(object)data, + language, + idtoshow, + urltoshow, + imageurltoshow, + showid + ) + ); break; } - return objectlist; } #region Accommodation - private static Schema.NET.Hotel TransformAccommodationToLD(DataModel.Accommodation acco, string language, string passedid, string passedurl, string passedimage, bool showid) + private static Schema.NET.Hotel TransformAccommodationToLD( + DataModel.Accommodation acco, + string language, + string passedid, + string passedurl, + string passedimage, + bool showid + ) { string fallbacklanguage = "en"; @@ -70,36 +176,56 @@ private static Schema.NET.Hotel TransformAccommodationToLD(DataModel.Accommodati if (showid) { if (String.IsNullOrEmpty(passedid)) - myhotel.Id = new Uri("http://service.suedtirol.info/api/Accommodation/" + acco.Id); + myhotel.Id = new Uri( + "http://service.suedtirol.info/api/Accommodation/" + acco.Id + ); else myhotel.Id = new Uri(passedid); } - myhotel.Description = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].Shortdesc : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].Shortdesc : ""; - myhotel.Email = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].Email : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].Email : ""; - myhotel.Name = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].Name : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].Name : ""; - myhotel.Telephone = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].Phone : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].Phone : ""; - + myhotel.Description = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].Shortdesc + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].Shortdesc + : ""; + myhotel.Email = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].Email + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].Email + : ""; + myhotel.Name = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].Name + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].Name + : ""; + myhotel.Telephone = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].Phone + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].Phone + : ""; if (String.IsNullOrEmpty(passedimage)) { if (acco.ImageGallery != null) if (acco.ImageGallery.Count > 0) if (!String.IsNullOrEmpty(acco.ImageGallery.FirstOrDefault().ImageUrl)) - myhotel.Image = new Uri(acco.ImageGallery.FirstOrDefault().ImageUrl + "&W=800"); + myhotel.Image = new Uri( + acco.ImageGallery.FirstOrDefault().ImageUrl + "&W=800" + ); } else myhotel.Image = new Uri(passedimage); - - //URL OVERWRITE if (String.IsNullOrEmpty(passedurl) && String.IsNullOrEmpty(passedid)) { - string url = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].Website : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].Website : ""; + string url = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].Website + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].Website + : ""; if (CheckURLValid(url)) myhotel.Url = new Uri(url); - } else if (!String.IsNullOrEmpty(passedurl)) { @@ -110,24 +236,59 @@ private static Schema.NET.Hotel TransformAccommodationToLD(DataModel.Accommodati myhotel.Url = new Uri(passedid); } - PostalAddress myaddress = new PostalAddress(); //myaddress.Type = "http://schema.org/PostalAddress"; - myaddress.StreetAddress = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].Street : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].Street : ""; - myaddress.PostalCode = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].Zip : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].Zip : ""; - myaddress.AddressLocality = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].City : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].City : ""; + myaddress.StreetAddress = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].Street + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].Street + : ""; + myaddress.PostalCode = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].Zip + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].Zip + : ""; + myaddress.AddressLocality = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].City + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].City + : ""; myaddress.AddressRegion = getRegionDependingonLanguage(language); myaddress.AddressCountry = getCountryDependingonLanguage(language); - myaddress.Telephone = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].Phone : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].Phone : ""; - - string adressurl = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].Website : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].Website : ""; + myaddress.Telephone = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].Phone + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].Phone + : ""; + + string adressurl = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].Website + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].Website + : ""; if (CheckURLValid(adressurl)) myhotel.Url = new Uri(adressurl); - myaddress.Email = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].Email : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].Email : ""; - myaddress.FaxNumber = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].Fax : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].Fax : ""; - myaddress.AlternateName = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].NameAddition : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].NameAddition : ""; - myaddress.Name = acco.AccoDetail.ContainsKey(language) ? acco.AccoDetail[language].Name : acco.AccoDetail.ContainsKey(fallbacklanguage) ? acco.AccoDetail[fallbacklanguage].Name : ""; + myaddress.Email = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].Email + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].Email + : ""; + myaddress.FaxNumber = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].Fax + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].Fax + : ""; + myaddress.AlternateName = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].NameAddition + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].NameAddition + : ""; + myaddress.Name = acco.AccoDetail.ContainsKey(language) + ? acco.AccoDetail[language].Name + : acco.AccoDetail.ContainsKey(fallbacklanguage) + ? acco.AccoDetail[fallbacklanguage].Name + : ""; myhotel.Address = myaddress; @@ -170,7 +331,6 @@ private static Schema.NET.Hotel TransformAccommodationToLD(DataModel.Accommodati } } - return myhotel; } @@ -198,13 +358,30 @@ private static string GetPriceRange(string categoryid) { string comparator = ""; - if (categoryid == "1star" || categoryid == "1flower" || categoryid == "1sun" || categoryid == "2stars" || categoryid == "2flowers" || categoryid == "2suns") + if ( + categoryid == "1star" + || categoryid == "1flower" + || categoryid == "1sun" + || categoryid == "2stars" + || categoryid == "2flowers" + || categoryid == "2suns" + ) comparator = "1"; - else if (categoryid == "3stars" || categoryid == "3flowers" || categoryid == "3suns" || categoryid == "3sstars") + else if ( + categoryid == "3stars" + || categoryid == "3flowers" + || categoryid == "3suns" + || categoryid == "3sstars" + ) comparator = "2"; else if (categoryid == "4stars" || categoryid == "4flowers" || categoryid == "4suns") comparator = "3"; - else if (categoryid == "4sstars" || categoryid == "5stars" || categoryid == "5flowers" || categoryid == "5suns") + else if ( + categoryid == "4sstars" + || categoryid == "5stars" + || categoryid == "5flowers" + || categoryid == "5suns" + ) comparator = "4"; switch (comparator) @@ -226,7 +403,14 @@ private static string GetPriceRange(string categoryid) #region Gastronomy - private static Schema.NET.Restaurant TransformGastronomyToLD(DataModel.ODHActivityPoi gastro, string language, string passedid, string passedurl, string passedimage, bool showid) + private static Schema.NET.Restaurant TransformGastronomyToLD( + DataModel.ODHActivityPoi gastro, + string language, + string passedid, + string passedurl, + string passedimage, + bool showid + ) { Schema.NET.Restaurant mygastro = new Schema.NET.Restaurant(); @@ -235,19 +419,36 @@ private static Schema.NET.Restaurant TransformGastronomyToLD(DataModel.ODHActivi if (showid) { if (String.IsNullOrEmpty(passedid)) - mygastro.Id = new Uri("http://service.suedtirol.info/api/GBActivityPoi/" + gastro.Id); + mygastro.Id = new Uri( + "http://service.suedtirol.info/api/GBActivityPoi/" + gastro.Id + ); else mygastro.Id = new Uri(passedid); } //mygastro.type = "Restaurant"; - mygastro.Description = gastro.Detail.ContainsKey(language) ? gastro.Detail[language].BaseText : gastro.Detail.ContainsKey(fallbacklanguage) ? gastro.Detail[fallbacklanguage].BaseText : ""; - mygastro.Name = gastro.Detail.ContainsKey(language) ? gastro.Detail[language].Title : gastro.Detail.ContainsKey(fallbacklanguage) ? gastro.Detail[fallbacklanguage].Title : ""; - - mygastro.Email = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].Email : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].Email : ""; - mygastro.Telephone = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].Phonenumber : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].Phonenumber : ""; - + mygastro.Description = gastro.Detail.ContainsKey(language) + ? gastro.Detail[language].BaseText + : gastro.Detail.ContainsKey(fallbacklanguage) + ? gastro.Detail[fallbacklanguage].BaseText + : ""; + mygastro.Name = gastro.Detail.ContainsKey(language) + ? gastro.Detail[language].Title + : gastro.Detail.ContainsKey(fallbacklanguage) + ? gastro.Detail[fallbacklanguage].Title + : ""; + + mygastro.Email = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].Email + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].Email + : ""; + mygastro.Telephone = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].Phonenumber + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].Phonenumber + : ""; if (String.IsNullOrEmpty(passedimage)) { @@ -259,11 +460,14 @@ private static Schema.NET.Restaurant TransformGastronomyToLD(DataModel.ODHActivi else mygastro.Image = new Uri(passedimage); - //URL OVERWRITE if (String.IsNullOrEmpty(passedurl) && String.IsNullOrEmpty(passedid)) { - string url = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].Url : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].Url : ""; + string url = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].Url + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(url)) mygastro.Url = new Uri(url); } @@ -276,27 +480,64 @@ private static Schema.NET.Restaurant TransformGastronomyToLD(DataModel.ODHActivi mygastro.Url = new Uri(passedid); } - - - PostalAddress myaddress = new PostalAddress(); //myaddress.type = "http://schema.org/PostalAddress"; - myaddress.StreetAddress = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].Address : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].Address : ""; - myaddress.PostalCode = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].ZipCode : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].ZipCode : ""; - myaddress.AddressLocality = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].City : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].City : ""; + myaddress.StreetAddress = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].Address + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].Address + : ""; + myaddress.PostalCode = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].ZipCode + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].ZipCode + : ""; + myaddress.AddressLocality = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].City + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].City + : ""; myaddress.AddressRegion = getRegionDependingonLanguage(language); - myaddress.AddressCountry = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].CountryName : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].CountryName : ""; - - myaddress.Telephone = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].Phonenumber : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].Phonenumber : ""; - - string adressurl = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].Url : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].Url : ""; + myaddress.AddressCountry = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].CountryName + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].CountryName + : ""; + + myaddress.Telephone = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].Phonenumber + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].Phonenumber + : ""; + + string adressurl = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].Url + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(adressurl)) myaddress.Url = new Uri(adressurl); - myaddress.Email = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].Email : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].Email : ""; - myaddress.FaxNumber = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].Faxnumber : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].Faxnumber : ""; - myaddress.AlternateName = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].CompanyName : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].CompanyName : ""; - myaddress.Name = gastro.Detail.ContainsKey(language) ? gastro.Detail[language].Title : gastro.Detail.ContainsKey(fallbacklanguage) ? gastro.Detail[fallbacklanguage].Title : ""; + myaddress.Email = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].Email + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].Email + : ""; + myaddress.FaxNumber = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].Faxnumber + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].Faxnumber + : ""; + myaddress.AlternateName = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].CompanyName + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].CompanyName + : ""; + myaddress.Name = gastro.Detail.ContainsKey(language) + ? gastro.Detail[language].Title + : gastro.Detail.ContainsKey(fallbacklanguage) + ? gastro.Detail[fallbacklanguage].Title + : ""; mygastro.Address = myaddress; @@ -304,13 +545,22 @@ private static Schema.NET.Restaurant TransformGastronomyToLD(DataModel.ODHActivi //mygeo.type = "http://schema.org/GeoCoordinates"; mygeo.Latitude = gastro.GpsInfo != null ? gastro.GpsInfo.FirstOrDefault().Latitude : 0; - mygeo.Longitude = gastro.GpsInfo != null ? gastro.GpsInfo.FirstOrDefault().Longitude : 0; + mygeo.Longitude = + gastro.GpsInfo != null ? gastro.GpsInfo.FirstOrDefault().Longitude : 0; mygastro.Geo = mygeo; Person founder = new Person(); //founder.type = "http://schema.org/Person"; - founder.Name = gastro.ContactInfos.ContainsKey(language) ? gastro.ContactInfos[language].Givenname + " " + gastro.ContactInfos[language].Surname : gastro.ContactInfos.ContainsKey(fallbacklanguage) ? gastro.ContactInfos[fallbacklanguage].Givenname + " " + gastro.ContactInfos[fallbacklanguage].Surname : ""; + founder.Name = gastro.ContactInfos.ContainsKey(language) + ? gastro.ContactInfos[language].Givenname + + " " + + gastro.ContactInfos[language].Surname + : gastro.ContactInfos.ContainsKey(fallbacklanguage) + ? gastro.ContactInfos[fallbacklanguage].Givenname + + " " + + gastro.ContactInfos[fallbacklanguage].Surname + : ""; mygastro.Founder = founder; @@ -325,7 +575,10 @@ private static List GetCuisine(ICollection facilities) var validcuisine = ValidCuisineCodes(); if (facilities != null) - return facilities.Where(x => validcuisine.Contains(x.Id)).Select(x => x.Shortname).ToList(); + return facilities + .Where(x => validcuisine.Contains(x.Id)) + .Select(x => x.Shortname) + .ToList(); else return new List(); } @@ -364,7 +617,9 @@ private static List ValidCuisineCodes() }; } - private static List GetOpeningDatesGastronomy(ICollection operationschedules) + private static List GetOpeningDatesGastronomy( + ICollection operationschedules + ) { List openingtime = new List(); //openingtime.Add("Mo-Sa 11:00-14:30"); @@ -372,7 +627,11 @@ private static List GetOpeningDatesGastronomy(ICollection x.Start <= DateTime.Now && x.Stop >= DateTime.Now)) + foreach ( + var operationschedule in operationschedules.Where( + x => x.Start <= DateTime.Now && x.Stop >= DateTime.Now + ) + ) { //Zersch schaugn obs ollaweil offen isch! @@ -384,24 +643,41 @@ private static List GetOpeningDatesGastronomy(ICollection x.State == 2 && x.Timecode == 1)) + foreach ( + var operationtime in operationschedule.OperationScheduleTime.Where( + x => x.State == 2 && x.Timecode == 1 + ) + ) { if (operationtime.Monday) - openingtime.Add("Mo " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Mo " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Tuesday) - openingtime.Add("Tu " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Tu " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Wednesday) - openingtime.Add("We " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "We " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Thuresday) - openingtime.Add("Th " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Th " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Friday) - openingtime.Add("Fr " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Fr " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Saturday) - openingtime.Add("Sa " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Sa " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Sunday) - openingtime.Add("Su " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Su " + operationtime.Start + " - " + operationtime.End + ); } - } //Keine Zeiten drinn @@ -415,7 +691,14 @@ private static List GetOpeningDatesGastronomy(ICollection TransformEventToLD(DataModel.Event theevent, string language, string passedid, string passedurl, string passedimage, bool showid) + private static List TransformEventToLD( + DataModel.Event theevent, + string language, + string passedid, + string passedurl, + string passedimage, + bool showid + ) { string fallbacklanguage = "en"; @@ -429,31 +712,49 @@ private static List GetOpeningDatesGastronomy(ICollection 0) - if (!String.IsNullOrEmpty(theevent.ImageGallery.FirstOrDefault().ImageUrl)) - myevent.Image = new Uri(theevent.ImageGallery.FirstOrDefault().ImageUrl + "&W=800"); + if ( + !String.IsNullOrEmpty( + theevent.ImageGallery.FirstOrDefault().ImageUrl + ) + ) + myevent.Image = new Uri( + theevent.ImageGallery.FirstOrDefault().ImageUrl + "&W=800" + ); } else myevent.Image = new Uri(passedimage); - //URL OVERWRITE if (String.IsNullOrEmpty(passedurl) && String.IsNullOrEmpty(passedid)) { - string url = theevent.ContactInfos.ContainsKey(language) ? theevent.ContactInfos[language].Url : theevent.ContactInfos.ContainsKey(fallbacklanguage) ? theevent.ContactInfos[fallbacklanguage].Url : ""; + string url = theevent.ContactInfos.ContainsKey(language) + ? theevent.ContactInfos[language].Url + : theevent.ContactInfos.ContainsKey(fallbacklanguage) + ? theevent.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(url)) myevent.Url = new Uri(url); } @@ -466,45 +767,93 @@ private static List GetOpeningDatesGastronomy(ICollection GetOpeningDatesGastronomy(ICollection GetOpeningDatesGastronomy(ICollection GetOpeningDatesGastronomy(ICollection languagelist) { var languagetoreturn = new Language(); - List languages = new List(); ; + List languages = new List(); + ; foreach (var lang in languagelist) { @@ -677,11 +1121,12 @@ private static Language GetAvailableLanguages(List languagelist) languagetoreturn.Name = languages.ToArray(); - return languagetoreturn; } - private static List GetOpeningDatesActivityPoi(ICollection operationschedules) + private static List GetOpeningDatesActivityPoi( + ICollection operationschedules + ) { List openingtime = new List(); @@ -691,36 +1136,62 @@ private static List GetOpeningDatesActivityPoi(ICollection x.Start <= DateTime.Now && x.Stop >= DateTime.Now && x.Type == "1")) + foreach ( + var operationschedule in operationschedules.Where( + x => x.Start <= DateTime.Now && x.Stop >= DateTime.Now && x.Type == "1" + ) + ) { if (operationschedule.OperationScheduleTime != null) { foreach (var operationtime in operationschedule.OperationScheduleTime) { - if (operationtime.Monday && operationtime.Tuesday && operationtime.Wednesday && operationtime.Thuresday && operationtime.Friday && operationtime.Saturday && operationtime.Sunday) + if ( + operationtime.Monday + && operationtime.Tuesday + && operationtime.Wednesday + && operationtime.Thuresday + && operationtime.Friday + && operationtime.Saturday + && operationtime.Sunday + ) { - openingtime.Add("Mo-Su " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Mo-Su " + operationtime.Start + " - " + operationtime.End + ); } else { - if (operationtime.Monday) - openingtime.Add("Mo " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Mo " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Tuesday) - openingtime.Add("Tu " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Tu " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Wednesday) - openingtime.Add("We " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "We " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Thuresday) - openingtime.Add("Th " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Th " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Friday) - openingtime.Add("Fr " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Fr " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Saturday) - openingtime.Add("Sa " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Sa " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Sunday) - openingtime.Add("Su " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Su " + operationtime.Start + " - " + operationtime.End + ); } } - } //No opening time defined always open? else @@ -752,7 +1223,6 @@ private static List GetOpeningDatesActivityPoi(ICollection 01-05-2018 <= 03-05-2018 && 01-10-2018 >= 03-05-2018 OK //Case 1 normal outside: start 01-05-2019 end 01-10-2019 Now: 05-11-2020 --> 01-05-2018 <= 05-11-2018 && 01-10-2018 >= 05-11-2018 NOT OK @@ -767,32 +1237,53 @@ private static List GetOpeningDatesActivityPoi(ICollection GetOpeningDatesActivityPoi(ICollection persons = new Tuple("persons", "person"); + Tuple persons = new Tuple( + "persons", + "person" + ); if (languagetouse == "de") persons = new Tuple("Personen", "Person"); else if (languagetouse == "it") @@ -965,8 +1475,6 @@ private static RecipeDetails GetRecipeDetails(DataModel.Article recipe, string l } else recipeYield = recipeelement.Value; - - } if (recipeelement.Key == "zeit") { @@ -979,7 +1487,6 @@ private static RecipeDetails GetRecipeDetails(DataModel.Article recipe, string l int kochzeithours = 0; int kochzeitminutes = 0; - int.TryParse(kochzeit[0], out kochzeithours); int.TryParse(kochzeit[1], out kochzeitminutes); @@ -1028,7 +1535,11 @@ private static RecipeDetails GetRecipeDetails(DataModel.Article recipe, string l int.TryParse(verbereitungszeit[1], out verbereitungszeitminutes); if (verbereitungszeithours != 0 || verbereitungszeitminutes != 0) - prepTime = new TimeSpan(verbereitungszeithours, verbereitungszeitminutes, 0); + prepTime = new TimeSpan( + verbereitungszeithours, + verbereitungszeitminutes, + 0 + ); } } //"keywords" @@ -1046,7 +1557,7 @@ private static RecipeDetails GetRecipeDetails(DataModel.Article recipe, string l { recipetypecuisine = recipeelement.Value; } - //NEW ADDED + //NEW ADDED //"kalorien" if (recipeelement.Key == "kalorien") { @@ -1057,7 +1568,6 @@ private static RecipeDetails GetRecipeDetails(DataModel.Article recipe, string l //"bewertung" if (recipeelement.Key == "bewertung") { - char[] separator = { '-' }; var rating = recipeelement.Value.Split(separator, 2); @@ -1074,12 +1584,11 @@ private static RecipeDetails GetRecipeDetails(DataModel.Article recipe, string l aggregaterating.BestRating = 10; } - //Organization trustyou = new Organization(); //trustyou.Name = "TrustYou"; //trustyou.Url = new Uri("https://www.trustyou.com/"); - //aggregaterating.Author = trustyou; + //aggregaterating.Author = trustyou; } //"author" @@ -1089,7 +1598,6 @@ private static RecipeDetails GetRecipeDetails(DataModel.Article recipe, string l author.Name = recipeelement.Value; } } - } } @@ -1112,7 +1620,15 @@ private static RecipeDetails GetRecipeDetails(DataModel.Article recipe, string l #region Skiarea - private static Schema.NET.SkiResort TransformSkiResortToLD(DataModel.SkiArea skiarea, DataModel.SkiRegion skiregion, string language, string passedid, string passedurl, string passedimage, bool showid) + private static Schema.NET.SkiResort TransformSkiResortToLD( + DataModel.SkiArea skiarea, + DataModel.SkiRegion skiregion, + string language, + string passedid, + string passedurl, + string passedimage, + bool showid + ) { string fallbacklanguage = "en"; @@ -1121,15 +1637,33 @@ private static Schema.NET.SkiResort TransformSkiResortToLD(DataModel.SkiArea ski if (showid) { if (String.IsNullOrEmpty(passedid)) - myskiarea.Id = new Uri("http://service.suedtirol.info/api/Common/SkiArea/" + skiarea.Id); + myskiarea.Id = new Uri( + "http://service.suedtirol.info/api/Common/SkiArea/" + skiarea.Id + ); else myskiarea.Id = new Uri(passedid); } - myskiarea.Description = skiarea.Detail.ContainsKey(language) ? skiarea.Detail[language].BaseText : skiarea.Detail.ContainsKey(fallbacklanguage) ? skiarea.Detail[fallbacklanguage].BaseText : ""; - myskiarea.FaxNumber = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].Faxnumber : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].Faxnumber : ""; - myskiarea.Name = skiarea.Detail.ContainsKey(language) ? skiarea.Detail[language].Title : skiarea.Detail.ContainsKey(fallbacklanguage) ? skiarea.Detail[fallbacklanguage].Title : ""; - myskiarea.Telephone = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].Phonenumber : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].Phonenumber : ""; + myskiarea.Description = skiarea.Detail.ContainsKey(language) + ? skiarea.Detail[language].BaseText + : skiarea.Detail.ContainsKey(fallbacklanguage) + ? skiarea.Detail[fallbacklanguage].BaseText + : ""; + myskiarea.FaxNumber = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].Faxnumber + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].Faxnumber + : ""; + myskiarea.Name = skiarea.Detail.ContainsKey(language) + ? skiarea.Detail[language].Title + : skiarea.Detail.ContainsKey(fallbacklanguage) + ? skiarea.Detail[fallbacklanguage].Title + : ""; + myskiarea.Telephone = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].Phonenumber + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].Phonenumber + : ""; //Image Overwrite if (String.IsNullOrEmpty(passedimage)) @@ -1137,7 +1671,9 @@ private static Schema.NET.SkiResort TransformSkiResortToLD(DataModel.SkiArea ski if (skiarea.ImageGallery != null) if (skiarea.ImageGallery.Count > 0) if (!String.IsNullOrEmpty(skiarea.ImageGallery.FirstOrDefault().ImageUrl)) - myskiarea.Image = new Uri(skiarea.ImageGallery.FirstOrDefault().ImageUrl); + myskiarea.Image = new Uri( + skiarea.ImageGallery.FirstOrDefault().ImageUrl + ); } else myskiarea.Image = new Uri(passedimage); @@ -1145,7 +1681,11 @@ private static Schema.NET.SkiResort TransformSkiResortToLD(DataModel.SkiArea ski //URL OVERWRITE if (String.IsNullOrEmpty(passedurl) && String.IsNullOrEmpty(passedid)) { - string url = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].Url : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].Url : ""; + string url = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].Url + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(url)) myskiarea.Url = new Uri(url); } @@ -1158,39 +1698,78 @@ private static Schema.NET.SkiResort TransformSkiResortToLD(DataModel.SkiArea ski myskiarea.Url = new Uri(passedid); } - string logo = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].LogoUrl : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].LogoUrl : ""; + string logo = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].LogoUrl + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].LogoUrl + : ""; if (CheckURLValid(logo)) myskiarea.Logo = new Uri(logo); - myskiarea.OpeningHours = GetOpeningDatesSkiArea(skiarea.OperationSchedule); - if (CheckURLValid(skiarea.SkiAreaMapURL)) myskiarea.HasMap = new Uri(skiarea.SkiAreaMapURL); myskiarea.IsAccessibleForFree = false; - - PostalAddress myaddress = new PostalAddress(); //myaddress.Type = "http://schema.org/PostalAddress"; - myaddress.StreetAddress = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].Address : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].Address : ""; - myaddress.PostalCode = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].ZipCode : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].ZipCode : ""; - myaddress.AddressLocality = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].City : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].City : ""; + myaddress.StreetAddress = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].Address + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].Address + : ""; + myaddress.PostalCode = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].ZipCode + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].ZipCode + : ""; + myaddress.AddressLocality = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].City + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].City + : ""; myaddress.AddressRegion = getRegionDependingonLanguage(language); - myaddress.AddressCountry = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].CountryName : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].CountryName : ""; - myaddress.Telephone = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].Phonenumber : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].Phonenumber : ""; - - string adressurl = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].Url : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].Url : ""; + myaddress.AddressCountry = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].CountryName + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].CountryName + : ""; + myaddress.Telephone = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].Phonenumber + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].Phonenumber + : ""; + + string adressurl = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].Url + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(adressurl)) myaddress.Url = new Uri(adressurl); - myaddress.Email = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].Email : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].Email : ""; - myaddress.FaxNumber = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].Faxnumber : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].Faxnumber : ""; - myaddress.AlternateName = skiarea.ContactInfos.ContainsKey(language) ? skiarea.ContactInfos[language].CompanyName : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.ContactInfos[fallbacklanguage].CompanyName : ""; - myaddress.Name = skiarea.ContactInfos.ContainsKey(language) ? skiarea.Detail[language].Title : skiarea.ContactInfos.ContainsKey(fallbacklanguage) ? skiarea.Detail[fallbacklanguage].Title : ""; - + myaddress.Email = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].Email + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].Email + : ""; + myaddress.FaxNumber = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].Faxnumber + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].Faxnumber + : ""; + myaddress.AlternateName = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.ContactInfos[language].CompanyName + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.ContactInfos[fallbacklanguage].CompanyName + : ""; + myaddress.Name = skiarea.ContactInfos.ContainsKey(language) + ? skiarea.Detail[language].Title + : skiarea.ContactInfos.ContainsKey(fallbacklanguage) + ? skiarea.Detail[fallbacklanguage].Title + : ""; myskiarea.Address = myaddress; @@ -1201,29 +1780,73 @@ private static Schema.NET.SkiResort TransformSkiResortToLD(DataModel.SkiArea ski myskiarea.Geo = mygeo; - //Mitglied OSA DSS + //Mitglied OSA DSS if (skiregion != null) { var parentorganization = new Organization(); - parentorganization.Description = skiregion.Detail.ContainsKey(language) ? skiregion.Detail[language].BaseText : skiregion.Detail.ContainsKey(fallbacklanguage) ? skiregion.Detail[fallbacklanguage].BaseText : ""; - parentorganization.FaxNumber = skiregion.ContactInfos.ContainsKey(language) ? skiregion.ContactInfos[language].Faxnumber : skiregion.ContactInfos.ContainsKey(fallbacklanguage) ? skiregion.ContactInfos[fallbacklanguage].Faxnumber : ""; - parentorganization.Name = skiregion.Detail.ContainsKey(language) ? skiregion.Detail[language].Title : skiregion.Detail.ContainsKey(fallbacklanguage) ? skiregion.Detail[fallbacklanguage].Title : ""; - parentorganization.Telephone = skiregion.ContactInfos.ContainsKey(language) ? skiregion.ContactInfos[language].Phonenumber : skiregion.ContactInfos.ContainsKey(fallbacklanguage) ? skiregion.ContactInfos[fallbacklanguage].Phonenumber : ""; - string url = skiregion.ContactInfos.ContainsKey(language) ? skiregion.ContactInfos[language].Url : skiregion.ContactInfos.ContainsKey(fallbacklanguage) ? skiregion.ContactInfos[fallbacklanguage].Url : ""; + parentorganization.Description = skiregion.Detail.ContainsKey(language) + ? skiregion.Detail[language].BaseText + : skiregion.Detail.ContainsKey(fallbacklanguage) + ? skiregion.Detail[fallbacklanguage].BaseText + : ""; + parentorganization.FaxNumber = skiregion.ContactInfos.ContainsKey(language) + ? skiregion.ContactInfos[language].Faxnumber + : skiregion.ContactInfos.ContainsKey(fallbacklanguage) + ? skiregion.ContactInfos[fallbacklanguage].Faxnumber + : ""; + parentorganization.Name = skiregion.Detail.ContainsKey(language) + ? skiregion.Detail[language].Title + : skiregion.Detail.ContainsKey(fallbacklanguage) + ? skiregion.Detail[fallbacklanguage].Title + : ""; + parentorganization.Telephone = skiregion.ContactInfos.ContainsKey(language) + ? skiregion.ContactInfos[language].Phonenumber + : skiregion.ContactInfos.ContainsKey(fallbacklanguage) + ? skiregion.ContactInfos[fallbacklanguage].Phonenumber + : ""; + string url = skiregion.ContactInfos.ContainsKey(language) + ? skiregion.ContactInfos[language].Url + : skiregion.ContactInfos.ContainsKey(fallbacklanguage) + ? skiregion.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(url)) parentorganization.Url = new Uri(url); PostalAddress myskiregionaddress = new PostalAddress(); //myaddress.Type = "http://schema.org/PostalAddress"; - myskiregionaddress.StreetAddress = skiregion.ContactInfos.ContainsKey(language) ? skiregion.ContactInfos[language].Address : skiregion.ContactInfos.ContainsKey(fallbacklanguage) ? skiregion.ContactInfos[fallbacklanguage].Address : ""; - myskiregionaddress.PostalCode = skiregion.ContactInfos.ContainsKey(language) ? skiregion.ContactInfos[language].ZipCode : skiregion.ContactInfos.ContainsKey(fallbacklanguage) ? skiregion.ContactInfos[fallbacklanguage].ZipCode : ""; - myskiregionaddress.AddressLocality = skiregion.ContactInfos.ContainsKey(language) ? skiregion.ContactInfos[language].City : skiregion.ContactInfos.ContainsKey(fallbacklanguage) ? skiregion.ContactInfos[fallbacklanguage].City : ""; + myskiregionaddress.StreetAddress = skiregion.ContactInfos.ContainsKey(language) + ? skiregion.ContactInfos[language].Address + : skiregion.ContactInfos.ContainsKey(fallbacklanguage) + ? skiregion.ContactInfos[fallbacklanguage].Address + : ""; + myskiregionaddress.PostalCode = skiregion.ContactInfos.ContainsKey(language) + ? skiregion.ContactInfos[language].ZipCode + : skiregion.ContactInfos.ContainsKey(fallbacklanguage) + ? skiregion.ContactInfos[fallbacklanguage].ZipCode + : ""; + myskiregionaddress.AddressLocality = skiregion.ContactInfos.ContainsKey(language) + ? skiregion.ContactInfos[language].City + : skiregion.ContactInfos.ContainsKey(fallbacklanguage) + ? skiregion.ContactInfos[fallbacklanguage].City + : ""; myskiregionaddress.AddressRegion = getRegionDependingonLanguage(language); - myskiregionaddress.AddressCountry = skiregion.ContactInfos.ContainsKey(language) ? skiregion.ContactInfos[language].CountryName : skiregion.ContactInfos.ContainsKey(fallbacklanguage) ? skiregion.ContactInfos[fallbacklanguage].CountryName : ""; - myskiregionaddress.Telephone = skiregion.ContactInfos.ContainsKey(language) ? skiregion.ContactInfos[language].Phonenumber : skiregion.ContactInfos.ContainsKey(fallbacklanguage) ? skiregion.ContactInfos[fallbacklanguage].Phonenumber : ""; - - string adressurlskiregion = skiregion.ContactInfos.ContainsKey(language) ? skiregion.ContactInfos[language].Url : skiregion.ContactInfos.ContainsKey(fallbacklanguage) ? skiregion.ContactInfos[fallbacklanguage].Url : ""; + myskiregionaddress.AddressCountry = skiregion.ContactInfos.ContainsKey(language) + ? skiregion.ContactInfos[language].CountryName + : skiregion.ContactInfos.ContainsKey(fallbacklanguage) + ? skiregion.ContactInfos[fallbacklanguage].CountryName + : ""; + myskiregionaddress.Telephone = skiregion.ContactInfos.ContainsKey(language) + ? skiregion.ContactInfos[language].Phonenumber + : skiregion.ContactInfos.ContainsKey(fallbacklanguage) + ? skiregion.ContactInfos[fallbacklanguage].Phonenumber + : ""; + + string adressurlskiregion = skiregion.ContactInfos.ContainsKey(language) + ? skiregion.ContactInfos[language].Url + : skiregion.ContactInfos.ContainsKey(fallbacklanguage) + ? skiregion.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(adressurl)) myskiregionaddress.Url = new Uri(adressurlskiregion); @@ -1232,7 +1855,6 @@ private static Schema.NET.SkiResort TransformSkiResortToLD(DataModel.SkiArea ski myskiarea.ParentOrganization = parentorganization; } - //PriceRange var liftcount = 0; if (int.TryParse(skiarea.LiftCount, out liftcount)) @@ -1248,48 +1870,75 @@ private static Schema.NET.SkiResort TransformSkiResortToLD(DataModel.SkiArea ski } } - return myskiarea; } - private static List GetOpeningDatesSkiArea(ICollection operationschedules) + private static List GetOpeningDatesSkiArea( + ICollection operationschedules + ) { List openingtime = new List(); if (operationschedules != null) { - foreach (var operationschedule in operationschedules.Where(x => x.Start <= DateTime.Now && x.Stop >= DateTime.Now)) + foreach ( + var operationschedule in operationschedules.Where( + x => x.Start <= DateTime.Now && x.Stop >= DateTime.Now + ) + ) { - //IF there are + //IF there are if (operationschedule.OperationScheduleTime != null) { foreach (var operationtime in operationschedule.OperationScheduleTime) { - if (operationtime.Monday && operationtime.Tuesday && operationtime.Wednesday && operationtime.Thuresday && operationtime.Friday && operationtime.Saturday && operationtime.Sunday) + if ( + operationtime.Monday + && operationtime.Tuesday + && operationtime.Wednesday + && operationtime.Thuresday + && operationtime.Friday + && operationtime.Saturday + && operationtime.Sunday + ) { - openingtime.Add("Mo-Su " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Mo-Su " + operationtime.Start + " - " + operationtime.End + ); } else { - if (operationtime.Monday) - openingtime.Add("Mo " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Mo " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Tuesday) - openingtime.Add("Tu " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Tu " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Wednesday) - openingtime.Add("We " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "We " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Thuresday) - openingtime.Add("Th " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Th " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Friday) - openingtime.Add("Fr " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Fr " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Saturday) - openingtime.Add("Sa " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Sa " + operationtime.Start + " - " + operationtime.End + ); if (operationtime.Sunday) - openingtime.Add("Su " + operationtime.Start + " - " + operationtime.End); + openingtime.Add( + "Su " + operationtime.Start + " - " + operationtime.End + ); } } - } //No opening time defined valid for whole week default time entered for skiareas 08:30 - 16:30 else @@ -1302,12 +1951,18 @@ private static List GetOpeningDatesSkiArea(ICollection 0) - if (!String.IsNullOrEmpty(placetotrasform.ImageGallery.FirstOrDefault().ImageUrl)) - place.Image = new Uri(placetotrasform.ImageGallery.FirstOrDefault().ImageUrl); + if ( + !String.IsNullOrEmpty( + placetotrasform.ImageGallery.FirstOrDefault().ImageUrl + ) + ) + place.Image = new Uri( + placetotrasform.ImageGallery.FirstOrDefault().ImageUrl + ); } else place.Image = new Uri(passedimage); @@ -1341,7 +2020,11 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.Region placetotrasf // URL OVERWRITE if (String.IsNullOrEmpty(passedurl) && String.IsNullOrEmpty(passedid)) { - string url = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Url : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Url : ""; + string url = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Url + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(url)) place.Url = new Uri(url); } @@ -1356,29 +2039,71 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.Region placetotrasf place.Url = new Uri(passedid); } - string logo = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].LogoUrl : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].LogoUrl : ""; + string logo = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].LogoUrl + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].LogoUrl + : ""; if (CheckURLValid(logo)) place.Logo = new Uri(logo); - PostalAddress myaddress = new PostalAddress(); //myaddress.Type = "http://schema.org/PostalAddress"; - myaddress.StreetAddress = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Address : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Address : ""; - myaddress.PostalCode = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].ZipCode : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].ZipCode : ""; - myaddress.AddressLocality = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].City : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].City : ""; + myaddress.StreetAddress = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Address + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Address + : ""; + myaddress.PostalCode = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].ZipCode + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].ZipCode + : ""; + myaddress.AddressLocality = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].City + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].City + : ""; myaddress.AddressRegion = getRegionDependingonLanguage(language); - myaddress.AddressCountry = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].CountryName : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].CountryName : ""; - myaddress.Telephone = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Phonenumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber : ""; - - string adressurl = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Url : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Url : ""; + myaddress.AddressCountry = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].CountryName + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].CountryName + : ""; + myaddress.Telephone = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Phonenumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber + : ""; + + string adressurl = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Url + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(adressurl)) myaddress.Url = new Uri(adressurl); - myaddress.Email = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Email : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Email : ""; - myaddress.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Faxnumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber : ""; - myaddress.AlternateName = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].CompanyName : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].CompanyName : ""; - myaddress.Name = placetotrasform.Detail.ContainsKey(language) ? placetotrasform.Detail[language].Title : placetotrasform.Detail.ContainsKey(fallbacklanguage) ? placetotrasform.Detail[fallbacklanguage].Title : ""; - + myaddress.Email = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Email + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Email + : ""; + myaddress.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Faxnumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber + : ""; + myaddress.AlternateName = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].CompanyName + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].CompanyName + : ""; + myaddress.Name = placetotrasform.Detail.ContainsKey(language) + ? placetotrasform.Detail[language].Title + : placetotrasform.Detail.ContainsKey(fallbacklanguage) + ? placetotrasform.Detail[fallbacklanguage].Title + : ""; place.Address = myaddress; @@ -1392,7 +2117,14 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.Region placetotrasf return place; } - private static Schema.NET.Place TransformPlaceToLD(DataModel.Tourismverein placetotrasform, string language, string passedid, string passedurl, string passedimage, bool showid) + private static Schema.NET.Place TransformPlaceToLD( + DataModel.Tourismverein placetotrasform, + string language, + string passedid, + string passedurl, + string passedimage, + bool showid + ) { string fallbacklanguage = "en"; @@ -1401,25 +2133,49 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.Tourismverein place if (showid) { if (String.IsNullOrEmpty(passedid)) - place.Id = new Uri("http://service.suedtirol.info/api/Common/TourismAssociation/" + placetotrasform.Id); + place.Id = new Uri( + "http://service.suedtirol.info/api/Common/TourismAssociation/" + + placetotrasform.Id + ); else place.Id = new Uri(passedid); } - place.Description = placetotrasform.Detail.ContainsKey(language) ? placetotrasform.Detail[language].BaseText : placetotrasform.Detail.ContainsKey(fallbacklanguage) ? placetotrasform.Detail[fallbacklanguage].BaseText : ""; - place.Name = placetotrasform.Detail.ContainsKey(language) ? placetotrasform.Detail[language].Title : placetotrasform.Detail.ContainsKey(fallbacklanguage) ? placetotrasform.Detail[fallbacklanguage].Title : ""; - - place.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Faxnumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber : ""; - place.Telephone = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Phonenumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber : ""; - + place.Description = placetotrasform.Detail.ContainsKey(language) + ? placetotrasform.Detail[language].BaseText + : placetotrasform.Detail.ContainsKey(fallbacklanguage) + ? placetotrasform.Detail[fallbacklanguage].BaseText + : ""; + place.Name = placetotrasform.Detail.ContainsKey(language) + ? placetotrasform.Detail[language].Title + : placetotrasform.Detail.ContainsKey(fallbacklanguage) + ? placetotrasform.Detail[fallbacklanguage].Title + : ""; + + place.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Faxnumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber + : ""; + place.Telephone = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Phonenumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber + : ""; //Image Overwrite if (String.IsNullOrEmpty(passedimage)) { if (placetotrasform.ImageGallery != null) if (placetotrasform.ImageGallery.Count > 0) - if (!String.IsNullOrEmpty(placetotrasform.ImageGallery.FirstOrDefault().ImageUrl)) - place.Image = new Uri(placetotrasform.ImageGallery.FirstOrDefault().ImageUrl); + if ( + !String.IsNullOrEmpty( + placetotrasform.ImageGallery.FirstOrDefault().ImageUrl + ) + ) + place.Image = new Uri( + placetotrasform.ImageGallery.FirstOrDefault().ImageUrl + ); } else place.Image = new Uri(passedimage); @@ -1427,7 +2183,11 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.Tourismverein place //URL OVERWRITE if (String.IsNullOrEmpty(passedurl) && String.IsNullOrEmpty(passedid)) { - string url = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Url : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Url : ""; + string url = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Url + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(url)) place.Url = new Uri(url); } @@ -1442,29 +2202,71 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.Tourismverein place place.Url = new Uri(passedid); } - string logo = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].LogoUrl : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].LogoUrl : ""; + string logo = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].LogoUrl + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].LogoUrl + : ""; if (CheckURLValid(logo)) place.Logo = new Uri(logo); - PostalAddress myaddress = new PostalAddress(); //myaddress.Type = "http://schema.org/PostalAddress"; - myaddress.StreetAddress = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Address : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Address : ""; - myaddress.PostalCode = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].ZipCode : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].ZipCode : ""; - myaddress.AddressLocality = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].City : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].City : ""; + myaddress.StreetAddress = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Address + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Address + : ""; + myaddress.PostalCode = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].ZipCode + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].ZipCode + : ""; + myaddress.AddressLocality = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].City + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].City + : ""; myaddress.AddressRegion = getRegionDependingonLanguage(language); - myaddress.AddressCountry = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].CountryName : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].CountryName : ""; - myaddress.Telephone = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Phonenumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber : ""; - - string adressurl = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Url : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Url : ""; + myaddress.AddressCountry = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].CountryName + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].CountryName + : ""; + myaddress.Telephone = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Phonenumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber + : ""; + + string adressurl = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Url + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(adressurl)) myaddress.Url = new Uri(adressurl); - myaddress.Email = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Email : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Email : ""; - myaddress.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Faxnumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber : ""; - myaddress.AlternateName = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].CompanyName : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].CompanyName : ""; - myaddress.Name = placetotrasform.Detail.ContainsKey(language) ? placetotrasform.Detail[language].Title : placetotrasform.Detail.ContainsKey(fallbacklanguage) ? placetotrasform.Detail[fallbacklanguage].Title : ""; - + myaddress.Email = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Email + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Email + : ""; + myaddress.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Faxnumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber + : ""; + myaddress.AlternateName = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].CompanyName + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].CompanyName + : ""; + myaddress.Name = placetotrasform.Detail.ContainsKey(language) + ? placetotrasform.Detail[language].Title + : placetotrasform.Detail.ContainsKey(fallbacklanguage) + ? placetotrasform.Detail[fallbacklanguage].Title + : ""; place.Address = myaddress; @@ -1478,7 +2280,14 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.Tourismverein place return place; } - private static Schema.NET.Place TransformPlaceToLD(DataModel.Municipality placetotrasform, string language, string passedid, string passedurl, string passedimage, bool showid) + private static Schema.NET.Place TransformPlaceToLD( + DataModel.Municipality placetotrasform, + string language, + string passedid, + string passedurl, + string passedimage, + bool showid + ) { string fallbacklanguage = "en"; @@ -1487,33 +2296,61 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.Municipality placet if (showid) { if (String.IsNullOrEmpty(passedid)) - place.Id = new Uri("http://service.suedtirol.info/api/Common/Municipality/" + placetotrasform.Id); + place.Id = new Uri( + "http://service.suedtirol.info/api/Common/Municipality/" + + placetotrasform.Id + ); else place.Id = new Uri(passedid); } - place.Description = placetotrasform.Detail.ContainsKey(language) ? placetotrasform.Detail[language].BaseText : placetotrasform.Detail.ContainsKey(fallbacklanguage) ? placetotrasform.Detail[fallbacklanguage].BaseText : ""; - place.Name = placetotrasform.Detail.ContainsKey(language) ? placetotrasform.Detail[language].Title : placetotrasform.Detail.ContainsKey(fallbacklanguage) ? placetotrasform.Detail[fallbacklanguage].Title : ""; - - place.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Faxnumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber : ""; - place.Telephone = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Phonenumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber : ""; + place.Description = placetotrasform.Detail.ContainsKey(language) + ? placetotrasform.Detail[language].BaseText + : placetotrasform.Detail.ContainsKey(fallbacklanguage) + ? placetotrasform.Detail[fallbacklanguage].BaseText + : ""; + place.Name = placetotrasform.Detail.ContainsKey(language) + ? placetotrasform.Detail[language].Title + : placetotrasform.Detail.ContainsKey(fallbacklanguage) + ? placetotrasform.Detail[fallbacklanguage].Title + : ""; + + place.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Faxnumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber + : ""; + place.Telephone = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Phonenumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber + : ""; //Image Overwrite if (String.IsNullOrEmpty(passedimage)) { if (placetotrasform.ImageGallery != null) if (placetotrasform.ImageGallery.Count > 0) - if (!String.IsNullOrEmpty(placetotrasform.ImageGallery.FirstOrDefault().ImageUrl)) - place.Image = new Uri(placetotrasform.ImageGallery.FirstOrDefault().ImageUrl); + if ( + !String.IsNullOrEmpty( + placetotrasform.ImageGallery.FirstOrDefault().ImageUrl + ) + ) + place.Image = new Uri( + placetotrasform.ImageGallery.FirstOrDefault().ImageUrl + ); } else place.Image = new Uri(passedimage); - //URL OVERWRITE if (String.IsNullOrEmpty(passedurl) && String.IsNullOrEmpty(passedid)) { - string url = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Url : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Url : ""; + string url = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Url + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(url)) place.Url = new Uri(url); } @@ -1528,28 +2365,71 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.Municipality placet place.Url = new Uri(passedid); } - string logo = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].LogoUrl : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].LogoUrl : ""; + string logo = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].LogoUrl + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].LogoUrl + : ""; if (CheckURLValid(logo)) place.Logo = new Uri(logo); PostalAddress myaddress = new PostalAddress(); //myaddress.Type = "http://schema.org/PostalAddress"; - myaddress.StreetAddress = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Address : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Address : ""; - myaddress.PostalCode = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].ZipCode : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].ZipCode : ""; - myaddress.AddressLocality = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].City : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].City : ""; + myaddress.StreetAddress = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Address + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Address + : ""; + myaddress.PostalCode = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].ZipCode + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].ZipCode + : ""; + myaddress.AddressLocality = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].City + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].City + : ""; myaddress.AddressRegion = getRegionDependingonLanguage(language); - myaddress.AddressCountry = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].CountryName : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].CountryName : ""; - myaddress.Telephone = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Phonenumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber : ""; - - string adressurl = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Url : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Url : ""; + myaddress.AddressCountry = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].CountryName + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].CountryName + : ""; + myaddress.Telephone = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Phonenumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber + : ""; + + string adressurl = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Url + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(adressurl)) myaddress.Url = new Uri(adressurl); - myaddress.Email = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Email : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Email : ""; - myaddress.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Faxnumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber : ""; - myaddress.AlternateName = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].CompanyName : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].CompanyName : ""; - myaddress.Name = placetotrasform.Detail.ContainsKey(language) ? placetotrasform.Detail[language].Title : placetotrasform.Detail.ContainsKey(fallbacklanguage) ? placetotrasform.Detail[fallbacklanguage].Title : ""; - + myaddress.Email = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Email + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Email + : ""; + myaddress.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Faxnumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber + : ""; + myaddress.AlternateName = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].CompanyName + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].CompanyName + : ""; + myaddress.Name = placetotrasform.Detail.ContainsKey(language) + ? placetotrasform.Detail[language].Title + : placetotrasform.Detail.ContainsKey(fallbacklanguage) + ? placetotrasform.Detail[fallbacklanguage].Title + : ""; place.Address = myaddress; @@ -1563,7 +2443,14 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.Municipality placet return place; } - private static Schema.NET.Place TransformPlaceToLD(DataModel.District placetotrasform, string language, string passedid, string passedurl, string passedimage, bool showid) + private static Schema.NET.Place TransformPlaceToLD( + DataModel.District placetotrasform, + string language, + string passedid, + string passedurl, + string passedimage, + bool showid + ) { string fallbacklanguage = "en"; //Winery, Museum @@ -1573,25 +2460,48 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.District placetotra if (showid) { if (String.IsNullOrEmpty(passedid)) - place.Id = new Uri("http://service.suedtirol.info/api/Common/District/" + placetotrasform.Id); + place.Id = new Uri( + "http://service.suedtirol.info/api/Common/District/" + placetotrasform.Id + ); else place.Id = new Uri(passedid); } - place.Description = placetotrasform.Detail.ContainsKey(language) ? placetotrasform.Detail[language].BaseText : placetotrasform.Detail.ContainsKey(fallbacklanguage) ? placetotrasform.Detail[fallbacklanguage].BaseText : ""; - place.Name = placetotrasform.Detail.ContainsKey(language) ? placetotrasform.Detail[language].Title : placetotrasform.Detail.ContainsKey(fallbacklanguage) ? placetotrasform.Detail[fallbacklanguage].Title : ""; - - place.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Faxnumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber : ""; - place.Telephone = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Phonenumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber : ""; - + place.Description = placetotrasform.Detail.ContainsKey(language) + ? placetotrasform.Detail[language].BaseText + : placetotrasform.Detail.ContainsKey(fallbacklanguage) + ? placetotrasform.Detail[fallbacklanguage].BaseText + : ""; + place.Name = placetotrasform.Detail.ContainsKey(language) + ? placetotrasform.Detail[language].Title + : placetotrasform.Detail.ContainsKey(fallbacklanguage) + ? placetotrasform.Detail[fallbacklanguage].Title + : ""; + + place.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Faxnumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber + : ""; + place.Telephone = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Phonenumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber + : ""; //Image Overwrite if (String.IsNullOrEmpty(passedimage)) { if (placetotrasform.ImageGallery != null) if (placetotrasform.ImageGallery.Count > 0) - if (!String.IsNullOrEmpty(placetotrasform.ImageGallery.FirstOrDefault().ImageUrl)) - place.Image = new Uri(placetotrasform.ImageGallery.FirstOrDefault().ImageUrl); + if ( + !String.IsNullOrEmpty( + placetotrasform.ImageGallery.FirstOrDefault().ImageUrl + ) + ) + place.Image = new Uri( + placetotrasform.ImageGallery.FirstOrDefault().ImageUrl + ); } else place.Image = new Uri(passedimage); @@ -1599,7 +2509,11 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.District placetotra //URL OVERWRITE if (String.IsNullOrEmpty(passedurl) && String.IsNullOrEmpty(passedid)) { - string url = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Url : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Url : ""; + string url = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Url + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(url)) place.Url = new Uri(url); } @@ -1614,30 +2528,71 @@ private static Schema.NET.Place TransformPlaceToLD(DataModel.District placetotra place.Url = new Uri(passedid); } - - string logo = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].LogoUrl : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].LogoUrl : ""; + string logo = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].LogoUrl + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].LogoUrl + : ""; if (CheckURLValid(logo)) place.Logo = new Uri(logo); - PostalAddress myaddress = new PostalAddress(); //myaddress.Type = "http://schema.org/PostalAddress"; - myaddress.StreetAddress = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Address : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Address : ""; - myaddress.PostalCode = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].ZipCode : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].ZipCode : ""; - myaddress.AddressLocality = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].City : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].City : ""; + myaddress.StreetAddress = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Address + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Address + : ""; + myaddress.PostalCode = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].ZipCode + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].ZipCode + : ""; + myaddress.AddressLocality = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].City + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].City + : ""; myaddress.AddressRegion = getRegionDependingonLanguage(language); - myaddress.AddressCountry = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].CountryName : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].CountryName : ""; - myaddress.Telephone = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Phonenumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber : ""; - - string adressurl = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Url : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Url : ""; + myaddress.AddressCountry = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].CountryName + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].CountryName + : ""; + myaddress.Telephone = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Phonenumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Phonenumber + : ""; + + string adressurl = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Url + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Url + : ""; if (CheckURLValid(adressurl)) myaddress.Url = new Uri(adressurl); - myaddress.Email = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Email : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Email : ""; - myaddress.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].Faxnumber : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber : ""; - myaddress.AlternateName = placetotrasform.ContactInfos.ContainsKey(language) ? placetotrasform.ContactInfos[language].CompanyName : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) ? placetotrasform.ContactInfos[fallbacklanguage].CompanyName : ""; - myaddress.Name = placetotrasform.Detail.ContainsKey(language) ? placetotrasform.Detail[language].Title : placetotrasform.Detail.ContainsKey(fallbacklanguage) ? placetotrasform.Detail[fallbacklanguage].Title : ""; - + myaddress.Email = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Email + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Email + : ""; + myaddress.FaxNumber = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].Faxnumber + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].Faxnumber + : ""; + myaddress.AlternateName = placetotrasform.ContactInfos.ContainsKey(language) + ? placetotrasform.ContactInfos[language].CompanyName + : placetotrasform.ContactInfos.ContainsKey(fallbacklanguage) + ? placetotrasform.ContactInfos[fallbacklanguage].CompanyName + : ""; + myaddress.Name = placetotrasform.Detail.ContainsKey(language) + ? placetotrasform.Detail[language].Title + : placetotrasform.Detail.ContainsKey(fallbacklanguage) + ? placetotrasform.Detail[fallbacklanguage].Title + : ""; place.Address = myaddress; @@ -1706,7 +2661,8 @@ private static string getCountryDependingonLanguage(string language) public static bool CheckURLValid(string source) { Uri uriResult; - return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp; + return Uri.TryCreate(source, UriKind.Absolute, out uriResult) + && uriResult.Scheme == Uri.UriSchemeHttp; } } @@ -1720,23 +2676,23 @@ public class RecipeDetails //NEW //"kalorien" --> nutrition (Nutritioninformation.... calories) public NutritionInformation recipeNutritionInfo { get; set; } + //"vorbereitungszeit" --> prepTime (Duration) public TimeSpan prepTime { get; set; } + //"keywords" --> keywords (TEXT) public string recipeKeywords { get; set; } + //"kategorie" --> recipecategory (TEXT) public string recipeCategory { get; set; } //"artkueche" --> recipecousine (TEXT) public string recipeCuisinetype { get; set; } - //"author" --> author (Organization or Person) public Organization author { get; set; } //"bewertung" --> aggregaterating (Aggregaterating) public AggregateRating aggregateRating { get; set; } - - } } diff --git a/LCS/AccommodationDataLCS.cs b/LCS/AccommodationDataLCS.cs index 9b044e676..f0d5e26fc 100644 --- a/LCS/AccommodationDataLCS.cs +++ b/LCS/AccommodationDataLCS.cs @@ -14,8 +14,8 @@ public class GetAccommodationDataLCS public GetAccommodationDataLCS(string user, string pswd) { - //https://medium.com/grensesnittet/integrating-with-soap-web-services-in-net-core-adebfad173fb - //https://github.com/dotnet/wcf/issues/8 + //https://medium.com/grensesnittet/integrating-with-soap-web-services-in-net-core-adebfad173fb + //https://github.com/dotnet/wcf/issues/8 BasicHttpsBinding basicHttpBinding = new BasicHttpsBinding(); //basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; @@ -27,8 +27,9 @@ public GetAccommodationDataLCS(string user, string pswd) basicHttpBinding.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; basicHttpBinding.AllowCookies = true; - - EndpointAddress endpointAddress = new EndpointAddress("https://lcs.lts.it/api/data.svc/soap"); + EndpointAddress endpointAddress = new EndpointAddress( + "https://lcs.lts.it/api/data.svc/soap" + ); lcs = new ServiceReferenceLCS.DataClient(basicHttpBinding, endpointAddress); lcs.ClientCredentials.UserName.UserName = user; @@ -38,7 +39,9 @@ public GetAccommodationDataLCS(string user, string pswd) } //Accommodation Search - public ServiceReferenceLCS.AccommodationDataSearchRS GetAccommodationDataSearch(XElement myrequest) + public ServiceReferenceLCS.AccommodationDataSearchRS GetAccommodationDataSearch( + XElement myrequest + ) { try { @@ -53,7 +56,9 @@ public ServiceReferenceLCS.AccommodationDataSearchRS GetAccommodationDataSearch( } //Accommodation Search - public async Task GetAccommodationDataSearchAsync(XElement myrequest) + public async Task GetAccommodationDataSearchAsync( + XElement myrequest + ) { try { @@ -66,32 +71,32 @@ public ServiceReferenceLCS.AccommodationDataSearchRS GetAccommodationDataSearch( } public static XElement GetAccommodationDataSearchRequest( - string resultRID, - string pageNr, - string pageSize, - string language, - string sortingcriterion, - string sortingorder, - string sortingpromotebookable, - string request, - string filters, - string timespanstart, - string timespanend, - string checkavailabilitystatus, - string onlybookableresults, - List mealplans, - List accommodationrids, - List tourismorg, - List districts, - List marketinggroups, - List lcsroomstay, - string requestor, - string messagepswd - ) + string resultRID, + string pageNr, + string pageSize, + string language, + string sortingcriterion, + string sortingorder, + string sortingpromotebookable, + string request, + string filters, + string timespanstart, + string timespanend, + string checkavailabilitystatus, + string onlybookableresults, + List mealplans, + List accommodationrids, + List tourismorg, + List districts, + List marketinggroups, + List lcsroomstay, + string requestor, + string messagepswd + ) { XElement requestbody = new XElement("AccommodationDataSearchRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, messagepswd)); //Ende POS Element @@ -127,7 +132,11 @@ string messagepswd //"" - if (!String.IsNullOrEmpty(sortingcriterion) || !String.IsNullOrEmpty(sortingorder) || !String.IsNullOrEmpty(sortingpromotebookable)) + if ( + !String.IsNullOrEmpty(sortingcriterion) + || !String.IsNullOrEmpty(sortingorder) + || !String.IsNullOrEmpty(sortingpromotebookable) + ) { XElement sortingquery = new XElement("Sorting"); sortingquery.Add(new XAttribute("Criterion", sortingcriterion)); @@ -149,7 +158,6 @@ string messagepswd if (marketinggroups.Count > 0) parameters.Add(GetMarketingGroups(marketinggroups)); - // "" + if (!String.IsNullOrEmpty(timespanstart) && !String.IsNullOrEmpty(timespanend)) { @@ -165,7 +173,9 @@ string messagepswd if (!String.IsNullOrEmpty(onlybookableresults)) { XElement onlybookableresultsquery = new XElement("AdvanceBookingRestriction"); - onlybookableresultsquery.Add(new XAttribute("OnlyBookableResults", onlybookableresults)); + onlybookableresultsquery.Add( + new XAttribute("OnlyBookableResults", onlybookableresults) + ); parameters.Add(onlybookableresultsquery); } //Ende Searchtermphrase @@ -185,9 +195,6 @@ string messagepswd parameters.Add(myroomstaydata); } - - - //Facilities //if (facilities.Count > 0) // parameters.Add(GetFacilities(facilities)); @@ -362,7 +369,7 @@ public static List RoomstayTransformer(string roominfo) { if (!String.IsNullOrEmpty(roominfo) && roominfo != "null") { - //roominfo aufteilen Form 1Z-1P-18 oder 1Z-2P-18.18,1Z-1P-18 + //roominfo aufteilen Form 1Z-1P-18 oder 1Z-2P-18.18,1Z-1P-18 List myroominfo = new List(); var zimmerinfos = roominfo.Split('|'); @@ -397,7 +404,15 @@ public static List RoomstayTransformer(string roominfo) else { List myroominfostd = new List(); - myroominfostd.Add(new LCSRoomStay() { Index = "1", Type = "0", Guests = "2", Age = new List() { "18", "18" } }); + myroominfostd.Add( + new LCSRoomStay() + { + Index = "1", + Type = "0", + Guests = "2", + Age = new List() { "18", "18" } + } + ); return myroominfostd; } diff --git a/LCS/GetActivityDataLCS.cs b/LCS/GetActivityDataLCS.cs index 4691f4ac4..4431eabf8 100644 --- a/LCS/GetActivityDataLCS.cs +++ b/LCS/GetActivityDataLCS.cs @@ -27,7 +27,9 @@ public GetActivityDataLCS(string user, string pswd) basicHttpBinding.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; basicHttpBinding.AllowCookies = true; - EndpointAddress endpointAddress = new EndpointAddress("https://lcs.lts.it/api/data.svc/soap"); + EndpointAddress endpointAddress = new EndpointAddress( + "https://lcs.lts.it/api/data.svc/soap" + ); lcs = new ServiceReferenceLCS.DataClient(basicHttpBinding, endpointAddress); lcs.ClientCredentials.UserName.UserName = user; @@ -58,14 +60,18 @@ public ServiceReferenceLCS.ActivityChangedItemsRS GetActivityChanged(XElement my } //Weather Snow Observation Search - public ServiceReferenceLCS.WeatherSnowObservationSearchRS GetWeatherSnowSearch(XElement myrequest) + public ServiceReferenceLCS.WeatherSnowObservationSearchRS GetWeatherSnowSearch( + XElement myrequest + ) { var activitysearch = lcs.oWeatherSnowObservationSearch(myrequest.ToXmlElement()); return activitysearch; } //Weather Snow Observation Detail - public ServiceReferenceLCS.WeatherSnowObservationDetailRS GetWeatherSnowDetail(XElement myrequest) + public ServiceReferenceLCS.WeatherSnowObservationDetailRS GetWeatherSnowDetail( + XElement myrequest + ) { var activitydetail = lcs.oWeatherSnowObservationDetail(myrequest.ToXmlElement()); return activitydetail; @@ -119,12 +125,11 @@ public static XElement GetActivitySearchRequestAsync( List activityprefilter, string requestor, string ltsmsgpswd - ) + ) { - XElement requestbody = new XElement("ActivitySearchRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Ende POS Element @@ -172,7 +177,10 @@ string ltsmsgpswd if (!String.IsNullOrEmpty(sortcriterion)) { XElement sortcrit = new XElement("Sorting"); - sortcrit.Add(new XAttribute("Criterion", sortcriterion), new XAttribute("Order", order)); + sortcrit.Add( + new XAttribute("Criterion", sortcriterion), + new XAttribute("Order", order) + ); parameters.Add(sortcrit); } //Ende Sorting @@ -197,7 +205,7 @@ string ltsmsgpswd parameters.Add(GetOwners(ownercodes)); requestbody.Add(parameters); - //Ende Parameters + //Ende Parameters //Filters requestbody.Add(GetActivityPrefilters(activityprefilter)); @@ -240,12 +248,11 @@ public static XElement GetActivityByTagSearchRequestAsync( List activityprefilter, string requestor, string ltsmsgpswd - ) + ) { - XElement requestbody = new XElement("ActivitySearchRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Ende POS Element @@ -293,7 +300,10 @@ string ltsmsgpswd if (!String.IsNullOrEmpty(sortcriterion)) { XElement sortcrit = new XElement("Sorting"); - sortcrit.Add(new XAttribute("Criterion", sortcriterion), new XAttribute("Order", order)); + sortcrit.Add( + new XAttribute("Criterion", sortcriterion), + new XAttribute("Order", order) + ); parameters.Add(sortcrit); } //Ende Sorting @@ -307,7 +317,9 @@ string ltsmsgpswd } //Ende Searchtermphrase - parameters.Add(GetActivities(activities, new List(), activityenumcode, taggingtypes)); + parameters.Add( + GetActivities(activities, new List(), activityenumcode, taggingtypes) + ); //Ende Activities @@ -318,7 +330,7 @@ string ltsmsgpswd parameters.Add(GetOwners(ownercodes)); requestbody.Add(parameters); - //Ende Parameters + //Ende Parameters //Filters requestbody.Add(GetActivityPrefilters(activityprefilter)); @@ -348,11 +360,11 @@ public static XElement GetActivityDetailRequest( List activities, string requestor, string ltsmsgpswd - ) + ) { XElement requestbody = new XElement("ActivityDetailRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Parameters @@ -415,11 +427,11 @@ public static XElement GetWeatherSnowSearchRequest( List owner, string requestor, string ltsmsgpswd - ) + ) { XElement requestbody = new XElement("WeatherSnowObservationSearchRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Parameters @@ -462,7 +474,10 @@ string ltsmsgpswd if (!String.IsNullOrEmpty(sortcriterion)) { XElement sortcrit = new XElement("Sorting"); - sortcrit.Add(new XAttribute("Criterion", sortcriterion), new XAttribute("Order", order)); + sortcrit.Add( + new XAttribute("Criterion", sortcriterion), + new XAttribute("Order", order) + ); parameters.Add(sortcrit); } //Ende Sorting @@ -512,12 +527,11 @@ public static XElement GetWeatherSnowDetailRequest( List measuringpoints, string requestor, string ltsmsgpswd - ) + ) { - XElement requestbody = new XElement("WeatherSnowObservationDetailRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Parameters @@ -561,7 +575,10 @@ string ltsmsgpswd if (!String.IsNullOrEmpty(sortcriterion)) { XElement sortcrit = new XElement("Sorting"); - sortcrit.Add(new XAttribute("Criterion", sortcriterion), new XAttribute("Order", order)); + sortcrit.Add( + new XAttribute("Criterion", sortcriterion), + new XAttribute("Order", order) + ); parameters.Add(sortcrit); } //Ende Sorting @@ -601,12 +618,11 @@ public static XElement GetWebcamSearchRequest( List owner, string requestor, string ltsmsgpswd - ) + ) { - XElement requestbody = new XElement("WebCamSearchRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Parameters @@ -645,7 +661,10 @@ string ltsmsgpswd if (!String.IsNullOrEmpty(sortcriterion)) { XElement sortcrit = new XElement("Sorting"); - sortcrit.Add(new XAttribute("Criterion", sortcriterion), new XAttribute("Order", order)); + sortcrit.Add( + new XAttribute("Criterion", sortcriterion), + new XAttribute("Order", order) + ); parameters.Add(sortcrit); } //Ende Sorting @@ -657,7 +676,7 @@ string ltsmsgpswd searchterm.Add(new XAttribute("Phrase", searchtermphrase)); parameters.Add(searchterm); } - //Ende Searchtermphrase + //Ende Searchtermphrase if (areas.Count > 0) parameters.Add(GetAreas(areas)); if (owner.Count > 0) @@ -668,7 +687,6 @@ string ltsmsgpswd return requestbody; } - //Üebr Areas Measuringpoints rausfinden, Measuringpoints zwischenspeichern public static XElement GetWebcamDetailRequest( string language, @@ -688,12 +706,11 @@ public static XElement GetWebcamDetailRequest( List webcams, string requestor, string ltsmsgpswd - ) + ) { - XElement requestbody = new XElement("WebCamDetailRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Parameters @@ -738,7 +755,10 @@ string ltsmsgpswd if (!String.IsNullOrEmpty(sortcriterion)) { XElement sortcrit = new XElement("Sorting"); - sortcrit.Add(new XAttribute("Criterion", sortcriterion), new XAttribute("Order", order)); + sortcrit.Add( + new XAttribute("Criterion", sortcriterion), + new XAttribute("Order", order) + ); parameters.Add(sortcrit); } //Ende Sorting @@ -767,17 +787,18 @@ public static XElement GetActivityChangedRequest( string requestor, string dateFrom, string dataTypeID, - string ltsmsgpswd) + string ltsmsgpswd + ) { XElement requestbody = new XElement("ActivityChangedItemsRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Parameters XElement parameters = new XElement("Parameters"); - //TimeSpan + //TimeSpan XElement lang = new XElement("TimeSpan"); lang.Add(new XAttribute("Start", dateFrom)); parameters.Add(lang); @@ -801,17 +822,18 @@ public static XElement GetActivityByTagChangedRequest( string requestor, string dateFrom, string tagID, - string ltsmsgpswd) + string ltsmsgpswd + ) { XElement requestbody = new XElement("ActivityChangedItemsRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Parameters XElement parameters = new XElement("Parameters"); - //TimeSpan + //TimeSpan XElement lang = new XElement("TimeSpan"); lang.Add(new XAttribute("Start", dateFrom)); parameters.Add(lang); @@ -831,7 +853,6 @@ public static XElement GetActivityByTagChangedRequest( taggingtags.Add(taggingtyperid); activities.Add(taggingtags); - parameters.Add(activities); requestbody.Add(parameters); @@ -839,7 +860,6 @@ public static XElement GetActivityByTagChangedRequest( return requestbody; } - public static XElement GetPOS(string requestor, string ltsmsgpswd) { //POS Element Header @@ -858,7 +878,7 @@ public static XElement GetPOS(string requestor, string ltsmsgpswd) public static XElement GetAreas(List areas) { - //Activity AreaCodes + //Activity AreaCodes XElement myareacodes = new XElement("Areas"); if (areas.Count > 0) { @@ -876,7 +896,7 @@ public static XElement GetAreas(List areas) public static XElement GetOwners(List owner) { - //Activity Ownercodes + //Activity Ownercodes XElement myownercodes = new XElement("Owners"); if (owner.Count > 0) { @@ -894,7 +914,7 @@ public static XElement GetOwners(List owner) public static XElement GetMeasuringpoints(List measuringpoints) { - //Activity Mesuringpoints + //Activity Mesuringpoints XElement mymeasuringpoints = new XElement("MeasuringPoints"); if (measuringpoints.Count > 0) { @@ -927,9 +947,13 @@ public static XElement GetWebcams(List webcams) return mywebcams; } - public static XElement GetActivities(List activities, List activitydatatypes, List activityenumcodes) + public static XElement GetActivities( + List activities, + List activitydatatypes, + List activityenumcodes + ) { - //Activity Filters + //Activity Filters XElement myactivities = new XElement("Activities"); foreach (string myactivitydatatype in activitydatatypes) @@ -941,8 +965,6 @@ public static XElement GetActivities(List activities, List activ myactivities.Add(activitytype); } - - if (activityenumcodes.Count > 0) { XElement myactivityenumcodes = new XElement("EnumCodes"); @@ -970,9 +992,14 @@ public static XElement GetActivities(List activities, List activ return myactivities; } - public static XElement GetActivities(List activities, List activitydatatypes, List activityenumcodes, List taggingtypeRIDs) + public static XElement GetActivities( + List activities, + List activitydatatypes, + List activityenumcodes, + List taggingtypeRIDs + ) { - //Activity Filters + //Activity Filters XElement myactivities = new XElement("Activities"); //Werd obsolet @@ -1011,7 +1038,6 @@ public static XElement GetActivities(List activities, List activ tagging.Add(taggingtags); myactivities.Add(tagging); - //ENDE Tagging if (activityenumcodes.Count > 0) diff --git a/LCS/GetGastronomicDataLCS.cs b/LCS/GetGastronomicDataLCS.cs index c5ce382e2..3ee6931d4 100644 --- a/LCS/GetGastronomicDataLCS.cs +++ b/LCS/GetGastronomicDataLCS.cs @@ -28,7 +28,9 @@ public GetGastronomicDataLCS(string user, string pswd) basicHttpBinding.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; basicHttpBinding.AllowCookies = true; - EndpointAddress endpointAddress = new EndpointAddress("https://lcs.lts.it/api/data.svc/soap"); + EndpointAddress endpointAddress = new EndpointAddress( + "https://lcs.lts.it/api/data.svc/soap" + ); lcs = new ServiceReferenceLCS.DataClient(basicHttpBinding, endpointAddress); lcs.ClientCredentials.UserName.UserName = user; @@ -38,14 +40,18 @@ public GetGastronomicDataLCS(string user, string pswd) } //Gastronomy Search - public ServiceReferenceLCS.GastronomicDataSearchRS GetGastronomicDataSearch(XElement myrequest) + public ServiceReferenceLCS.GastronomicDataSearchRS GetGastronomicDataSearch( + XElement myrequest + ) { var gastrosearch = lcs.oGastronomicDataSearch(myrequest.ToXmlElement()); return gastrosearch; } //Gastronomy Detail - public ServiceReferenceLCS.GastronomicDataDetailRS GetGastronomicDataDetail(XElement myrequest) + public ServiceReferenceLCS.GastronomicDataDetailRS GetGastronomicDataDetail( + XElement myrequest + ) { var gastrodetail = lcs.oGastronomicDataDetail(myrequest.ToXmlElement()); return gastrodetail; @@ -71,7 +77,6 @@ public XElement GetXElementFromXmlElement(XmlElement xmlElement) return XElement.Load(xmlElement.CreateNavigator().ReadSubtree()); } - //Gastronomy List Changed LTS WS!!! THEORETISCH UM den SMG STatus abzufragen (A0NE) müsste man bei HotelBaseData anfragen hmmm was machen wir hier? Hier aber TVList übergeben??? //public static XDocument GetGastroChanged(DateTime startdate, string A0Ene, string G0Rids, string ltsuser, string ltspswd) //{ @@ -113,11 +118,11 @@ public static XElement GetGastronomicDataSearchRequestAsync( List facilityprefilter, string requestor, string ltsmsgpswd - ) + ) { XElement requestbody = new XElement("GastronomicDataSearchRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Ende POS Element @@ -233,11 +238,11 @@ public static XElement GetGastronomicDataDetailRequestAsync( string newsandfeatures, string requestor, string ltsmsgpswd - ) + ) { XElement requestbody = new XElement("GastronomicDataDetailRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Ende POS Element @@ -282,11 +287,11 @@ public static XElement GetGastronomicCodesRequestAsync( string language, string requestor, string ltsmsgpswd - ) + ) { XElement requestbody = new XElement("GastronomicCodesRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Ende POS Element @@ -297,24 +302,23 @@ string ltsmsgpswd XElement lang = new XElement("Language"); lang.Add(new XAttribute("Code", language)); parameters.Add(lang); - //Ende Language + //Ende Language requestbody.Add(parameters); return requestbody; } - public static XElement GetGastronomicDataChangedRequestAsync( string timespan, string tvrid, string requestor, string ltsmsgpswd - ) + ) { XElement requestbody = new XElement("GastronomicDataChangedItemsRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Ende POS Element @@ -325,7 +329,7 @@ string ltsmsgpswd XElement ts = new XElement("TimeSpan"); ts.Add(new XAttribute("Start", timespan)); parameters.Add(ts); - //Ende Language + //Ende Language if (!String.IsNullOrEmpty(tvrid)) { @@ -338,13 +342,11 @@ string ltsmsgpswd parameters.Add(toursimverein); } - requestbody.Add(parameters); return requestbody; } - public static XElement GetPOS(string requestor, string ltsmsgpswd) { //POS Element Header @@ -464,7 +466,7 @@ public static XElement GetFacilities(List facilities) return myfacilities; } - //Categorycode Prefilters + //Categorycode Prefilters public static XElement GetCategoryPreFilter(List categoryprefilter) { XElement mycatprefilter = new XElement("CategoryCodes"); @@ -491,7 +493,7 @@ public static XElement GetCategoryPreFilter(List categoryprefilter) return mycatprefilter; } - //Facility Prefilters + //Facility Prefilters public static XElement GetFacilityPreFilter(List facilityprefilter) { XElement myfacilityprefilter = new XElement("Facilities"); @@ -518,7 +520,5 @@ public static XElement GetFacilityPreFilter(List facilityprefilter) } return myfacilityprefilter; } - - } } diff --git a/LCS/GetPoiDataLCS.cs b/LCS/GetPoiDataLCS.cs index 2694622ca..19497d2dc 100644 --- a/LCS/GetPoiDataLCS.cs +++ b/LCS/GetPoiDataLCS.cs @@ -27,7 +27,9 @@ public GetPoiDataLCS(string user, string pswd) basicHttpBinding.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; basicHttpBinding.AllowCookies = true; - EndpointAddress endpointAddress = new EndpointAddress("https://lcs.lts.it/api/data.svc/soap"); + EndpointAddress endpointAddress = new EndpointAddress( + "https://lcs.lts.it/api/data.svc/soap" + ); lcs = new ServiceReferenceLCS.DataClient(basicHttpBinding, endpointAddress); lcs.ClientCredentials.UserName.UserName = user; @@ -50,7 +52,6 @@ public ServiceReferenceLCS.POIDetailRS GetPoiDetail(XElement myrequest) return poidetail; } - //Poi Changed Request public ServiceReferenceLCS.POIChangedItemsRS GetPoiChanged(XElement myrequest) { @@ -58,7 +59,6 @@ public ServiceReferenceLCS.POIChangedItemsRS GetPoiChanged(XElement myrequest) return poichanged; } - //Get the Activities public static XElement GetPoiSearchRequestAsync( string resultRID, @@ -93,12 +93,11 @@ public static XElement GetPoiSearchRequestAsync( List poiprefilter, string requestor, string ltsmsgpswd - ) + ) { - XElement requestbody = new XElement("POISearchRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Ende POS Element @@ -146,7 +145,10 @@ string ltsmsgpswd if (!String.IsNullOrEmpty(sortcriterion)) { XElement sortcrit = new XElement("Sorting"); - sortcrit.Add(new XAttribute("Criterion", sortcriterion), new XAttribute("Order", order)); + sortcrit.Add( + new XAttribute("Criterion", sortcriterion), + new XAttribute("Order", order) + ); parameters.Add(sortcrit); } //Ende Sorting @@ -171,7 +173,7 @@ string ltsmsgpswd parameters.Add(GetOwners(ownercodes)); requestbody.Add(parameters); - //Ende Parameters + //Ende Parameters //Filters requestbody.Add(GetPoiPrefilters(poiprefilter)); @@ -214,12 +216,11 @@ public static XElement GetPoibyTagSearchRequestAsync( List poiprefilter, string requestor, string ltsmsgpswd - ) + ) { - XElement requestbody = new XElement("POISearchRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Ende POS Element @@ -267,7 +268,10 @@ string ltsmsgpswd if (!String.IsNullOrEmpty(sortcriterion)) { XElement sortcrit = new XElement("Sorting"); - sortcrit.Add(new XAttribute("Criterion", sortcriterion), new XAttribute("Order", order)); + sortcrit.Add( + new XAttribute("Criterion", sortcriterion), + new XAttribute("Order", order) + ); parameters.Add(sortcrit); } //Ende Sorting @@ -292,7 +296,7 @@ string ltsmsgpswd parameters.Add(GetOwners(ownercodes)); requestbody.Add(parameters); - //Ende Parameters + //Ende Parameters //Filters requestbody.Add(GetPoiPrefilters(poiprefilter)); @@ -320,11 +324,11 @@ public static XElement GetPoiDetailRequest( List pois, string requestor, string ltsmsgpswd - ) + ) { XElement requestbody = new XElement("POIDetailRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Parameters @@ -362,23 +366,23 @@ string ltsmsgpswd return requestbody; } - //Get The Request for Activity Changed Items public static XElement GetPOIChangedRequest( string requestor, string dateFrom, string dataTypeID, - string ltsmsgpswd) + string ltsmsgpswd + ) { XElement requestbody = new XElement("POIChangedItemsRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Parameters XElement parameters = new XElement("Parameters"); - //TimeSpan + //TimeSpan XElement lang = new XElement("TimeSpan"); lang.Add(new XAttribute("Start", dateFrom)); parameters.Add(lang); @@ -403,17 +407,18 @@ public static XElement GetPOIbyTagChangedRequest( string requestor, string dateFrom, string tagRID, - string ltsmsgpswd) + string ltsmsgpswd + ) { XElement requestbody = new XElement("POIChangedItemsRQ"); - //POS Element Header + //POS Element Header requestbody.Add(GetPOS(requestor, ltsmsgpswd)); //Parameters XElement parameters = new XElement("Parameters"); - //TimeSpan + //TimeSpan XElement lang = new XElement("TimeSpan"); lang.Add(new XAttribute("Start", dateFrom)); parameters.Add(lang); @@ -423,7 +428,6 @@ public static XElement GetPOIbyTagChangedRequest( //Activities if (!String.IsNullOrEmpty(tagRID)) { - XElement activities = new XElement("POIS"); //XElement activitydatatype = new XElement("POI"); //activitydatatype.Add(new XAttribute("DataTypeID", "")); @@ -445,7 +449,6 @@ public static XElement GetPOIbyTagChangedRequest( return requestbody; } - public static XElement GetPOS(string requestor, string ltsmsgpswd) { //POS Element Header @@ -464,7 +467,7 @@ public static XElement GetPOS(string requestor, string ltsmsgpswd) public static XElement GetAreas(List areas) { - //Activity AreaCodes + //Activity AreaCodes XElement myareacodes = new XElement("Areas"); if (areas.Count > 0) { @@ -482,7 +485,7 @@ public static XElement GetAreas(List areas) public static XElement GetOwners(List owner) { - //Activity Ownercodes + //Activity Ownercodes XElement myownercodes = new XElement("Owners"); if (owner.Count > 0) { @@ -500,7 +503,7 @@ public static XElement GetOwners(List owner) public static XElement GetMeasuringpoints(List measuringpoints) { - //Activity Mesuringpoints + //Activity Mesuringpoints XElement mymeasuringpoints = new XElement("MeasuringPoints"); if (measuringpoints.Count > 0) { @@ -533,9 +536,13 @@ public static XElement GetWebcams(List webcams) return mywebcams; } - public static XElement GetPois(List activities, List activitydatatypes, List activityenumcodes) + public static XElement GetPois( + List activities, + List activitydatatypes, + List activityenumcodes + ) { - //Activity Filters + //Activity Filters XElement myactivities = new XElement("POIs"); foreach (string myactivitydatatype in activitydatatypes) @@ -574,9 +581,14 @@ public static XElement GetPois(List activities, List activitydat return myactivities; } - public static XElement GetPois(List activities, List activitydatatypes, List activityenumcodes, List taggingtypeRIDs) + public static XElement GetPois( + List activities, + List activitydatatypes, + List activityenumcodes, + List taggingtypeRIDs + ) { - //Activity Filters + //Activity Filters XElement myactivities = new XElement("POIs"); //Werd obsolet @@ -615,7 +627,6 @@ public static XElement GetPois(List activities, List activitydat tagging.Add(taggingtags); myactivities.Add(tagging); - //ENDE Tagging @@ -646,7 +657,6 @@ public static XElement GetPois(List activities, List activitydat return myactivities; } - public static XElement GetPoiPrefilters(List activityprefilter) { XElement filters = new XElement("Filters"); diff --git a/LCS/GetSnowReport.cs b/LCS/GetSnowReport.cs index 423d0a0b7..7df7e7e90 100644 --- a/LCS/GetSnowReport.cs +++ b/LCS/GetSnowReport.cs @@ -10,16 +10,22 @@ namespace LCS public class GetSnowReport { //Get Simple Snowreport for one Area - public static SnowReportBaseData GetLiveSnowReport(string lang, SkiArea myskiarea, string requestor, string ltsuser, string ltspswd, string ltsmsgpswd) + public static SnowReportBaseData GetLiveSnowReport( + string lang, + SkiArea myskiarea, + string requestor, + string ltsuser, + string ltspswd, + string ltsmsgpswd + ) { List myareas = myskiarea.AreaId.ToList(); - List prefilter2 = new List(); prefilter2.Add("1330A749F05A441EA702B64A8F82CD3C"); //Lift prefilter2.Add("CFF9182A21DC4C0B88030EBE98D73A67"); //Pischtn prefilter2.Add("C84ACF76753D48BCA2F3E5ACC89FF45E"); //Longlafn - prefilter2.Add("077EED61EE2F49AE95E472EA7B5C93AB"); //Roudlan + prefilter2.Add("077EED61EE2F49AE95E472EA7B5C93AB"); //Roudlan List activitytype = new List(); activitytype.Add("LIFT"); @@ -29,27 +35,88 @@ public static SnowReportBaseData GetLiveSnowReport(string lang, SkiArea myskiare //INFOS für LIFT SLOPE SKITRACK SLIDE var myactivityrequest = LCS.GetActivityDataLCS.GetActivitySearchRequestAsync( - "", "1", "25", lang, "1", "1", "", "0", "1", "0", "0", "1", "0", "0", "0", "0", "0", "0", "0", "1", "", "", "", "", new List(), activitytype, new List(), myareas, new List(), prefilter2, requestor, ltsmsgpswd); + "", + "1", + "25", + lang, + "1", + "1", + "", + "0", + "1", + "0", + "0", + "1", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "1", + "", + "", + "", + "", + new List(), + activitytype, + new List(), + myareas, + new List(), + prefilter2, + requestor, + ltsmsgpswd + ); //INFOS für MEASURINGPOINTS ??? - var mysnowsearchrequest = GetActivityDataLCS.GetWeatherSnowSearchRequest - ("", "1", "25", lang, "0", "0", "1", "1", "0", "0", "1", "", "1", "1", "0", "1", new List(), myareas, new List(), requestor, ltsmsgpswd); + var mysnowsearchrequest = GetActivityDataLCS.GetWeatherSnowSearchRequest( + "", + "1", + "25", + lang, + "0", + "0", + "1", + "1", + "0", + "0", + "1", + "", + "1", + "1", + "0", + "1", + new List(), + myareas, + new List(), + requestor, + ltsmsgpswd + ); //Detailinfos für Measuringpoints try { - GetActivityDataLCS myactivitysearch = new GetActivityDataLCS(ltsuser, ltspswd); var myactivityresponse = myactivitysearch.GetActivitySearch(myactivityrequest); - var mysnowobservationresponse = myactivitysearch.GetWeatherSnowSearch(mysnowsearchrequest); + var mysnowobservationresponse = myactivitysearch.GetWeatherSnowSearch( + mysnowsearchrequest + ); //Sowolla iatz muassi aus de 2 Responsen richtig ausserparsen - var measuringpointlist = ParseSnowDataLive.ParseMyMeasuringPoint(mysnowobservationresponse); + var measuringpointlist = ParseSnowDataLive.ParseMyMeasuringPoint( + mysnowobservationresponse + ); - var mysnowreport = ParseSnowDataLive.ParseMySnowReportData(lang, myskiarea, myactivityresponse, measuringpointlist); + var mysnowreport = ParseSnowDataLive.ParseMySnowReportData( + lang, + myskiarea, + myactivityresponse, + measuringpointlist + ); return mysnowreport; } @@ -57,8 +124,6 @@ public static SnowReportBaseData GetLiveSnowReport(string lang, SkiArea myskiare { return null; } - } - } } diff --git a/LCS/GetWeatherDataLCS.cs b/LCS/GetWeatherDataLCS.cs index 46bfd0bf8..b07e17621 100644 --- a/LCS/GetWeatherDataLCS.cs +++ b/LCS/GetWeatherDataLCS.cs @@ -8,11 +8,38 @@ namespace LCS public class GetWeatherDataLCS { //Methode wos Live die Wetterdaten holt zu an Messpunkt! - public static ServiceReferenceLCS.WeatherSnowObservationDetailRS GetMeasuringpointData(string lang, List measuringpointList, string ltsuser, string ltspswd, string ltsmsgpswd) + public static ServiceReferenceLCS.WeatherSnowObservationDetailRS GetMeasuringpointData( + string lang, + List measuringpointList, + string ltsuser, + string ltspswd, + string ltsmsgpswd + ) { List areas = new List(); - var myweathersnowrequest = GetActivityDataLCS.GetWeatherSnowDetailRequest("", "1", "25", lang, "0", "0", "1", "1", "0", "1", "1", "1", "1", "1", "", "", "", measuringpointList, "SMG", ltsmsgpswd); + var myweathersnowrequest = GetActivityDataLCS.GetWeatherSnowDetailRequest( + "", + "1", + "25", + lang, + "0", + "0", + "1", + "1", + "0", + "1", + "1", + "1", + "1", + "1", + "", + "", + "", + measuringpointList, + "SMG", + ltsmsgpswd + ); GetActivityDataLCS myactivitysearch = new GetActivityDataLCS(ltsuser, ltspswd); @@ -22,11 +49,38 @@ public static ServiceReferenceLCS.WeatherSnowObservationDetailRS GetMeasuringpoi } //Methode wos Live die Wetterdaten holt zu an Messpunkt! - public static ServiceReferenceLCS.WeatherSnowObservationDetailRS GetMeasuringpointDataReduced(string lang, List measuringpointList, string ltsuser, string ltspswd, string ltsmsgpswd) + public static ServiceReferenceLCS.WeatherSnowObservationDetailRS GetMeasuringpointDataReduced( + string lang, + List measuringpointList, + string ltsuser, + string ltspswd, + string ltsmsgpswd + ) { List areas = new List(); - var myweathersnowrequest = GetActivityDataLCS.GetWeatherSnowDetailRequest("", "1", "25", lang, "0", "0", "0", "1", "0", "0", "1", "1", "0", "1", "", "", "", measuringpointList, "SMG", ltsmsgpswd); + var myweathersnowrequest = GetActivityDataLCS.GetWeatherSnowDetailRequest( + "", + "1", + "25", + lang, + "0", + "0", + "0", + "1", + "0", + "0", + "1", + "1", + "0", + "1", + "", + "", + "", + measuringpointList, + "SMG", + ltsmsgpswd + ); GetActivityDataLCS myactivitysearch = new GetActivityDataLCS(ltsuser, ltspswd); diff --git a/LCS/Parser/ParseAccoSearchResult.cs b/LCS/Parser/ParseAccoSearchResult.cs index cf5334a97..6189fc3fd 100644 --- a/LCS/Parser/ParseAccoSearchResult.cs +++ b/LCS/Parser/ParseAccoSearchResult.cs @@ -10,16 +10,20 @@ namespace LCS { public class ParseAccoSearchResult { - public static MssResult ParsemyLCSResponse(string lang, ServiceReferenceLCS.AccommodationDataSearchRS lcsresponse, int rooms) + public static MssResult ParsemyLCSResponse( + string lang, + ServiceReferenceLCS.AccommodationDataSearchRS lcsresponse, + int rooms + ) { if (lcsresponse != null) { - CultureInfo culturede = CultureInfo.CreateSpecificCulture("de"); MssResult result = new MssResult(); result.ResultId = lcsresponse.Result != null ? lcsresponse.Result.RID : ""; - result.bookableHotels = lcsresponse.Result != null ? lcsresponse.Result.ResultsQty : 0; + result.bookableHotels = + lcsresponse.Result != null ? lcsresponse.Result.ResultsQty : 0; result.CheapestChannel = "lts"; result.Cheapestprice = 0; @@ -64,32 +68,65 @@ public static MssResult ParsemyLCSResponse(string lang, ServiceReferenceLCS.Acco myroomdetail.Roommin = 0; myroomdetail.Roomstd = 0; //TODO - myroomdetail.Roomtype = roomdetail.Genre != null ? Convert.ToInt32(roomdetail.Genre) : 0; //roomdetail.Genre; + myroomdetail.Roomtype = + roomdetail.Genre != null + ? Convert.ToInt32(roomdetail.Genre) + : 0; //roomdetail.Genre; //myroomdetail.Roomtype = 0; if (roomdetailoffer.AmountAI != 0) { - var mycheapestofferai = new CheapestOffer() { RoomId = roomdetail.RID, Price = roomdetailoffer.AmountAI, RoomSeq = (int)roomdetailoffer.RoomStayIndex, RoomFree = roomdetail.Qty }; + var mycheapestofferai = new CheapestOffer() + { + RoomId = roomdetail.RID, + Price = roomdetailoffer.AmountAI, + RoomSeq = (int)roomdetailoffer.RoomStayIndex, + RoomFree = roomdetail.Qty + }; CheapestOffer_ai.Add(mycheapestofferai); } if (roomdetailoffer.AmountBB != 0) { - var mycheapestofferbb = new CheapestOffer() { RoomId = roomdetail.RID, Price = roomdetailoffer.AmountBB, RoomSeq = (int)roomdetailoffer.RoomStayIndex, RoomFree = roomdetail.Qty }; + var mycheapestofferbb = new CheapestOffer() + { + RoomId = roomdetail.RID, + Price = roomdetailoffer.AmountBB, + RoomSeq = (int)roomdetailoffer.RoomStayIndex, + RoomFree = roomdetail.Qty + }; CheapestOffer_bb.Add(mycheapestofferbb); } if (roomdetailoffer.AmountHB != 0) { - var mycheapestofferhb = new CheapestOffer() { RoomId = roomdetail.RID, Price = roomdetailoffer.AmountHB, RoomSeq = (int)roomdetailoffer.RoomStayIndex, RoomFree = roomdetail.Qty }; + var mycheapestofferhb = new CheapestOffer() + { + RoomId = roomdetail.RID, + Price = roomdetailoffer.AmountHB, + RoomSeq = (int)roomdetailoffer.RoomStayIndex, + RoomFree = roomdetail.Qty + }; CheapestOffer_hb.Add(mycheapestofferhb); } if (roomdetailoffer.AmountFB != 0) { - var mycheapestofferfb = new CheapestOffer() { RoomId = roomdetail.RID, Price = roomdetailoffer.AmountFB, RoomSeq = (int)roomdetailoffer.RoomStayIndex, RoomFree = roomdetail.Qty }; + var mycheapestofferfb = new CheapestOffer() + { + RoomId = roomdetail.RID, + Price = roomdetailoffer.AmountFB, + RoomSeq = (int)roomdetailoffer.RoomStayIndex, + RoomFree = roomdetail.Qty + }; CheapestOffer_fb.Add(mycheapestofferfb); } if (roomdetailoffer.AmountWS != 0) { - var mycheapestofferws = new CheapestOffer() { RoomId = roomdetail.RID, Price = roomdetailoffer.AmountWS, RoomSeq = (int)roomdetailoffer.RoomStayIndex, RoomFree = roomdetail.Qty }; + var mycheapestofferws = new CheapestOffer() + { + RoomId = roomdetail.RID, + Price = roomdetailoffer.AmountWS, + RoomSeq = (int)roomdetailoffer.RoomStayIndex, + RoomFree = roomdetail.Qty + }; CheapestOffer_ws.Add(mycheapestofferws); } @@ -98,28 +135,53 @@ public static MssResult ParsemyLCSResponse(string lang, ServiceReferenceLCS.Acco } //Getting cheapest offer - var cheapestofferobj_ai = RoomCalculationHelper.CalculateCheapestRooms(CheapestOffer_ai, rooms, "ai"); - lcsresponseshort.CheapestOffer_ai = cheapestofferobj_ai != null ? cheapestofferobj_ai.Price : 0; + var cheapestofferobj_ai = RoomCalculationHelper.CalculateCheapestRooms( + CheapestOffer_ai, + rooms, + "ai" + ); + lcsresponseshort.CheapestOffer_ai = + cheapestofferobj_ai != null ? cheapestofferobj_ai.Price : 0; if (cheapestofferobj_ai != null && cheapestofferobj_ai.Price > 0) lcsresponseshort.CheapestOfferDetail.Add(cheapestofferobj_ai); - var cheapestofferobj_bb = RoomCalculationHelper.CalculateCheapestRooms(CheapestOffer_bb, rooms, "bb"); - lcsresponseshort.CheapestOffer_bb = cheapestofferobj_bb != null ? cheapestofferobj_bb.Price : 0; + var cheapestofferobj_bb = RoomCalculationHelper.CalculateCheapestRooms( + CheapestOffer_bb, + rooms, + "bb" + ); + lcsresponseshort.CheapestOffer_bb = + cheapestofferobj_bb != null ? cheapestofferobj_bb.Price : 0; if (cheapestofferobj_bb != null && cheapestofferobj_bb.Price > 0) lcsresponseshort.CheapestOfferDetail.Add(cheapestofferobj_bb); - var cheapestofferobj_hb = RoomCalculationHelper.CalculateCheapestRooms(CheapestOffer_hb, rooms, "hb"); - lcsresponseshort.CheapestOffer_hb = cheapestofferobj_hb != null ? cheapestofferobj_hb.Price : 0; + var cheapestofferobj_hb = RoomCalculationHelper.CalculateCheapestRooms( + CheapestOffer_hb, + rooms, + "hb" + ); + lcsresponseshort.CheapestOffer_hb = + cheapestofferobj_hb != null ? cheapestofferobj_hb.Price : 0; if (cheapestofferobj_hb != null && cheapestofferobj_hb.Price > 0) lcsresponseshort.CheapestOfferDetail.Add(cheapestofferobj_hb); - var cheapestofferobj_fb = RoomCalculationHelper.CalculateCheapestRooms(CheapestOffer_fb, rooms, "fb"); - lcsresponseshort.CheapestOffer_fb = cheapestofferobj_fb != null ? cheapestofferobj_fb.Price : 0; + var cheapestofferobj_fb = RoomCalculationHelper.CalculateCheapestRooms( + CheapestOffer_fb, + rooms, + "fb" + ); + lcsresponseshort.CheapestOffer_fb = + cheapestofferobj_fb != null ? cheapestofferobj_fb.Price : 0; if (cheapestofferobj_fb != null && cheapestofferobj_fb.Price > 0) lcsresponseshort.CheapestOfferDetail.Add(cheapestofferobj_fb); - var cheapestofferobj_ws = RoomCalculationHelper.CalculateCheapestRooms(CheapestOffer_ws, rooms, "ws"); - lcsresponseshort.CheapestOffer_ws = cheapestofferobj_ws != null ? cheapestofferobj_ws.Price : 0; + var cheapestofferobj_ws = RoomCalculationHelper.CalculateCheapestRooms( + CheapestOffer_ws, + rooms, + "ws" + ); + lcsresponseshort.CheapestOffer_ws = + cheapestofferobj_ws != null ? cheapestofferobj_ws.Price : 0; if (cheapestofferobj_ws != null && cheapestofferobj_ws.Price > 0) lcsresponseshort.CheapestOfferDetail.Add(cheapestofferobj_ws); @@ -140,20 +202,27 @@ public static MssResult ParsemyLCSResponse(string lang, ServiceReferenceLCS.Acco if (cheapestoffertotal.Count > 0) { - var cheapestofferdouble = cheapestoffertotal.OrderBy(x => x).FirstOrDefault(); + var cheapestofferdouble = cheapestoffertotal + .OrderBy(x => x) + .FirstOrDefault(); lcsresponseshort.CheapestOffer = cheapestofferdouble; - lcsresponseshort.CheapestOfferString = String.Format(culturede, "{0:0,0.00}", cheapestofferdouble); + lcsresponseshort.CheapestOfferString = String.Format( + culturede, + "{0:0,0.00}", + cheapestofferdouble + ); } - } //Add only if there is a valid Offer (enough Roomfree etc..) - if (lcsresponseshort.CheapestOfferDetail != null && lcsresponseshort.CheapestOfferDetail.Count > 0) + if ( + lcsresponseshort.CheapestOfferDetail != null + && lcsresponseshort.CheapestOfferDetail.Count > 0 + ) result.MssResponseShort.Add(lcsresponseshort); } } - return result; } else diff --git a/LCS/Parser/ParseActivityData.cs b/LCS/Parser/ParseActivityData.cs index c12f30092..fd2f10616 100644 --- a/LCS/Parser/ParseActivityData.cs +++ b/LCS/Parser/ParseActivityData.cs @@ -13,15 +13,82 @@ public class ParseActivityData public static CultureInfo myculture = new CultureInfo("en"); //Get the Activity Detail Information - public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string rid, PoiBaseInfos hike, string ltsuser, string ltspswd, string ltsmsgpswd) + public static PoiBaseInfos GetActivitiesDetailLTS( + string activitytype, + string rid, + PoiBaseInfos hike, + string ltsuser, + string ltspswd, + string ltsmsgpswd + ) { List myactivitylist = new List(); myactivitylist.Add(rid); //Get LTS Data - var myactivityrequestde = GetActivityDataLCS.GetActivityDetailRequest("de", "0", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "0", myactivitylist, "SMG", ltsmsgpswd); - var myactivityrequestit = GetActivityDataLCS.GetActivityDetailRequest("it", "0", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "0", myactivitylist, "SMG", ltsmsgpswd); - var myactivityrequesten = GetActivityDataLCS.GetActivityDetailRequest("en", "0", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "0", myactivitylist, "SMG", ltsmsgpswd); + var myactivityrequestde = GetActivityDataLCS.GetActivityDetailRequest( + "de", + "0", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "0", + myactivitylist, + "SMG", + ltsmsgpswd + ); + var myactivityrequestit = GetActivityDataLCS.GetActivityDetailRequest( + "it", + "0", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "0", + myactivitylist, + "SMG", + ltsmsgpswd + ); + var myactivityrequesten = GetActivityDataLCS.GetActivityDetailRequest( + "en", + "0", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "0", + myactivitylist, + "SMG", + ltsmsgpswd + ); GetActivityDataLCS myactivitysearch = new GetActivityDataLCS(ltsuser, ltspswd); var myactivityresponsede = myactivitysearch.GetActivityDetail(myactivityrequestde); @@ -63,9 +130,17 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri //Altitude Total if (theactivityde.GeoDatas.GeoData.FirstOrDefault().Altitude != null) { - hike.AltitudeDifference = theactivityde.GeoDatas.GeoData.FirstOrDefault().Altitude.Difference; - hike.AltitudeHighestPoint = theactivityde.GeoDatas.GeoData.FirstOrDefault().Altitude.Max != null ? theactivityde.GeoDatas.GeoData.FirstOrDefault().Altitude.Max : 0; - hike.AltitudeLowestPoint = theactivityde.GeoDatas.GeoData.FirstOrDefault().Altitude.Min != null ? theactivityde.GeoDatas.GeoData.FirstOrDefault().Altitude.Min : 0; + hike.AltitudeDifference = theactivityde.GeoDatas.GeoData + .FirstOrDefault() + .Altitude.Difference; + hike.AltitudeHighestPoint = + theactivityde.GeoDatas.GeoData.FirstOrDefault().Altitude.Max != null + ? theactivityde.GeoDatas.GeoData.FirstOrDefault().Altitude.Max + : 0; + hike.AltitudeLowestPoint = + theactivityde.GeoDatas.GeoData.FirstOrDefault().Altitude.Min != null + ? theactivityde.GeoDatas.GeoData.FirstOrDefault().Altitude.Min + : 0; } else { @@ -76,9 +151,17 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri if (theactivityde.GeoDatas.GeoData.FirstOrDefault().Distance != null) { - hike.DistanceLength = theactivityde.GeoDatas.GeoData.FirstOrDefault().Distance.Length; - hike.AltitudeSumUp = theactivityde.GeoDatas.GeoData.FirstOrDefault().Distance.SumUp != null ? theactivityde.GeoDatas.GeoData.FirstOrDefault().Distance.SumUp : 0; - hike.AltitudeSumDown = theactivityde.GeoDatas.GeoData.FirstOrDefault().Distance.SumDown != null ? theactivityde.GeoDatas.GeoData.FirstOrDefault().Distance.SumDown : 0; + hike.DistanceLength = theactivityde.GeoDatas.GeoData + .FirstOrDefault() + .Distance.Length; + hike.AltitudeSumUp = + theactivityde.GeoDatas.GeoData.FirstOrDefault().Distance.SumUp != null + ? theactivityde.GeoDatas.GeoData.FirstOrDefault().Distance.SumUp + : 0; + hike.AltitudeSumDown = + theactivityde.GeoDatas.GeoData.FirstOrDefault().Distance.SumDown != null + ? theactivityde.GeoDatas.GeoData.FirstOrDefault().Distance.SumDown + : 0; } else { @@ -91,10 +174,16 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri { if (theactivityde.GeoDatas.GeoData.FirstOrDefault().Distance.Duration != null) { - string duration = theactivityde.GeoDatas.GeoData.FirstOrDefault().Distance.Duration; + string duration = theactivityde.GeoDatas.GeoData + .FirstOrDefault() + .Distance.Duration; var durationsplittet = duration.Split(':'); - TimeSpan durationts = new TimeSpan(int.Parse(durationsplittet[0]), int.Parse(durationsplittet[1]), 0); + TimeSpan durationts = new TimeSpan( + int.Parse(durationsplittet[0]), + int.Parse(durationsplittet[1]), + 0 + ); //int tshours = Convert.ToInt32(durationsplittet[0]); //int tsminutes = Convert.ToInt32(durationsplittet[1]); @@ -103,7 +192,6 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri hike.DistanceDuration = Math.Round(durationts.TotalHours, 2); //hike.DistanceDuration = Convert.ToDouble(durationsplittet[0] + "," + durationsplittet[1]); - } else hike.DistanceDuration = 0; @@ -111,14 +199,35 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri else hike.DistanceDuration = 0; - hike.HasRentals = theactivityde.Features.HasRentals != null ? Convert.ToBoolean(theactivityde.Features.HasRentals) : false; - hike.IsWithLigth = theactivityde.Features.IsWithLight != null ? Convert.ToBoolean(theactivityde.Features.IsWithLight) : false; - hike.IsOpen = theactivityde.News.Status.IsOpen != null ? Convert.ToBoolean(theactivityde.News.Status.IsOpen) : false; - hike.IsPrepared = theactivityde.News.Status.IsPrepared != null ? Convert.ToBoolean(theactivityde.News.Status.IsPrepared) : false; - hike.RunToValley = theactivityde.News.RunToValley.IsPossible != null ? Convert.ToBoolean(theactivityde.News.RunToValley.IsPossible) : false; - - hike.FeetClimb = theactivityde.Features.FeetClimb != null ? Convert.ToBoolean(theactivityde.Features.FeetClimb) : false; - hike.LiftAvailable = theactivityde.Features.LiftAvailable != null ? Convert.ToBoolean(theactivityde.Features.LiftAvailable) : false; + hike.HasRentals = + theactivityde.Features.HasRentals != null + ? Convert.ToBoolean(theactivityde.Features.HasRentals) + : false; + hike.IsWithLigth = + theactivityde.Features.IsWithLight != null + ? Convert.ToBoolean(theactivityde.Features.IsWithLight) + : false; + hike.IsOpen = + theactivityde.News.Status.IsOpen != null + ? Convert.ToBoolean(theactivityde.News.Status.IsOpen) + : false; + hike.IsPrepared = + theactivityde.News.Status.IsPrepared != null + ? Convert.ToBoolean(theactivityde.News.Status.IsPrepared) + : false; + hike.RunToValley = + theactivityde.News.RunToValley.IsPossible != null + ? Convert.ToBoolean(theactivityde.News.RunToValley.IsPossible) + : false; + + hike.FeetClimb = + theactivityde.Features.FeetClimb != null + ? Convert.ToBoolean(theactivityde.Features.FeetClimb) + : false; + hike.LiftAvailable = + theactivityde.Features.LiftAvailable != null + ? Convert.ToBoolean(theactivityde.Features.LiftAvailable) + : false; //New Way Number + Right to use the way, set this info only if i get it from interface if (theactivityde.WayNumber != null && theactivityde.WayNumber != 0) @@ -132,7 +241,10 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri else hike.Number = null; - hike.BikeTransport = theactivityde.Features.BikeTransport != null ? Convert.ToBoolean(theactivityde.Features.BikeTransport) : false; + hike.BikeTransport = + theactivityde.Features.BikeTransport != null + ? Convert.ToBoolean(theactivityde.Features.BikeTransport) + : false; hike.LastChange = DateTime.Now; @@ -142,27 +254,53 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri if (theactivityde.Rating != null) { Ratings myrating = new Ratings(); - myrating.Difficulty = theactivityde.Rating.Difficulty != null ? theactivityde.Rating.Difficulty.ToString() : ""; - myrating.Experience = theactivityde.Rating.Experience != null ? theactivityde.Rating.Experience.ToString() : ""; - myrating.Landscape = theactivityde.Rating.Landscape != null ? theactivityde.Rating.Landscape.ToString() : ""; - myrating.Stamina = theactivityde.Rating.Stamina != null ? theactivityde.Rating.Stamina.ToString() : ""; - - myrating.Technique = theactivityde.Rating.Technique != null ? theactivityde.Rating.Technique.ToString() : ""; + myrating.Difficulty = + theactivityde.Rating.Difficulty != null + ? theactivityde.Rating.Difficulty.ToString() + : ""; + myrating.Experience = + theactivityde.Rating.Experience != null + ? theactivityde.Rating.Experience.ToString() + : ""; + myrating.Landscape = + theactivityde.Rating.Landscape != null + ? theactivityde.Rating.Landscape.ToString() + : ""; + myrating.Stamina = + theactivityde.Rating.Stamina != null + ? theactivityde.Rating.Stamina.ToString() + : ""; + + myrating.Technique = + theactivityde.Rating.Technique != null + ? theactivityde.Rating.Technique.ToString() + : ""; //Sonderfall TEchnik bei Alpinklettern, Hochtouren, Klettersteige foreach (var myltstag in theactivityde.Tags.Tag) { - if (myltstag.Name.FirstOrDefault().InnerText == "Alpinklettern" || myltstag.Name.FirstOrDefault().InnerText == "Hochtour") - myrating.Technique = theactivityde.Rating.Technique_UIAA != null ? theactivityde.Rating.Technique_UIAA : ""; + if ( + myltstag.Name.FirstOrDefault().InnerText == "Alpinklettern" + || myltstag.Name.FirstOrDefault().InnerText == "Hochtour" + ) + myrating.Technique = + theactivityde.Rating.Technique_UIAA != null + ? theactivityde.Rating.Technique_UIAA + : ""; if (myltstag.Name.FirstOrDefault().InnerText == "Klettersteig") - myrating.Technique = theactivityde.Rating.Technique_VF != null ? theactivityde.Rating.Technique_VF : ""; - + myrating.Technique = + theactivityde.Rating.Technique_VF != null + ? theactivityde.Rating.Technique_VF + : ""; } hike.Ratings = myrating; - hike.Difficulty = theactivityde.Rating.Difficulty != null ? theactivityde.Rating.Difficulty.ToString() : ""; + hike.Difficulty = + theactivityde.Rating.Difficulty != null + ? theactivityde.Rating.Difficulty.ToString() + : ""; } //ContactInfos @@ -172,34 +310,65 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri var parsedcontactinfode = theactivityde.ContactInfos.ContactInfo.FirstOrDefault(); if (parsedcontactinfode != null) { - ContactInfos mycontactinfo = new ContactInfos(); var myadresselement = parsedcontactinfode.Addresses; mycontactinfo.Address = myadresselement.Address.FirstOrDefault().AddressLine; - mycontactinfo.City = parsedcontactinfode.Addresses.Address.FirstOrDefault().CityName; - mycontactinfo.CountryCode = parsedcontactinfode.Addresses.Address.FirstOrDefault().CountryName.Code; - mycontactinfo.CountryName = parsedcontactinfode.Addresses.Address.FirstOrDefault().CountryName.InnerText; - mycontactinfo.ZipCode = parsedcontactinfode.Addresses.Address.FirstOrDefault().PostalCode; - - mycontactinfo.Email = parsedcontactinfode.Emails.Email.FirstOrDefault().InnerText; + mycontactinfo.City = parsedcontactinfode.Addresses.Address + .FirstOrDefault() + .CityName; + mycontactinfo.CountryCode = parsedcontactinfode.Addresses.Address + .FirstOrDefault() + .CountryName.Code; + mycontactinfo.CountryName = parsedcontactinfode.Addresses.Address + .FirstOrDefault() + .CountryName.InnerText; + mycontactinfo.ZipCode = parsedcontactinfode.Addresses.Address + .FirstOrDefault() + .PostalCode; + + mycontactinfo.Email = parsedcontactinfode.Emails.Email + .FirstOrDefault() + .InnerText; mycontactinfo.Faxnumber = ""; - mycontactinfo.Givenname = parsedcontactinfode.Names.Name.FirstOrDefault().GivenName; + mycontactinfo.Givenname = parsedcontactinfode.Names.Name + .FirstOrDefault() + .GivenName; mycontactinfo.Surname = parsedcontactinfode.Names.Name.FirstOrDefault().Surname; - mycontactinfo.NamePrefix = parsedcontactinfode.Names.Name.FirstOrDefault().NamePrefix; + mycontactinfo.NamePrefix = parsedcontactinfode.Names.Name + .FirstOrDefault() + .NamePrefix; mycontactinfo.CompanyName = parsedcontactinfode.CompanyName.InnerText; mycontactinfo.Language = "de"; //mycontactinfo.Phonenumber = parsedcontactinfode.Phones.Phone.FirstOrDefault().PhoneNumber; - mycontactinfo.Phonenumber = parsedcontactinfode.Phones != null ? parsedcontactinfode.Phones.Phone.Where(x => x.PhoneTechType == "1").Count() > 0 ? parsedcontactinfode.Phones.Phone.Where(x => x.PhoneTechType == "1").FirstOrDefault().PhoneNumber : "" : ""; - mycontactinfo.Faxnumber = parsedcontactinfode.Phones != null ? parsedcontactinfode.Phones.Phone.Where(x => x.PhoneTechType == "3").Count() > 0 ? parsedcontactinfode.Phones.Phone.Where(x => x.PhoneTechType == "3").FirstOrDefault().PhoneNumber : "" : ""; - - + mycontactinfo.Phonenumber = + parsedcontactinfode.Phones != null + ? parsedcontactinfode.Phones.Phone + .Where(x => x.PhoneTechType == "1") + .Count() > 0 + ? parsedcontactinfode.Phones.Phone + .Where(x => x.PhoneTechType == "1") + .FirstOrDefault() + .PhoneNumber + : "" + : ""; + mycontactinfo.Faxnumber = + parsedcontactinfode.Phones != null + ? parsedcontactinfode.Phones.Phone + .Where(x => x.PhoneTechType == "3") + .Count() > 0 + ? parsedcontactinfode.Phones.Phone + .Where(x => x.PhoneTechType == "3") + .FirstOrDefault() + .PhoneNumber + : "" + : ""; mycontactinfo.Url = parsedcontactinfode.URLs.URL.FirstOrDefault().InnerText; @@ -214,33 +383,65 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri var parsedcontactinfoit = theactivityit.ContactInfos.ContactInfo.FirstOrDefault(); if (parsedcontactinfoit != null) { - ContactInfos mycontactinfo = new ContactInfos(); var myadresselement = parsedcontactinfoit.Addresses; mycontactinfo.Address = myadresselement.Address.FirstOrDefault().AddressLine; - mycontactinfo.City = parsedcontactinfoit.Addresses.Address.FirstOrDefault().CityName; - mycontactinfo.CountryCode = parsedcontactinfoit.Addresses.Address.FirstOrDefault().CountryName.Code; - mycontactinfo.CountryName = parsedcontactinfoit.Addresses.Address.FirstOrDefault().CountryName.InnerText; - mycontactinfo.ZipCode = parsedcontactinfoit.Addresses.Address.FirstOrDefault().PostalCode; - - mycontactinfo.Email = parsedcontactinfoit.Emails.Email.FirstOrDefault().InnerText; + mycontactinfo.City = parsedcontactinfoit.Addresses.Address + .FirstOrDefault() + .CityName; + mycontactinfo.CountryCode = parsedcontactinfoit.Addresses.Address + .FirstOrDefault() + .CountryName.Code; + mycontactinfo.CountryName = parsedcontactinfoit.Addresses.Address + .FirstOrDefault() + .CountryName.InnerText; + mycontactinfo.ZipCode = parsedcontactinfoit.Addresses.Address + .FirstOrDefault() + .PostalCode; + + mycontactinfo.Email = parsedcontactinfoit.Emails.Email + .FirstOrDefault() + .InnerText; mycontactinfo.Faxnumber = ""; - mycontactinfo.Givenname = parsedcontactinfoit.Names.Name.FirstOrDefault().GivenName; + mycontactinfo.Givenname = parsedcontactinfoit.Names.Name + .FirstOrDefault() + .GivenName; mycontactinfo.Surname = parsedcontactinfoit.Names.Name.FirstOrDefault().Surname; - mycontactinfo.NamePrefix = parsedcontactinfoit.Names.Name.FirstOrDefault().NamePrefix; + mycontactinfo.NamePrefix = parsedcontactinfoit.Names.Name + .FirstOrDefault() + .NamePrefix; mycontactinfo.CompanyName = parsedcontactinfoit.CompanyName.InnerText; mycontactinfo.Language = "it"; //mycontactinfo.Phonenumber = parsedcontactinfoit.Phones.Phone.FirstOrDefault().PhoneNumber; - mycontactinfo.Phonenumber = parsedcontactinfoit.Phones != null ? parsedcontactinfoit.Phones.Phone.Where(x => x.PhoneTechType == "1").Count() > 0 ? parsedcontactinfoit.Phones.Phone.Where(x => x.PhoneTechType == "1").FirstOrDefault().PhoneNumber : "" : ""; - mycontactinfo.Faxnumber = parsedcontactinfoit.Phones != null ? parsedcontactinfoit.Phones.Phone.Where(x => x.PhoneTechType == "3").Count() > 0 ? parsedcontactinfoit.Phones.Phone.Where(x => x.PhoneTechType == "3").FirstOrDefault().PhoneNumber : "" : ""; - + mycontactinfo.Phonenumber = + parsedcontactinfoit.Phones != null + ? parsedcontactinfoit.Phones.Phone + .Where(x => x.PhoneTechType == "1") + .Count() > 0 + ? parsedcontactinfoit.Phones.Phone + .Where(x => x.PhoneTechType == "1") + .FirstOrDefault() + .PhoneNumber + : "" + : ""; + mycontactinfo.Faxnumber = + parsedcontactinfoit.Phones != null + ? parsedcontactinfoit.Phones.Phone + .Where(x => x.PhoneTechType == "3") + .Count() > 0 + ? parsedcontactinfoit.Phones.Phone + .Where(x => x.PhoneTechType == "3") + .FirstOrDefault() + .PhoneNumber + : "" + : ""; mycontactinfo.Url = parsedcontactinfoit.URLs.URL.FirstOrDefault().InnerText; @@ -254,33 +455,65 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri var parsedcontactinfoen = theactivityen.ContactInfos.ContactInfo.FirstOrDefault(); if (parsedcontactinfoen != null) { - ContactInfos mycontactinfo = new ContactInfos(); var myadresselement = parsedcontactinfoen.Addresses; mycontactinfo.Address = myadresselement.Address.FirstOrDefault().AddressLine; - mycontactinfo.City = parsedcontactinfoen.Addresses.Address.FirstOrDefault().CityName; - mycontactinfo.CountryCode = parsedcontactinfoen.Addresses.Address.FirstOrDefault().CountryName.Code; - mycontactinfo.CountryName = parsedcontactinfoen.Addresses.Address.FirstOrDefault().CountryName.InnerText; - mycontactinfo.ZipCode = parsedcontactinfoen.Addresses.Address.FirstOrDefault().PostalCode; - - mycontactinfo.Email = parsedcontactinfoen.Emails.Email.FirstOrDefault().InnerText; + mycontactinfo.City = parsedcontactinfoen.Addresses.Address + .FirstOrDefault() + .CityName; + mycontactinfo.CountryCode = parsedcontactinfoen.Addresses.Address + .FirstOrDefault() + .CountryName.Code; + mycontactinfo.CountryName = parsedcontactinfoen.Addresses.Address + .FirstOrDefault() + .CountryName.InnerText; + mycontactinfo.ZipCode = parsedcontactinfoen.Addresses.Address + .FirstOrDefault() + .PostalCode; + + mycontactinfo.Email = parsedcontactinfoen.Emails.Email + .FirstOrDefault() + .InnerText; mycontactinfo.Faxnumber = ""; - mycontactinfo.Givenname = parsedcontactinfoen.Names.Name.FirstOrDefault().GivenName; + mycontactinfo.Givenname = parsedcontactinfoen.Names.Name + .FirstOrDefault() + .GivenName; mycontactinfo.Surname = parsedcontactinfoen.Names.Name.FirstOrDefault().Surname; - mycontactinfo.NamePrefix = parsedcontactinfoen.Names.Name.FirstOrDefault().NamePrefix; + mycontactinfo.NamePrefix = parsedcontactinfoen.Names.Name + .FirstOrDefault() + .NamePrefix; mycontactinfo.CompanyName = parsedcontactinfoen.CompanyName.InnerText; mycontactinfo.Language = "en"; //mycontactinfo.Phonenumber = parsedcontactinfoen.Phones.Phone.FirstOrDefault().PhoneNumber; - mycontactinfo.Phonenumber = parsedcontactinfoen.Phones != null ? parsedcontactinfoen.Phones.Phone.Where(x => x.PhoneTechType == "1").Count() > 0 ? parsedcontactinfoen.Phones.Phone.Where(x => x.PhoneTechType == "1").FirstOrDefault().PhoneNumber : "" : ""; - mycontactinfo.Faxnumber = parsedcontactinfoen.Phones != null ? parsedcontactinfoen.Phones.Phone.Where(x => x.PhoneTechType == "3").Count() > 0 ? parsedcontactinfoen.Phones.Phone.Where(x => x.PhoneTechType == "3").FirstOrDefault().PhoneNumber : "" : ""; - + mycontactinfo.Phonenumber = + parsedcontactinfoen.Phones != null + ? parsedcontactinfoen.Phones.Phone + .Where(x => x.PhoneTechType == "1") + .Count() > 0 + ? parsedcontactinfoen.Phones.Phone + .Where(x => x.PhoneTechType == "1") + .FirstOrDefault() + .PhoneNumber + : "" + : ""; + mycontactinfo.Faxnumber = + parsedcontactinfoen.Phones != null + ? parsedcontactinfoen.Phones.Phone + .Where(x => x.PhoneTechType == "3") + .Count() > 0 + ? parsedcontactinfoen.Phones.Phone + .Where(x => x.PhoneTechType == "3") + .FirstOrDefault() + .PhoneNumber + : "" + : ""; mycontactinfo.Url = parsedcontactinfoen.URLs.URL.FirstOrDefault().InnerText; @@ -291,7 +524,7 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri //Ende ContactInfos - //Multimedia Infos IMAGEGALLERY + DETAIL + //Multimedia Infos IMAGEGALLERY + DETAIL List imagegallerylist = new List(); @@ -304,7 +537,8 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri } } - var parsedmultimediainfode = theactivityde.MultimediaDescriptions.MultimediaDescription.FirstOrDefault(); + var parsedmultimediainfode = + theactivityde.MultimediaDescriptions.MultimediaDescription.FirstOrDefault(); if (parsedmultimediainfode != null) { if (parsedmultimediainfode.ImageItems.ImageItem != null) @@ -315,11 +549,14 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri { ImageGallery myimggallery = new ImageGallery(); myimggallery.Height = imageelement.ImageFormat.Height; - myimggallery.ImageDesc.TryAddOrUpdate("de", imageelement.Description.FirstOrDefault().InnerText); + myimggallery.ImageDesc.TryAddOrUpdate( + "de", + imageelement.Description.FirstOrDefault().InnerText + ); myimggallery.ImageSource = "LTS"; myimggallery.ImageName = imageelement.RID; myimggallery.ImageUrl = imageelement.ImageFormat.URL.InnerText; - myimggallery.IsInGallery = true; // imageelement.ImageFormat.IsEnabled; + myimggallery.IsInGallery = true; // imageelement.ImageFormat.IsEnabled; myimggallery.ListPosition = i; myimggallery.Width = imageelement.ImageFormat.Width; myimggallery.CopyRight = imageelement.ImageFormat.CopyrightOwner; @@ -370,61 +607,138 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri mydetailde = hike.Detail["de"]; } //mydetailde.Title = theactivityde.Name != null ? theactivityde.Name.FirstOrDefault().InnerText.Trim() : ""; - mydetailde.Title = theactivityde.Name != null ? theactivityde.Name.FirstOrDefault().InnerText != null ? theactivityde.Name.FirstOrDefault().InnerText.Trim() : "" : ""; + mydetailde.Title = + theactivityde.Name != null + ? theactivityde.Name.FirstOrDefault().InnerText != null + ? theactivityde.Name.FirstOrDefault().InnerText.Trim() + : "" + : ""; //mydetailde.Header = ""; mydetailde.Language = "de"; //mydetailde.AdditionalText = ""; //mydetailde.Alttext = ""; - //mydetailde.IntroText = ""; + //mydetailde.IntroText = ""; if (mytextitems.TextItem != null) { foreach (var textelement in mytextitems.TextItem) { //Allgemeine Beschreibung 732512C9492340F4AB30FFB800461BE7 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "732512C9492340F4AB30FFB800461BE7") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "732512C9492340F4AB30FFB800461BE7" + ) { - mydetailde.BaseText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.BaseText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Anfahrtsbeschreibung C26C826A239C47BDB773B4E4B3F27547 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "C26C826A239C47BDB773B4E4B3F27547") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "C26C826A239C47BDB773B4E4B3F27547" + ) { - mydetailde.GetThereText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.GetThereText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } - //Wegbeschreibung ECEB7021321445648CE37A9A84D64930 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "ECEB7021321445648CE37A9A84D64930") + //Wegbeschreibung ECEB7021321445648CE37A9A84D64930 + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "ECEB7021321445648CE37A9A84D64930" + ) { - mydetailde.AdditionalText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.AdditionalText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Kurzbeschreibung A143F1FF0A0A4185A907208D643D3BB8 --> Placing in Introtext - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "A143F1FF0A0A4185A907208D643D3BB8") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "A143F1FF0A0A4185A907208D643D3BB8" + ) { - mydetailde.IntroText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.IntroText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Parken AFB5C1F8662949108105DAC81DD8B18F - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "AFB5C1F8662949108105DAC81DD8B18F") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "AFB5C1F8662949108105DAC81DD8B18F" + ) { - mydetailde.ParkingInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.ParkingInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Öffentliche Verkehrsmittel C67DBA804FAD4B4EB64A4A758771B723 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "C67DBA804FAD4B4EB64A4A758771B723") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "C67DBA804FAD4B4EB64A4A758771B723" + ) { - mydetailde.PublicTransportationInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.PublicTransportationInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Tipp des Autors 643EDEE9CE2D44AC932FC714256B6C9C - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "643EDEE9CE2D44AC932FC714256B6C9C") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "643EDEE9CE2D44AC932FC714256B6C9C" + ) { - mydetailde.AuthorTip = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.AuthorTip = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Sicherheitshinweise 73EC4F8F7AAC48CE82A23E8EBDCA750E - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "73EC4F8F7AAC48CE82A23E8EBDCA750E") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "73EC4F8F7AAC48CE82A23E8EBDCA750E" + ) { - mydetailde.SafetyInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.SafetyInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Ausrüstung 933D29E15E82415DBEDE877C477212D2 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "933D29E15E82415DBEDE877C477212D2") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "933D29E15E82415DBEDE877C477212D2" + ) { - mydetailde.EquipmentInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.EquipmentInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } } } @@ -434,7 +748,8 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri } //it - var parsedmultimediainfoit = theactivityit.MultimediaDescriptions.MultimediaDescription.FirstOrDefault(); + var parsedmultimediainfoit = + theactivityit.MultimediaDescriptions.MultimediaDescription.FirstOrDefault(); if (parsedmultimediainfoit != null) { if (parsedmultimediainfoit.ImageItems.ImageItem != null) @@ -443,20 +758,24 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri foreach (var imageelement in parsedmultimediainfoit.ImageItems.ImageItem) { - imagegallerylist.Where(x => x.ListPosition == i && x.ImageSource == "LTS").FirstOrDefault().ImageDesc.TryAddOrUpdate("it", imageelement.Description.FirstOrDefault().InnerText); + imagegallerylist + .Where(x => x.ListPosition == i && x.ImageSource == "LTS") + .FirstOrDefault() + .ImageDesc.TryAddOrUpdate( + "it", + imageelement.Description.FirstOrDefault().InnerText + ); i++; //ImageGallery myimggallery = hike.ImageGallery.Where(x => x.ListPosition == 0).FirstOrDefault(); - //myimggallery.ImageDesc.Add("it", imageelement.Description.FirstOrDefault().InnerText); + //myimggallery.ImageDesc.Add("it", imageelement.Description.FirstOrDefault().InnerText); - //myimggallery.Height = imageelement.ImageFormat.Height; + //myimggallery.Height = imageelement.ImageFormat.Height; //myimggallery.ImageName = imageelement.RID; //myimggallery.ImageUrl = imageelement.ImageFormat.URL.InnerText; //myimggallery.IsInGallery = true; //myimggallery.Language = "it"; //myimggallery.ListPosition = 0; //myimggallery.Width = imageelement.ImageFormat.Width; - - } } @@ -469,62 +788,139 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri mydetailit = hike.Detail["it"]; } - mydetailit.Title = theactivityit.Name != null ? theactivityit.Name.FirstOrDefault().InnerText != null ? theactivityit.Name.FirstOrDefault().InnerText.Trim() : "" : ""; + mydetailit.Title = + theactivityit.Name != null + ? theactivityit.Name.FirstOrDefault().InnerText != null + ? theactivityit.Name.FirstOrDefault().InnerText.Trim() + : "" + : ""; //mydetailit.Header = ""; mydetailit.Language = "it"; //mydetailit.AdditionalText = ""; //mydetailit.Alttext = ""; - //mydetailit.IntroText = ""; + //mydetailit.IntroText = ""; if (mytextitems.TextItem != null) { foreach (var textelement in mytextitems.TextItem) { //Allgemeine Beschreibung - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "732512C9492340F4AB30FFB800461BE7") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "732512C9492340F4AB30FFB800461BE7" + ) { - mydetailit.BaseText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.BaseText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Anfahrtstext - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "C26C826A239C47BDB773B4E4B3F27547") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "C26C826A239C47BDB773B4E4B3F27547" + ) { - mydetailit.GetThereText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.GetThereText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Wegbeschreibung - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "ECEB7021321445648CE37A9A84D64930") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "ECEB7021321445648CE37A9A84D64930" + ) { - mydetailit.AdditionalText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.AdditionalText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Kurzbeschreibung A143F1FF0A0A4185A907208D643D3BB8 --> Placing in Introtext - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "A143F1FF0A0A4185A907208D643D3BB8") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "A143F1FF0A0A4185A907208D643D3BB8" + ) { - mydetailit.IntroText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.IntroText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Parken AFB5C1F8662949108105DAC81DD8B18F - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "AFB5C1F8662949108105DAC81DD8B18F") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "AFB5C1F8662949108105DAC81DD8B18F" + ) { - mydetailit.ParkingInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.ParkingInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Öffentliche Verkehrsmittel C67DBA804FAD4B4EB64A4A758771B723 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "C67DBA804FAD4B4EB64A4A758771B723") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "C67DBA804FAD4B4EB64A4A758771B723" + ) { - mydetailit.PublicTransportationInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.PublicTransportationInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Tipp des Autors 643EDEE9CE2D44AC932FC714256B6C9C - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "643EDEE9CE2D44AC932FC714256B6C9C") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "643EDEE9CE2D44AC932FC714256B6C9C" + ) { - mydetailit.AuthorTip = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.AuthorTip = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Sicherheitshinweise 73EC4F8F7AAC48CE82A23E8EBDCA750E - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "73EC4F8F7AAC48CE82A23E8EBDCA750E") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "73EC4F8F7AAC48CE82A23E8EBDCA750E" + ) { - mydetailit.SafetyInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.SafetyInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Ausrüstung 933D29E15E82415DBEDE877C477212D2 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "933D29E15E82415DBEDE877C477212D2") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "933D29E15E82415DBEDE877C477212D2" + ) { - mydetailit.EquipmentInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.EquipmentInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } } } @@ -534,16 +930,22 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri } //en - var parsedmultimediainfoen = theactivityen.MultimediaDescriptions.MultimediaDescription.FirstOrDefault(); + var parsedmultimediainfoen = + theactivityen.MultimediaDescriptions.MultimediaDescription.FirstOrDefault(); if (parsedmultimediainfoen != null) { - if (parsedmultimediainfoen.ImageItems.ImageItem != null) { int i = 0; foreach (var imageelement in parsedmultimediainfoen.ImageItems.ImageItem) { - imagegallerylist.Where(x => x.ListPosition == i && x.ImageSource == "LTS").FirstOrDefault().ImageDesc.TryAddOrUpdate("en", imageelement.Description.FirstOrDefault().InnerText); + imagegallerylist + .Where(x => x.ListPosition == i && x.ImageSource == "LTS") + .FirstOrDefault() + .ImageDesc.TryAddOrUpdate( + "en", + imageelement.Description.FirstOrDefault().InnerText + ); i++; //ImageGallery myimggallery = new ImageGallery(); //myimggallery.Height = imageelement.ImageFormat.Height; @@ -559,7 +961,6 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri } } - var mytextitems = parsedmultimediainfoen.TextItems; Detail mydetailen = new Detail(); @@ -570,61 +971,138 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri } //mydetailen.Title = theactivityen.Name != null ? theactivityen.Name.FirstOrDefault().InnerText.Trim() : ""; - mydetailen.Title = theactivityen.Name != null ? theactivityen.Name.FirstOrDefault().InnerText != null ? theactivityen.Name.FirstOrDefault().InnerText.Trim() : "" : ""; + mydetailen.Title = + theactivityen.Name != null + ? theactivityen.Name.FirstOrDefault().InnerText != null + ? theactivityen.Name.FirstOrDefault().InnerText.Trim() + : "" + : ""; //mydetailen.Header = ""; mydetailen.Language = "en"; //mydetailen.AdditionalText = ""; //mydetailen.Alttext = ""; - //mydetailen.IntroText = ""; + //mydetailen.IntroText = ""; if (mytextitems.TextItem != null) { foreach (var textelement in mytextitems.TextItem) { //Allgemeine Beschreibung - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "732512C9492340F4AB30FFB800461BE7") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "732512C9492340F4AB30FFB800461BE7" + ) { - mydetailen.BaseText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.BaseText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Anfahrtstext - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "C26C826A239C47BDB773B4E4B3F27547") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "C26C826A239C47BDB773B4E4B3F27547" + ) { - mydetailen.GetThereText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.GetThereText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Wegbeschreibung - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "ECEB7021321445648CE37A9A84D64930") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "ECEB7021321445648CE37A9A84D64930" + ) { - mydetailen.AdditionalText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.AdditionalText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Kurzbeschreibung A143F1FF0A0A4185A907208D643D3BB8 --> Placing in Introtext - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "A143F1FF0A0A4185A907208D643D3BB8") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "A143F1FF0A0A4185A907208D643D3BB8" + ) { - mydetailen.IntroText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.IntroText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Parken AFB5C1F8662949108105DAC81DD8B18F - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "AFB5C1F8662949108105DAC81DD8B18F") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "AFB5C1F8662949108105DAC81DD8B18F" + ) { - mydetailen.ParkingInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.ParkingInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Öffentliche Verkehrsmittel C67DBA804FAD4B4EB64A4A758771B723 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "C67DBA804FAD4B4EB64A4A758771B723") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "C67DBA804FAD4B4EB64A4A758771B723" + ) { - mydetailen.PublicTransportationInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.PublicTransportationInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Tipp des Autors 643EDEE9CE2D44AC932FC714256B6C9C - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "643EDEE9CE2D44AC932FC714256B6C9C") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "643EDEE9CE2D44AC932FC714256B6C9C" + ) { - mydetailen.AuthorTip = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.AuthorTip = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Sicherheitshinweise 73EC4F8F7AAC48CE82A23E8EBDCA750E - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "73EC4F8F7AAC48CE82A23E8EBDCA750E") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "73EC4F8F7AAC48CE82A23E8EBDCA750E" + ) { - mydetailen.SafetyInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.SafetyInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Ausrüstung 933D29E15E82415DBEDE877C477212D2 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "933D29E15E82415DBEDE877C477212D2") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "933D29E15E82415DBEDE877C477212D2" + ) { - mydetailen.EquipmentInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.EquipmentInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } } } @@ -685,7 +1163,11 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri { GpsInfo mygpsinfo = new GpsInfo(); - mygpsinfo.Gpstype = position.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().Name.FirstOrDefault().InnerText; + mygpsinfo.Gpstype = position.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .Name.FirstOrDefault() + .InnerText; mygpsinfo.AltitudeUnitofMeasure = "m"; mygpsinfo.Altitude = position.Altitude; mygpsinfo.Longitude = Convert.ToDouble(position.Longitude, myculture); @@ -715,15 +1197,36 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri mygpstrack.Id = gpstrack.RID; mygpstrack.GpxTrackUrl = gpstrack.File.URL.InnerText; - if (gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText == "Übersicht") + if ( + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText == "Übersicht" + ) mygpstrack.Type = "overview"; - if (gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText == "Datei zum herunterladen") + if ( + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText == "Datei zum herunterladen" + ) mygpstrack.Type = "detailed"; - //EN und IT Info? - mygpstrack.GpxTrackDesc.TryAddOrUpdate("de", gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText); + mygpstrack.GpxTrackDesc.TryAddOrUpdate( + "de", + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + ); mygpstracklist.Add(mygpstrack); } @@ -740,8 +1243,18 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri { foreach (var gpstrack in gpstracksit) { - GpsTrack mygpstrack = mygpstracklist.Where(x => x.Id == gpstrack.RID).FirstOrDefault(); - mygpstrack.GpxTrackDesc.TryAddOrUpdate("it", gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText); + GpsTrack mygpstrack = mygpstracklist + .Where(x => x.Id == gpstrack.RID) + .FirstOrDefault(); + mygpstrack.GpxTrackDesc.TryAddOrUpdate( + "it", + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + ); //mygpstracklist.Add(mygpstrack); } } @@ -757,8 +1270,18 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri { foreach (var gpstrack in gpstracksen) { - GpsTrack mygpstrack = mygpstracklist.Where(x => x.Id == gpstrack.RID).FirstOrDefault(); - mygpstrack.GpxTrackDesc.TryAddOrUpdate("en", gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText); + GpsTrack mygpstrack = mygpstracklist + .Where(x => x.Id == gpstrack.RID) + .FirstOrDefault(); + mygpstrack.GpxTrackDesc.TryAddOrUpdate( + "en", + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + ); //mygpstracklist.Add(mygpstrack); } } @@ -792,7 +1315,10 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri myltstag.LTSRID = ltstag.RID; myltstag.Id = ltstag.Name.FirstOrDefault().InnerText.Trim().Replace("/", ""); - myltstag.TagName.TryAddOrUpdate("de", ltstag.Name != null ? ltstag.Name.FirstOrDefault().InnerText : ""); + myltstag.TagName.TryAddOrUpdate( + "de", + ltstag.Name != null ? ltstag.Name.FirstOrDefault().InnerText : "" + ); //Sonderfix Tag DE enthält / if (myltstag.TagName["de"].Contains("/")) @@ -804,7 +1330,10 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri foreach (var ltstin in ltstag.Tins.Tin) { LTSTins mytin = new LTSTins(); - mytin.TinName.TryAddOrUpdate("de", ltstin.Name != null ? ltstin.Name.FirstOrDefault().InnerText : ""); + mytin.TinName.TryAddOrUpdate( + "de", + ltstin.Name != null ? ltstin.Name.FirstOrDefault().InnerText : "" + ); mytin.LTSRID = ltstin.RID; myltstag.LTSTins.Add(mytin); @@ -816,34 +1345,56 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri foreach (var ltstag in theactivityit.Tags.Tag) { - var currentltstagit = ltstaglist.Where(x => x.LTSRID == ltstag.RID).FirstOrDefault(); - currentltstagit.TagName.TryAddOrUpdate("it", ltstag.Name != null ? ltstag.Name.FirstOrDefault().InnerText : ""); + var currentltstagit = ltstaglist + .Where(x => x.LTSRID == ltstag.RID) + .FirstOrDefault(); + currentltstagit.TagName.TryAddOrUpdate( + "it", + ltstag.Name != null ? ltstag.Name.FirstOrDefault().InnerText : "" + ); //add the tin info in IT if (ltstag.Tins != null) { foreach (var ltstin in ltstag.Tins.Tin) { - var currentltstinit = currentltstagit.LTSTins.Where(x => x.LTSRID == ltstin.RID).FirstOrDefault(); - currentltstinit.TinName.TryAddOrUpdate("it", ltstin.Name != null ? ltstin.Name.FirstOrDefault().InnerText : ""); + var currentltstinit = currentltstagit.LTSTins + .Where(x => x.LTSRID == ltstin.RID) + .FirstOrDefault(); + currentltstinit.TinName.TryAddOrUpdate( + "it", + ltstin.Name != null ? ltstin.Name.FirstOrDefault().InnerText : "" + ); } } } foreach (var ltstag in theactivityen.Tags.Tag) { - var currentltstagen = ltstaglist.Where(x => x.LTSRID == ltstag.RID).FirstOrDefault(); - currentltstagen.TagName.TryAddOrUpdate("en", ltstag.Name != null ? ltstag.Name.FirstOrDefault().InnerText : ""); + var currentltstagen = ltstaglist + .Where(x => x.LTSRID == ltstag.RID) + .FirstOrDefault(); + currentltstagen.TagName.TryAddOrUpdate( + "en", + ltstag.Name != null ? ltstag.Name.FirstOrDefault().InnerText : "" + ); //add the tin info in EN and set the id to EN object if (ltstag.Tins != null) { foreach (var ltstin in ltstag.Tins.Tin) { - var currentltstinen = currentltstagen.LTSTins.Where(x => x.LTSRID == ltstin.RID).FirstOrDefault(); - currentltstinen.TinName.TryAddOrUpdate("en", ltstin.Name != null ? ltstin.Name.FirstOrDefault().InnerText : ""); + var currentltstinen = currentltstagen.LTSTins + .Where(x => x.LTSRID == ltstin.RID) + .FirstOrDefault(); + currentltstinen.TinName.TryAddOrUpdate( + "en", + ltstin.Name != null ? ltstin.Name.FirstOrDefault().InnerText : "" + ); //Set ID - currentltstinen.Id = ltstin.Name.FirstOrDefault().InnerText.ComputeSHA1Hash(); + currentltstinen.Id = ltstin.Name + .FirstOrDefault() + .InnerText.ComputeSHA1Hash(); } } } @@ -856,17 +1407,70 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri //BEGIN TYPE SYNC //Assign Type Level 1 - hike.Type = theactivityde.EnumCodes != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Name != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Name.FirstOrDefault().InnerText : GetActivityMainType(activitytype)["de"] : GetActivityMainType(activitytype)["de"]; + hike.Type = + theactivityde.EnumCodes != null + ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Name != null + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : GetActivityMainType(activitytype)["de"] + : GetActivityMainType(activitytype)["de"]; //Bei lift subtype level 2 fehlt komplett? ging das nicht - hike.SubType = theactivityde.EnumCodes != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").Count() > 0 ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText : "" : "" : ""; + hike.SubType = + theactivityde.EnumCodes != null + ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code != null + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .Count() > 0 + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : "" + : "" + : ""; //PoiType setzen falls vorhanden - hike.PoiType = theactivityde.EnumCodes != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "2").Count() > 0 ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "2").FirstOrDefault().Name.FirstOrDefault().InnerText : "" : "" : ""; + hike.PoiType = + theactivityde.EnumCodes != null + ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code != null + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "2") + .Count() > 0 + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "2") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : "" + : "" + : ""; if (activitytype == "SLOPE" || activitytype == "SKITRACK") { - hike.PoiType = theactivityde.EnumCodes != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "0").Count() > 0 ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "0").FirstOrDefault().Name.FirstOrDefault().InnerText : "" : "" : ""; + hike.PoiType = + theactivityde.EnumCodes != null + ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code != null + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "0") + .Count() > 0 + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "0") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : "" + : "" + : ""; } //AdditionalPoiInfos @@ -879,27 +1483,151 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri myaddpoiinfosit.Language = "it"; myaddpoiinfosen.Language = "en"; - myaddpoiinfosde.MainType = theactivityde.EnumCodes != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Name != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Name.FirstOrDefault().InnerText : GetActivityMainType(activitytype)["de"] : GetActivityMainType(activitytype)["de"]; - myaddpoiinfosit.MainType = theactivityit.EnumCodes != null ? theactivityit.EnumCodes.EnumCode.FirstOrDefault().Name != null ? theactivityit.EnumCodes.EnumCode.FirstOrDefault().Name.FirstOrDefault().InnerText : GetActivityMainType(activitytype)["it"] : GetActivityMainType(activitytype)["it"]; - myaddpoiinfosen.MainType = theactivityen.EnumCodes != null ? theactivityen.EnumCodes.EnumCode.FirstOrDefault().Name != null ? theactivityen.EnumCodes.EnumCode.FirstOrDefault().Name.FirstOrDefault().InnerText : GetActivityMainType(activitytype)["en"] : GetActivityMainType(activitytype)["en"]; - - myaddpoiinfosde.SubType = theactivityde.EnumCodes != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").Count() > 0 ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText : "" : "" : ""; - myaddpoiinfosit.SubType = theactivityit.EnumCodes != null ? theactivityit.EnumCodes.EnumCode.FirstOrDefault().Code != null ? theactivityit.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").Count() > 0 ? theactivityit.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText : "" : "" : ""; - myaddpoiinfosen.SubType = theactivityen.EnumCodes != null ? theactivityen.EnumCodes.EnumCode.FirstOrDefault().Code != null ? theactivityen.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").Count() > 0 ? theactivityen.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText : "" : "" : ""; - - myaddpoiinfosde.PoiType = theactivityde.EnumCodes != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "2").Count() > 0 ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "2").FirstOrDefault().Name.FirstOrDefault().InnerText : "" : "" : ""; - myaddpoiinfosit.PoiType = theactivityit.EnumCodes != null ? theactivityit.EnumCodes.EnumCode.FirstOrDefault().Code != null ? theactivityit.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "2").Count() > 0 ? theactivityit.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "2").FirstOrDefault().Name.FirstOrDefault().InnerText : "" : "" : ""; - myaddpoiinfosen.PoiType = theactivityen.EnumCodes != null ? theactivityen.EnumCodes.EnumCode.FirstOrDefault().Code != null ? theactivityen.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "2").Count() > 0 ? theactivityen.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "2").FirstOrDefault().Name.FirstOrDefault().InnerText : "" : "" : ""; - - + myaddpoiinfosde.MainType = + theactivityde.EnumCodes != null + ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Name != null + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : GetActivityMainType(activitytype)["de"] + : GetActivityMainType(activitytype)["de"]; + myaddpoiinfosit.MainType = + theactivityit.EnumCodes != null + ? theactivityit.EnumCodes.EnumCode.FirstOrDefault().Name != null + ? theactivityit.EnumCodes.EnumCode + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : GetActivityMainType(activitytype)["it"] + : GetActivityMainType(activitytype)["it"]; + myaddpoiinfosen.MainType = + theactivityen.EnumCodes != null + ? theactivityen.EnumCodes.EnumCode.FirstOrDefault().Name != null + ? theactivityen.EnumCodes.EnumCode + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : GetActivityMainType(activitytype)["en"] + : GetActivityMainType(activitytype)["en"]; + + myaddpoiinfosde.SubType = + theactivityde.EnumCodes != null + ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code != null + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .Count() > 0 + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : "" + : "" + : ""; + myaddpoiinfosit.SubType = + theactivityit.EnumCodes != null + ? theactivityit.EnumCodes.EnumCode.FirstOrDefault().Code != null + ? theactivityit.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .Count() > 0 + ? theactivityit.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : "" + : "" + : ""; + myaddpoiinfosen.SubType = + theactivityen.EnumCodes != null + ? theactivityen.EnumCodes.EnumCode.FirstOrDefault().Code != null + ? theactivityen.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .Count() > 0 + ? theactivityen.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : "" + : "" + : ""; + + myaddpoiinfosde.PoiType = + theactivityde.EnumCodes != null + ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code != null + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "2") + .Count() > 0 + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "2") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : "" + : "" + : ""; + myaddpoiinfosit.PoiType = + theactivityit.EnumCodes != null + ? theactivityit.EnumCodes.EnumCode.FirstOrDefault().Code != null + ? theactivityit.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "2") + .Count() > 0 + ? theactivityit.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "2") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : "" + : "" + : ""; + myaddpoiinfosen.PoiType = + theactivityen.EnumCodes != null + ? theactivityen.EnumCodes.EnumCode.FirstOrDefault().Code != null + ? theactivityen.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "2") + .Count() > 0 + ? theactivityen.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "2") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : "" + : "" + : ""; if (activitytype == "SLIDE" || activitytype == "SLOPE" || activitytype == "SKITRACK") { if (hike.SubType == "" || hike.SubType == "no Subtype") { - myaddpoiinfosde.SubType = SubTypeSpecialTranslator("de", hike.Type, ltstaglist.Select(x => x.Id).ToList()); - myaddpoiinfosit.SubType = SubTypeSpecialTranslator("it", hike.Type, ltstaglist.Select(x => x.Id).ToList()); - myaddpoiinfosen.SubType = SubTypeSpecialTranslator("en", hike.Type, ltstaglist.Select(x => x.Id).ToList()); + myaddpoiinfosde.SubType = SubTypeSpecialTranslator( + "de", + hike.Type, + ltstaglist.Select(x => x.Id).ToList() + ); + myaddpoiinfosit.SubType = SubTypeSpecialTranslator( + "it", + hike.Type, + ltstaglist.Select(x => x.Id).ToList() + ); + myaddpoiinfosen.SubType = SubTypeSpecialTranslator( + "en", + hike.Type, + ltstaglist.Select(x => x.Id).ToList() + ); } } @@ -920,11 +1648,34 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri hike.AdditionalPoiInfos.TryAddOrUpdate("it", myaddpoiinfosit); hike.AdditionalPoiInfos.TryAddOrUpdate("en", myaddpoiinfosen); - //Tags beibehalten. Maintyp + Subtyp als Tag übernehmen + //Tags beibehalten. Maintyp + Subtyp als Tag übernehmen List currenttags = new List(); - string type = theactivityde.EnumCodes != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Name != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Name.FirstOrDefault().InnerText : GetActivityMainType(activitytype)["de"] : GetActivityMainType(activitytype)["de"]; - string subtype = theactivityde.EnumCodes != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code != null ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").Count() > 0 ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText : "no Subtype" : "no Subtype" : "no Subtype"; + string type = + theactivityde.EnumCodes != null + ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Name != null + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : GetActivityMainType(activitytype)["de"] + : GetActivityMainType(activitytype)["de"]; + string subtype = + theactivityde.EnumCodes != null + ? theactivityde.EnumCodes.EnumCode.FirstOrDefault().Code != null + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .Count() > 0 + ? theactivityde.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + : "no Subtype" + : "no Subtype" + : "no Subtype"; if (!currenttags.Contains(type)) currenttags.Add(type); @@ -944,7 +1695,11 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri { if (hike.SubType == "" || hike.SubType == "no Subtype") { - hike.SubType = SubTypeSpecialTranslator("de", hike.Type, ltstaglist.Select(x => x.Id).ToList()); + hike.SubType = SubTypeSpecialTranslator( + "de", + hike.Type, + ltstaglist.Select(x => x.Id).ToList() + ); } } @@ -960,7 +1715,6 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri currenttags.Add(hike.PoiType); } - hike.SmgTags = currenttags.Distinct().ToList(); //Fix no subtype as tag @@ -976,23 +1730,37 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri { if (theactivityde.OperationSchedules.OperationSchedule != null) { - foreach (var myoperationschedule in theactivityde.OperationSchedules.OperationSchedule) + foreach ( + var myoperationschedule in theactivityde + .OperationSchedules + .OperationSchedule + ) { OperationSchedule theoperationschedule = new OperationSchedule(); - theoperationschedule.OperationscheduleName["de"] = myoperationschedule.Name != null ? myoperationschedule.Name.FirstOrDefault().InnerText : ""; + theoperationschedule.OperationscheduleName["de"] = + myoperationschedule.Name != null + ? myoperationschedule.Name.FirstOrDefault().InnerText + : ""; theoperationschedule.Start = DateTime.Parse(myoperationschedule.Start); theoperationschedule.Stop = DateTime.Parse(myoperationschedule.End); theoperationschedule.Type = myoperationschedule.Type; - List myopeningtimes = new List(); + List myopeningtimes = + new List(); if (myoperationschedule.OperationTime != null) { foreach (var operationscheduletime in myoperationschedule.OperationTime) { OperationScheduleTime mytime = new OperationScheduleTime(); - mytime.Start = operationscheduletime.Start == null ? TimeSpan.Parse("00:00:00") : TimeSpan.Parse(operationscheduletime.Start); - mytime.End = operationscheduletime.End == null ? TimeSpan.Parse("23:59:00") : TimeSpan.Parse(operationscheduletime.End); + mytime.Start = + operationscheduletime.Start == null + ? TimeSpan.Parse("00:00:00") + : TimeSpan.Parse(operationscheduletime.Start); + mytime.End = + operationscheduletime.End == null + ? TimeSpan.Parse("23:59:00") + : TimeSpan.Parse(operationscheduletime.End); mytime.Monday = operationscheduletime.Mon; mytime.Tuesday = operationscheduletime.Tue; mytime.Wednesday = operationscheduletime.Weds; @@ -1021,7 +1789,6 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri else hike.Active = false; - if (theactivityde.News.Status.CopyrightChecked == 1) hike.CopyrightChecked = true; else if (theactivityde.News.Status.CopyrightChecked == 0) @@ -1029,9 +1796,8 @@ public static PoiBaseInfos GetActivitiesDetailLTS(string activitytype, string ri else hike.CopyrightChecked = null; - //Add The available Languages - //Check wo überall in Details sprachknoten enthalten sind + //Check wo überall in Details sprachknoten enthalten sind var availablelanguages = hike.Detail.Select(x => x.Key).ToList(); hike.HasLanguage = availablelanguages; @@ -1100,13 +1866,16 @@ public static Dictionary GetActivityMainType(string mainType) } // - private static string SubTypeSpecialTranslator(string lang, string maintype, List ltstags) + private static string SubTypeSpecialTranslator( + string lang, + string maintype, + List ltstags + ) { string subtypetoreturn = ""; if (lang == "de") { - if (maintype == "Loipen") { if (ltstags.Contains("Klassisch und Skating")) @@ -1128,7 +1897,6 @@ private static string SubTypeSpecialTranslator(string lang, string maintype, Lis return "Ski alpin"; else return "Ski alpin"; - } else if (maintype == "Rodelbahnen") { @@ -1148,7 +1916,6 @@ private static string SubTypeSpecialTranslator(string lang, string maintype, Lis } else if (lang == "it") { - if (maintype == "Loipen") { if (ltstags.Contains("Klassisch und Skating")) @@ -1170,7 +1937,6 @@ private static string SubTypeSpecialTranslator(string lang, string maintype, Lis return "Sci alpino"; else return "Sci alpino"; - } else if (maintype == "Rodelbahnen") { @@ -1190,7 +1956,6 @@ private static string SubTypeSpecialTranslator(string lang, string maintype, Lis } else if (lang == "en") { - if (maintype == "Loipen") { if (ltstags.Contains("Klassisch und Skating")) @@ -1212,7 +1977,6 @@ private static string SubTypeSpecialTranslator(string lang, string maintype, Lis return "Ski alpin"; else return "Ski alpin"; - } else if (maintype == "Rodelbahnen") { diff --git a/LCS/Parser/ParseGastronomicData.cs b/LCS/Parser/ParseGastronomicData.cs index 07c9998f8..3c47bacc1 100644 --- a/LCS/Parser/ParseGastronomicData.cs +++ b/LCS/Parser/ParseGastronomicData.cs @@ -16,16 +16,71 @@ public class ParseGastronomicData public static CultureInfo myculture = new CultureInfo("en"); //Gets Gastronomy Detail - public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gastro, bool newgastro, string ltsuser, string ltspswd, string ltsmsgpswd) + public static Gastronomy GetGastronomyDetailLTS( + string gastroRID, + Gastronomy gastro, + bool newgastro, + string ltsuser, + string ltspswd, + string ltsmsgpswd + ) { - var mygastrodetailrequestde = GetGastronomicDataLCS.GetGastronomicDataDetailRequestAsync(gastroRID, "de", "1", "1", "1", "1", "1", "1", "1", "1", "SMG", ltsmsgpswd); - var mygastrodetailrequestit = GetGastronomicDataLCS.GetGastronomicDataDetailRequestAsync(gastroRID, "it", "1", "1", "1", "1", "1", "1", "1", "1", "SMG", ltsmsgpswd); - var mygastrodetailrequesten = GetGastronomicDataLCS.GetGastronomicDataDetailRequestAsync(gastroRID, "en", "1", "1", "1", "1", "1", "1", "1", "1", "SMG", ltsmsgpswd); + var mygastrodetailrequestde = + GetGastronomicDataLCS.GetGastronomicDataDetailRequestAsync( + gastroRID, + "de", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "SMG", + ltsmsgpswd + ); + var mygastrodetailrequestit = + GetGastronomicDataLCS.GetGastronomicDataDetailRequestAsync( + gastroRID, + "it", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "SMG", + ltsmsgpswd + ); + var mygastrodetailrequesten = + GetGastronomicDataLCS.GetGastronomicDataDetailRequestAsync( + gastroRID, + "en", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "SMG", + ltsmsgpswd + ); GetGastronomicDataLCS mygastrosearch = new GetGastronomicDataLCS(ltsuser, ltspswd); - var mygastroresponsede = mygastrosearch.GetGastronomicDataDetail(mygastrodetailrequestde); - var mygastroresponseit = mygastrosearch.GetGastronomicDataDetail(mygastrodetailrequestit); - var mygastroresponseen = mygastrosearch.GetGastronomicDataDetail(mygastrodetailrequesten); + var mygastroresponsede = mygastrosearch.GetGastronomicDataDetail( + mygastrodetailrequestde + ); + var mygastroresponseit = mygastrosearch.GetGastronomicDataDetail( + mygastrodetailrequestit + ); + var mygastroresponseen = mygastrosearch.GetGastronomicDataDetail( + mygastrodetailrequesten + ); //NEW if Service gives Gastronomic RID(s) for GastronomicDataDetail not found or not a gastronomic object. @@ -40,7 +95,9 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas gastro.LastChange = DateTime.Now; Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("Gastronomy " + gastro.Id + " deactivated on source, deactivating!"); + Console.WriteLine( + "Gastronomy " + gastro.Id + " deactivated on source, deactivating!" + ); return gastro; } @@ -54,11 +111,12 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas if (thegastrononomyde.ContactInfos != null) if (thegastrononomyde.ContactInfos.ContactInfo.FirstOrDefault().CompanyName != null) - nome = thegastrononomyde.ContactInfos.ContactInfo.FirstOrDefault().CompanyName.InnerText; + nome = thegastrononomyde.ContactInfos.ContactInfo + .FirstOrDefault() + .CompanyName.InnerText; gastro.Shortname = nome; - //Gastro anhängen weil es sein kann dass Hotel auch Gastro ist gastro.Id = "GASTRO" + thegastrononomyde.RID; @@ -80,8 +138,6 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas gastro.LastChange = DateTime.Now; } - - //Add The available Languages List availablelangs = new List() { "de", "it", "en" }; gastro.HasLanguage = availablelangs; @@ -92,7 +148,10 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas //LastChange: Wann wurde das Objekt das letzte Mal geändert. //Mode: Das Objekt soll nur dann publiziert werden wenn Mode > 0. gastro.Active = Convert.ToBoolean(thegastrononomyde.News.Status.IsEnabled); - gastro.RepresentationRestriction = thegastrononomyde.News != null ? Convert.ToInt32(thegastrononomyde.News.RepresentationRestriction.Mode) : 0; + gastro.RepresentationRestriction = + thegastrononomyde.News != null + ? Convert.ToInt32(thegastrononomyde.News.RepresentationRestriction.Mode) + : 0; //if (gastro.RepresentationRestriction > 0 && gastro.Active) // gastro.SmgActive = true; @@ -107,14 +166,12 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas gastro.Active = false; } - //Contactinfo DE if (thegastrononomyde.ContactInfos.ContactInfo != null) { var parsedcontactinfo = thegastrononomyde.ContactInfos.ContactInfo.FirstOrDefault(); if (parsedcontactinfo != null) { - //de ContactInfos mycontactinfode = new ContactInfos(); @@ -122,28 +179,79 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas if (myadresselement != null) { - mycontactinfode.Address = myadresselement.Address.FirstOrDefault().AddressLine; - - mycontactinfode.City = parsedcontactinfo.Addresses.Address.FirstOrDefault().CityName; - mycontactinfode.CountryCode = parsedcontactinfo.Addresses.Address.FirstOrDefault().CountryName.Code; - mycontactinfode.CountryName = parsedcontactinfo.Addresses.Address.FirstOrDefault().CountryName != null ? parsedcontactinfo.Addresses.Address.FirstOrDefault().CountryName.InnerText : ""; - mycontactinfode.ZipCode = parsedcontactinfo.Addresses.Address.FirstOrDefault().PostalCode; - - mycontactinfode.Email = parsedcontactinfo.Emails != null ? parsedcontactinfo.Emails.Email.FirstOrDefault().InnerText : ""; + mycontactinfode.Address = myadresselement.Address + .FirstOrDefault() + .AddressLine; + + mycontactinfode.City = parsedcontactinfo.Addresses.Address + .FirstOrDefault() + .CityName; + mycontactinfode.CountryCode = parsedcontactinfo.Addresses.Address + .FirstOrDefault() + .CountryName.Code; + mycontactinfode.CountryName = + parsedcontactinfo.Addresses.Address.FirstOrDefault().CountryName != null + ? parsedcontactinfo.Addresses.Address + .FirstOrDefault() + .CountryName.InnerText + : ""; + mycontactinfode.ZipCode = parsedcontactinfo.Addresses.Address + .FirstOrDefault() + .PostalCode; + + mycontactinfode.Email = + parsedcontactinfo.Emails != null + ? parsedcontactinfo.Emails.Email.FirstOrDefault().InnerText + : ""; mycontactinfode.Faxnumber = ""; - mycontactinfode.Givenname = parsedcontactinfo.Names != null ? parsedcontactinfo.Names.Name.FirstOrDefault().GivenName : ""; - mycontactinfode.Surname = parsedcontactinfo.Names != null ? parsedcontactinfo.Names.Name.FirstOrDefault().Surname : ""; - mycontactinfode.NamePrefix = parsedcontactinfo.Names != null ? parsedcontactinfo.Names.Name.FirstOrDefault().NamePrefix : ""; - - mycontactinfode.CompanyName = parsedcontactinfo.CompanyName != null ? parsedcontactinfo.CompanyName.InnerText : ""; + mycontactinfode.Givenname = + parsedcontactinfo.Names != null + ? parsedcontactinfo.Names.Name.FirstOrDefault().GivenName + : ""; + mycontactinfode.Surname = + parsedcontactinfo.Names != null + ? parsedcontactinfo.Names.Name.FirstOrDefault().Surname + : ""; + mycontactinfode.NamePrefix = + parsedcontactinfo.Names != null + ? parsedcontactinfo.Names.Name.FirstOrDefault().NamePrefix + : ""; + + mycontactinfode.CompanyName = + parsedcontactinfo.CompanyName != null + ? parsedcontactinfo.CompanyName.InnerText + : ""; mycontactinfode.Language = "de"; - mycontactinfode.Phonenumber = parsedcontactinfo.Phones != null ? parsedcontactinfo.Phones.Phone.Where(x => x.PhoneTechType == "1").Count() > 0 ? parsedcontactinfo.Phones.Phone.Where(x => x.PhoneTechType == "1").FirstOrDefault().PhoneNumber : "" : ""; - mycontactinfode.Faxnumber = parsedcontactinfo.Phones != null ? parsedcontactinfo.Phones.Phone.Where(x => x.PhoneTechType == "3").Count() > 0 ? parsedcontactinfo.Phones.Phone.Where(x => x.PhoneTechType == "3").FirstOrDefault().PhoneNumber : "" : ""; - - mycontactinfode.Url = parsedcontactinfo.URLs != null ? parsedcontactinfo.URLs.URL.FirstOrDefault().InnerText : ""; + mycontactinfode.Phonenumber = + parsedcontactinfo.Phones != null + ? parsedcontactinfo.Phones.Phone + .Where(x => x.PhoneTechType == "1") + .Count() > 0 + ? parsedcontactinfo.Phones.Phone + .Where(x => x.PhoneTechType == "1") + .FirstOrDefault() + .PhoneNumber + : "" + : ""; + mycontactinfode.Faxnumber = + parsedcontactinfo.Phones != null + ? parsedcontactinfo.Phones.Phone + .Where(x => x.PhoneTechType == "3") + .Count() > 0 + ? parsedcontactinfo.Phones.Phone + .Where(x => x.PhoneTechType == "3") + .FirstOrDefault() + .PhoneNumber + : "" + : ""; + + mycontactinfode.Url = + parsedcontactinfo.URLs != null + ? parsedcontactinfo.URLs.URL.FirstOrDefault().InnerText + : ""; //contactinfolist.Add(mycontactinfode); gastro.ContactInfos.TryAddOrUpdate("de", mycontactinfode); @@ -163,36 +271,84 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas var parsedcontactinfo = thegastrononomyit.ContactInfos.ContactInfo.FirstOrDefault(); if (parsedcontactinfo != null) { - ContactInfos mycontactinfoit = new ContactInfos(); var myadresselement = parsedcontactinfo.Addresses; if (myadresselement != null) { - mycontactinfoit.Address = myadresselement.Address.FirstOrDefault().AddressLine; - - mycontactinfoit.City = parsedcontactinfo.Addresses.Address.FirstOrDefault().CityName; - mycontactinfoit.CountryCode = parsedcontactinfo.Addresses.Address.FirstOrDefault().CountryName.Code; - mycontactinfoit.CountryName = parsedcontactinfo.Addresses.Address.FirstOrDefault().CountryName != null ? parsedcontactinfo.Addresses.Address.FirstOrDefault().CountryName.InnerText : ""; - mycontactinfoit.ZipCode = parsedcontactinfo.Addresses.Address.FirstOrDefault().PostalCode; - - mycontactinfoit.Email = parsedcontactinfo.Emails != null ? parsedcontactinfo.Emails.Email.FirstOrDefault().InnerText : ""; + mycontactinfoit.Address = myadresselement.Address + .FirstOrDefault() + .AddressLine; + + mycontactinfoit.City = parsedcontactinfo.Addresses.Address + .FirstOrDefault() + .CityName; + mycontactinfoit.CountryCode = parsedcontactinfo.Addresses.Address + .FirstOrDefault() + .CountryName.Code; + mycontactinfoit.CountryName = + parsedcontactinfo.Addresses.Address.FirstOrDefault().CountryName != null + ? parsedcontactinfo.Addresses.Address + .FirstOrDefault() + .CountryName.InnerText + : ""; + mycontactinfoit.ZipCode = parsedcontactinfo.Addresses.Address + .FirstOrDefault() + .PostalCode; + + mycontactinfoit.Email = + parsedcontactinfo.Emails != null + ? parsedcontactinfo.Emails.Email.FirstOrDefault().InnerText + : ""; mycontactinfoit.Faxnumber = ""; - mycontactinfoit.Givenname = parsedcontactinfo.Names != null ? parsedcontactinfo.Names.Name.FirstOrDefault().GivenName : ""; - mycontactinfoit.Surname = parsedcontactinfo.Names != null ? parsedcontactinfo.Names.Name.FirstOrDefault().Surname : ""; - mycontactinfoit.NamePrefix = parsedcontactinfo.Names != null ? parsedcontactinfo.Names.Name.FirstOrDefault().NamePrefix : ""; - - mycontactinfoit.CompanyName = parsedcontactinfo.CompanyName != null ? parsedcontactinfo.CompanyName.InnerText : ""; + mycontactinfoit.Givenname = + parsedcontactinfo.Names != null + ? parsedcontactinfo.Names.Name.FirstOrDefault().GivenName + : ""; + mycontactinfoit.Surname = + parsedcontactinfo.Names != null + ? parsedcontactinfo.Names.Name.FirstOrDefault().Surname + : ""; + mycontactinfoit.NamePrefix = + parsedcontactinfo.Names != null + ? parsedcontactinfo.Names.Name.FirstOrDefault().NamePrefix + : ""; + + mycontactinfoit.CompanyName = + parsedcontactinfo.CompanyName != null + ? parsedcontactinfo.CompanyName.InnerText + : ""; mycontactinfoit.Language = "it"; - mycontactinfoit.Phonenumber = parsedcontactinfo.Phones != null ? parsedcontactinfo.Phones.Phone.Where(x => x.PhoneTechType == "1").Count() > 0 ? parsedcontactinfo.Phones.Phone.Where(x => x.PhoneTechType == "1").FirstOrDefault().PhoneNumber : "" : ""; - mycontactinfoit.Faxnumber = parsedcontactinfo.Phones != null ? parsedcontactinfo.Phones.Phone.Where(x => x.PhoneTechType == "3").Count() > 0 ? parsedcontactinfo.Phones.Phone.Where(x => x.PhoneTechType == "3").FirstOrDefault().PhoneNumber : "" : ""; - - - - mycontactinfoit.Url = parsedcontactinfo.URLs != null ? parsedcontactinfo.URLs.URL.FirstOrDefault().InnerText : ""; + mycontactinfoit.Phonenumber = + parsedcontactinfo.Phones != null + ? parsedcontactinfo.Phones.Phone + .Where(x => x.PhoneTechType == "1") + .Count() > 0 + ? parsedcontactinfo.Phones.Phone + .Where(x => x.PhoneTechType == "1") + .FirstOrDefault() + .PhoneNumber + : "" + : ""; + mycontactinfoit.Faxnumber = + parsedcontactinfo.Phones != null + ? parsedcontactinfo.Phones.Phone + .Where(x => x.PhoneTechType == "3") + .Count() > 0 + ? parsedcontactinfo.Phones.Phone + .Where(x => x.PhoneTechType == "3") + .FirstOrDefault() + .PhoneNumber + : "" + : ""; + + mycontactinfoit.Url = + parsedcontactinfo.URLs != null + ? parsedcontactinfo.URLs.URL.FirstOrDefault().InnerText + : ""; //contactinfolist.Add(mycontactinfoit); @@ -218,28 +374,79 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas var myadresselement = parsedcontactinfo.Addresses; if (myadresselement != null) { - mycontactinfoen.Address = myadresselement.Address.FirstOrDefault().AddressLine; - - mycontactinfoen.City = parsedcontactinfo.Addresses.Address.FirstOrDefault().CityName; - mycontactinfoen.CountryCode = parsedcontactinfo.Addresses.Address.FirstOrDefault().CountryName.Code; - mycontactinfoen.CountryName = parsedcontactinfo.Addresses.Address.FirstOrDefault().CountryName != null ? parsedcontactinfo.Addresses.Address.FirstOrDefault().CountryName.InnerText : ""; - mycontactinfoen.ZipCode = parsedcontactinfo.Addresses.Address.FirstOrDefault().PostalCode; - - mycontactinfoen.Email = parsedcontactinfo.Emails != null ? parsedcontactinfo.Emails.Email.FirstOrDefault().InnerText : ""; + mycontactinfoen.Address = myadresselement.Address + .FirstOrDefault() + .AddressLine; + + mycontactinfoen.City = parsedcontactinfo.Addresses.Address + .FirstOrDefault() + .CityName; + mycontactinfoen.CountryCode = parsedcontactinfo.Addresses.Address + .FirstOrDefault() + .CountryName.Code; + mycontactinfoen.CountryName = + parsedcontactinfo.Addresses.Address.FirstOrDefault().CountryName != null + ? parsedcontactinfo.Addresses.Address + .FirstOrDefault() + .CountryName.InnerText + : ""; + mycontactinfoen.ZipCode = parsedcontactinfo.Addresses.Address + .FirstOrDefault() + .PostalCode; + + mycontactinfoen.Email = + parsedcontactinfo.Emails != null + ? parsedcontactinfo.Emails.Email.FirstOrDefault().InnerText + : ""; mycontactinfoen.Faxnumber = ""; - mycontactinfoen.Givenname = parsedcontactinfo.Names != null ? parsedcontactinfo.Names.Name.FirstOrDefault().GivenName : ""; - mycontactinfoen.Surname = parsedcontactinfo.Names != null ? parsedcontactinfo.Names.Name.FirstOrDefault().Surname : ""; - mycontactinfoen.NamePrefix = parsedcontactinfo.Names != null ? parsedcontactinfo.Names.Name.FirstOrDefault().NamePrefix : ""; - - mycontactinfoen.CompanyName = parsedcontactinfo.CompanyName != null ? parsedcontactinfo.CompanyName.InnerText : ""; + mycontactinfoen.Givenname = + parsedcontactinfo.Names != null + ? parsedcontactinfo.Names.Name.FirstOrDefault().GivenName + : ""; + mycontactinfoen.Surname = + parsedcontactinfo.Names != null + ? parsedcontactinfo.Names.Name.FirstOrDefault().Surname + : ""; + mycontactinfoen.NamePrefix = + parsedcontactinfo.Names != null + ? parsedcontactinfo.Names.Name.FirstOrDefault().NamePrefix + : ""; + + mycontactinfoen.CompanyName = + parsedcontactinfo.CompanyName != null + ? parsedcontactinfo.CompanyName.InnerText + : ""; mycontactinfoen.Language = "en"; - mycontactinfoen.Phonenumber = parsedcontactinfo.Phones != null ? parsedcontactinfo.Phones.Phone.Where(x => x.PhoneTechType == "1").Count() > 0 ? parsedcontactinfo.Phones.Phone.Where(x => x.PhoneTechType == "1").FirstOrDefault().PhoneNumber : "" : ""; - mycontactinfoen.Faxnumber = parsedcontactinfo.Phones != null ? parsedcontactinfo.Phones.Phone.Where(x => x.PhoneTechType == "3").Count() > 0 ? parsedcontactinfo.Phones.Phone.Where(x => x.PhoneTechType == "3").FirstOrDefault().PhoneNumber : "" : ""; - - mycontactinfoen.Url = parsedcontactinfo.URLs != null ? parsedcontactinfo.URLs.URL.FirstOrDefault().InnerText : ""; + mycontactinfoen.Phonenumber = + parsedcontactinfo.Phones != null + ? parsedcontactinfo.Phones.Phone + .Where(x => x.PhoneTechType == "1") + .Count() > 0 + ? parsedcontactinfo.Phones.Phone + .Where(x => x.PhoneTechType == "1") + .FirstOrDefault() + .PhoneNumber + : "" + : ""; + mycontactinfoen.Faxnumber = + parsedcontactinfo.Phones != null + ? parsedcontactinfo.Phones.Phone + .Where(x => x.PhoneTechType == "3") + .Count() > 0 + ? parsedcontactinfo.Phones.Phone + .Where(x => x.PhoneTechType == "3") + .FirstOrDefault() + .PhoneNumber + : "" + : ""; + + mycontactinfoen.Url = + parsedcontactinfo.URLs != null + ? parsedcontactinfo.URLs.URL.FirstOrDefault().InnerText + : ""; //contactinfolist.Add(mycontactinfoen); @@ -263,10 +470,14 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas List imagegallerylist = new List(); //DE Infos - var parsedmultimediainfogeneralde = thegastrononomyde.MultimediaDescriptions.MultimediaDescription; + var parsedmultimediainfogeneralde = thegastrononomyde + .MultimediaDescriptions + .MultimediaDescription; if (parsedmultimediainfogeneralde != null) { - var parsedmultimediainfode = parsedmultimediainfogeneralde.Where(x => x.InfoCode == "23").FirstOrDefault(); + var parsedmultimediainfode = parsedmultimediainfogeneralde + .Where(x => x.InfoCode == "23") + .FirstOrDefault(); if (parsedmultimediainfode.ImageItems.ImageItem != null) { @@ -274,15 +485,34 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas { ImageGallery myimggallery = new ImageGallery(); myimggallery.Height = imageelement.ImageFormat.Height; - myimggallery.ImageDesc.TryAddOrUpdate("de", imageelement.Description != null ? imageelement.Description.FirstOrDefault().InnerText : ""); + myimggallery.ImageDesc.TryAddOrUpdate( + "de", + imageelement.Description != null + ? imageelement.Description.FirstOrDefault().InnerText + : "" + ); myimggallery.ImageName = imageelement.RID; - myimggallery.ImageUrl = imageelement.ImageFormat.URL != null ? imageelement.ImageFormat.URL.InnerText : ""; + myimggallery.ImageUrl = + imageelement.ImageFormat.URL != null + ? imageelement.ImageFormat.URL.InnerText + : ""; myimggallery.IsInGallery = true; //myimggallery.Language = "de"; - myimggallery.ListPosition = Convert.ToInt32(imageelement.ImageFormat.RecordID) - 1; + myimggallery.ListPosition = + Convert.ToInt32(imageelement.ImageFormat.RecordID) - 1; myimggallery.Width = imageelement.ImageFormat.Width; - myimggallery.ValidFrom = imageelement.ImageFormat.ApplicableStart != null ? Convert.ToDateTime("2000-" + imageelement.ImageFormat.ApplicableStart) : DateTime.MinValue; - myimggallery.ValidTo = imageelement.ImageFormat.ApplicableEnd != null ? Convert.ToDateTime("2000-" + imageelement.ImageFormat.ApplicableEnd) : DateTime.MaxValue; + myimggallery.ValidFrom = + imageelement.ImageFormat.ApplicableStart != null + ? Convert.ToDateTime( + "2000-" + imageelement.ImageFormat.ApplicableStart + ) + : DateTime.MinValue; + myimggallery.ValidTo = + imageelement.ImageFormat.ApplicableEnd != null + ? Convert.ToDateTime( + "2000-" + imageelement.ImageFormat.ApplicableEnd + ) + : DateTime.MaxValue; myimggallery.CopyRight = imageelement.ImageFormat.CopyrightOwner; myimggallery.License = imageelement.ImageFormat.License; @@ -294,22 +524,43 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas } } - var parsedtextinfo = parsedmultimediainfogeneralde.Where(x => x.InfoCode == "1").FirstOrDefault(); - var parsedshorttextinfo = parsedmultimediainfogeneralde.Where(x => x.InfoCode == "17").FirstOrDefault(); + var parsedtextinfo = parsedmultimediainfogeneralde + .Where(x => x.InfoCode == "1") + .FirstOrDefault(); + var parsedshorttextinfo = parsedmultimediainfogeneralde + .Where(x => x.InfoCode == "17") + .FirstOrDefault(); Detail mydetailde = new Detail(); //Titel - mydetailde.Title = thegastrononomyde.ContactInfos.ContactInfo.FirstOrDefault().CompanyName != null ? thegastrononomyde.ContactInfos.ContactInfo.FirstOrDefault().CompanyName.InnerText : "no name"; + mydetailde.Title = + thegastrononomyde.ContactInfos.ContactInfo.FirstOrDefault().CompanyName != null + ? thegastrononomyde.ContactInfos.ContactInfo + .FirstOrDefault() + .CompanyName.InnerText + : "no name"; mydetailde.Header = ""; mydetailde.Language = "de"; mydetailde.AdditionalText = ""; //mydetailde.MainImage = ""; mydetailde.GetThereText = ""; if (parsedtextinfo != null) - mydetailde.BaseText = parsedtextinfo.TextItems.TextItem.FirstOrDefault().Description != null ? parsedtextinfo.TextItems.TextItem.FirstOrDefault().Description.FirstOrDefault().InnerText : ""; + mydetailde.BaseText = + parsedtextinfo.TextItems.TextItem.FirstOrDefault().Description != null + ? parsedtextinfo.TextItems.TextItem + .FirstOrDefault() + .Description.FirstOrDefault() + .InnerText + : ""; if (parsedshorttextinfo != null) - mydetailde.IntroText = parsedshorttextinfo.TextItems.TextItem.FirstOrDefault().Description != null ? parsedshorttextinfo.TextItems.TextItem.FirstOrDefault().Description.FirstOrDefault().InnerText : ""; + mydetailde.IntroText = + parsedshorttextinfo.TextItems.TextItem.FirstOrDefault().Description != null + ? parsedshorttextinfo.TextItems.TextItem + .FirstOrDefault() + .Description.FirstOrDefault() + .InnerText + : ""; //detaillist.Add(mydetailde); @@ -317,16 +568,32 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas } //IT Infos - var parsedmultimediainfogeneralit = thegastrononomyit.MultimediaDescriptions.MultimediaDescription; + var parsedmultimediainfogeneralit = thegastrononomyit + .MultimediaDescriptions + .MultimediaDescription; if (parsedmultimediainfogeneralit != null) { - var parsedmultimediainfoit = parsedmultimediainfogeneralit.Where(x => x.InfoCode == "23").FirstOrDefault(); + var parsedmultimediainfoit = parsedmultimediainfogeneralit + .Where(x => x.InfoCode == "23") + .FirstOrDefault(); if (parsedmultimediainfoit.ImageItems.ImageItem != null) { foreach (var imageelement in parsedmultimediainfoit.ImageItems.ImageItem) { - imagegallerylist.Where(x => x.ListPosition == (Convert.ToInt32(imageelement.ImageFormat.RecordID) - 1)).FirstOrDefault().ImageDesc.TryAddOrUpdate("it", imageelement.Description != null ? imageelement.Description.FirstOrDefault().InnerText : ""); + imagegallerylist + .Where( + x => + x.ListPosition + == (Convert.ToInt32(imageelement.ImageFormat.RecordID) - 1) + ) + .FirstOrDefault() + .ImageDesc.TryAddOrUpdate( + "it", + imageelement.Description != null + ? imageelement.Description.FirstOrDefault().InnerText + : "" + ); //ImageGallery myimggallery = new ImageGallery(); //myimggallery.Height = imageelement.ImageFormat.Height; @@ -342,21 +609,43 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas } } - var parsedtextinfo = parsedmultimediainfogeneralit.Where(x => x.InfoCode == "1").FirstOrDefault(); - var parsedshorttextinfo = parsedmultimediainfogeneralit.Where(x => x.InfoCode == "17").FirstOrDefault(); + var parsedtextinfo = parsedmultimediainfogeneralit + .Where(x => x.InfoCode == "1") + .FirstOrDefault(); + var parsedshorttextinfo = parsedmultimediainfogeneralit + .Where(x => x.InfoCode == "17") + .FirstOrDefault(); Detail mydetailit = new Detail(); - mydetailit.Title = thegastrononomyit.ContactInfos.ContactInfo.FirstOrDefault().CompanyName != null ? thegastrononomyit.ContactInfos.ContactInfo.FirstOrDefault().CompanyName.InnerText : "no name"; ; + mydetailit.Title = + thegastrononomyit.ContactInfos.ContactInfo.FirstOrDefault().CompanyName != null + ? thegastrononomyit.ContactInfos.ContactInfo + .FirstOrDefault() + .CompanyName.InnerText + : "no name"; + ; mydetailit.Header = ""; mydetailit.Language = "it"; mydetailit.AdditionalText = ""; //mydetailit.MainImage = ""; mydetailit.GetThereText = ""; if (parsedtextinfo != null) - mydetailit.BaseText = parsedtextinfo.TextItems.TextItem.FirstOrDefault().Description != null ? parsedtextinfo.TextItems.TextItem.FirstOrDefault().Description.FirstOrDefault().InnerText : ""; + mydetailit.BaseText = + parsedtextinfo.TextItems.TextItem.FirstOrDefault().Description != null + ? parsedtextinfo.TextItems.TextItem + .FirstOrDefault() + .Description.FirstOrDefault() + .InnerText + : ""; if (parsedshorttextinfo != null) - mydetailit.IntroText = parsedshorttextinfo.TextItems.TextItem.FirstOrDefault().Description != null ? parsedshorttextinfo.TextItems.TextItem.FirstOrDefault().Description.FirstOrDefault().InnerText : ""; + mydetailit.IntroText = + parsedshorttextinfo.TextItems.TextItem.FirstOrDefault().Description != null + ? parsedshorttextinfo.TextItems.TextItem + .FirstOrDefault() + .Description.FirstOrDefault() + .InnerText + : ""; //detaillist.Add(mydetailit); @@ -365,16 +654,32 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas //en //DE Infos - var parsedmultimediainfogeneralen = thegastrononomyen.MultimediaDescriptions.MultimediaDescription; + var parsedmultimediainfogeneralen = thegastrononomyen + .MultimediaDescriptions + .MultimediaDescription; if (parsedmultimediainfogeneralen != null) { - var parsedmultimediainfoen = parsedmultimediainfogeneralen.Where(x => x.InfoCode == "23").FirstOrDefault(); + var parsedmultimediainfoen = parsedmultimediainfogeneralen + .Where(x => x.InfoCode == "23") + .FirstOrDefault(); if (parsedmultimediainfoen.ImageItems.ImageItem != null) { foreach (var imageelement in parsedmultimediainfoen.ImageItems.ImageItem) { - imagegallerylist.Where(x => x.ListPosition == (Convert.ToInt32(imageelement.ImageFormat.RecordID) - 1)).FirstOrDefault().ImageDesc.TryAddOrUpdate("en", imageelement.Description != null ? imageelement.Description.FirstOrDefault().InnerText : ""); + imagegallerylist + .Where( + x => + x.ListPosition + == (Convert.ToInt32(imageelement.ImageFormat.RecordID) - 1) + ) + .FirstOrDefault() + .ImageDesc.TryAddOrUpdate( + "en", + imageelement.Description != null + ? imageelement.Description.FirstOrDefault().InnerText + : "" + ); //ImageGallery myimggallery = new ImageGallery(); //myimggallery.Height = imageelement.ImageFormat.Height; //myimggallery.ImageDesc = imageelement.Description != null ? imageelement.Description.FirstOrDefault().InnerText : ""; @@ -389,28 +694,49 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas } } - var parsedtextinfo = parsedmultimediainfogeneralen.Where(x => x.InfoCode == "1").FirstOrDefault(); - var parsedshorttextinfo = parsedmultimediainfogeneralen.Where(x => x.InfoCode == "17").FirstOrDefault(); + var parsedtextinfo = parsedmultimediainfogeneralen + .Where(x => x.InfoCode == "1") + .FirstOrDefault(); + var parsedshorttextinfo = parsedmultimediainfogeneralen + .Where(x => x.InfoCode == "17") + .FirstOrDefault(); Detail mydetailen = new Detail(); - mydetailen.Title = thegastrononomyen.ContactInfos.ContactInfo.FirstOrDefault().CompanyName != null ? thegastrononomyen.ContactInfos.ContactInfo.FirstOrDefault().CompanyName.InnerText : "no name"; ; + mydetailen.Title = + thegastrononomyen.ContactInfos.ContactInfo.FirstOrDefault().CompanyName != null + ? thegastrononomyen.ContactInfos.ContactInfo + .FirstOrDefault() + .CompanyName.InnerText + : "no name"; + ; mydetailen.Header = ""; mydetailen.Language = "en"; mydetailen.AdditionalText = ""; //mydetailen.MainImage = ""; mydetailen.GetThereText = ""; if (parsedtextinfo != null) - mydetailen.BaseText = parsedtextinfo.TextItems.TextItem.FirstOrDefault().Description != null ? parsedtextinfo.TextItems.TextItem.FirstOrDefault().Description.FirstOrDefault().InnerText : ""; + mydetailen.BaseText = + parsedtextinfo.TextItems.TextItem.FirstOrDefault().Description != null + ? parsedtextinfo.TextItems.TextItem + .FirstOrDefault() + .Description.FirstOrDefault() + .InnerText + : ""; if (parsedshorttextinfo != null) - mydetailen.IntroText = parsedshorttextinfo.TextItems.TextItem.FirstOrDefault().Description != null ? parsedshorttextinfo.TextItems.TextItem.FirstOrDefault().Description.FirstOrDefault().InnerText : ""; + mydetailen.IntroText = + parsedshorttextinfo.TextItems.TextItem.FirstOrDefault().Description != null + ? parsedshorttextinfo.TextItems.TextItem + .FirstOrDefault() + .Description.FirstOrDefault() + .InnerText + : ""; //detaillist.Add(mydetailen); gastro.Detail.TryAddOrUpdate("en", mydetailen); } - gastro.ImageGallery = imagegallerylist.ToList(); //gastro.Detail = detaillist.ToList(); @@ -448,19 +774,30 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas foreach (var myoperationschedule in operationschedules.OperationSchedule) { OperationSchedule theoperationschedule = new OperationSchedule(); - theoperationschedule.OperationscheduleName["de"] = myoperationschedule.Name != null ? myoperationschedule.Name.FirstOrDefault().InnerText : ""; + theoperationschedule.OperationscheduleName["de"] = + myoperationschedule.Name != null + ? myoperationschedule.Name.FirstOrDefault().InnerText + : ""; theoperationschedule.Start = DateTime.Parse(myoperationschedule.Start); theoperationschedule.Stop = DateTime.Parse(myoperationschedule.End); - theoperationschedule.Type = myoperationschedule.Type == null ? "1" : myoperationschedule.Type; + theoperationschedule.Type = + myoperationschedule.Type == null ? "1" : myoperationschedule.Type; if (myoperationschedule.OperationTime != null) { - List operationscheduletimelist = new List(); + List operationscheduletimelist = + new List(); foreach (var timeschedule in myoperationschedule.OperationTime) { OperationScheduleTime myopscheduletime = new OperationScheduleTime(); - myopscheduletime.Start = timeschedule.Start == null ? TimeSpan.Parse("00:00:00") : TimeSpan.Parse(timeschedule.Start); - myopscheduletime.End = timeschedule.End == null ? TimeSpan.Parse("23:59:00") : TimeSpan.Parse(timeschedule.End); + myopscheduletime.Start = + timeschedule.Start == null + ? TimeSpan.Parse("00:00:00") + : TimeSpan.Parse(timeschedule.Start); + myopscheduletime.End = + timeschedule.End == null + ? TimeSpan.Parse("23:59:00") + : TimeSpan.Parse(timeschedule.End); myopscheduletime.Monday = timeschedule.Mon; myopscheduletime.Tuesday = timeschedule.Tue; myopscheduletime.Wednesday = timeschedule.Weds; @@ -474,7 +811,8 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas operationscheduletimelist.Add(myopscheduletime); } - theoperationschedule.OperationScheduleTime = operationscheduletimelist.ToList(); + theoperationschedule.OperationScheduleTime = + operationscheduletimelist.ToList(); } operationschedulelist.Add(theoperationschedule); } @@ -519,7 +857,7 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas // myfac.Language = "en"; // facilitieslist.Add(myfac); - //} + //} } //Ende Facilities Element gastro.Facilities = facilitieslist.ToList(); @@ -562,7 +900,7 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas // mycatcode.Language = "en"; // categorycodeslist.Add(mycatcode); - //} + //} } gastro.CategoryCodes = categorycodeslist.ToList(); //Ende CategoryCodes Element @@ -580,7 +918,10 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas { DishRates mydishrate = new DishRates(); mydishrate.Id = dishrate.DishCodeRID; - mydishrate.Shortname = dishrate.DishName != null ? dishrate.DishName.FirstOrDefault().InnerText : ""; + mydishrate.Shortname = + dishrate.DishName != null + ? dishrate.DishName.FirstOrDefault().InnerText + : ""; mydishrate.CurrencyCode = dishrate.CurrencyCode; mydishrate.MaxAmount = dishrate.MaxAmount; mydishrate.MinAmount = dishrate.MinAmount; @@ -615,7 +956,7 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas // mydishrate.Language = "en"; // dishrateslist.Add(mydishrate); - //} + //} } gastro.DishRates = dishrateslist.ToList(); //Ende Dishrates Element @@ -632,7 +973,10 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas { CapacityCeremony mycapcer = new CapacityCeremony(); mycapcer.Id = capceremony.CeremonyCodeRID; - mycapcer.Shortname = capceremony.CeremonyName != null ? capceremony.CeremonyName.FirstOrDefault().InnerText : ""; + mycapcer.Shortname = + capceremony.CeremonyName != null + ? capceremony.CeremonyName.FirstOrDefault().InnerText + : ""; mycapcer.MaxSeatingCapacity = capceremony.MaxSeatingCapacity; //mycapcer.Language = "de"; capacitycerlist.Add(mycapcer); @@ -656,7 +1000,7 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas // mycapcer.MaxSeatingCapacity = capceremony.MaxSeatingCapacity; // mycapcer.Language = "en"; // capacitycerlist.Add(mycapcer); - //} + //} } gastro.CapacityCeremony = capacitycerlist.ToList(); @@ -692,14 +1036,44 @@ public static Gastronomy GetGastronomyDetailLTS(string gastroRID, Gastronomy gas } //Gets the Gastronomy List - public static void GetGastronomyListLTS(string destinationpath, string ltsuser, string ltspswd, string ltsmsgpswd) + public static void GetGastronomyListLTS( + string destinationpath, + string ltsuser, + string ltspswd, + string ltsmsgpswd + ) { Console.WriteLine("Get Gastronomy RIDs"); XDocument mygastrolist = new XDocument(); XElement mygastro = new XElement("Gastronomies"); - var mygastrorequest = GetGastronomicDataLCS.GetGastronomicDataSearchRequestAsync("", "1", "25", "de", "1", "0", "0", "0", "0", "0", "", "0", "0", "0", new List(), new List(), new List(), new List(), new List(), new List(), new List(), new List(), "SMG", ltsmsgpswd); + var mygastrorequest = GetGastronomicDataLCS.GetGastronomicDataSearchRequestAsync( + "", + "1", + "25", + "de", + "1", + "0", + "0", + "0", + "0", + "0", + "", + "0", + "0", + "0", + new List(), + new List(), + new List(), + new List(), + new List(), + new List(), + new List(), + new List(), + "SMG", + ltsmsgpswd + ); GetGastronomicDataLCS mygastrosearch = new GetGastronomicDataLCS(ltsuser, ltspswd); @@ -711,7 +1085,32 @@ public static void GetGastronomyListLTS(string destinationpath, string ltsuser, for (int i = 2; i <= pages; i++) { - mygastrorequest = GetGastronomicDataLCS.GetGastronomicDataSearchRequestAsync(resultrid, i.ToString(), "25", "de", "1", "0", "0", "0", "0", "0", "", "0", "0", "0", new List(), new List(), new List(), new List(), new List(), new List(), new List(), new List(), "SMG", ltsmsgpswd); + mygastrorequest = GetGastronomicDataLCS.GetGastronomicDataSearchRequestAsync( + resultrid, + i.ToString(), + "25", + "de", + "1", + "0", + "0", + "0", + "0", + "0", + "", + "0", + "0", + "0", + new List(), + new List(), + new List(), + new List(), + new List(), + new List(), + new List(), + new List(), + "SMG", + ltsmsgpswd + ); mygastroresponse = mygastrosearch.GetGastronomicDataSearch(mygastrorequest); mygastro.Add(GetGastroRid(mygastroresponse).ToList()); @@ -729,14 +1128,45 @@ public static void GetGastronomyListLTS(string destinationpath, string ltsuser, } //Gets the Gastronomy List - public static void GetGastronomyListLTS(string destinationpath, List tourismorganizations, string ltsuser, string ltspswd, string ltsmsgpswd) + public static void GetGastronomyListLTS( + string destinationpath, + List tourismorganizations, + string ltsuser, + string ltspswd, + string ltsmsgpswd + ) { Console.WriteLine("Get Gastronomy RIDs"); XDocument mygastrolist = new XDocument(); XElement mygastro = new XElement("Gastronomies"); - var mygastrorequest = GetGastronomicDataLCS.GetGastronomicDataSearchRequestAsync("", "1", "25", "de", "1", "0", "0", "0", "0", "0", "", "0", "0", "0", new List(), new List(), tourismorganizations, new List(), new List(), new List(), new List(), new List(), "SMG", ltsmsgpswd); + var mygastrorequest = GetGastronomicDataLCS.GetGastronomicDataSearchRequestAsync( + "", + "1", + "25", + "de", + "1", + "0", + "0", + "0", + "0", + "0", + "", + "0", + "0", + "0", + new List(), + new List(), + tourismorganizations, + new List(), + new List(), + new List(), + new List(), + new List(), + "SMG", + ltsmsgpswd + ); GetGastronomicDataLCS mygastrosearch = new GetGastronomicDataLCS(ltsuser, ltspswd); @@ -748,7 +1178,32 @@ public static void GetGastronomyListLTS(string destinationpath, List tou for (int i = 2; i <= pages; i++) { - mygastrorequest = GetGastronomicDataLCS.GetGastronomicDataSearchRequestAsync(resultrid, i.ToString(), "25", "de", "1", "0", "0", "0", "0", "0", "", "0", "0", "0", new List(), new List(), new List(), new List(), new List(), new List(), new List(), new List(), "SMG", ltsmsgpswd); + mygastrorequest = GetGastronomicDataLCS.GetGastronomicDataSearchRequestAsync( + resultrid, + i.ToString(), + "25", + "de", + "1", + "0", + "0", + "0", + "0", + "0", + "", + "0", + "0", + "0", + new List(), + new List(), + new List(), + new List(), + new List(), + new List(), + new List(), + new List(), + "SMG", + ltsmsgpswd + ); mygastroresponse = mygastrosearch.GetGastronomicDataSearch(mygastrorequest); mygastro.Add(GetGastroRid(mygastroresponse).ToList()); @@ -766,7 +1221,9 @@ public static void GetGastronomyListLTS(string destinationpath, List tou } //Gets the RID List Gastronomies - private static List GetGastroRid(ServiceReferenceLCS.GastronomicDataSearchRS myresult) + private static List GetGastroRid( + ServiceReferenceLCS.GastronomicDataSearchRS myresult + ) { List mylist = new List(); @@ -812,7 +1269,5 @@ private static List GetGastroRid(ServiceReferenceLCS.GastronomicDataSe // Console.WriteLine("Gastronomy List generated"); //} - } } - diff --git a/LCS/Parser/ParseMeasuringPoint.cs b/LCS/Parser/ParseMeasuringPoint.cs index 4dfe16d8c..1a5cea6cb 100644 --- a/LCS/Parser/ParseMeasuringPoint.cs +++ b/LCS/Parser/ParseMeasuringPoint.cs @@ -11,21 +11,58 @@ public class ParseMeasuringPoint { public static CultureInfo myculture = new CultureInfo("en"); - public static Measuringpoint ParseMyMeasuringPoint(ServiceReferenceLCS.WeatherSnowObservationDetailRS measuringpoints, bool newmeasuringpoint, Measuringpoint mymeasuringpoint) + public static Measuringpoint ParseMyMeasuringPoint( + ServiceReferenceLCS.WeatherSnowObservationDetailRS measuringpoints, + bool newmeasuringpoint, + Measuringpoint mymeasuringpoint + ) { var measuringpoint = measuringpoints.MeasuringPoints.MeasuringPoint.FirstOrDefault(); mymeasuringpoint.Id = measuringpoint.RID; mymeasuringpoint.Shortname = measuringpoint.Name.FirstOrDefault().InnerText; - mymeasuringpoint.SmgActive = measuringpoint.News.Status.IsActive != null ? Convert.ToBoolean(measuringpoint.News.Status.IsActive) : false; - mymeasuringpoint.Active = measuringpoint.News.Status.IsActive != null ? Convert.ToBoolean(measuringpoint.News.Status.IsActive) : false; + mymeasuringpoint.SmgActive = + measuringpoint.News.Status.IsActive != null + ? Convert.ToBoolean(measuringpoint.News.Status.IsActive) + : false; + mymeasuringpoint.Active = + measuringpoint.News.Status.IsActive != null + ? Convert.ToBoolean(measuringpoint.News.Status.IsActive) + : false; if (measuringpoint.GeoDatas.GeoData != null) { - mymeasuringpoint.Latitude = measuringpoint.GeoDatas.GeoData.FirstOrDefault().Positions.Position != null ? Convert.ToDouble(measuringpoint.GeoDatas.GeoData.FirstOrDefault().Positions.Position.FirstOrDefault().Latitude, myculture) : 0; - mymeasuringpoint.Longitude = measuringpoint.GeoDatas.GeoData.FirstOrDefault().Positions.Position != null ? Convert.ToDouble(measuringpoint.GeoDatas.GeoData.FirstOrDefault().Positions.Position.FirstOrDefault().Longitude, myculture) : 0; - mymeasuringpoint.Altitude = measuringpoint.GeoDatas.GeoData.FirstOrDefault().Positions.Position != null ? Convert.ToDouble(measuringpoint.GeoDatas.GeoData.FirstOrDefault().Positions.Position.FirstOrDefault().Altitude, myculture) : 0; + mymeasuringpoint.Latitude = + measuringpoint.GeoDatas.GeoData.FirstOrDefault().Positions.Position != null + ? Convert.ToDouble( + measuringpoint.GeoDatas.GeoData + .FirstOrDefault() + .Positions.Position.FirstOrDefault() + .Latitude, + myculture + ) + : 0; + mymeasuringpoint.Longitude = + measuringpoint.GeoDatas.GeoData.FirstOrDefault().Positions.Position != null + ? Convert.ToDouble( + measuringpoint.GeoDatas.GeoData + .FirstOrDefault() + .Positions.Position.FirstOrDefault() + .Longitude, + myculture + ) + : 0; + mymeasuringpoint.Altitude = + measuringpoint.GeoDatas.GeoData.FirstOrDefault().Positions.Position != null + ? Convert.ToDouble( + measuringpoint.GeoDatas.GeoData + .FirstOrDefault() + .Positions.Position.FirstOrDefault() + .Altitude, + myculture + ) + : 0; mymeasuringpoint.AltitudeUnitofMeasure = "m"; mymeasuringpoint.Gpstype = "center"; } @@ -37,10 +74,22 @@ public static Measuringpoint ParseMyMeasuringPoint(ServiceReferenceLCS.WeatherSn mymeasuringpoint.LastChange = DateTime.Now; - mymeasuringpoint.SnowHeight = measuringpoint.Observation.Snow.Height != null ? measuringpoint.Observation.Snow.Height.ToString() : "-"; - mymeasuringpoint.newSnowHeight = measuringpoint.Observation.Snow.NewHeight != null ? measuringpoint.Observation.Snow.NewHeight.ToString() : "-"; - mymeasuringpoint.Temperature = measuringpoint.Observation.Temperature != null ? measuringpoint.Observation.Temperature.ToString() + " °" : "-"; - mymeasuringpoint.LastSnowDate = measuringpoint.Observation.Snow.DateLastSnow != null ? Convert.ToDateTime(measuringpoint.Observation.Snow.DateLastSnow) : DateTime.MinValue; + mymeasuringpoint.SnowHeight = + measuringpoint.Observation.Snow.Height != null + ? measuringpoint.Observation.Snow.Height.ToString() + : "-"; + mymeasuringpoint.newSnowHeight = + measuringpoint.Observation.Snow.NewHeight != null + ? measuringpoint.Observation.Snow.NewHeight.ToString() + : "-"; + mymeasuringpoint.Temperature = + measuringpoint.Observation.Temperature != null + ? measuringpoint.Observation.Temperature.ToString() + " °" + : "-"; + mymeasuringpoint.LastSnowDate = + measuringpoint.Observation.Snow.DateLastSnow != null + ? Convert.ToDateTime(measuringpoint.Observation.Snow.DateLastSnow) + : DateTime.MinValue; List myweatherobservationlist = new List(); @@ -48,7 +97,12 @@ public static Measuringpoint ParseMyMeasuringPoint(ServiceReferenceLCS.WeatherSn { if (measuringpoint.Observation.WeatherForecasts.WeatherForecast != null) { - foreach (var weatherobservation in measuringpoint.Observation.WeatherForecasts.WeatherForecast) + foreach ( + var weatherobservation in measuringpoint + .Observation + .WeatherForecasts + .WeatherForecast + ) { WeatherObservation myobservation = new WeatherObservation(); myobservation.Level = ""; @@ -59,7 +113,10 @@ public static Measuringpoint ParseMyMeasuringPoint(ServiceReferenceLCS.WeatherSn if (!String.IsNullOrEmpty(weatherobservation.Date)) myobservation.Date = DateTime.Parse(weatherobservation.Date); - myobservation.WeatherStatus["de"] = weatherobservation.Description != null ? weatherobservation.Description.InnerText : ""; + myobservation.WeatherStatus["de"] = + weatherobservation.Description != null + ? weatherobservation.Description.InnerText + : ""; myweatherobservationlist.Add(myobservation); } @@ -86,6 +143,5 @@ public static Measuringpoint ParseMyMeasuringPoint(ServiceReferenceLCS.WeatherSn return mymeasuringpoint; } - } } diff --git a/LCS/Parser/ParsePoiData.cs b/LCS/Parser/ParsePoiData.cs index e57ccc652..05d51bc1e 100644 --- a/LCS/Parser/ParsePoiData.cs +++ b/LCS/Parser/ParsePoiData.cs @@ -14,15 +14,74 @@ public class ParsePoiData public static CultureInfo myculture = new CultureInfo("en"); //Get the POI Detail Information //string activitytype - public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, string ltspswd, string ltsmsgpswd) + public static LTSPoi GetPoiDetailLTSNEW( + string rid, + LTSPoi hike, + string ltsuser, + string ltspswd, + string ltsmsgpswd + ) { - List myactivitylist = new List(); myactivitylist.Add(rid); - var mypoirequestde = GetPoiDataLCS.GetPoiDetailRequest("de", "0", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", myactivitylist, "SMG", ltsmsgpswd); - var mypoirequestit = GetPoiDataLCS.GetPoiDetailRequest("it", "0", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", myactivitylist, "SMG", ltsmsgpswd); - var mypoirequesten = GetPoiDataLCS.GetPoiDetailRequest("en", "0", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", myactivitylist, "SMG", ltsmsgpswd); + var mypoirequestde = GetPoiDataLCS.GetPoiDetailRequest( + "de", + "0", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + myactivitylist, + "SMG", + ltsmsgpswd + ); + var mypoirequestit = GetPoiDataLCS.GetPoiDetailRequest( + "it", + "0", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + myactivitylist, + "SMG", + ltsmsgpswd + ); + var mypoirequesten = GetPoiDataLCS.GetPoiDetailRequest( + "en", + "0", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + myactivitylist, + "SMG", + ltsmsgpswd + ); GetPoiDataLCS mypoisearch = new GetPoiDataLCS(ltsuser, ltspswd); var myactivityresponsede = mypoisearch.GetPoiDetail(mypoirequestde); @@ -41,7 +100,6 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, var thepoiit = myactivityresponseit.POIs.POI.FirstOrDefault(); var thepoien = myactivityresponseen.POIs.POI.FirstOrDefault(); - string nome = ""; if (thepoide.Name != null) @@ -56,12 +114,14 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, if (thepoide.ID.StartsWith("SMG-")) hike.SmgId = thepoide.ID.Replace("SMG-", ""); - //SMG ACtive übernehmen + //SMG ACtive übernehmen hike.Active = true; hike.SmgActive = hike.SmgActive; if (thepoide.GeoDatas.GeoData.FirstOrDefault().Altitude != null) - hike.AltitudeDifference = thepoide.GeoDatas.GeoData.FirstOrDefault().Altitude.Difference; + hike.AltitudeDifference = thepoide.GeoDatas.GeoData + .FirstOrDefault() + .Altitude.Difference; else hike.AltitudeDifference = 0; @@ -80,7 +140,9 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, //Ondere Meglichkeit string duration = thepoide.GeoDatas.GeoData.FirstOrDefault().Distance.Duration; var durationsplittet = duration.Split(':'); - hike.DistanceDuration = Convert.ToDouble(durationsplittet[0] + "," + durationsplittet[1]); + hike.DistanceDuration = Convert.ToDouble( + durationsplittet[0] + "," + durationsplittet[1] + ); } else hike.DistanceDuration = 0; @@ -109,30 +171,45 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, var parsedcontactinfode = thepoide.ContactInfos.ContactInfo.FirstOrDefault(); if (parsedcontactinfode != null) { - ContactInfos mycontactinfo = new ContactInfos(); var myadresselement = parsedcontactinfode.Addresses; mycontactinfo.Address = myadresselement.Address.FirstOrDefault().AddressLine; - mycontactinfo.City = parsedcontactinfode.Addresses.Address.FirstOrDefault().CityName; - mycontactinfo.CountryCode = parsedcontactinfode.Addresses.Address.FirstOrDefault().CountryName.Code; - mycontactinfo.CountryName = parsedcontactinfode.Addresses.Address.FirstOrDefault().CountryName.InnerText; - mycontactinfo.ZipCode = parsedcontactinfode.Addresses.Address.FirstOrDefault().PostalCode; - - mycontactinfo.Email = parsedcontactinfode.Emails.Email.FirstOrDefault().InnerText; + mycontactinfo.City = parsedcontactinfode.Addresses.Address + .FirstOrDefault() + .CityName; + mycontactinfo.CountryCode = parsedcontactinfode.Addresses.Address + .FirstOrDefault() + .CountryName.Code; + mycontactinfo.CountryName = parsedcontactinfode.Addresses.Address + .FirstOrDefault() + .CountryName.InnerText; + mycontactinfo.ZipCode = parsedcontactinfode.Addresses.Address + .FirstOrDefault() + .PostalCode; + + mycontactinfo.Email = parsedcontactinfode.Emails.Email + .FirstOrDefault() + .InnerText; mycontactinfo.Faxnumber = ""; - mycontactinfo.Givenname = parsedcontactinfode.Names.Name.FirstOrDefault().GivenName; + mycontactinfo.Givenname = parsedcontactinfode.Names.Name + .FirstOrDefault() + .GivenName; mycontactinfo.Surname = parsedcontactinfode.Names.Name.FirstOrDefault().Surname; - mycontactinfo.NamePrefix = parsedcontactinfode.Names.Name.FirstOrDefault().NamePrefix; + mycontactinfo.NamePrefix = parsedcontactinfode.Names.Name + .FirstOrDefault() + .NamePrefix; mycontactinfo.CompanyName = parsedcontactinfode.CompanyName.InnerText; mycontactinfo.Language = "de"; - mycontactinfo.Phonenumber = parsedcontactinfode.Phones.Phone.FirstOrDefault().PhoneNumber; + mycontactinfo.Phonenumber = parsedcontactinfode.Phones.Phone + .FirstOrDefault() + .PhoneNumber; mycontactinfo.Url = parsedcontactinfode.URLs.URL.FirstOrDefault().InnerText; //contactinfolist.Add(mycontactinfo); @@ -146,30 +223,45 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, var parsedcontactinfoit = thepoiit.ContactInfos.ContactInfo.FirstOrDefault(); if (parsedcontactinfoit != null) { - ContactInfos mycontactinfo = new ContactInfos(); var myadresselement = parsedcontactinfoit.Addresses; mycontactinfo.Address = myadresselement.Address.FirstOrDefault().AddressLine; - mycontactinfo.City = parsedcontactinfoit.Addresses.Address.FirstOrDefault().CityName; - mycontactinfo.CountryCode = parsedcontactinfoit.Addresses.Address.FirstOrDefault().CountryName.Code; - mycontactinfo.CountryName = parsedcontactinfoit.Addresses.Address.FirstOrDefault().CountryName.InnerText; - mycontactinfo.ZipCode = parsedcontactinfoit.Addresses.Address.FirstOrDefault().PostalCode; - - mycontactinfo.Email = parsedcontactinfoit.Emails.Email.FirstOrDefault().InnerText; + mycontactinfo.City = parsedcontactinfoit.Addresses.Address + .FirstOrDefault() + .CityName; + mycontactinfo.CountryCode = parsedcontactinfoit.Addresses.Address + .FirstOrDefault() + .CountryName.Code; + mycontactinfo.CountryName = parsedcontactinfoit.Addresses.Address + .FirstOrDefault() + .CountryName.InnerText; + mycontactinfo.ZipCode = parsedcontactinfoit.Addresses.Address + .FirstOrDefault() + .PostalCode; + + mycontactinfo.Email = parsedcontactinfoit.Emails.Email + .FirstOrDefault() + .InnerText; mycontactinfo.Faxnumber = ""; - mycontactinfo.Givenname = parsedcontactinfoit.Names.Name.FirstOrDefault().GivenName; + mycontactinfo.Givenname = parsedcontactinfoit.Names.Name + .FirstOrDefault() + .GivenName; mycontactinfo.Surname = parsedcontactinfoit.Names.Name.FirstOrDefault().Surname; - mycontactinfo.NamePrefix = parsedcontactinfoit.Names.Name.FirstOrDefault().NamePrefix; + mycontactinfo.NamePrefix = parsedcontactinfoit.Names.Name + .FirstOrDefault() + .NamePrefix; mycontactinfo.CompanyName = parsedcontactinfoit.CompanyName.InnerText; mycontactinfo.Language = "it"; - mycontactinfo.Phonenumber = parsedcontactinfoit.Phones.Phone.FirstOrDefault().PhoneNumber; + mycontactinfo.Phonenumber = parsedcontactinfoit.Phones.Phone + .FirstOrDefault() + .PhoneNumber; mycontactinfo.Url = parsedcontactinfoit.URLs.URL.FirstOrDefault().InnerText; //contactinfolist.Add(mycontactinfo); @@ -183,30 +275,45 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, var parsedcontactinfoen = thepoien.ContactInfos.ContactInfo.FirstOrDefault(); if (parsedcontactinfoen != null) { - ContactInfos mycontactinfo = new ContactInfos(); var myadresselement = parsedcontactinfoen.Addresses; mycontactinfo.Address = myadresselement.Address.FirstOrDefault().AddressLine; - mycontactinfo.City = parsedcontactinfoen.Addresses.Address.FirstOrDefault().CityName; - mycontactinfo.CountryCode = parsedcontactinfoen.Addresses.Address.FirstOrDefault().CountryName.Code; - mycontactinfo.CountryName = parsedcontactinfoen.Addresses.Address.FirstOrDefault().CountryName.InnerText; - mycontactinfo.ZipCode = parsedcontactinfoen.Addresses.Address.FirstOrDefault().PostalCode; - - mycontactinfo.Email = parsedcontactinfoen.Emails.Email.FirstOrDefault().InnerText; + mycontactinfo.City = parsedcontactinfoen.Addresses.Address + .FirstOrDefault() + .CityName; + mycontactinfo.CountryCode = parsedcontactinfoen.Addresses.Address + .FirstOrDefault() + .CountryName.Code; + mycontactinfo.CountryName = parsedcontactinfoen.Addresses.Address + .FirstOrDefault() + .CountryName.InnerText; + mycontactinfo.ZipCode = parsedcontactinfoen.Addresses.Address + .FirstOrDefault() + .PostalCode; + + mycontactinfo.Email = parsedcontactinfoen.Emails.Email + .FirstOrDefault() + .InnerText; mycontactinfo.Faxnumber = ""; - mycontactinfo.Givenname = parsedcontactinfoen.Names.Name.FirstOrDefault().GivenName; + mycontactinfo.Givenname = parsedcontactinfoen.Names.Name + .FirstOrDefault() + .GivenName; mycontactinfo.Surname = parsedcontactinfoen.Names.Name.FirstOrDefault().Surname; - mycontactinfo.NamePrefix = parsedcontactinfoen.Names.Name.FirstOrDefault().NamePrefix; + mycontactinfo.NamePrefix = parsedcontactinfoen.Names.Name + .FirstOrDefault() + .NamePrefix; mycontactinfo.CompanyName = parsedcontactinfoen.CompanyName.InnerText; mycontactinfo.Language = "en"; - mycontactinfo.Phonenumber = parsedcontactinfoen.Phones.Phone.FirstOrDefault().PhoneNumber; + mycontactinfo.Phonenumber = parsedcontactinfoen.Phones.Phone + .FirstOrDefault() + .PhoneNumber; mycontactinfo.Url = parsedcontactinfoen.URLs.URL.FirstOrDefault().InnerText; //contactinfolist.Add(mycontactinfo); @@ -223,7 +330,8 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, //List detaillist = new List(); List imagegallerylist = new List(); - var parsedmultimediainfode = thepoide.MultimediaDescriptions.MultimediaDescription.FirstOrDefault(); + var parsedmultimediainfode = + thepoide.MultimediaDescriptions.MultimediaDescription.FirstOrDefault(); if (parsedmultimediainfode != null) { if (parsedmultimediainfode.ImageItems.ImageItem != null) @@ -233,7 +341,10 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, { ImageGallery myimggallery = new ImageGallery(); myimggallery.Height = imageelement.ImageFormat.Height; - myimggallery.ImageDesc.TryAddOrUpdate("de", imageelement.Description.FirstOrDefault().InnerText); + myimggallery.ImageDesc.TryAddOrUpdate( + "de", + imageelement.Description.FirstOrDefault().InnerText + ); myimggallery.ImageName = imageelement.RID; myimggallery.ImageUrl = imageelement.ImageFormat.URL.InnerText; myimggallery.IsInGallery = true; @@ -253,7 +364,10 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, Detail mydetailde = new Detail(); - mydetailde.Title = thepoide.Name.FirstOrDefault() != null ? thepoide.Name.FirstOrDefault().InnerText.Trim() : ""; + mydetailde.Title = + thepoide.Name.FirstOrDefault() != null + ? thepoide.Name.FirstOrDefault().InnerText.Trim() + : ""; mydetailde.Header = ""; mydetailde.Language = "de"; mydetailde.AdditionalText = ""; @@ -265,49 +379,121 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, foreach (var textelement in mytextitems.TextItem) { //Allgemeine Beschreibung - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "732512C9492340F4AB30FFB800461BE7") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "732512C9492340F4AB30FFB800461BE7" + ) { - mydetailde.BaseText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.BaseText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Anfahrtstext - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "C26C826A239C47BDB773B4E4B3F27547") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "C26C826A239C47BDB773B4E4B3F27547" + ) { - mydetailde.GetThereText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.GetThereText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Wegbeschreibung - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "ECEB7021321445648CE37A9A84D64930") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "ECEB7021321445648CE37A9A84D64930" + ) { - mydetailde.AdditionalText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.AdditionalText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Kurzbeschreibung A143F1FF0A0A4185A907208D643D3BB8 --> Placing in Introtext - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "A143F1FF0A0A4185A907208D643D3BB8") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "A143F1FF0A0A4185A907208D643D3BB8" + ) { - mydetailde.IntroText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.IntroText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Parken AFB5C1F8662949108105DAC81DD8B18F - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "AFB5C1F8662949108105DAC81DD8B18F") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "AFB5C1F8662949108105DAC81DD8B18F" + ) { - mydetailde.ParkingInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.ParkingInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Öffentliche Verkehrsmittel C67DBA804FAD4B4EB64A4A758771B723 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "C67DBA804FAD4B4EB64A4A758771B723") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "C67DBA804FAD4B4EB64A4A758771B723" + ) { - mydetailde.PublicTransportationInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.PublicTransportationInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Tipp des Autors 643EDEE9CE2D44AC932FC714256B6C9C - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "643EDEE9CE2D44AC932FC714256B6C9C") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "643EDEE9CE2D44AC932FC714256B6C9C" + ) { - mydetailde.AuthorTip = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.AuthorTip = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Sicherheitshinweise 73EC4F8F7AAC48CE82A23E8EBDCA750E - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "73EC4F8F7AAC48CE82A23E8EBDCA750E") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "73EC4F8F7AAC48CE82A23E8EBDCA750E" + ) { - mydetailde.SafetyInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.SafetyInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Ausrüstung 933D29E15E82415DBEDE877C477212D2 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "933D29E15E82415DBEDE877C477212D2") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "933D29E15E82415DBEDE877C477212D2" + ) { - mydetailde.EquipmentInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailde.EquipmentInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } } } @@ -317,7 +503,8 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, } //it - var parsedmultimediainfoit = thepoiit.MultimediaDescriptions.MultimediaDescription.FirstOrDefault(); + var parsedmultimediainfoit = + thepoiit.MultimediaDescriptions.MultimediaDescription.FirstOrDefault(); if (parsedmultimediainfoit != null) { if (parsedmultimediainfoit.ImageItems.ImageItem != null) @@ -325,7 +512,13 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, int i = 0; foreach (var imageelement in parsedmultimediainfoit.ImageItems.ImageItem) { - imagegallerylist.Where(x => x.ListPosition == i && x.ImageSource == "LTS").FirstOrDefault().ImageDesc.TryAddOrUpdate("it", imageelement.Description.FirstOrDefault().InnerText); + imagegallerylist + .Where(x => x.ListPosition == i && x.ImageSource == "LTS") + .FirstOrDefault() + .ImageDesc.TryAddOrUpdate( + "it", + imageelement.Description.FirstOrDefault().InnerText + ); i++; //ImageGallery myimggallery = new ImageGallery(); //myimggallery.Height = imageelement.ImageFormat.Height; @@ -345,7 +538,10 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, Detail mydetailit = new Detail(); - mydetailit.Title = thepoiit.Name.FirstOrDefault() != null ? thepoiit.Name.FirstOrDefault().InnerText.Trim() : ""; + mydetailit.Title = + thepoiit.Name.FirstOrDefault() != null + ? thepoiit.Name.FirstOrDefault().InnerText.Trim() + : ""; mydetailit.Header = ""; mydetailit.Language = "it"; mydetailit.AdditionalText = ""; @@ -357,49 +553,121 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, foreach (var textelement in mytextitems.TextItem) { //Allgemeine Beschreibung - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "732512C9492340F4AB30FFB800461BE7") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "732512C9492340F4AB30FFB800461BE7" + ) { - mydetailit.BaseText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.BaseText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Anfahrtstext - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "C26C826A239C47BDB773B4E4B3F27547") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "C26C826A239C47BDB773B4E4B3F27547" + ) { - mydetailit.GetThereText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.GetThereText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Wegbeschreibung - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "ECEB7021321445648CE37A9A84D64930") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "ECEB7021321445648CE37A9A84D64930" + ) { - mydetailit.AdditionalText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.AdditionalText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Kurzbeschreibung A143F1FF0A0A4185A907208D643D3BB8 --> Placing in Introtext - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "A143F1FF0A0A4185A907208D643D3BB8") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "A143F1FF0A0A4185A907208D643D3BB8" + ) { - mydetailit.IntroText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.IntroText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Parken AFB5C1F8662949108105DAC81DD8B18F - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "AFB5C1F8662949108105DAC81DD8B18F") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "AFB5C1F8662949108105DAC81DD8B18F" + ) { - mydetailit.ParkingInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.ParkingInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Öffentliche Verkehrsmittel C67DBA804FAD4B4EB64A4A758771B723 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "C67DBA804FAD4B4EB64A4A758771B723") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "C67DBA804FAD4B4EB64A4A758771B723" + ) { - mydetailit.PublicTransportationInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.PublicTransportationInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Tipp des Autors 643EDEE9CE2D44AC932FC714256B6C9C - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "643EDEE9CE2D44AC932FC714256B6C9C") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "643EDEE9CE2D44AC932FC714256B6C9C" + ) { - mydetailit.AuthorTip = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.AuthorTip = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Sicherheitshinweise 73EC4F8F7AAC48CE82A23E8EBDCA750E - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "73EC4F8F7AAC48CE82A23E8EBDCA750E") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "73EC4F8F7AAC48CE82A23E8EBDCA750E" + ) { - mydetailit.SafetyInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.SafetyInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Ausrüstung 933D29E15E82415DBEDE877C477212D2 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "933D29E15E82415DBEDE877C477212D2") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "933D29E15E82415DBEDE877C477212D2" + ) { - mydetailit.EquipmentInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailit.EquipmentInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } } } @@ -409,16 +677,22 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, } //en - var parsedmultimediainfoen = thepoien.MultimediaDescriptions.MultimediaDescription.FirstOrDefault(); + var parsedmultimediainfoen = + thepoien.MultimediaDescriptions.MultimediaDescription.FirstOrDefault(); if (parsedmultimediainfoen != null) { - if (parsedmultimediainfoen.ImageItems.ImageItem != null) { int i = 0; foreach (var imageelement in parsedmultimediainfoen.ImageItems.ImageItem) { - imagegallerylist.Where(x => x.ListPosition == i && x.ImageSource == "LTS").FirstOrDefault().ImageDesc.TryAddOrUpdate("en", imageelement.Description.FirstOrDefault().InnerText); + imagegallerylist + .Where(x => x.ListPosition == i && x.ImageSource == "LTS") + .FirstOrDefault() + .ImageDesc.TryAddOrUpdate( + "en", + imageelement.Description.FirstOrDefault().InnerText + ); i++; //ImageGallery myimggallery = new ImageGallery(); @@ -435,12 +709,14 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, } } - var mytextitems = parsedmultimediainfoen.TextItems; Detail mydetailen = new Detail(); - mydetailen.Title = thepoien.Name.FirstOrDefault() != null ? thepoien.Name.FirstOrDefault().InnerText.Trim() : ""; + mydetailen.Title = + thepoien.Name.FirstOrDefault() != null + ? thepoien.Name.FirstOrDefault().InnerText.Trim() + : ""; mydetailen.Header = ""; mydetailen.Language = "en"; mydetailen.AdditionalText = ""; @@ -452,49 +728,121 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, foreach (var textelement in mytextitems.TextItem) { //Allgemeine Beschreibung - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "732512C9492340F4AB30FFB800461BE7") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "732512C9492340F4AB30FFB800461BE7" + ) { - mydetailen.BaseText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.BaseText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Anfahrtstext - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "C26C826A239C47BDB773B4E4B3F27547") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "C26C826A239C47BDB773B4E4B3F27547" + ) { - mydetailen.GetThereText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.GetThereText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Wegbeschreibung - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "ECEB7021321445648CE37A9A84D64930") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "ECEB7021321445648CE37A9A84D64930" + ) { - mydetailen.AdditionalText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.AdditionalText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Kurzbeschreibung A143F1FF0A0A4185A907208D643D3BB8 --> Placing in Introtext - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "A143F1FF0A0A4185A907208D643D3BB8") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "A143F1FF0A0A4185A907208D643D3BB8" + ) { - mydetailen.IntroText = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.IntroText = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Parken AFB5C1F8662949108105DAC81DD8B18F - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "AFB5C1F8662949108105DAC81DD8B18F") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "AFB5C1F8662949108105DAC81DD8B18F" + ) { - mydetailen.ParkingInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.ParkingInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Öffentliche Verkehrsmittel C67DBA804FAD4B4EB64A4A758771B723 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "C67DBA804FAD4B4EB64A4A758771B723") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "C67DBA804FAD4B4EB64A4A758771B723" + ) { - mydetailen.PublicTransportationInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.PublicTransportationInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Tipp des Autors 643EDEE9CE2D44AC932FC714256B6C9C - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "643EDEE9CE2D44AC932FC714256B6C9C") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "643EDEE9CE2D44AC932FC714256B6C9C" + ) { - mydetailen.AuthorTip = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.AuthorTip = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Sicherheitshinweise 73EC4F8F7AAC48CE82A23E8EBDCA750E - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "73EC4F8F7AAC48CE82A23E8EBDCA750E") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "73EC4F8F7AAC48CE82A23E8EBDCA750E" + ) { - mydetailen.SafetyInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.SafetyInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } //Ausrüstung 933D29E15E82415DBEDE877C477212D2 - if (textelement.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().RID == "933D29E15E82415DBEDE877C477212D2") + if ( + textelement.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .RID == "933D29E15E82415DBEDE877C477212D2" + ) { - mydetailen.EquipmentInfo = textelement.Description.Count() > 0 ? textelement.Description.FirstOrDefault().InnerText : ""; + mydetailen.EquipmentInfo = + textelement.Description.Count() > 0 + ? textelement.Description.FirstOrDefault().InnerText + : ""; } } } @@ -512,7 +860,7 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, //hike.SubType = thepoide.EnumCodes.EnumCode != null ? thepoide.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText : ""; - //Tags beibehalten. Maintyp + Subtyp als Tag übernehmen + //Tags beibehalten. Maintyp + Subtyp als Tag übernehmen //List currenttags = new List(); //if (thepoide.EnumCodes.EnumCode != null) @@ -523,7 +871,7 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, // if (!currenttags.Contains(type)) // currenttags.Add(type); // //if (!currenttags.Contains(subtype)) - // // currenttags.Add(subtype); + // // currenttags.Add(subtype); //} //NEU gehe alle LTS Tags durch @@ -542,7 +890,10 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, myltstag.LTSRID = ltstag.RID; myltstag.Id = ltstag.Name.FirstOrDefault().InnerText.Trim().Replace("/", ""); - myltstag.TagName.TryAddOrUpdate("de", ltstag.Name != null ? ltstag.Name.FirstOrDefault().InnerText : ""); + myltstag.TagName.TryAddOrUpdate( + "de", + ltstag.Name != null ? ltstag.Name.FirstOrDefault().InnerText : "" + ); //Sonderfix Tag DE enthält / if (myltstag.TagName["de"].Contains("/")) @@ -554,7 +905,10 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, foreach (var ltstin in ltstag.Tins.Tin) { LTSTins mytin = new LTSTins(); - mytin.TinName.TryAddOrUpdate("de", ltstin.Name != null ? ltstin.Name.FirstOrDefault().InnerText : ""); + mytin.TinName.TryAddOrUpdate( + "de", + ltstin.Name != null ? ltstin.Name.FirstOrDefault().InnerText : "" + ); mytin.LTSRID = ltstin.RID; myltstag.LTSTins.Add(mytin); @@ -566,34 +920,56 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, foreach (var ltstag in thepoiit.Tags.Tag) { - var currentltstagit = ltstaglist.Where(x => x.LTSRID == ltstag.RID).FirstOrDefault(); - currentltstagit.TagName.TryAddOrUpdate("it", ltstag.Name != null ? ltstag.Name.FirstOrDefault().InnerText : ""); + var currentltstagit = ltstaglist + .Where(x => x.LTSRID == ltstag.RID) + .FirstOrDefault(); + currentltstagit.TagName.TryAddOrUpdate( + "it", + ltstag.Name != null ? ltstag.Name.FirstOrDefault().InnerText : "" + ); //add the tin info in IT if (ltstag.Tins != null) { foreach (var ltstin in ltstag.Tins.Tin) { - var currentltstinit = currentltstagit.LTSTins.Where(x => x.LTSRID == ltstin.RID).FirstOrDefault(); - currentltstinit.TinName.TryAddOrUpdate("it", ltstin.Name != null ? ltstin.Name.FirstOrDefault().InnerText : ""); + var currentltstinit = currentltstagit.LTSTins + .Where(x => x.LTSRID == ltstin.RID) + .FirstOrDefault(); + currentltstinit.TinName.TryAddOrUpdate( + "it", + ltstin.Name != null ? ltstin.Name.FirstOrDefault().InnerText : "" + ); } } } foreach (var ltstag in thepoien.Tags.Tag) { - var currentltstagen = ltstaglist.Where(x => x.LTSRID == ltstag.RID).FirstOrDefault(); - currentltstagen.TagName.TryAddOrUpdate("en", ltstag.Name != null ? ltstag.Name.FirstOrDefault().InnerText : ""); + var currentltstagen = ltstaglist + .Where(x => x.LTSRID == ltstag.RID) + .FirstOrDefault(); + currentltstagen.TagName.TryAddOrUpdate( + "en", + ltstag.Name != null ? ltstag.Name.FirstOrDefault().InnerText : "" + ); //add the tin info in EN and set the id to EN object if (ltstag.Tins != null) { foreach (var ltstin in ltstag.Tins.Tin) { - var currentltstinen = currentltstagen.LTSTins.Where(x => x.LTSRID == ltstin.RID).FirstOrDefault(); - currentltstinen.TinName.TryAddOrUpdate("en", ltstin.Name != null ? ltstin.Name.FirstOrDefault().InnerText : ""); + var currentltstinen = currentltstagen.LTSTins + .Where(x => x.LTSRID == ltstin.RID) + .FirstOrDefault(); + currentltstinen.TinName.TryAddOrUpdate( + "en", + ltstin.Name != null ? ltstin.Name.FirstOrDefault().InnerText : "" + ); //Set ID - currentltstinen.Id = ltstin.Name.FirstOrDefault().InnerText.ComputeSHA1Hash(); + currentltstinen.Id = ltstin.Name + .FirstOrDefault() + .InnerText.ComputeSHA1Hash(); } } } @@ -665,7 +1041,11 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, { GpsInfo mygpsinfo = new GpsInfo(); - mygpsinfo.Gpstype = position.EnumCodes.EnumCode.FirstOrDefault().Code.FirstOrDefault().Name.FirstOrDefault().InnerText; + mygpsinfo.Gpstype = position.EnumCodes.EnumCode + .FirstOrDefault() + .Code.FirstOrDefault() + .Name.FirstOrDefault() + .InnerText; mygpsinfo.AltitudeUnitofMeasure = "m"; mygpsinfo.Altitude = position.Altitude; mygpsinfo.Longitude = Convert.ToDouble(position.Longitude, myculture); @@ -697,7 +1077,15 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, //EN und IT Info? - mygpstrack.GpxTrackDesc.TryAddOrUpdate("de", gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText); + mygpstrack.GpxTrackDesc.TryAddOrUpdate( + "de", + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + ); mygpstracklist.Add(mygpstrack); } @@ -714,8 +1102,18 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, { foreach (var gpstrack in gpstracksit) { - GpsTrack mygpstrack = mygpstracklist.Where(x => x.Id == gpstrack.RID).FirstOrDefault(); - mygpstrack.GpxTrackDesc.TryAddOrUpdate("it", gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText); + GpsTrack mygpstrack = mygpstracklist + .Where(x => x.Id == gpstrack.RID) + .FirstOrDefault(); + mygpstrack.GpxTrackDesc.TryAddOrUpdate( + "it", + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + ); //mygpstracklist.Add(mygpstrack); } } @@ -731,8 +1129,18 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, { foreach (var gpstrack in gpstracksen) { - GpsTrack mygpstrack = mygpstracklist.Where(x => x.Id == gpstrack.RID).FirstOrDefault(); - mygpstrack.GpxTrackDesc.TryAddOrUpdate("en", gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText); + GpsTrack mygpstrack = mygpstracklist + .Where(x => x.Id == gpstrack.RID) + .FirstOrDefault(); + mygpstrack.GpxTrackDesc.TryAddOrUpdate( + "en", + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + ); //mygpstracklist.Add(mygpstrack); } } @@ -740,7 +1148,6 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, hike.GpsTrack = mygpstracklist.ToList(); - List arearidlist = new List(); if (thepoide.Memberships != null) @@ -763,7 +1170,6 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, { foreach (var myarea in member.Area) { - string z = myarea.RID; arearidlist.Add(z); } @@ -771,7 +1177,6 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, } hike.AreaId = arearidlist.ToList(); - } //Neu Smg Favorit über Area @@ -787,23 +1192,35 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, { if (thepoide.OperationSchedules.OperationSchedule != null) { - foreach (var myoperationschedule in thepoide.OperationSchedules.OperationSchedule) + foreach ( + var myoperationschedule in thepoide.OperationSchedules.OperationSchedule + ) { OperationSchedule theoperationschedule = new OperationSchedule(); - theoperationschedule.OperationscheduleName["de"] = myoperationschedule.Name != null ? myoperationschedule.Name.FirstOrDefault().InnerText : ""; + theoperationschedule.OperationscheduleName["de"] = + myoperationschedule.Name != null + ? myoperationschedule.Name.FirstOrDefault().InnerText + : ""; theoperationschedule.Start = DateTime.Parse(myoperationschedule.Start); theoperationschedule.Stop = DateTime.Parse(myoperationschedule.End); theoperationschedule.Type = myoperationschedule.Type; - List myopeningtimes = new List(); + List myopeningtimes = + new List(); if (myoperationschedule.OperationTime != null) { foreach (var operationscheduletime in myoperationschedule.OperationTime) { OperationScheduleTime mytime = new OperationScheduleTime(); - mytime.Start = operationscheduletime.Start == null ? TimeSpan.Parse("00:00:00") : TimeSpan.Parse(operationscheduletime.Start); - mytime.End = operationscheduletime.End == null ? TimeSpan.Parse("23:59:00") : TimeSpan.Parse(operationscheduletime.End); + mytime.Start = + operationscheduletime.Start == null + ? TimeSpan.Parse("00:00:00") + : TimeSpan.Parse(operationscheduletime.Start); + mytime.End = + operationscheduletime.End == null + ? TimeSpan.Parse("23:59:00") + : TimeSpan.Parse(operationscheduletime.End); mytime.Monday = operationscheduletime.Mon; mytime.Tuesday = operationscheduletime.Tue; mytime.Wednesday = operationscheduletime.Weds; @@ -853,9 +1270,8 @@ public static LTSPoi GetPoiDetailLTSNEW(string rid, LTSPoi hike, string ltsuser, } hike.ChildPoiIds = childpois.ToList(); - //Add The available Languages - //Check wo überall in Details sprachknoten enthalten sind + //Check wo überall in Details sprachknoten enthalten sind var availablelanguages = hike.Detail.Select(x => x.Key).ToList(); hike.HasLanguage = availablelanguages; @@ -917,6 +1333,5 @@ public static Dictionary GetPoiMainType(string mainType) return maintypedict; } - } } diff --git a/LCS/Parser/ParseSnowDataLive.cs b/LCS/Parser/ParseSnowDataLive.cs index 73b223d57..66ffb6dc6 100644 --- a/LCS/Parser/ParseSnowDataLive.cs +++ b/LCS/Parser/ParseSnowDataLive.cs @@ -13,14 +13,14 @@ public class ParseSnowDataLive { public static CultureInfo myculture = new CultureInfo("en"); - public static List ParseMyMeasuringPoint(ServiceReferenceLCS.WeatherSnowObservationSearchRS measuringpoints) + public static List ParseMyMeasuringPoint( + ServiceReferenceLCS.WeatherSnowObservationSearchRS measuringpoints + ) { List mymeasuringpointlist = new List(); if (measuringpoints.MeasuringPoints.MeasuringPoint != null) { - - foreach (var measuringpoint in measuringpoints.MeasuringPoints.MeasuringPoint) { var mymeasuringpoint = new MeasuringpointReduced(); @@ -28,29 +28,48 @@ public static List ParseMyMeasuringPoint(ServiceReference mymeasuringpoint.Id = measuringpoint.RID; mymeasuringpoint.Shortname = measuringpoint.Name.FirstOrDefault().InnerText; - mymeasuringpoint.LastUpdate = Convert.ToDateTime(measuringpoint.News.Status.LastChange); - - mymeasuringpoint.SnowHeight = measuringpoint.Observation.Snow.Height != null ? measuringpoint.Observation.Snow.Height.ToString() : "0"; - mymeasuringpoint.newSnowHeight = measuringpoint.Observation.Snow.NewHeight != null ? measuringpoint.Observation.Snow.NewHeight.ToString() : "-"; - mymeasuringpoint.Temperature = measuringpoint.Observation.Temperature != null ? measuringpoint.Observation.Temperature.ToString() + " °" : "-"; - mymeasuringpoint.LastSnowDate = measuringpoint.Observation.Snow.DateLastSnow != null ? Convert.ToDateTime(measuringpoint.Observation.Snow.DateLastSnow) : DateTime.MinValue; + mymeasuringpoint.LastUpdate = Convert.ToDateTime( + measuringpoint.News.Status.LastChange + ); + + mymeasuringpoint.SnowHeight = + measuringpoint.Observation.Snow.Height != null + ? measuringpoint.Observation.Snow.Height.ToString() + : "0"; + mymeasuringpoint.newSnowHeight = + measuringpoint.Observation.Snow.NewHeight != null + ? measuringpoint.Observation.Snow.NewHeight.ToString() + : "-"; + mymeasuringpoint.Temperature = + measuringpoint.Observation.Temperature != null + ? measuringpoint.Observation.Temperature.ToString() + " °" + : "-"; + mymeasuringpoint.LastSnowDate = + measuringpoint.Observation.Snow.DateLastSnow != null + ? Convert.ToDateTime(measuringpoint.Observation.Snow.DateLastSnow) + : DateTime.MinValue; mymeasuringpoint.Source = "lts"; - List myweatherobservationlist = new List(); - + List myweatherobservationlist = + new List(); if (measuringpoint.Observation.EnumCodes != null) { if (measuringpoint.Observation.EnumCodes.EnumCode != null) { - - foreach (var weatherobservation in measuringpoint.Observation.EnumCodes.EnumCode.FirstOrDefault().Code) + foreach ( + var weatherobservation in measuringpoint.Observation.EnumCodes.EnumCode + .FirstOrDefault() + .Code + ) { WeatherObservation myobservation = new WeatherObservation(); myobservation.Level = weatherobservation.Level; myobservation.LevelId = weatherobservation.ID; myobservation.Id = weatherobservation.RID; - myobservation.WeatherStatus["de"] = weatherobservation.Name.FirstOrDefault().InnerText; + myobservation.WeatherStatus["de"] = weatherobservation.Name + .FirstOrDefault() + .InnerText; myweatherobservationlist.Add(myobservation); } @@ -58,15 +77,9 @@ public static List ParseMyMeasuringPoint(ServiceReference } mymeasuringpoint.WeatherObservation = myweatherobservationlist.ToList(); - - //NEU add the Measuringpoint only if DateTime is actual if (mymeasuringpoint.LastUpdate > DateTime.Now.AddYears(-1)) mymeasuringpointlist.Add(mymeasuringpoint); - - - - } //NEU Bergstation - Talstation / Mittelstation fix @@ -77,54 +90,75 @@ public static List ParseMyMeasuringPoint(ServiceReference if (mymeasuringpointlist.Where(x => x.Shortname.Contains("Berg")).Count() > 0) hasbergstation = true; - if (mymeasuringpointlist.Where(x => x.Shortname.Contains("Tal") || x.Shortname.Contains("Mittel")).Count() > 0) + if ( + mymeasuringpointlist + .Where(x => x.Shortname.Contains("Tal") || x.Shortname.Contains("Mittel")) + .Count() > 0 + ) hasmittelstation = true; - //IF only 1 available --> Bergstation if (!hasbergstation && !hasmittelstation && mymeasuringpointlist.Count == 1) { - mymeasuringpointlist.FirstOrDefault().Shortname = "Berg " + mymeasuringpointlist.FirstOrDefault().Shortname; + mymeasuringpointlist.FirstOrDefault().Shortname = + "Berg " + mymeasuringpointlist.FirstOrDefault().Shortname; } else if (!hasbergstation || !hasmittelstation && mymeasuringpointlist.Count > 1) { //Fall 2 kein Berg und keine Mittel mehr als 1 MEsspunkt if (!hasbergstation && !hasmittelstation && mymeasuringpointlist.Count > 1) { - var mypointtomodify = mymeasuringpointlist.Where(x => !x.Shortname.Contains("Berg") && !x.Shortname.Contains("Mittel") && !x.Shortname.Contains("Tal")).OrderByDescending(x => Convert.ToInt32(x.SnowHeight)); + var mypointtomodify = mymeasuringpointlist + .Where( + x => + !x.Shortname.Contains("Berg") + && !x.Shortname.Contains("Mittel") + && !x.Shortname.Contains("Tal") + ) + .OrderByDescending(x => Convert.ToInt32(x.SnowHeight)); if (mypointtomodify.Count() > 0) - mypointtomodify.FirstOrDefault().Shortname = "Berg " + mypointtomodify.FirstOrDefault().Shortname; + mypointtomodify.FirstOrDefault().Shortname = + "Berg " + mypointtomodify.FirstOrDefault().Shortname; if (mypointtomodify.Count() > 1) - mypointtomodify.LastOrDefault().Shortname = "Tal " + mypointtomodify.LastOrDefault().Shortname; + mypointtomodify.LastOrDefault().Shortname = + "Tal " + mypointtomodify.LastOrDefault().Shortname; } //Fall 3 keine Mittel mehr als 1 Messpunkt else if (hasbergstation && !hasmittelstation && mymeasuringpointlist.Count > 1) { - var mypointtomodify = mymeasuringpointlist.Where(x => !x.Shortname.Contains("Berg")).OrderBy(x => Convert.ToInt32(x.SnowHeight)); + var mypointtomodify = mymeasuringpointlist + .Where(x => !x.Shortname.Contains("Berg")) + .OrderBy(x => Convert.ToInt32(x.SnowHeight)); if (mypointtomodify.Count() > 0) - mypointtomodify.FirstOrDefault().Shortname = "Tal " + mypointtomodify.FirstOrDefault().Shortname; + mypointtomodify.FirstOrDefault().Shortname = + "Tal " + mypointtomodify.FirstOrDefault().Shortname; } - //Fall 4 keine Berg mehr als 1 Messpunkt else if (!hasbergstation && hasmittelstation && mymeasuringpointlist.Count > 1) { - var mypointtomodify = mymeasuringpointlist.Where(x => !x.Shortname.Contains("Tal") && !x.Shortname.Contains("Mittel")).OrderByDescending(x => Convert.ToInt32(x.SnowHeight)); + var mypointtomodify = mymeasuringpointlist + .Where( + x => !x.Shortname.Contains("Tal") && !x.Shortname.Contains("Mittel") + ) + .OrderByDescending(x => Convert.ToInt32(x.SnowHeight)); if (mypointtomodify.Count() > 0) - mypointtomodify.FirstOrDefault().Shortname = "Berg " + mypointtomodify.FirstOrDefault().Shortname; + mypointtomodify.FirstOrDefault().Shortname = + "Berg " + mypointtomodify.FirstOrDefault().Shortname; } //Fall 5 beide vorhanden mache nix - - - } - } return mymeasuringpointlist; } - public static SnowReportBaseData ParseMySnowReportData(string lang, SkiArea skiarea, ServiceReferenceLCS.ActivitySearchRS snowdatalts, List measuringpoints) + public static SnowReportBaseData ParseMySnowReportData( + string lang, + SkiArea skiarea, + ServiceReferenceLCS.ActivitySearchRS snowdatalts, + List measuringpoints + ) { SnowReportBaseData mysnowreport = new SnowReportBaseData(); @@ -157,78 +191,138 @@ public static SnowReportBaseData ParseMySnowReportData(string lang, SkiArea skia //var randomwebcam = new Random(); mysnowreport.WebcamUrl = skiarea.Webcam.Select(x => x.Webcamurl).ToList(); - - //Lese Lift infos aus Summaries + //Lese Lift infos aus Summaries //var myliftsummary = snowdatalts.Filters.EnumCodes.Item.Where(x => x.OrderID == "1").FirstOrDefault(); - var myliftsummary = snowdatalts.Filters.Tagging.Tags.FirstOrDefault().Item.Where(x => x.ItemValue.FirstOrDefault().RID == "E23AA37B2AE3477F96D1C0782195AFDF").FirstOrDefault(); - + var myliftsummary = snowdatalts.Filters.Tagging.Tags + .FirstOrDefault() + .Item.Where( + x => x.ItemValue.FirstOrDefault().RID == "E23AA37B2AE3477F96D1C0782195AFDF" + ) + .FirstOrDefault(); //activityresponse.Root.Elements("Filters").Elements("EnumCodes").Elements("Item").Where(x => x.Attribute("OrderID").Value.Equals("1")).FirstOrDefault(); if (myliftsummary != null) { - mysnowreport.openskilift = myliftsummary.CountIsOpen != null ? myliftsummary.CountIsOpen.ToString() : noinfotext; + mysnowreport.openskilift = + myliftsummary.CountIsOpen != null + ? myliftsummary.CountIsOpen.ToString() + : noinfotext; //myliftsummary != null ? myliftsummary.Attribute("CountIsOpen").Value : noinfotext; - mysnowreport.totalskilift = myliftsummary.Count != null ? myliftsummary.Count.ToString() : noinfotext; + mysnowreport.totalskilift = + myliftsummary.Count != null ? myliftsummary.Count.ToString() : noinfotext; //myliftsummary != null ? myliftsummary.Attribute("Count").Value : noinfotext; - mysnowreport.openskiliftkm = myliftsummary.SumLenghtOpen != null ? myliftsummary.SumLenghtOpen.ToString() : noinfotext; + mysnowreport.openskiliftkm = + myliftsummary.SumLenghtOpen != null + ? myliftsummary.SumLenghtOpen.ToString() + : noinfotext; //myliftsummary != null ? myliftsummary.Attribute("SumLengthOpen").Value : noinfotext; - mysnowreport.totalskiliftkm = myliftsummary.SumLenght != null ? myliftsummary.SumLenght.ToString() : noinfotext; + mysnowreport.totalskiliftkm = + myliftsummary.SumLenght != null + ? myliftsummary.SumLenght.ToString() + : noinfotext; //myliftsummary != null ? myliftsummary.Attribute("SumLength").Value : noinfotext; } - //Lese Pisten infos aus Summaries + //Lese Pisten infos aus Summaries //var mypistensummary = snowdatalts.Filters.EnumCodes.Item.Where(x => x.OrderID == "2").FirstOrDefault(); - var mypistensummary = snowdatalts.Filters.Tagging.Tags.FirstOrDefault().Item.Where(x => x.ItemValue.FirstOrDefault().RID == "EB5D6F10C0CB4797A2A04818088CD6AB").FirstOrDefault(); + var mypistensummary = snowdatalts.Filters.Tagging.Tags + .FirstOrDefault() + .Item.Where( + x => x.ItemValue.FirstOrDefault().RID == "EB5D6F10C0CB4797A2A04818088CD6AB" + ) + .FirstOrDefault(); //activityresponse.Root.Elements("Filters").Elements("EnumCodes").Elements("Item").Where(x => x.Attribute("OrderID").Value.Equals("2")).FirstOrDefault(); if (mypistensummary != null) { - mysnowreport.openskislopes = mypistensummary.CountIsOpen != null ? mypistensummary.CountIsOpen.ToString() : noinfotext; - mysnowreport.totalskislopes = mypistensummary.Count != null ? mypistensummary.Count.ToString() : noinfotext; + mysnowreport.openskislopes = + mypistensummary.CountIsOpen != null + ? mypistensummary.CountIsOpen.ToString() + : noinfotext; + mysnowreport.totalskislopes = + mypistensummary.Count != null + ? mypistensummary.Count.ToString() + : noinfotext; //mysnowreport.openskislopeskm = mypistensummary.SumLenghtOpenSpecified ? myliftsummary.SumLenghtOpen.ToString() : noinfotext; //mysnowreport.totalskislopeskm = mypistensummary.SumLenghtSpecified ? myliftsummary.SumLenght.ToString() : noinfotext; - double openskislopeskmdb = mypistensummary != null ? Convert.ToDouble(mypistensummary.SumLenghtOpen) : 0; + double openskislopeskmdb = + mypistensummary != null + ? Convert.ToDouble(mypistensummary.SumLenghtOpen) + : 0; double tempopenskislopeskmdb = openskislopeskmdb / 1000; mysnowreport.openskislopeskm = String.Format("{0:0}", tempopenskislopeskmdb); - double totalskislopeskmdb = mypistensummary != null ? Convert.ToDouble(mypistensummary.SumLenght) : 0; + double totalskislopeskmdb = + mypistensummary != null ? Convert.ToDouble(mypistensummary.SumLenght) : 0; double temptotalskislopeskmdb = totalskislopeskmdb / 1000; mysnowreport.totalskislopeskm = String.Format("{0:0}", temptotalskislopeskmdb); } - //Lese Longlaf infos aus Summaries + //Lese Longlaf infos aus Summaries //var mylonglafsummary = snowdatalts.Filters.EnumCodes.Item.Where(x => x.OrderID == "3").FirstOrDefault(); - var mylonglafsummary = snowdatalts.Filters.Tagging.Tags.FirstOrDefault().Item.Where(x => x.ItemValue.FirstOrDefault().RID == "D544A6312F8A47CF80CC4DFF8833FE50").FirstOrDefault(); + var mylonglafsummary = snowdatalts.Filters.Tagging.Tags + .FirstOrDefault() + .Item.Where( + x => x.ItemValue.FirstOrDefault().RID == "D544A6312F8A47CF80CC4DFF8833FE50" + ) + .FirstOrDefault(); if (mylonglafsummary != null) { //activityresponse.Root.Elements("Filters").Elements("EnumCodes").Elements("Item").Where(x => x.Attribute("OrderID").Value.Equals("3")).FirstOrDefault(); - mysnowreport.opentracks = mylonglafsummary.CountIsOpen != null ? mylonglafsummary.CountIsOpen.ToString() : noinfotext; - mysnowreport.totaltracks = mylonglafsummary.Count != null ? mylonglafsummary.Count.ToString() : noinfotext; + mysnowreport.opentracks = + mylonglafsummary.CountIsOpen != null + ? mylonglafsummary.CountIsOpen.ToString() + : noinfotext; + mysnowreport.totaltracks = + mylonglafsummary.Count != null + ? mylonglafsummary.Count.ToString() + : noinfotext; //mysnowreport.opentrackskm = mylonglafsummary != null ? mylonglafsummary.Attribute("SumLengthOpen").Value : noinfotext; //mysnowreport.totaltrackskm = mylonglafsummary != null ? mylonglafsummary.Attribute("SumLength").Value : noinfotext; - double openskitrackkmdb = mylonglafsummary != null ? Convert.ToDouble(mylonglafsummary.SumLenghtOpen) : 0; + double openskitrackkmdb = + mylonglafsummary != null + ? Convert.ToDouble(mylonglafsummary.SumLenghtOpen) + : 0; double tempopenskitrackkmdb = openskitrackkmdb / 1000; mysnowreport.opentrackskm = String.Format("{0:0}", tempopenskitrackkmdb); - double totalskitrackkmdb = mylonglafsummary != null ? Convert.ToDouble(mylonglafsummary.SumLenght) : 0; + double totalskitrackkmdb = + mylonglafsummary != null ? Convert.ToDouble(mylonglafsummary.SumLenght) : 0; double temptotalskitrackkmdb = totalskitrackkmdb / 1000; mysnowreport.totaltrackskm = String.Format("{0:0}", temptotalskitrackkmdb); } - //Lese Rodel infos aus Summaries + //Lese Rodel infos aus Summaries //var myrodelsummary = snowdatalts.Filters.EnumCodes.Item.Where(x => x.OrderID == "4").FirstOrDefault(); - var myrodelsummary = snowdatalts.Filters.Tagging.Tags.FirstOrDefault().Item.Where(x => x.ItemValue.FirstOrDefault().RID == "F3B08D06569646F38462EDCA506D81D4").FirstOrDefault(); + var myrodelsummary = snowdatalts.Filters.Tagging.Tags + .FirstOrDefault() + .Item.Where( + x => x.ItemValue.FirstOrDefault().RID == "F3B08D06569646F38462EDCA506D81D4" + ) + .FirstOrDefault(); //activityresponse.Root.Elements("Filters").Elements("EnumCodes").Elements("Item").Where(x => x.Attribute("OrderID").Value.Equals("4")).FirstOrDefault(); if (myrodelsummary != null) { - mysnowreport.opentslides = myrodelsummary.CountIsOpen != null ? myrodelsummary.CountIsOpen.ToString() : noinfotext; - mysnowreport.totalslides = myrodelsummary.Count != null ? myrodelsummary.Count.ToString() : noinfotext; - mysnowreport.opentslideskm = myrodelsummary.SumLenghtOpen != null ? myrodelsummary.SumLenghtOpen.ToString() : noinfotext; - mysnowreport.totalslideskm = myrodelsummary.SumLenght != null ? myrodelsummary.SumLenght.ToString() : noinfotext; + mysnowreport.opentslides = + myrodelsummary.CountIsOpen != null + ? myrodelsummary.CountIsOpen.ToString() + : noinfotext; + mysnowreport.totalslides = + myrodelsummary.Count != null ? myrodelsummary.Count.ToString() : noinfotext; + mysnowreport.opentslideskm = + myrodelsummary.SumLenghtOpen != null + ? myrodelsummary.SumLenghtOpen.ToString() + : noinfotext; + mysnowreport.totalslideskm = + myrodelsummary.SumLenght != null + ? myrodelsummary.SumLenght.ToString() + : noinfotext; } - mysnowreport.Measuringpoints = measuringpoints.OrderByDescending(x => x.LastUpdate).ToList(); + mysnowreport.Measuringpoints = measuringpoints + .OrderByDescending(x => x.LastUpdate) + .ToList(); return mysnowreport; } diff --git a/LCS/Parser/ParseWebcamData.cs b/LCS/Parser/ParseWebcamData.cs index 91adb0d38..94f739965 100644 --- a/LCS/Parser/ParseWebcamData.cs +++ b/LCS/Parser/ParseWebcamData.cs @@ -13,14 +13,74 @@ public class ParseWebcamData public static CultureInfo myculture = new CultureInfo("en"); //Get the Webcam Detail Information - public static WebcamInfo GetWebcamDetailLTS(string rid, WebcamInfo webcam, string ltsuser, string ltspswd, string ltsmsgpswd) + public static WebcamInfo GetWebcamDetailLTS( + string rid, + WebcamInfo webcam, + string ltsuser, + string ltspswd, + string ltsmsgpswd + ) { List mywebcamlist = new List(); mywebcamlist.Add(rid); - var mywebcamrequestde = GetActivityDataLCS.GetWebcamDetailRequest("de", "0", "0", "1", "1", "1", "1", "1", "1", "1", "1", "", "", "", mywebcamlist, "NOI", ltsmsgpswd); - var mywebcamrequestit = GetActivityDataLCS.GetWebcamDetailRequest("it", "0", "0", "1", "1", "1", "1", "1", "1", "1", "1", "", "", "", mywebcamlist, "NOI", ltsmsgpswd); - var mywebcamrequesten = GetActivityDataLCS.GetWebcamDetailRequest("en", "0", "0", "1", "1", "1", "1", "1", "1", "1", "1", "", "", "", mywebcamlist, "NOI", ltsmsgpswd); + var mywebcamrequestde = GetActivityDataLCS.GetWebcamDetailRequest( + "de", + "0", + "0", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "", + "", + "", + mywebcamlist, + "NOI", + ltsmsgpswd + ); + var mywebcamrequestit = GetActivityDataLCS.GetWebcamDetailRequest( + "it", + "0", + "0", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "", + "", + "", + mywebcamlist, + "NOI", + ltsmsgpswd + ); + var mywebcamrequesten = GetActivityDataLCS.GetWebcamDetailRequest( + "en", + "0", + "0", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "1", + "", + "", + "", + mywebcamlist, + "NOI", + ltsmsgpswd + ); GetActivityDataLCS myactivitysearch = new GetActivityDataLCS(ltsuser, ltspswd); var myactivityresponsede = myactivitysearch.GetWebcamDetail(mywebcamrequestde); @@ -91,15 +151,36 @@ public static WebcamInfo GetWebcamDetailLTS(string rid, WebcamInfo webcam, strin mygpstrack.Id = gpstrack.RID; mygpstrack.GpxTrackUrl = gpstrack.File.URL.InnerText; - if (gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText == "Übersicht") + if ( + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText == "Übersicht" + ) mygpstrack.Type = "overview"; - if (gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText == "Datei zum herunterladen") + if ( + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText == "Datei zum herunterladen" + ) mygpstrack.Type = "detailed"; - //EN und IT Info? - mygpstrack.GpxTrackDesc.TryAddOrUpdate("de", gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText); + mygpstrack.GpxTrackDesc.TryAddOrUpdate( + "de", + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + ); mygpstracklist.Add(mygpstrack); } @@ -116,8 +197,18 @@ public static WebcamInfo GetWebcamDetailLTS(string rid, WebcamInfo webcam, strin { foreach (var gpstrack in gpstracksit) { - GpsTrack mygpstrack = mygpstracklist.Where(x => x.Id == gpstrack.RID).FirstOrDefault(); - mygpstrack.GpxTrackDesc.TryAddOrUpdate("it", gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText); + GpsTrack mygpstrack = mygpstracklist + .Where(x => x.Id == gpstrack.RID) + .FirstOrDefault(); + mygpstrack.GpxTrackDesc.TryAddOrUpdate( + "it", + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + ); //mygpstracklist.Add(mygpstrack); } } @@ -133,8 +224,18 @@ public static WebcamInfo GetWebcamDetailLTS(string rid, WebcamInfo webcam, strin { foreach (var gpstrack in gpstracksen) { - GpsTrack mygpstrack = mygpstracklist.Where(x => x.Id == gpstrack.RID).FirstOrDefault(); - mygpstrack.GpxTrackDesc.TryAddOrUpdate("en", gpstrack.EnumCodes.EnumCode.FirstOrDefault().Code.Where(x => x.Level == "1").FirstOrDefault().Name.FirstOrDefault().InnerText); + GpsTrack mygpstrack = mygpstracklist + .Where(x => x.Id == gpstrack.RID) + .FirstOrDefault(); + mygpstrack.GpxTrackDesc.TryAddOrUpdate( + "en", + gpstrack.EnumCodes.EnumCode + .FirstOrDefault() + .Code.Where(x => x.Level == "1") + .FirstOrDefault() + .Name.FirstOrDefault() + .InnerText + ); //mygpstracklist.Add(mygpstrack); } } @@ -146,7 +247,8 @@ public static WebcamInfo GetWebcamDetailLTS(string rid, WebcamInfo webcam, strin //URls webcam.Webcamurl = thewebcamde.URL != null ? thewebcamde.URL.InnerText : ""; webcam.Streamurl = thewebcamde.StreamURL != null ? thewebcamde.StreamURL.InnerText : ""; - webcam.Previewurl = thewebcamde.PreviewURL != null ? thewebcamde.PreviewURL.InnerText : ""; + webcam.Previewurl = + thewebcamde.PreviewURL != null ? thewebcamde.PreviewURL.InnerText : ""; //Name if (thewebcamde.Name != null) @@ -159,7 +261,10 @@ public static WebcamInfo GetWebcamDetailLTS(string rid, WebcamInfo webcam, strin if (webcam.FirstImport == null) webcam.FirstImport = DateTime.Now; - webcam.LastChange = thewebcamde.News.Status != null ? Convert.ToDateTime(thewebcamde.News.Status.LastChange) : DateTime.MinValue; + webcam.LastChange = + thewebcamde.News.Status != null + ? Convert.ToDateTime(thewebcamde.News.Status.LastChange) + : DateTime.MinValue; webcam.Source = "LTS"; diff --git a/LCS/ServiceReferenceConfig.cs b/LCS/ServiceReferenceConfig.cs index 60d3fccbc..77bd06d80 100644 --- a/LCS/ServiceReferenceConfig.cs +++ b/LCS/ServiceReferenceConfig.cs @@ -6,18 +6,23 @@ namespace LCS { public class ServiceReferenceConfig { - private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration) + private static System.ServiceModel.Channels.Binding GetBindingForEndpoint( + EndpointConfiguration endpointConfiguration + ) { if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_ISimpleService)) { - System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding(); + System.ServiceModel.BasicHttpBinding result = + new System.ServiceModel.BasicHttpBinding(); result.MaxBufferSize = int.MaxValue; result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; result.MaxReceivedMessageSize = int.MaxValue; result.AllowCookies = true; return result; } - throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration)); + throw new System.InvalidOperationException( + string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration) + ); } //private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(TimeSpan timeout) @@ -40,13 +45,19 @@ private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(Endpoi // return httpsBinding; //} - private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration) + private static System.ServiceModel.EndpointAddress GetEndpointAddress( + EndpointConfiguration endpointConfiguration + ) { if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_ISimpleService)) { - return new System.ServiceModel.EndpointAddress("https://lcs.lts.it/api/data.svc/soap"); + return new System.ServiceModel.EndpointAddress( + "https://lcs.lts.it/api/data.svc/soap" + ); } - throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration)); + throw new System.InvalidOperationException( + string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration) + ); } public enum EndpointConfiguration diff --git a/MSS/GetMssData.cs b/MSS/GetMssData.cs index 787baef68..3570659b0 100644 --- a/MSS/GetMssData.cs +++ b/MSS/GetMssData.cs @@ -25,21 +25,45 @@ public static class GetMssData /// Abreisedatum /// Verpflegungsart /// - public static async Task GetMssResponse(HttpClient httpClient, string lang, List idlist, string idsofchannel, string[] mybookingchannels, List>> myroomdata, DateTime arrival, DateTime departure, int service, string hgvservicecode, XElement offerdetails, XElement hoteldetails, int rooms, string requestsource, string version, string mssuser, string msspswd, bool withoutmssids = false) + public static async Task GetMssResponse( + HttpClient httpClient, + string lang, + List idlist, + string idsofchannel, + string[] mybookingchannels, + List>> myroomdata, + DateTime arrival, + DateTime departure, + int service, + string hgvservicecode, + XElement offerdetails, + XElement hoteldetails, + int rooms, + string requestsource, + string version, + string mssuser, + string msspswd, + bool withoutmssids = false + ) { try { - - List myroompersons = (from x in myroomdata - select new Room { RoomSeq = x.Item1, RoomType = x.Item2, Person = x.Item3 }).ToList(); + List myroompersons = ( + from x in myroomdata + select new Room + { + RoomSeq = x.Item1, + RoomType = x.Item2, + Person = x.Item3 + } + ).ToList(); var myroomlist = MssRequest.BuildRoomData(myroompersons); XElement mychannels = MssRequest.BuildChannelList(mybookingchannels); - XElement myidlist = - withoutmssids - ? MssRequest.BuildIDList(new List()) + XElement myidlist = withoutmssids + ? MssRequest.BuildIDList(new List()) : myidlist = MssRequest.BuildIDList(idlist); XElement mytyp = MssRequest.BuildType("10"); @@ -51,7 +75,23 @@ public static class GetMssData // tracesource.TraceEvent(TraceEventType.Information, 0, "MSS Request Hotel ID Count: " + A0Ridlist.Count + " Period: " + arrival.ToShortDateString() + " " + departure.ToShortDateString() + " Service: " + service.ToString() + " Rooms: " + myroompersons.Count + " Result from Cache: " + withoutmssids.ToString()); //} - XDocument myrequest = MssRequest.BuildPostData(myidlist, mychannels, myroomlist, arrival, departure, offerdetails, hoteldetails, mytyp, service, lang, idsofchannel, requestsource, version, mssuser, msspswd); + XDocument myrequest = MssRequest.BuildPostData( + myidlist, + mychannels, + myroomlist, + arrival, + departure, + offerdetails, + hoteldetails, + mytyp, + service, + lang, + idsofchannel, + requestsource, + version, + mssuser, + msspswd + ); var myresponses = await MssRequest.RequestAsync(httpClient, myrequest); @@ -59,19 +99,25 @@ public static class GetMssData XElement allmyresponses = XElement.Parse(activityresponsecontent); - List allmyoffers = (from xy in allmyresponses.Element("result").Elements("hotel") - where - xy.Elements("channel").Count() > 0 - select xy).ToList(); + List allmyoffers = ( + from xy in allmyresponses.Element("result").Elements("hotel") + where xy.Elements("channel").Count() > 0 + select xy + ).ToList(); XElement myresult = new XElement("root"); - myresult.Add( - allmyresponses.Element("header"), - new XElement("result", - allmyoffers)); + myresult.Add(allmyresponses.Element("header"), new XElement("result", allmyoffers)); //Und iatz no parsen - MssResult myparsedresponse = ParseMssResponse.ParsemyMssResponse(lang, hgvservicecode, myresult, idlist, myroompersons, requestsource, version); + MssResult myparsedresponse = ParseMssResponse.ParsemyMssResponse( + lang, + hgvservicecode, + myresult, + idlist, + myroompersons, + requestsource, + version + ); return myparsedresponse; } @@ -80,13 +126,16 @@ public static class GetMssData //var tracesource = new TraceSource("MssData"); //tracesource.TraceEvent(TraceEventType.Error, 0, "MSS Request Error: " + ex.Message); - Log.Logger.Error(ex, "Error while retrieving MSS information for {A0Ridlist}", idlist); + Log.Logger.Error( + ex, + "Error while retrieving MSS information for {A0Ridlist}", + idlist + ); return null; } } - #region obsoleteCode ///// @@ -138,7 +187,7 @@ public static class GetMssData // new XDeclaration("1.0", "utf-8", "yes"), myroot); - // //var servicecode = mysuedtirolcontainer.AccoBoardSet.Where(x => x.BoardIdHGV == service).FirstOrDefault().BoardnameHGV; + // //var servicecode = mysuedtirolcontainer.AccoBoardSet.Where(x => x.BoardIdHGV == service).FirstOrDefault().BoardnameHGV; // //Und iatz no parsen // MssResult myparsedresponse = ParseMssResponse.ParsemyMssResponse(lang, hgvservicecode, encodedDoc8, myroompersons, source); @@ -329,7 +378,7 @@ public static class GetMssData // //DEs geat no net ! Index fahler // //var bookableaccos = session.Query() // // .Where(x => x.Id.In(A0Ridlist)) - // // .Where(x => x.AccoBookingChannel.Any(y => y.Id.In(myhotelchannellist))) + // // .Where(x => x.AccoBookingChannel.Any(y => y.Id.In(myhotelchannellist))) // // .TransformWith() // // .ToList(); @@ -346,7 +395,7 @@ public static class GetMssData // { // var myidlist = buildidList(mya0rids); - // //Channel Data + // //Channel Data // var mychannellist = buildChannelList(bookingportal); // Tuple mytuple = new Tuple(myidlist, mychannellist); diff --git a/MSS/GetMssRoomList.cs b/MSS/GetMssRoomList.cs index 71fb9c99c..62220f1e9 100644 --- a/MSS/GetMssRoomList.cs +++ b/MSS/GetMssRoomList.cs @@ -10,13 +10,31 @@ namespace MSS { public class GetMssRoomlist { - public static async Task> GetMssRoomlistAsync(HttpClient httpClient, string lang, string hotelid, string hotelidofchannel, XElement roomdetails, XDocument roomamenities, string source, string version, string mssuser, string msspswd) + public static async Task> GetMssRoomlistAsync( + HttpClient httpClient, + string lang, + string hotelid, + string hotelidofchannel, + XElement roomdetails, + XDocument roomamenities, + string source, + string version, + string mssuser, + string msspswd + ) { try { - - - XDocument myrequest = MssRequest.BuildRoomlistPostData(roomdetails, hotelid, hotelidofchannel, lang, source, version, mssuser, msspswd); + XDocument myrequest = MssRequest.BuildRoomlistPostData( + roomdetails, + hotelid, + hotelidofchannel, + lang, + source, + version, + mssuser, + msspswd + ); var myresponses = MssRequest.RequestRoomAsync(httpClient, myrequest); await Task.WhenAll(myresponses); @@ -28,10 +46,13 @@ public static async Task> GetMssRoomlistAsync(HttpClient httpClie XElement fullresponse = XElement.Parse(roomresponsecontent.Result); //do muassmen iatz nuie method schreiben - var myparsedresponse = ParseMssRoomResponse.ParseMyRoomResponse(lang, fullresponse, roomamenities); + var myparsedresponse = ParseMssRoomResponse.ParseMyRoomResponse( + lang, + fullresponse, + roomamenities + ); return myparsedresponse; - } catch (Exception) { @@ -39,13 +60,31 @@ public static async Task> GetMssRoomlistAsync(HttpClient httpClie } } - public static List GetMssRoomlistSync(HttpClient httpClient, string lang, string hotelid, string hotelidofchannel, XElement roomdetails, XDocument roomamenities, string source, string version, string mssuser, string msspswd) + public static List GetMssRoomlistSync( + HttpClient httpClient, + string lang, + string hotelid, + string hotelidofchannel, + XElement roomdetails, + XDocument roomamenities, + string source, + string version, + string mssuser, + string msspswd + ) { try { - - - XDocument myrequest = MssRequest.BuildRoomlistPostData(roomdetails, hotelid, hotelidofchannel, lang, source, version, mssuser, msspswd); + XDocument myrequest = MssRequest.BuildRoomlistPostData( + roomdetails, + hotelid, + hotelidofchannel, + lang, + source, + version, + mssuser, + msspswd + ); var myresponses = MssRequest.RequestRoom(httpClient, myrequest); string roomresponsecontent = myresponses.Content.ReadAsStringAsync().Result; @@ -53,10 +92,13 @@ public static List GetMssRoomlistSync(HttpClient httpClient, string la XElement fullresponse = XElement.Parse(roomresponsecontent); //do muassmen iatz nuie method schreiben - var myparsedresponse = ParseMssRoomResponse.ParseMyRoomResponse(lang, fullresponse, roomamenities); + var myparsedresponse = ParseMssRoomResponse.ParseMyRoomResponse( + lang, + fullresponse, + roomamenities + ); return myparsedresponse; - } catch (Exception) { diff --git a/MSS/GetMssSpecial.cs b/MSS/GetMssSpecial.cs index 72a7a187b..26a9e4c85 100644 --- a/MSS/GetMssSpecial.cs +++ b/MSS/GetMssSpecial.cs @@ -12,7 +12,21 @@ namespace MSS public class GetMssSpecial { //Objekt Validity - public static async Task> GetMssSpecialPackages(HttpClient httpClient, string lang, List Packageidlist, DateTime from, DateTime to, XElement specialdetails, int typ, int service, List>> myroomdata, string source, string version, string mssuser, string msspswd) + public static async Task> GetMssSpecialPackages( + HttpClient httpClient, + string lang, + List Packageidlist, + DateTime from, + DateTime to, + XElement specialdetails, + int typ, + int service, + List>> myroomdata, + string source, + string version, + string mssuser, + string msspswd + ) { try { @@ -20,30 +34,53 @@ public static async Task> GetMssSpecialPackages(HttpClient httpCli if (myroomdata != null) { - List myroompersons = (from x in myroomdata - select new Room { RoomSeq = x.Item1, RoomType = x.Item2, Person = x.Item3 }).ToList(); + List myroompersons = ( + from x in myroomdata + select new Room + { + RoomSeq = x.Item1, + RoomType = x.Item2, + Person = x.Item3 + } + ).ToList(); myroomlist = MssRequest.BuildRoomData(myroompersons); } XElement myidlist = MssRequest.BuildOfferIDList(Packageidlist); - XDocument myrequest = MssRequest.BuildSpecialPostData(myidlist, myroomlist, from, to, specialdetails, typ, service, lang, source, version, mssuser, msspswd); + XDocument myrequest = MssRequest.BuildSpecialPostData( + myidlist, + myroomlist, + from, + to, + specialdetails, + typ, + service, + lang, + source, + version, + mssuser, + msspswd + ); var myresponses = MssRequest.RequestSpecialAsync(httpClient, myrequest); await Task.WhenAll(myresponses); - Task specialresponsecontent = myresponses.Result.Content.ReadAsStringAsync(); + Task specialresponsecontent = + myresponses.Result.Content.ReadAsStringAsync(); await Task.WhenAll(specialresponsecontent); XElement fullresponse = XElement.Parse(specialresponsecontent.Result); - var myparsedresponse = ParseMssSpecialResponse.ParseMySpecialResponse(lang, fullresponse); + var myparsedresponse = ParseMssSpecialResponse.ParseMySpecialResponse( + lang, + fullresponse + ); return myparsedresponse; - } catch (Exception) { @@ -51,39 +88,82 @@ public static async Task> GetMssSpecialPackages(HttpClient httpCli } } - public static async Task GetMssSpecialPackages(HttpClient httpClient, string lang, List hgvIdList, List offerIdList, DateTime from, DateTime to, XElement specialdetails, XElement hoteldetails, int typ, int service, string hgvservicecode, List>> myroomdata, string source, string version, string mssuser, string msspswd) + public static async Task GetMssSpecialPackages( + HttpClient httpClient, + string lang, + List hgvIdList, + List offerIdList, + DateTime from, + DateTime to, + XElement specialdetails, + XElement hoteldetails, + int typ, + int service, + string hgvservicecode, + List>> myroomdata, + string source, + string version, + string mssuser, + string msspswd + ) { try { XElement myroomlist = new XElement("room"); - List myroompersons = (from x in myroomdata - select new Room { RoomSeq = x.Item1, RoomType = x.Item2, Person = x.Item3 }).ToList(); + List myroompersons = ( + from x in myroomdata + select new Room + { + RoomSeq = x.Item1, + RoomType = x.Item2, + Person = x.Item3 + } + ).ToList(); myroomlist = MssRequest.BuildRoomData(myroompersons); - XElement myidlist = MssRequest.BuildIDList(hgvIdList); XElement myofferidlist = MssRequest.BuildOfferIDList(offerIdList); - XDocument myrequest = MssRequest.BuildSpecialPostDataCheckAvailability(myidlist, myofferidlist, myroomlist, from, to, specialdetails, hoteldetails, typ, service, lang, source, version, mssuser, msspswd); + XDocument myrequest = MssRequest.BuildSpecialPostDataCheckAvailability( + myidlist, + myofferidlist, + myroomlist, + from, + to, + specialdetails, + hoteldetails, + typ, + service, + lang, + source, + version, + mssuser, + msspswd + ); var myresponses = MssRequest.RequestSpecialAsync(httpClient, myrequest); await Task.WhenAll(myresponses); - Task specialresponsecontent = myresponses.Result.Content.ReadAsStringAsync(); + Task specialresponsecontent = + myresponses.Result.Content.ReadAsStringAsync(); await Task.WhenAll(specialresponsecontent); XElement fullresponse = XElement.Parse(specialresponsecontent.Result); //do muassmen iatz schaugn! - var myparsedresponse = ParseMssSpecialResponse.ParsemyMssSpecialResponse(lang, hgvservicecode, fullresponse, myroompersons); + var myparsedresponse = ParseMssSpecialResponse.ParsemyMssSpecialResponse( + lang, + hgvservicecode, + fullresponse, + myroompersons + ); //var myparsedresponse = new MssResult(); return myparsedresponse; - } catch (Exception) { @@ -91,10 +171,24 @@ public static async Task GetMssSpecialPackages(HttpClient httpClient, } } - #region Premium included - public static async Task> GetMssSpecialPackages(HttpClient httpClient, string lang, List Packageidlist, DateTime from, DateTime to, XElement specialdetails, int typ, int premium, int service, List>> myroomdata, string source, string version, string mssuser, string msspswd) + public static async Task> GetMssSpecialPackages( + HttpClient httpClient, + string lang, + List Packageidlist, + DateTime from, + DateTime to, + XElement specialdetails, + int typ, + int premium, + int service, + List>> myroomdata, + string source, + string version, + string mssuser, + string msspswd + ) { try { @@ -102,30 +196,54 @@ public static async Task> GetMssSpecialPackages(HttpClient httpCli if (myroomdata != null) { - List myroompersons = (from x in myroomdata - select new Room { RoomSeq = x.Item1, RoomType = x.Item2, Person = x.Item3 }).ToList(); + List myroompersons = ( + from x in myroomdata + select new Room + { + RoomSeq = x.Item1, + RoomType = x.Item2, + Person = x.Item3 + } + ).ToList(); myroomlist = MssRequest.BuildRoomData(myroompersons); } XElement myidlist = MssRequest.BuildOfferIDList(Packageidlist); - XDocument myrequest = MssRequest.BuildSpecialPostDatawithPremium(myidlist, myroomlist, from, to, specialdetails, typ, premium, service, lang, source, version, mssuser, msspswd); + XDocument myrequest = MssRequest.BuildSpecialPostDatawithPremium( + myidlist, + myroomlist, + from, + to, + specialdetails, + typ, + premium, + service, + lang, + source, + version, + mssuser, + msspswd + ); var myresponses = MssRequest.RequestSpecialAsync(httpClient, myrequest); await Task.WhenAll(myresponses); - Task specialresponsecontent = myresponses.Result.Content.ReadAsStringAsync(); + Task specialresponsecontent = + myresponses.Result.Content.ReadAsStringAsync(); await Task.WhenAll(specialresponsecontent); XElement fullresponse = XElement.Parse(specialresponsecontent.Result); - var myparsedresponse = ParseMssSpecialResponse.ParseMySpecialResponse(lang, fullresponse); + var myparsedresponse = ParseMssSpecialResponse.ParseMySpecialResponse( + lang, + fullresponse + ); return myparsedresponse; - } catch (Exception) { @@ -133,39 +251,83 @@ public static async Task> GetMssSpecialPackages(HttpClient httpCli } } - public static async Task GetMssSpecialPackages(HttpClient httpClient, string lang, List hgvIdList, List offerIdList, DateTime from, DateTime to, XElement specialdetails, XElement hoteldetails, int typ, int premium, int service, string hgvservicecode, List>> myroomdata, string source, string version, string mssuser, string msspswd) + public static async Task GetMssSpecialPackages( + HttpClient httpClient, + string lang, + List hgvIdList, + List offerIdList, + DateTime from, + DateTime to, + XElement specialdetails, + XElement hoteldetails, + int typ, + int premium, + int service, + string hgvservicecode, + List>> myroomdata, + string source, + string version, + string mssuser, + string msspswd + ) { try { XElement myroomlist = new XElement("room"); - List myroompersons = (from x in myroomdata - select new Room { RoomSeq = x.Item1, RoomType = x.Item2, Person = x.Item3 }).ToList(); + List myroompersons = ( + from x in myroomdata + select new Room + { + RoomSeq = x.Item1, + RoomType = x.Item2, + Person = x.Item3 + } + ).ToList(); myroomlist = MssRequest.BuildRoomData(myroompersons); - XElement myidlist = MssRequest.BuildIDList(hgvIdList); XElement myofferidlist = MssRequest.BuildOfferIDList(offerIdList); - XDocument myrequest = MssRequest.BuildSpecialPostDataCheckAvailability(myidlist, myofferidlist, myroomlist, from, to, specialdetails, hoteldetails, typ, service, lang, source, version, mssuser, msspswd); + XDocument myrequest = MssRequest.BuildSpecialPostDataCheckAvailability( + myidlist, + myofferidlist, + myroomlist, + from, + to, + specialdetails, + hoteldetails, + typ, + service, + lang, + source, + version, + mssuser, + msspswd + ); var myresponses = MssRequest.RequestSpecialAsync(httpClient, myrequest); await Task.WhenAll(myresponses); - Task specialresponsecontent = myresponses.Result.Content.ReadAsStringAsync(); + Task specialresponsecontent = + myresponses.Result.Content.ReadAsStringAsync(); await Task.WhenAll(specialresponsecontent); XElement fullresponse = XElement.Parse(specialresponsecontent.Result); //do muassmen iatz schaugn! - var myparsedresponse = ParseMssSpecialResponse.ParsemyMssSpecialResponse(lang, hgvservicecode, fullresponse, myroompersons); + var myparsedresponse = ParseMssSpecialResponse.ParsemyMssSpecialResponse( + lang, + hgvservicecode, + fullresponse, + myroompersons + ); //var myparsedresponse = new MssResult(); return myparsedresponse; - } catch (Exception) { @@ -173,8 +335,6 @@ public static async Task GetMssSpecialPackages(HttpClient httpClient, } } - #endregion - } } diff --git a/MSS/MssRequest.cs b/MSS/MssRequest.cs index 35d9cc4e2..92731f7ef 100644 --- a/MSS/MssRequest.cs +++ b/MSS/MssRequest.cs @@ -10,56 +10,90 @@ namespace MSS { public class MssRequest { - public const string serviceurl = @"http://www.easymailing.eu/mss/mss_service.php?function=getHotelList&mode=1"; - public const string serviceurlspecial = @"http://www.easymailing.eu/mss/mss_service.php?function=getSpecialList&mode=1"; + public const string serviceurl = + @"http://www.easymailing.eu/mss/mss_service.php?function=getHotelList&mode=1"; + public const string serviceurlspecial = + @"http://www.easymailing.eu/mss/mss_service.php?function=getSpecialList&mode=1"; + //neu getroomlist - public const string serviceurlroomlist = @"http://www.easymailing.eu/mss/mss_service.php?function=getRoomList&mode=1"; + public const string serviceurlroomlist = + @"http://www.easymailing.eu/mss/mss_service.php?function=getRoomList&mode=1"; - public static async Task RequestAsync(HttpClient httpClient, XDocument request) + public static async Task RequestAsync( + HttpClient httpClient, + XDocument request + ) { try { //HttpClient myclient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); //myclient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate"); - var myresponse = await httpClient.PostAsync(serviceurl, new StringContent(request.ToString(), Encoding.UTF8, "text/xml")); + var myresponse = await httpClient.PostAsync( + serviceurl, + new StringContent(request.ToString(), Encoding.UTF8, "text/xml") + ); return myresponse; } catch (Exception ex) { - return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(ex.Message) }; + return new HttpResponseMessage + { + StatusCode = HttpStatusCode.BadRequest, + Content = new StringContent(ex.Message) + }; } } - public static async Task RequestSpecialAsync(HttpClient httpClient, XDocument request) + public static async Task RequestSpecialAsync( + HttpClient httpClient, + XDocument request + ) { try { //HttpClient myclient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); //myclient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate"); - var myresponse = await httpClient.PostAsync(serviceurlspecial, new StringContent(request.ToString(), Encoding.UTF8, "text/xml")); + var myresponse = await httpClient.PostAsync( + serviceurlspecial, + new StringContent(request.ToString(), Encoding.UTF8, "text/xml") + ); return myresponse; } catch (Exception ex) { - return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(ex.Message) }; + return new HttpResponseMessage + { + StatusCode = HttpStatusCode.BadRequest, + Content = new StringContent(ex.Message) + }; } } - public static async Task RequestRoomAsync(HttpClient httpClient, XDocument request) + public static async Task RequestRoomAsync( + HttpClient httpClient, + XDocument request + ) { try { //HttpClient myclient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); //myclient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate"); - var myresponse = await httpClient.PostAsync(serviceurlroomlist, new StringContent(request.ToString(), Encoding.UTF8, "text/xml")); + var myresponse = await httpClient.PostAsync( + serviceurlroomlist, + new StringContent(request.ToString(), Encoding.UTF8, "text/xml") + ); return myresponse; } catch (Exception ex) { - return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(ex.Message) }; + return new HttpResponseMessage + { + StatusCode = HttpStatusCode.BadRequest, + Content = new StringContent(ex.Message) + }; } } @@ -69,411 +103,501 @@ public static HttpResponseMessage RequestRoom(HttpClient httpClient, XDocument r { //HttpClient myclient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); //myclient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate"); - var myresponse = httpClient.PostAsync(serviceurlroomlist, new StringContent(request.ToString(), Encoding.UTF8, "text/xml")).Result; + var myresponse = httpClient + .PostAsync( + serviceurlroomlist, + new StringContent(request.ToString(), Encoding.UTF8, "text/xml") + ) + .Result; return myresponse; } catch (Exception ex) { - return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(ex.Message) }; + return new HttpResponseMessage + { + StatusCode = HttpStatusCode.BadRequest, + Content = new StringContent(ex.Message) + }; } } - - public static XDocument BuildPostData(XElement idlist, XElement channel, XElement roomlist, DateTime arrival, DateTime departure, XElement offerdetails, XElement hoteldetails, XElement type, int service, string lang, string idofchannel, string source, string version, string mssuser, string msspswd) + public static XDocument BuildPostData( + XElement idlist, + XElement channel, + XElement roomlist, + DateTime arrival, + DateTime departure, + XElement offerdetails, + XElement hoteldetails, + XElement type, + int service, + string lang, + string idofchannel, + string source, + string version, + string mssuser, + string msspswd + ) { - XElement myroot = - new XElement("root", + XElement myroot = new XElement( + "root", new XElement("version", version + ".0"), - new XElement("header", - new XElement("credentials", + new XElement( + "header", + new XElement( + "credentials", new XElement("user", mssuser), new XElement("password", msspswd), new XElement("source", source) - ), + ), new XElement("method", "getHotelList"), - new XElement("paging", - new XElement("start", "0"), - new XElement("limit", "0") - )), - new XElement("request", - new XElement("search", + new XElement("paging", new XElement("start", "0"), new XElement("limit", "0")) + ), + new XElement( + "request", + new XElement( + "search", new XElement("lang", lang), idlist.Elements("id"), new XElement("id_ofchannel", idofchannel), - new XElement("search_offer", + new XElement( + "search_offer", channel.Elements("channel_id"), new XElement("arrival", String.Format("{0:yyyy-MM-dd}", arrival)), new XElement("departure", String.Format("{0:yyyy-MM-dd}", departure)), new XElement("service", service), roomlist.Elements("room"), type - ) - ), - new XElement("options", - offerdetails, - hoteldetails - ), - new XElement("order"), - new XElement("logging", - new XElement("step") - ) - ) - ); - - XDocument encodedDoc8 = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - myroot + ) + ), + new XElement("options", offerdetails, hoteldetails), + new XElement("order"), + new XElement("logging", new XElement("step")) + ) ); + XDocument encodedDoc8 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), myroot); + return encodedDoc8; } - public static XDocument BuildPostData(XElement channel, XElement roomlist, DateTime arrival, DateTime departure, XElement offerdetails, XElement hoteldetails, XElement type, int service, string lang, string source, string version, string mssuser, string msspswd) + public static XDocument BuildPostData( + XElement channel, + XElement roomlist, + DateTime arrival, + DateTime departure, + XElement offerdetails, + XElement hoteldetails, + XElement type, + int service, + string lang, + string source, + string version, + string mssuser, + string msspswd + ) { - XElement myroot = - new XElement("root", + XElement myroot = new XElement( + "root", new XElement("version", version + ".0"), - new XElement("header", - new XElement("credentials", + new XElement( + "header", + new XElement( + "credentials", new XElement("user", mssuser), new XElement("password", msspswd), new XElement("source", source) - ), + ), new XElement("method", "getHotelList"), - new XElement("paging", - new XElement("start", "0"), - new XElement("limit", "0") - )), - new XElement("request", - new XElement("search", + new XElement("paging", new XElement("start", "0"), new XElement("limit", "0")) + ), + new XElement( + "request", + new XElement( + "search", new XElement("lang", lang), - new XElement("search_offer", + new XElement( + "search_offer", channel, new XElement("arrival", String.Format("{0:yyyy-MM-dd}", arrival)), new XElement("departure", String.Format("{0:yyyy-MM-dd}", departure)), new XElement("service", service), roomlist.Elements("room"), type - ) - ), - new XElement("options", - offerdetails, - hoteldetails - ), - new XElement("order"), - new XElement("logging", - new XElement("step") - ) - ) - ); - - XDocument encodedDoc8 = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - myroot + ) + ), + new XElement("options", offerdetails, hoteldetails), + new XElement("order"), + new XElement("logging", new XElement("step")) + ) ); + XDocument encodedDoc8 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), myroot); + return encodedDoc8; } - public static XDocument BuildPostData2(XElement channels, XElement roomlist, DateTime arrival, DateTime departure, XElement offerdetails, XElement hoteldetails, XElement type, int service, string lang, string source, string version, string mssuser, string msspswd) + public static XDocument BuildPostData2( + XElement channels, + XElement roomlist, + DateTime arrival, + DateTime departure, + XElement offerdetails, + XElement hoteldetails, + XElement type, + int service, + string lang, + string source, + string version, + string mssuser, + string msspswd + ) { - XElement myroot = - new XElement("root", + XElement myroot = new XElement( + "root", new XElement("version", version + ".0"), - new XElement("header", - new XElement("credentials", + new XElement( + "header", + new XElement( + "credentials", new XElement("user", mssuser), new XElement("password", msspswd), new XElement("source", source) - ), + ), new XElement("method", "getHotelList"), - new XElement("paging", - new XElement("start", "0"), - new XElement("limit", "0") - )), - new XElement("request", - new XElement("search", + new XElement("paging", new XElement("start", "0"), new XElement("limit", "0")) + ), + new XElement( + "request", + new XElement( + "search", new XElement("lang", lang), - new XElement("search_offer", + new XElement( + "search_offer", channels.Elements("channel_id"), new XElement("arrival", String.Format("{0:yyyy-MM-dd}", arrival)), new XElement("departure", String.Format("{0:yyyy-MM-dd}", departure)), new XElement("service", service), roomlist.Elements("room"), type - ) - ), - new XElement("options", - offerdetails, - hoteldetails - ), - new XElement("order"), - new XElement("logging", - new XElement("step") - ) - ) - ); - - XDocument encodedDoc8 = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - myroot + ) + ), + new XElement("options", offerdetails, hoteldetails), + new XElement("order"), + new XElement("logging", new XElement("step")) + ) ); + XDocument encodedDoc8 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), myroot); + return encodedDoc8; } - public static XDocument BuildSpecialPostData(XElement offerid, XElement roomlist, DateTime arrival, DateTime departure, XElement specialdetails, int typ, int service, string lang, string source, string version, string mssuser, string msspswd) + public static XDocument BuildSpecialPostData( + XElement offerid, + XElement roomlist, + DateTime arrival, + DateTime departure, + XElement specialdetails, + int typ, + int service, + string lang, + string source, + string version, + string mssuser, + string msspswd + ) { - XElement myroot = - new XElement("root", + XElement myroot = new XElement( + "root", new XElement("version", version + ".0"), - new XElement("header", - new XElement("credentials", + new XElement( + "header", + new XElement( + "credentials", new XElement("user", mssuser), new XElement("password", msspswd), new XElement("source", source) - ), + ), new XElement("method", "getSpecialList"), - new XElement("paging", - new XElement("start", "0"), - new XElement("limit", "0") - )), - new XElement("request", - new XElement("search", + new XElement("paging", new XElement("start", "0"), new XElement("limit", "0")) + ), + new XElement( + "request", + new XElement( + "search", new XElement("lang", lang), - new XElement("search_special", + new XElement( + "search_special", offerid.Elements("offer_id"), new XElement("date_from", String.Format("{0:yyyy-MM-dd}", arrival)), new XElement("date_to", String.Format("{0:yyyy-MM-dd}", departure)), new XElement("typ", typ), - new XElement("validity", + new XElement( + "validity", new XElement("valid", "0"), new XElement("offers", "0"), new XElement("service", service), roomlist.Elements("room") - ) - ) - ), - new XElement("options", - specialdetails - ), - new XElement("order", - new XElement("field", "date"), - new XElement("dir", "asc") ) ) - ); - - XDocument encodedDoc8 = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - myroot + ), + new XElement("options", specialdetails), + new XElement("order", new XElement("field", "date"), new XElement("dir", "asc")) + ) ); + XDocument encodedDoc8 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), myroot); + return encodedDoc8; } - public static XDocument BuildRoomlistPostData(XElement roomdetails, string hotelid, string idofchannel, string lang, string source, string version, string mssuser, string msspswd) + public static XDocument BuildRoomlistPostData( + XElement roomdetails, + string hotelid, + string idofchannel, + string lang, + string source, + string version, + string mssuser, + string msspswd + ) { - XElement myroot = - new XElement("root", + XElement myroot = new XElement( + "root", new XElement("version", version + ".0"), - new XElement("header", - new XElement("credentials", + new XElement( + "header", + new XElement( + "credentials", new XElement("user", mssuser), new XElement("password", msspswd), new XElement("source", source) - ), + ), new XElement("method", "getRoomList"), - new XElement("paging", - new XElement("start", "0"), - new XElement("limit", "0") - )), - new XElement("request", - new XElement("search", + new XElement("paging", new XElement("start", "0"), new XElement("limit", "0")) + ), + new XElement( + "request", + new XElement( + "search", new XElement("lang", lang), new XElement("id", hotelid), new XElement("id_ofchannel", idofchannel) - ), - new XElement("options", - roomdetails - ) - ) - ); - - XDocument encodedDoc8 = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - myroot + ), + new XElement("options", roomdetails) + ) ); + XDocument encodedDoc8 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), myroot); + return encodedDoc8; } //Premium includiert - public static XDocument BuildSpecialPostDatawithPremium(XElement offerid, XElement roomlist, DateTime arrival, DateTime departure, XElement specialdetails, int typ, int premium, int service, string lang, string source, string version, string mssuser, string msspswd) + public static XDocument BuildSpecialPostDatawithPremium( + XElement offerid, + XElement roomlist, + DateTime arrival, + DateTime departure, + XElement specialdetails, + int typ, + int premium, + int service, + string lang, + string source, + string version, + string mssuser, + string msspswd + ) { - XElement myroot = - new XElement("root", + XElement myroot = new XElement( + "root", new XElement("version", version + ".0"), - new XElement("header", - new XElement("credentials", + new XElement( + "header", + new XElement( + "credentials", new XElement("user", mssuser), new XElement("password", msspswd), new XElement("source", source) - ), + ), new XElement("method", "getSpecialList"), - new XElement("paging", - new XElement("start", "0"), - new XElement("limit", "0") - )), - new XElement("request", - new XElement("search", + new XElement("paging", new XElement("start", "0"), new XElement("limit", "0")) + ), + new XElement( + "request", + new XElement( + "search", new XElement("lang", lang), - new XElement("search_special", + new XElement( + "search_special", offerid.Elements("offer_id"), new XElement("date_from", String.Format("{0:yyyy-MM-dd}", arrival)), new XElement("date_to", String.Format("{0:yyyy-MM-dd}", departure)), new XElement("typ", typ), new XElement("premium", premium), - new XElement("validity", + new XElement( + "validity", new XElement("valid", "0"), new XElement("offers", "0"), new XElement("service", service), roomlist.Elements("room") - ) - ) - ), - new XElement("options", - specialdetails - ), - new XElement("order", - new XElement("field", "date"), - new XElement("dir", "asc") ) ) - ); - - XDocument encodedDoc8 = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - myroot + ), + new XElement("options", specialdetails), + new XElement("order", new XElement("field", "date"), new XElement("dir", "asc")) + ) ); + XDocument encodedDoc8 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), myroot); + return encodedDoc8; } - public static XDocument BuildSpecialPostDataCheckAvailability(XElement idlist, XElement offerid, XElement roomlist, DateTime arrival, DateTime departure, XElement specialdetails, XElement hoteldetails, int typ, int service, string lang, string source, string version, string mssuser, string msspswd) + public static XDocument BuildSpecialPostDataCheckAvailability( + XElement idlist, + XElement offerid, + XElement roomlist, + DateTime arrival, + DateTime departure, + XElement specialdetails, + XElement hoteldetails, + int typ, + int service, + string lang, + string source, + string version, + string mssuser, + string msspswd + ) { - XElement myroot = - new XElement("root", + XElement myroot = new XElement( + "root", new XElement("version", version + ".0"), - new XElement("header", - new XElement("credentials", + new XElement( + "header", + new XElement( + "credentials", new XElement("user", mssuser), new XElement("password", msspswd), new XElement("source", source) - ), + ), new XElement("method", "getSpecialList"), - new XElement("paging", - new XElement("start", "0"), - new XElement("limit", "0") - ), new XElement("result_id")), - new XElement("request", - new XElement("search", + new XElement("paging", new XElement("start", "0"), new XElement("limit", "0")), + new XElement("result_id") + ), + new XElement( + "request", + new XElement( + "search", new XElement("lang", lang), idlist.Elements("id"), //new XElement("id_ofchannel", "lts"), - new XElement("search_special", + new XElement( + "search_special", //new XElement("date_from", String.Format("{0:yyyy-MM-dd}", arrival)), //new XElement("date_to", String.Format("{0:yyyy-MM-dd}", departure)), offerid.Elements("offer_id"), new XElement("typ", typ), - new XElement("validity", + new XElement( + "validity", new XElement("valid", "0"), new XElement("offers", "1"), new XElement("arrival", String.Format("{0:yyyy-MM-dd}", arrival)), - new XElement("departure", String.Format("{0:yyyy-MM-dd}", departure)), + new XElement( + "departure", + String.Format("{0:yyyy-MM-dd}", departure) + ), new XElement("service", service), roomlist.Elements("room") - ) - ) - ), - new XElement("options", - specialdetails, - hoteldetails - ), - new XElement("order", - new XElement("field", "date"), - new XElement("dir", "asc") ) ) - ); - - XDocument encodedDoc8 = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - myroot + ), + new XElement("options", specialdetails, hoteldetails), + new XElement("order", new XElement("field", "date"), new XElement("dir", "asc")) + ) ); + XDocument encodedDoc8 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), myroot); + return encodedDoc8; } //Premium includiert - public static XDocument BuildSpecialPostDataCheckAvailabilitywithPremium(XElement idlist, XElement offerid, XElement roomlist, DateTime arrival, DateTime departure, XElement specialdetails, XElement hoteldetails, int typ, int premium, int service, string lang, string source, string version, string mssuser, string msspswd) + public static XDocument BuildSpecialPostDataCheckAvailabilitywithPremium( + XElement idlist, + XElement offerid, + XElement roomlist, + DateTime arrival, + DateTime departure, + XElement specialdetails, + XElement hoteldetails, + int typ, + int premium, + int service, + string lang, + string source, + string version, + string mssuser, + string msspswd + ) { - XElement myroot = - new XElement("root", + XElement myroot = new XElement( + "root", new XElement("version", version + ".0"), - new XElement("header", - new XElement("credentials", + new XElement( + "header", + new XElement( + "credentials", new XElement("user", mssuser), new XElement("password", msspswd), new XElement("source", source) - ), + ), new XElement("method", "getSpecialList"), - new XElement("paging", - new XElement("start", "0"), - new XElement("limit", "0") - ), new XElement("result_id")), - new XElement("request", - new XElement("search", + new XElement("paging", new XElement("start", "0"), new XElement("limit", "0")), + new XElement("result_id") + ), + new XElement( + "request", + new XElement( + "search", new XElement("lang", lang), idlist.Elements("id"), //new XElement("id_ofchannel", "lts"), - new XElement("search_special", + new XElement( + "search_special", //new XElement("date_from", String.Format("{0:yyyy-MM-dd}", arrival)), //new XElement("date_to", String.Format("{0:yyyy-MM-dd}", departure)), offerid.Elements("offer_id"), new XElement("typ", typ), new XElement("premium", premium), - new XElement("validity", + new XElement( + "validity", new XElement("valid", "0"), new XElement("offers", "1"), new XElement("arrival", String.Format("{0:yyyy-MM-dd}", arrival)), - new XElement("departure", String.Format("{0:yyyy-MM-dd}", departure)), + new XElement( + "departure", + String.Format("{0:yyyy-MM-dd}", departure) + ), new XElement("service", service), roomlist.Elements("room") - ) - ) - ), - new XElement("options", - specialdetails, - hoteldetails - ), - new XElement("order", - new XElement("field", "date"), - new XElement("dir", "asc") ) ) - ); - - XDocument encodedDoc8 = new XDocument( - new XDeclaration("1.0", "utf-8", "yes"), - myroot + ), + new XElement("options", specialdetails, hoteldetails), + new XElement("order", new XElement("field", "date"), new XElement("dir", "asc")) + ) ); + XDocument encodedDoc8 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), myroot); + return encodedDoc8; } - public static XElement BuildRoomData(List myroompropertys) { XElement myroomlist = new XElement("roomlist"); @@ -489,7 +613,7 @@ public static XElement BuildRoomData(List myroompropertys) roomroot.Add( new XElement("room_seq", room.RoomSeq), new XElement("room_type", room.RoomType) - ); + ); myroomlist.Add(roomroot); } @@ -528,7 +652,6 @@ public static XElement BuildType(string typ) return typxelement; } - public static XElement BuildChannelList(List channels) { XElement mychannellist = new XElement("channellist"); diff --git a/MSS/ParseMssResponse.cs b/MSS/ParseMssResponse.cs index 9ad3e2686..c805eae97 100644 --- a/MSS/ParseMssResponse.cs +++ b/MSS/ParseMssResponse.cs @@ -11,49 +11,99 @@ namespace MSS { public class ParseMssResponse { - public static MssResult ParsemyMssResponse(string lang, string servicecode, XDocument mssresponse, List myroompersons, string requestsource, string version) + public static MssResult ParsemyMssResponse( + string lang, + string servicecode, + XDocument mssresponse, + List myroompersons, + string requestsource, + string version + ) { try { var resultid = mssresponse.Root.Element("header").Element("result_id").Value; - var myresult = mssresponse.Root.Elements("root").Elements("result").Elements("hotel"); - - return ResponseParser(myresult, servicecode, myroompersons, resultid, requestsource, lang, version); + var myresult = mssresponse.Root + .Elements("root") + .Elements("result") + .Elements("hotel"); + + return ResponseParser( + myresult, + servicecode, + myroompersons, + resultid, + requestsource, + lang, + version + ); } catch (Exception) { return null; } - } - public static MssResult ParsemyMssResponse(string lang, string servicecode, XDocument mssresponse, List A0Rids, List myroompersons, string requestsource, string version) + public static MssResult ParsemyMssResponse( + string lang, + string servicecode, + XDocument mssresponse, + List A0Rids, + List myroompersons, + string requestsource, + string version + ) { try { - foreach (XElement mytime in mssresponse.Root.Elements("root").Elements("header").Elements("time")) + foreach ( + XElement mytime in mssresponse.Root + .Elements("root") + .Elements("header") + .Elements("time") + ) { Console.WriteLine("Requestdauer: " + mytime.Value); } var resultid = mssresponse.Root.Element("header").Element("result_id").Value; - var myresult = mssresponse.Root.Elements("root").Elements("result").Elements("hotel").Where - (x => A0Rids.Contains(x.Element("id_lts").Value.ToLower()) && x.Elements("channel").Count() > 0); - - return ResponseParser(myresult, servicecode, myroompersons, resultid, requestsource, lang, version); - - + var myresult = mssresponse.Root + .Elements("root") + .Elements("result") + .Elements("hotel") + .Where( + x => + A0Rids.Contains(x.Element("id_lts").Value.ToLower()) + && x.Elements("channel").Count() > 0 + ); + + return ResponseParser( + myresult, + servicecode, + myroompersons, + resultid, + requestsource, + lang, + version + ); } catch (Exception) { return null; } - } - public static MssResult ParsemyMssResponse(string lang, string servicecode, XElement mssresponse, List A0Rids, List myroompersons, string requestsource, string version) + public static MssResult ParsemyMssResponse( + string lang, + string servicecode, + XElement mssresponse, + List A0Rids, + List myroompersons, + string requestsource, + string version + ) { try { @@ -64,19 +114,40 @@ public static MssResult ParsemyMssResponse(string lang, string servicecode, XEle var resultid = mssresponse.Element("header").Element("result_id").Value; - var myresult = mssresponse.Elements("result").Elements("hotel").Where - (x => A0Rids.Contains(x.Element("id_lts").Value.ToUpper()) && x.Elements("channel").Count() > 0); - - return ResponseParser(myresult, servicecode, myroompersons, resultid, requestsource, lang, version); + var myresult = mssresponse + .Elements("result") + .Elements("hotel") + .Where( + x => + A0Rids.Contains(x.Element("id_lts").Value.ToUpper()) + && x.Elements("channel").Count() > 0 + ); + + return ResponseParser( + myresult, + servicecode, + myroompersons, + resultid, + requestsource, + lang, + version + ); } catch (Exception) { return null; } - } - public static MssResult ResponseParser(IEnumerable myresult, string servicecode, List roompersons, string resultid, string requestsource, string lang, string version) + public static MssResult ResponseParser( + IEnumerable myresult, + string servicecode, + List roompersons, + string resultid, + string requestsource, + string lang, + string version + ) { try { @@ -89,7 +160,9 @@ public static MssResult ResponseParser(IEnumerable myresult, string se List poslist = myresult.Elements("pos").Elements("id_pos").ToList(); - foreach (var myhotelresult in myresult.Where(x => x.Elements("channel").Count() > 0)) + foreach ( + var myhotelresult in myresult.Where(x => x.Elements("channel").Count() > 0) + ) { //Nur wenn ein Angebot eines Channels vorhanden ist if (myhotelresult.Elements("channel").Count() > 0) @@ -121,14 +194,35 @@ public static MssResult ResponseParser(IEnumerable myresult, string se var myonlinepayment = myhotelresult.Element("online_payment"); if (myonlinepayment != null) { - myresp.OnlinepaymentMethods = myonlinepayment.Element("methods") != null ? myonlinepayment.Element("methods").Value : ""; - myresp.OnlinepaymentPrepayment = myonlinepayment.Element("prepayment") != null ? myonlinepayment.Element("prepayment").Value : ""; - myresp.OnlinepaymentCCards = myonlinepayment.Element("ccards") != null ? myonlinepayment.Element("ccards").Value : ""; + myresp.OnlinepaymentMethods = + myonlinepayment.Element("methods") != null + ? myonlinepayment.Element("methods").Value + : ""; + myresp.OnlinepaymentPrepayment = + myonlinepayment.Element("prepayment") != null + ? myonlinepayment.Element("prepayment").Value + : ""; + myresp.OnlinepaymentCCards = + myonlinepayment.Element("ccards") != null + ? myonlinepayment.Element("ccards").Value + : ""; } if (myresp.ChannelID == "pos") { - string posid = poslist.Where(x => x.Value != "sinfo" && x.Value != "bok" && x.Value != "esy" && x.Value != "lts" && x.Value != "htl" && x.Value != "hgv" && x.Value != "exp").FirstOrDefault().Value; + string posid = poslist + .Where( + x => + x.Value != "sinfo" + && x.Value != "bok" + && x.Value != "esy" + && x.Value != "lts" + && x.Value != "htl" + && x.Value != "hgv" + && x.Value != "exp" + ) + .FirstOrDefault() + .Value; switch (posid) { @@ -165,15 +259,17 @@ public static MssResult ResponseParser(IEnumerable myresult, string se myresp.ChannelID = "valgardenait"; break; } - } - if (mychanneloffer.Element("channel_link") != null) myresp.Channellink = mychanneloffer.Element("channel_link").Value; //Specialcase build the bookinglink for Booking Südtirol - if (myresp.ChannelID == "esy" || myresp.ChannelID == "lts" || myresp.ChannelID == "hgv") + if ( + myresp.ChannelID == "esy" + || myresp.ChannelID == "lts" + || myresp.ChannelID == "hgv" + ) { //http://www.bookingsuedtirol.com/index.php?action=view&src=" + + "&id=10096&result_id=ec373a3d116ce01806a1c5f9f110c16b&room_qty_0=1&room_occ_0=18&room_rid_0=3124 //http://www.bookingsuedtirol.com/index.php?action=view&src=sinfo&id=10096&result_id=fba3a11c1a9cf7c9ce636e10188507bd&room_qty_0=1&room_occ_0=18&room_rid_0=3124&room_qty_1=1&room_occ_1=18,18&room_rid_1=3125 @@ -186,7 +282,8 @@ public static MssResult ResponseParser(IEnumerable myresult, string se string person = String.Join(",", room.Person.ToArray()); roomstring = roomstring + "room_qty_" + roomcounter + "=1&"; - roomstring = roomstring + "room_occ_" + roomcounter + "=" + person + "&"; + roomstring = + roomstring + "room_occ_" + roomcounter + "=" + person + "&"; roomcounter++; } @@ -195,15 +292,33 @@ public static MssResult ResponseParser(IEnumerable myresult, string se if (lang.ToLower() == "it") bookingurl = "https://www.bookingaltoadige.com"; - else if (lang.ToLower() == "en" || lang.ToLower() == "nl" || lang.ToLower() == "fr" || lang.ToLower() == "ru" || lang.ToLower() == "pl" || lang.ToLower() == "cs") + else if ( + lang.ToLower() == "en" + || lang.ToLower() == "nl" + || lang.ToLower() == "fr" + || lang.ToLower() == "ru" + || lang.ToLower() == "pl" + || lang.ToLower() == "cs" + ) bookingurl = "https://www.bookingsouthtyrol.com"; - string bookinglink = bookingurl + "/index.php?action=view&src=" + requestsource + "&id=" + myresp.HotelId + "&result_id=" + resultid + "&" + roomstring; - - myresp.Channellink = bookinglink.Substring(0, bookinglink.Length - 1); + string bookinglink = + bookingurl + + "/index.php?action=view&src=" + + requestsource + + "&id=" + + myresp.HotelId + + "&result_id=" + + resultid + + "&" + + roomstring; + + myresp.Channellink = bookinglink.Substring( + 0, + bookinglink.Length - 1 + ); } - var myofferdescription = mychanneloffer.Element("offer_description"); if (myofferdescription != null) @@ -213,18 +328,38 @@ public static MssResult ResponseParser(IEnumerable myresult, string se { int offershow = 0; if (myofferdetails.Element("offer_gid") != null) - myresp.OfferGid = !String.IsNullOrEmpty(myofferdetails.Element("offer_gid").Value) ? myofferdetails.Element("offer_gid").Value : ""; + myresp.OfferGid = !String.IsNullOrEmpty( + myofferdetails.Element("offer_gid").Value + ) + ? myofferdetails.Element("offer_gid").Value + : ""; if (myofferdetails.Element("offer_id") != null) - myresp.OfferId = !String.IsNullOrEmpty(myofferdetails.Element("offer_id").Value) ? myofferdetails.Element("offer_id").Value : ""; + myresp.OfferId = !String.IsNullOrEmpty( + myofferdetails.Element("offer_id").Value + ) + ? myofferdetails.Element("offer_id").Value + : ""; if (myofferdetails.Element("offer_show") != null) - myresp.OfferShow = Int32.TryParse(myofferdetails.Element("offer_show").Value, out offershow) ? offershow : 0; + myresp.OfferShow = Int32.TryParse( + myofferdetails.Element("offer_show").Value, + out offershow + ) + ? offershow + : 0; int offertyp = 0; if (myofferdetails.Element("offer_typ") != null) - myresp.OfferTyp = Int32.TryParse(myofferdetails.Element("offer_typ").Value, out offertyp) ? offertyp : 0; + myresp.OfferTyp = Int32.TryParse( + myofferdetails.Element("offer_typ").Value, + out offertyp + ) + ? offertyp + : 0; } } - var myroomdetails = mychanneloffer.Element("room_price").Elements("price"); + var myroomdetails = mychanneloffer + .Element("room_price") + .Elements("price"); foreach (var myroomdetail in myroomdetails) { RoomDetails myroom = new RoomDetails(); @@ -239,36 +374,96 @@ public static MssResult ResponseParser(IEnumerable myresult, string se int roomseq = 0; if (myroomdetail.Element("room_seq") != null) - myroom.RoomSeq = Int32.TryParse(myroomdetail.Element("room_seq").Value, out roomseq) ? roomseq : 0; - + myroom.RoomSeq = Int32.TryParse( + myroomdetail.Element("room_seq").Value, + out roomseq + ) + ? roomseq + : 0; //NEU MSS VERSION 2.0 if (version == "2") { - string cancelpolicyid = myroomdetail.Element("cancel_policy_id") != null ? myroomdetail.Element("cancel_policy_id").Value : null; - string paymenttermid = myroomdetail.Element("cancel_policy_id") != null ? myroomdetail.Element("payment_term_id").Value : null; - + string cancelpolicyid = + myroomdetail.Element("cancel_policy_id") != null + ? myroomdetail.Element("cancel_policy_id").Value + : null; + string paymenttermid = + myroomdetail.Element("cancel_policy_id") != null + ? myroomdetail.Element("payment_term_id").Value + : null; if (!String.IsNullOrEmpty(paymenttermid)) { - var mypaymentterm = mychanneloffer.Element("payment_terms").Elements("payment_term").Where(x => x.Element("id").Value == paymenttermid).FirstOrDefault(); + var mypaymentterm = mychanneloffer + .Element("payment_terms") + .Elements("payment_term") + .Where(x => x.Element("id").Value == paymenttermid) + .FirstOrDefault(); if (mypaymentterm != null) { PaymentTerm paymentterm = new PaymentTerm(); - paymentterm.Id = mypaymentterm.Element("id") != null ? mypaymentterm.Element("id").Value : ""; - paymentterm.Methods = mypaymentterm.Element("methods") != null ? Convert.ToInt32(mypaymentterm.Element("methods").Value) : 0; - paymentterm.Prepayment = mypaymentterm.Element("prepayment") != null ? Convert.ToInt32(mypaymentterm.Element("prepayment").Value) : 0; - paymentterm.Ccards = mypaymentterm.Element("ccards") != null ? Convert.ToInt32(mypaymentterm.Element("ccards").Value) : 0; - paymentterm.Description = mypaymentterm.Element("description") != null ? mypaymentterm.Element("description").Value : ""; - paymentterm.Priority = mypaymentterm.Element("priority") != null ? Convert.ToInt32(mypaymentterm.Element("priority").Value) : 0; + paymentterm.Id = + mypaymentterm.Element("id") != null + ? mypaymentterm.Element("id").Value + : ""; + paymentterm.Methods = + mypaymentterm.Element("methods") != null + ? Convert.ToInt32( + mypaymentterm.Element("methods").Value + ) + : 0; + paymentterm.Prepayment = + mypaymentterm.Element("prepayment") != null + ? Convert.ToInt32( + mypaymentterm.Element("prepayment").Value + ) + : 0; + paymentterm.Ccards = + mypaymentterm.Element("ccards") != null + ? Convert.ToInt32( + mypaymentterm.Element("ccards").Value + ) + : 0; + paymentterm.Description = + mypaymentterm.Element("description") != null + ? mypaymentterm.Element("description").Value + : ""; + paymentterm.Priority = + mypaymentterm.Element("priority") != null + ? Convert.ToInt32( + mypaymentterm.Element("priority").Value + ) + : 0; if (mypaymentterm.Element("bank") != null) { Bank bank = new Bank(); - bank.Name = mypaymentterm.Element("bank").Element("name") != null ? mypaymentterm.Element("bank").Element("name").Value : ""; - bank.Iban = mypaymentterm.Element("bank").Element("iban") != null ? mypaymentterm.Element("bank").Element("iban").Value : ""; - bank.Swift = mypaymentterm.Element("bank").Element("swift") != null ? mypaymentterm.Element("bank").Element("swift").Value : ""; + bank.Name = + mypaymentterm.Element("bank").Element("name") + != null + ? mypaymentterm + .Element("bank") + .Element("name") + .Value + : ""; + bank.Iban = + mypaymentterm.Element("bank").Element("iban") + != null + ? mypaymentterm + .Element("bank") + .Element("iban") + .Value + : ""; + bank.Swift = + mypaymentterm.Element("bank").Element("swift") + != null + ? mypaymentterm + .Element("bank") + .Element("swift") + .Value + : ""; paymentterm.Bank = bank; } @@ -278,53 +473,90 @@ public static MssResult ResponseParser(IEnumerable myresult, string se } if (!String.IsNullOrEmpty(cancelpolicyid)) { - var mycancelpolicy = mychanneloffer.Element("cancel_policies").Elements("cancel_policy").Where(x => x.Element("id").Value == cancelpolicyid).FirstOrDefault(); + var mycancelpolicy = mychanneloffer + .Element("cancel_policies") + .Elements("cancel_policy") + .Where(x => x.Element("id").Value == cancelpolicyid) + .FirstOrDefault(); if (mycancelpolicy != null) { CancelPolicy cancelpolicy = new CancelPolicy(); - cancelpolicy.Id = mycancelpolicy.Element("id") != null ? mycancelpolicy.Element("id").Value : ""; + cancelpolicy.Id = + mycancelpolicy.Element("id") != null + ? mycancelpolicy.Element("id").Value + : ""; if (mycancelpolicy.Element("refundable") != null) - cancelpolicy.Refundable = Convert.ToInt32(mycancelpolicy.Element("refundable").Value); + cancelpolicy.Refundable = Convert.ToInt32( + mycancelpolicy.Element("refundable").Value + ); else cancelpolicy.Refundable = null; if (mycancelpolicy.Element("refundable_until") != null) { - if (!String.IsNullOrEmpty(mycancelpolicy.Element("refundable_until").Value)) - cancelpolicy.RefundableUntil = Convert.ToDateTime(mycancelpolicy.Element("refundable_until").Value); + if ( + !String.IsNullOrEmpty( + mycancelpolicy + .Element("refundable_until") + .Value + ) + ) + cancelpolicy.RefundableUntil = + Convert.ToDateTime( + mycancelpolicy + .Element("refundable_until") + .Value + ); else cancelpolicy.RefundableUntil = null; } else cancelpolicy.RefundableUntil = null; - cancelpolicy.Description = mycancelpolicy.Element("description") != null ? mycancelpolicy.Element("description").Value : ""; + cancelpolicy.Description = + mycancelpolicy.Element("description") != null + ? mycancelpolicy.Element("description").Value + : ""; if (mycancelpolicy.Element("penalties") != null) { cancelpolicy.Penalties = new List(); - foreach (var penalty in mycancelpolicy.Element("penalties").Elements("penalty")) + foreach ( + var penalty in mycancelpolicy + .Element("penalties") + .Elements("penalty") + ) { Penalty mypenalty = new Penalty(); if (penalty.Element("percent") != null) - mypenalty.Percent = Convert.ToInt32(penalty.Element("percent").Value); + mypenalty.Percent = Convert.ToInt32( + penalty.Element("percent").Value + ); else mypenalty.Percent = null; if (penalty.Element("datefrom") != null) - if (String.IsNullOrEmpty(penalty.Element("datefrom").Value)) + if ( + String.IsNullOrEmpty( + penalty.Element("datefrom").Value + ) + ) mypenalty.Datefrom = null; else - Convert.ToDateTime(penalty.Element("datefrom").Value); + Convert.ToDateTime( + penalty.Element("datefrom").Value + ); else mypenalty.Datefrom = null; if (penalty.Element("daysarrival") != null) - mypenalty.Daysarrival = Convert.ToInt32(penalty.Element("daysarrival").Value); + mypenalty.Daysarrival = Convert.ToInt32( + penalty.Element("daysarrival").Value + ); else mypenalty.Daysarrival = null; @@ -335,10 +567,8 @@ public static MssResult ResponseParser(IEnumerable myresult, string se myroom.CancelPolicy = cancelpolicy; } } - } - //ENDE NEU VERSION 2.0 //TODO Test and ensure functionality @@ -347,52 +577,147 @@ public static MssResult ResponseParser(IEnumerable myresult, string se { if (requestedservice == "price_ws") { - double mycurrentpricews = myroomdetail.Element("price_total").Element(requestedservice) != null ? Convert.ToDouble(myroomdetail.Element("price_total").Element(requestedservice).Value, CultureInfo.InvariantCulture.NumberFormat) : 0; + double mycurrentpricews = + myroomdetail + .Element("price_total") + .Element(requestedservice) != null + ? Convert.ToDouble( + myroomdetail + .Element("price_total") + .Element(requestedservice) + .Value, + CultureInfo.InvariantCulture.NumberFormat + ) + : 0; myroom.Price_ws = mycurrentpricews; if (mycurrentpricews > 0) { - cheapestofferlist_ws.Add(new CheapestOffer() { RoomId = myroom.RoomId, RoomSeq = (int)myroom.RoomSeq, Price = mycurrentpricews, RoomFree = 0 }); + cheapestofferlist_ws.Add( + new CheapestOffer() + { + RoomId = myroom.RoomId, + RoomSeq = (int)myroom.RoomSeq, + Price = mycurrentpricews, + RoomFree = 0 + } + ); } } if (requestedservice == "price_bb") { - double mycurrentpricebb = myroomdetail.Element("price_total").Element(requestedservice) != null ? Convert.ToDouble(myroomdetail.Element("price_total").Element(requestedservice).Value, CultureInfo.InvariantCulture.NumberFormat) : 0; + double mycurrentpricebb = + myroomdetail + .Element("price_total") + .Element(requestedservice) != null + ? Convert.ToDouble( + myroomdetail + .Element("price_total") + .Element(requestedservice) + .Value, + CultureInfo.InvariantCulture.NumberFormat + ) + : 0; myroom.Price_bb = mycurrentpricebb; if (mycurrentpricebb > 0) { - cheapestofferlist_bb.Add(new CheapestOffer() { RoomId = myroom.RoomId, RoomSeq = (int)myroom.RoomSeq, Price = mycurrentpricebb, RoomFree = 0 }); + cheapestofferlist_bb.Add( + new CheapestOffer() + { + RoomId = myroom.RoomId, + RoomSeq = (int)myroom.RoomSeq, + Price = mycurrentpricebb, + RoomFree = 0 + } + ); } } if (requestedservice == "price_hb") { - double mycurrentpricehb = myroomdetail.Element("price_total").Element(requestedservice) != null ? Convert.ToDouble(myroomdetail.Element("price_total").Element(requestedservice).Value, CultureInfo.InvariantCulture.NumberFormat) : 0; + double mycurrentpricehb = + myroomdetail + .Element("price_total") + .Element(requestedservice) != null + ? Convert.ToDouble( + myroomdetail + .Element("price_total") + .Element(requestedservice) + .Value, + CultureInfo.InvariantCulture.NumberFormat + ) + : 0; myroom.Price_hb = mycurrentpricehb; if (mycurrentpricehb > 0) { - cheapestofferlist_hb.Add(new CheapestOffer() { RoomId = myroom.RoomId, RoomSeq = (int)myroom.RoomSeq, Price = mycurrentpricehb, RoomFree = 0 }); + cheapestofferlist_hb.Add( + new CheapestOffer() + { + RoomId = myroom.RoomId, + RoomSeq = (int)myroom.RoomSeq, + Price = mycurrentpricehb, + RoomFree = 0 + } + ); } } if (requestedservice == "price_fb") { - double mycurrentpricefb = myroomdetail.Element("price_total").Element(requestedservice) != null ? Convert.ToDouble(myroomdetail.Element("price_total").Element(requestedservice).Value, CultureInfo.InvariantCulture.NumberFormat) : 0; + double mycurrentpricefb = + myroomdetail + .Element("price_total") + .Element(requestedservice) != null + ? Convert.ToDouble( + myroomdetail + .Element("price_total") + .Element(requestedservice) + .Value, + CultureInfo.InvariantCulture.NumberFormat + ) + : 0; myroom.Price_fb = mycurrentpricefb; if (mycurrentpricefb > 0) { - cheapestofferlist_fb.Add(new CheapestOffer() { RoomId = myroom.RoomId, RoomSeq = (int)myroom.RoomSeq, Price = mycurrentpricefb, RoomFree = 0 }); + cheapestofferlist_fb.Add( + new CheapestOffer() + { + RoomId = myroom.RoomId, + RoomSeq = (int)myroom.RoomSeq, + Price = mycurrentpricefb, + RoomFree = 0 + } + ); } } if (requestedservice == "price_ai") { - double mycurrentpriceai = myroomdetail.Element("price_total").Element(requestedservice) != null ? Convert.ToDouble(myroomdetail.Element("price_total").Element(requestedservice).Value, CultureInfo.InvariantCulture.NumberFormat) : 0; + double mycurrentpriceai = + myroomdetail + .Element("price_total") + .Element(requestedservice) != null + ? Convert.ToDouble( + myroomdetail + .Element("price_total") + .Element(requestedservice) + .Value, + CultureInfo.InvariantCulture.NumberFormat + ) + : 0; myroom.Price_ai = mycurrentpriceai; if (mycurrentpriceai > 0) - { - cheapestofferlist_ai.Add(new CheapestOffer() { RoomId = myroom.RoomId, RoomSeq = (int)myroom.RoomSeq, Price = mycurrentpriceai, RoomFree = 0 }); + { + cheapestofferlist_ai.Add( + new CheapestOffer() + { + RoomId = myroom.RoomId, + RoomSeq = (int)myroom.RoomSeq, + Price = mycurrentpriceai, + RoomFree = 0 + } + ); } } } @@ -400,21 +725,54 @@ public static MssResult ResponseParser(IEnumerable myresult, string se //Spezial falls mehrere Services angefragt werden if (splittedservice.Count == 1) { - double mycurrentprice = !String.IsNullOrEmpty(myroomdetail.Element("price_total").Element(servicecode).Value) ? Convert.ToDouble(myroomdetail.Element("price_total").Element(servicecode).Value, CultureInfo.InvariantCulture.NumberFormat) : 0; - - cheapestofferlist.Add(new CheapestOffer() { RoomId = myroom.RoomId, RoomSeq = (int)myroom.RoomSeq, Price = mycurrentprice, RoomFree = 0 }); + double mycurrentprice = !String.IsNullOrEmpty( + myroomdetail + .Element("price_total") + .Element(servicecode) + .Value + ) + ? Convert.ToDouble( + myroomdetail + .Element("price_total") + .Element(servicecode) + .Value, + CultureInfo.InvariantCulture.NumberFormat + ) + : 0; + + cheapestofferlist.Add( + new CheapestOffer() + { + RoomId = myroom.RoomId, + RoomSeq = (int)myroom.RoomSeq, + Price = mycurrentprice, + RoomFree = 0 + } + ); myroom.TotalPrice = mycurrentprice; - myroom.TotalPriceString = String.Format(culturede, "{0:0,0.00}", mycurrentprice); + myroom.TotalPriceString = String.Format( + culturede, + "{0:0,0.00}", + mycurrentprice + ); } else { //billigsten preis suchen TODO! myroom.TotalPrice = 0; - myroom.TotalPriceString = String.Format(culturede, "{0:0,0.00}", 0); + myroom.TotalPriceString = String.Format( + culturede, + "{0:0,0.00}", + 0 + ); } - var myroomdesc = mychanneloffer.Element("room_description").Elements("room").Where(x => x.Element("room_id").Value == roomid).FirstOrDefault(); + var myroomdesc = mychanneloffer + .Element("room_description") + .Elements("room") + .Where(x => x.Element("room_id").Value == roomid) + .FirstOrDefault(); if (myroomdesc != null) { if (myroomdesc.Element("title") != null) @@ -422,36 +780,67 @@ public static MssResult ResponseParser(IEnumerable myresult, string se if (myroomdesc.Element("description") != null) myroom.Roomdesc = myroomdesc.Element("description").Value; - if (myroomdesc.Element("room_type") != null) - myroom.Roomtype = !String.IsNullOrEmpty(myroomdesc.Element("room_type").Value) ? Convert.ToInt32(myroomdesc.Element("room_type").Value) : 0; + myroom.Roomtype = !String.IsNullOrEmpty( + myroomdesc.Element("room_type").Value + ) + ? Convert.ToInt32(myroomdesc.Element("room_type").Value) + : 0; if (myroomdesc.Element("room_free") != null) - myroom.Roomfree = !String.IsNullOrEmpty(myroomdesc.Element("room_free").Value) ? Convert.ToInt32(myroomdesc.Element("room_free").Value) : 0; + myroom.Roomfree = !String.IsNullOrEmpty( + myroomdesc.Element("room_free").Value + ) + ? Convert.ToInt32(myroomdesc.Element("room_free").Value) + : 0; //TODO add Roomfree also to cheapeast channel list if (myroom.Roomfree != null && myroom.Roomfree > 0) { - foreach (var cheapeastoffersingle in cheapestofferlist.Where(x => x.RoomId == myroom.RoomId).ToList()) + foreach ( + var cheapeastoffersingle in cheapestofferlist + .Where(x => x.RoomId == myroom.RoomId) + .ToList() + ) { cheapeastoffersingle.RoomFree = myroom.Roomfree; } - foreach (var cheapeastoffersingle in cheapestofferlist_ws.Where(x => x.RoomId == myroom.RoomId).ToList()) + foreach ( + var cheapeastoffersingle in cheapestofferlist_ws + .Where(x => x.RoomId == myroom.RoomId) + .ToList() + ) { cheapeastoffersingle.RoomFree = myroom.Roomfree; } - foreach (var cheapeastoffersingle in cheapestofferlist_bb.Where(x => x.RoomId == myroom.RoomId).ToList()) + foreach ( + var cheapeastoffersingle in cheapestofferlist_bb + .Where(x => x.RoomId == myroom.RoomId) + .ToList() + ) { cheapeastoffersingle.RoomFree = myroom.Roomfree; } - foreach (var cheapeastoffersingle in cheapestofferlist_hb.Where(x => x.RoomId == myroom.RoomId).ToList()) + foreach ( + var cheapeastoffersingle in cheapestofferlist_hb + .Where(x => x.RoomId == myroom.RoomId) + .ToList() + ) { cheapeastoffersingle.RoomFree = myroom.Roomfree; } - foreach (var cheapeastoffersingle in cheapestofferlist_fb.Where(x => x.RoomId == myroom.RoomId).ToList()) + foreach ( + var cheapeastoffersingle in cheapestofferlist_fb + .Where(x => x.RoomId == myroom.RoomId) + .ToList() + ) { cheapeastoffersingle.RoomFree = myroom.Roomfree; } - foreach (var cheapeastoffersingle in cheapestofferlist_ai.Where(x => x.RoomId == myroom.RoomId).ToList()) + foreach ( + var cheapeastoffersingle in cheapestofferlist_ai + .Where(x => x.RoomId == myroom.RoomId) + .ToList() + ) { cheapeastoffersingle.RoomFree = myroom.Roomfree; } @@ -463,13 +852,23 @@ public static MssResult ResponseParser(IEnumerable myresult, string se var myroomprops = myroomdesc.Element("properties"); if (myroomprops.Element("min") != null) - myroom.Roommin = !String.IsNullOrEmpty(myroomprops.Element("min").Value) ? Convert.ToInt32(myroomprops.Element("min").Value) : 0; + myroom.Roommin = !String.IsNullOrEmpty( + myroomprops.Element("min").Value + ) + ? Convert.ToInt32(myroomprops.Element("min").Value) + : 0; if (myroomprops.Element("max") != null) - myroom.Roommax = !String.IsNullOrEmpty(myroomprops.Element("max").Value) ? Convert.ToInt32(myroomprops.Element("max").Value) : 0; + myroom.Roommax = !String.IsNullOrEmpty( + myroomprops.Element("max").Value + ) + ? Convert.ToInt32(myroomprops.Element("max").Value) + : 0; if (myroomprops.Element("std") != null) - myroom.Roomstd = !String.IsNullOrEmpty(myroomprops.Element("std").Value) ? Convert.ToInt32(myroomprops.Element("std").Value) : 0; - - + myroom.Roomstd = !String.IsNullOrEmpty( + myroomprops.Element("std").Value + ) + ? Convert.ToInt32(myroomprops.Element("std").Value) + : 0; } //Zimmerbilder @@ -479,49 +878,84 @@ public static MssResult ResponseParser(IEnumerable myresult, string se { if (myroompic.Element("url") != null) { - RoomPictures mypicture = new RoomPictures() { Pictureurl = myroompic.Element("url").Value }; + RoomPictures mypicture = new RoomPictures() + { + Pictureurl = myroompic.Element("url").Value + }; //myroom.RoomPictures.Add(mypicture); myroompiclist.Add(mypicture); } } myroom.RoomPictures = myroompiclist.ToList(); - } //myroom.MssResponseShort = myresp; myresp.RoomDetails.Add(myroom); } - - var cheapestofferobj = RoomCalculationHelper.CalculateCheapestRooms(cheapestofferlist, rooms, ""); + + var cheapestofferobj = RoomCalculationHelper.CalculateCheapestRooms( + cheapestofferlist, + rooms, + "" + ); double cheapestchanneloffer = cheapestofferobj.Price; myresp.CheapestOffer = cheapestchanneloffer; - myresp.CheapestOfferString = String.Format(culturede, "{0:0,0.00}", cheapestchanneloffer); - + myresp.CheapestOfferString = String.Format( + culturede, + "{0:0,0.00}", + cheapestchanneloffer + ); + //Cheapest offers calculation - var cheapestofferobj_ws = RoomCalculationHelper.CalculateCheapestRooms(cheapestofferlist_ws, rooms, "ws"); - myresp.CheapestOffer_ws = cheapestofferobj_ws != null ? cheapestofferobj_ws.Price : 0; + var cheapestofferobj_ws = RoomCalculationHelper.CalculateCheapestRooms( + cheapestofferlist_ws, + rooms, + "ws" + ); + myresp.CheapestOffer_ws = + cheapestofferobj_ws != null ? cheapestofferobj_ws.Price : 0; if (cheapestofferobj_ws != null && cheapestofferobj_ws.Price > 0) myresp.CheapestOfferDetail.Add(cheapestofferobj_ws); - var cheapestofferobj_bb = RoomCalculationHelper.CalculateCheapestRooms(cheapestofferlist_bb, rooms, "bb"); - myresp.CheapestOffer_bb = cheapestofferobj_bb != null ? cheapestofferobj_bb.Price : 0; + var cheapestofferobj_bb = RoomCalculationHelper.CalculateCheapestRooms( + cheapestofferlist_bb, + rooms, + "bb" + ); + myresp.CheapestOffer_bb = + cheapestofferobj_bb != null ? cheapestofferobj_bb.Price : 0; if (cheapestofferobj_bb != null && cheapestofferobj_bb.Price > 0) myresp.CheapestOfferDetail.Add(cheapestofferobj_bb); - var cheapestofferobj_hb = RoomCalculationHelper.CalculateCheapestRooms(cheapestofferlist_hb, rooms, "hb"); - myresp.CheapestOffer_hb = cheapestofferobj_hb != null ? cheapestofferobj_hb.Price : 0; + var cheapestofferobj_hb = RoomCalculationHelper.CalculateCheapestRooms( + cheapestofferlist_hb, + rooms, + "hb" + ); + myresp.CheapestOffer_hb = + cheapestofferobj_hb != null ? cheapestofferobj_hb.Price : 0; if (cheapestofferobj_hb != null && cheapestofferobj_hb.Price > 0) myresp.CheapestOfferDetail.Add(cheapestofferobj_hb); - var cheapestofferobj_fb = RoomCalculationHelper.CalculateCheapestRooms(cheapestofferlist_fb, rooms, "fb"); - myresp.CheapestOffer_fb = cheapestofferobj_fb != null ? cheapestofferobj_fb.Price : 0; + var cheapestofferobj_fb = RoomCalculationHelper.CalculateCheapestRooms( + cheapestofferlist_fb, + rooms, + "fb" + ); + myresp.CheapestOffer_fb = + cheapestofferobj_fb != null ? cheapestofferobj_fb.Price : 0; if (cheapestofferobj_fb != null && cheapestofferobj_fb.Price > 0) myresp.CheapestOfferDetail.Add(cheapestofferobj_fb); - var cheapestofferobj_ai = RoomCalculationHelper.CalculateCheapestRooms(cheapestofferlist_ai, rooms, "ai"); - myresp.CheapestOffer_ai = cheapestofferobj_ai != null ? cheapestofferobj_ai.Price : 0; + var cheapestofferobj_ai = RoomCalculationHelper.CalculateCheapestRooms( + cheapestofferlist_ai, + rooms, + "ai" + ); + myresp.CheapestOffer_ai = + cheapestofferobj_ai != null ? cheapestofferobj_ai.Price : 0; if (cheapestofferobj_ai != null && cheapestofferobj_ai.Price > 0) myresp.CheapestOfferDetail.Add(cheapestofferobj_ai); @@ -542,17 +976,27 @@ public static MssResult ResponseParser(IEnumerable myresult, string se if (cheapestoffertotal.Count > 0) { - var cheapestofferdouble = cheapestoffertotal.OrderBy(x => x).FirstOrDefault(); + var cheapestofferdouble = cheapestoffertotal + .OrderBy(x => x) + .FirstOrDefault(); myresp.CheapestOffer = cheapestofferdouble; - myresp.CheapestOfferString = String.Format(culturede, "{0:0,0.00}", cheapestofferdouble); + myresp.CheapestOfferString = String.Format( + culturede, + "{0:0,0.00}", + cheapestofferdouble + ); } } - if (myresp.CheapestOfferDetail != null && myresp.CheapestOfferDetail.Count > 0) + if ( + myresp.CheapestOfferDetail != null + && myresp.CheapestOfferDetail.Count > 0 + ) myparsedresponselist.MssResponseShort.Add(myresp); } } - }; + } + ; //myparsedresponselist.CheapestChannel = cheapestchannel; //myparsedresponselist.Cheapestprice = cheapestprice; @@ -567,6 +1011,5 @@ public static MssResult ResponseParser(IEnumerable myresult, string se return null; } } - } } diff --git a/MSS/ParseMssRoomResponse.cs b/MSS/ParseMssRoomResponse.cs index 35686fc2a..3f55351d2 100644 --- a/MSS/ParseMssRoomResponse.cs +++ b/MSS/ParseMssRoomResponse.cs @@ -11,7 +11,11 @@ namespace MSS { public class ParseMssRoomResponse { - public static List ParseMyRoomResponse(string lang, XElement mssresponse, XDocument roomamenities) + public static List ParseMyRoomResponse( + string lang, + XElement mssresponse, + XDocument roomamenities + ) { try { @@ -30,11 +34,13 @@ public static List ParseMyRoomResponse(string lang, XElement mssrespon { return null; } - } - - public static List ResponseRoomParser(XElement myresult, XDocument roomamenities, string language) + public static List ResponseRoomParser( + XElement myresult, + XDocument roomamenities, + string language + ) { try { @@ -54,20 +60,28 @@ public static List ResponseRoomParser(XElement myresult, XDocument roo { if (mychannelresult.Element("channel_id").Value == "hgv") { - var myroomlist = mychannelresult.Element("room_description").Elements("room"); + var myroomlist = mychannelresult + .Element("room_description") + .Elements("room"); foreach (var myroom in myroomlist) { AccoRoom myroomtosave = new AccoRoom(); string roomid = myroom.Element("room_id").Value; - string roomidlts = myroom.Element("room_lts_id").Value != null ? myroom.Element("room_lts_id").Value : ""; + string roomidlts = + myroom.Element("room_lts_id").Value != null + ? myroom.Element("room_lts_id").Value + : ""; myroomtosave.Id = roomid + "hgv" + roomidlts; myroomtosave.A0RID = A0RID.ToUpper(); myroomtosave.RoomCode = myroom.Element("room_code").Value; myroomtosave.HGVId = roomid; - myroomtosave.LTSId = myroom.Element("room_lts_id").Value != null ? myroom.Element("room_lts_id").Value : ""; + myroomtosave.LTSId = + myroom.Element("room_lts_id").Value != null + ? myroom.Element("room_lts_id").Value + : ""; myroomtosave.Source = "hgv"; string roomtyp = myroom.Element("room_type").Value; @@ -79,7 +93,10 @@ public static List ResponseRoomParser(XElement myresult, XDocument roo myroomtosave.Roomtype = "undefined"; myroomtosave.RoomtypeInt = Convert.ToInt32(roomtyp); - myroomtosave.RoomClassificationCodes = AlpineBitsHelper.GetRoomClassificationCode(myroomtosave.Roomtype); + myroomtosave.RoomClassificationCodes = + AlpineBitsHelper.GetRoomClassificationCode( + myroomtosave.Roomtype + ); string roommax = myroom.Element("occupancy").Element("max").Value; string roommin = myroom.Element("occupancy").Element("min").Value; @@ -100,7 +117,6 @@ public static List ResponseRoomParser(XElement myresult, XDocument roo else myroomtosave.Roomstd = null; - string pricefrom = myroom.Element("price_from").Value; if (!String.IsNullOrEmpty(pricefrom)) @@ -108,18 +124,24 @@ public static List ResponseRoomParser(XElement myresult, XDocument roo else myroomtosave.PriceFrom = null; - myroomtosave.Shortname = myroom.Element("title").Value; //zimmeranzahl if (myroom.Element("room_numbers") != null) { - var myroomcount = myroom.Element("room_numbers").Elements("number").Count(); + var myroomcount = myroom + .Element("room_numbers") + .Elements("number") + .Count(); myroomtosave.RoomQuantity = myroomcount; - myroomtosave.RoomNumbers = myroom.Element("room_numbers").Elements("number").Select(x => x.Value).ToList(); + myroomtosave.RoomNumbers = myroom + .Element("room_numbers") + .Elements("number") + .Select(x => x.Value) + .ToList(); } //Roomdetail @@ -133,11 +155,13 @@ public static List ResponseRoomParser(XElement myresult, XDocument roo myroomtosave.AccoRoomDetail.TryAddOrUpdate(language, mydetail); - //Features + //Features if (myroom.Element("features_view") != null) { - var myfeatures = myroom.Element("features_view").Elements("feature"); + var myfeatures = myroom + .Element("features_view") + .Elements("feature"); List myroomfeatureslist = new List(); foreach (var feature in myfeatures) @@ -149,16 +173,22 @@ public static List ResponseRoomParser(XElement myresult, XDocument roo myroomfeature.HgvId = amenityid; myroomfeature.Name = feature.Element("title").Value; - //LTS Feature ID + OTA Code + //LTS Feature ID + OTA Code string ltsamenityid = ""; string otacodes = ""; - var myamenity = roomamenities.Root.Elements("amenity").Where(x => x.Element("hgvid").Value == amenityid).FirstOrDefault(); + var myamenity = roomamenities.Root + .Elements("amenity") + .Where(x => x.Element("hgvid").Value == amenityid) + .FirstOrDefault(); if (myamenity != null) { ltsamenityid = myamenity.Element("ltsrid").Value; - otacodes = myamenity.Element("ota_codes") != null ? myamenity.Element("ota_codes").Value : ""; + otacodes = + myamenity.Element("ota_codes") != null + ? myamenity.Element("ota_codes").Value + : ""; } myroomfeature.Id = ltsamenityid; @@ -177,7 +207,6 @@ public static List ResponseRoomParser(XElement myresult, XDocument roo myroomfeature.RoomAmenityCodes = amenitycodes; } - myroomfeatureslist.Add(myroomfeature); } @@ -187,7 +216,9 @@ public static List ResponseRoomParser(XElement myresult, XDocument roo if (myroom.Element("pictures") != null) { - var myroompictures = myroom.Element("pictures").Elements("picture"); + var myroompictures = myroom + .Element("pictures") + .Elements("picture"); int i = 0; @@ -197,7 +228,10 @@ public static List ResponseRoomParser(XElement myresult, XDocument roo ImageGallery mainimage = new ImageGallery(); mainimage.ImageUrl = picture.Element("url").Value; - mainimage.ImageName = picture.Element("title").Value != null ? picture.Element("title").Value : ""; + mainimage.ImageName = + picture.Element("title").Value != null + ? picture.Element("title").Value + : ""; mainimage.Height = 0; mainimage.Width = 0; mainimage.ImageSource = "HGV"; @@ -213,7 +247,6 @@ public static List ResponseRoomParser(XElement myresult, XDocument roo } } } - } return myaccorooms; @@ -223,6 +256,5 @@ public static List ResponseRoomParser(XElement myresult, XDocument roo return null; } } - } } diff --git a/MSS/ParseMssSpecialResponse.cs b/MSS/ParseMssSpecialResponse.cs index 1d779b689..8b84de395 100644 --- a/MSS/ParseMssSpecialResponse.cs +++ b/MSS/ParseMssSpecialResponse.cs @@ -29,10 +29,14 @@ public static List ParseMySpecialResponse(string lang, XElement mssresp { return null; } - } - public static MssResult ParsemyMssSpecialResponse(string lang, string servicecode, XElement mssresponse, List myroompersons) + public static MssResult ParsemyMssSpecialResponse( + string lang, + string servicecode, + XElement mssresponse, + List myroompersons + ) { try { @@ -41,17 +45,13 @@ public static MssResult ParsemyMssSpecialResponse(string lang, string servicecod var myresult = mssresponse.Elements("result").Elements("special"); return ResponseSpecialParser(myresult, servicecode, myroompersons, resultid, lang); - - } catch (Exception) { return null; } - } - public static Package ResponseSpecialParser(XElement myresult, string language) { try @@ -68,17 +68,39 @@ public static Package ResponseSpecialParser(XElement myresult, string language) myparsedpackage.Active = true; - myparsedpackage.ChildrenMin = Convert.ToInt32(myresult.Element("children_min").Value); + myparsedpackage.ChildrenMin = Convert.ToInt32( + myresult.Element("children_min").Value + ); myparsedpackage.Specialtyp = Convert.ToInt32(myresult.Element("special_typ").Value); - myparsedpackage.Premiumtyp = Convert.ToInt32(myresult.Element("special_premium").Value); - myparsedpackage.DaysArrival = Convert.ToInt32(myresult.Element("days_arrival").Value); - myparsedpackage.DaysDeparture = Convert.ToInt32(myresult.Element("days_departure").Value); - myparsedpackage.DaysDurMin = Convert.ToInt32(myresult.Element("days_dur_min").Value); - myparsedpackage.DaysDurMax = Convert.ToInt32(myresult.Element("days_dur_max").Value); - myparsedpackage.DaysArrivalMin = Convert.ToInt32(myresult.Element("days_arrival_min").Value); - myparsedpackage.DaysArrivalMax = Convert.ToInt32(myresult.Element("days_arrival_max").Value); - myparsedpackage.ValidStart = myresult.Element("valid_start").Value == "0000-00-00" ? DateTime.MinValue : Convert.ToDateTime(myresult.Element("valid_start").Value); - myparsedpackage.ValidStop = myresult.Element("valid_end").Value == "0000-00-00" ? DateTime.MinValue : Convert.ToDateTime(myresult.Element("valid_end").Value); + myparsedpackage.Premiumtyp = Convert.ToInt32( + myresult.Element("special_premium").Value + ); + myparsedpackage.DaysArrival = Convert.ToInt32( + myresult.Element("days_arrival").Value + ); + myparsedpackage.DaysDeparture = Convert.ToInt32( + myresult.Element("days_departure").Value + ); + myparsedpackage.DaysDurMin = Convert.ToInt32( + myresult.Element("days_dur_min").Value + ); + myparsedpackage.DaysDurMax = Convert.ToInt32( + myresult.Element("days_dur_max").Value + ); + myparsedpackage.DaysArrivalMin = Convert.ToInt32( + myresult.Element("days_arrival_min").Value + ); + myparsedpackage.DaysArrivalMax = Convert.ToInt32( + myresult.Element("days_arrival_max").Value + ); + myparsedpackage.ValidStart = + myresult.Element("valid_start").Value == "0000-00-00" + ? DateTime.MinValue + : Convert.ToDateTime(myresult.Element("valid_start").Value); + myparsedpackage.ValidStop = + myresult.Element("valid_end").Value == "0000-00-00" + ? DateTime.MinValue + : Convert.ToDateTime(myresult.Element("valid_end").Value); //Shortstay Longstay Unterscheidung if (myparsedpackage.DaysDurMin <= 4) @@ -108,8 +130,6 @@ public static Package ResponseSpecialParser(XElement myresult, string language) myparsedpackage.ImageGallery = myimagegallerylist.ToList(); } - - if (myresult.Element("hotels") != null) { List hotelhgvidlist = new List(); @@ -127,7 +147,6 @@ public static Package ResponseSpecialParser(XElement myresult, string language) myparsedpackage.HotelHgvId = hotelhgvidlist.ToList(); } - if (myresult.Element("seasons") != null) { List myseasonlist = new List(); @@ -143,7 +162,6 @@ public static Package ResponseSpecialParser(XElement myresult, string language) myparsedpackage.Season = myseasonlist.ToList(); } - if (myresult.Element("services") != null) { List servicelist = new List(); @@ -154,7 +172,6 @@ public static Package ResponseSpecialParser(XElement myresult, string language) myparsedpackage.Services = servicelist.ToList(); } - if (myresult.Element("inclusive") != null) { foreach (XElement inclusive in myresult.Element("inclusive").Elements("price")) @@ -164,7 +181,9 @@ public static Package ResponseSpecialParser(XElement myresult, string language) int priceid = Convert.ToInt32(inclusive.Element("price_id").Value); myinclusive.PriceId = priceid; - myinclusive.PriceTyp = Convert.ToInt32(inclusive.Element("price_typ").Value); + myinclusive.PriceTyp = Convert.ToInt32( + inclusive.Element("price_typ").Value + ); PackageDetail myinclusivedetail = new PackageDetail(); myinclusivedetail.Desc = inclusive.Element("description").Value; @@ -175,8 +194,11 @@ public static Package ResponseSpecialParser(XElement myresult, string language) if (inclusive.Element("pictures") != null) { - List mypackagedetailimggallerylist = new List(); - foreach (XElement image in inclusive.Element("pictures").Elements("picture")) + List mypackagedetailimggallerylist = + new List(); + foreach ( + XElement image in inclusive.Element("pictures").Elements("picture") + ) { ImageGallery myinclusiveimg = new ImageGallery(); myinclusiveimg.ImageUrl = image.Element("url").Value; @@ -190,7 +212,6 @@ public static Package ResponseSpecialParser(XElement myresult, string language) } } - if (myresult.Element("themes") != null) { List packagedetaillist = new List(); @@ -218,7 +239,6 @@ public static Package ResponseSpecialParser(XElement myresult, string language) myparsedpackage.PackageThemeList = packagethemelist.ToList(); } - return myparsedpackage; } catch (Exception) @@ -227,7 +247,13 @@ public static Package ResponseSpecialParser(XElement myresult, string language) } } - public static MssResult ResponseSpecialParser(IEnumerable myresult, string servicecode, List roompersons, string resultid, string lang) + public static MssResult ResponseSpecialParser( + IEnumerable myresult, + string servicecode, + List roompersons, + string resultid, + string lang + ) { try { @@ -238,8 +264,12 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st int rooms = roompersons.Count; - - foreach (var myhotelresult in myresult.Elements("hotels").Elements("hotel").Where(x => x.Elements("channel").Count() > 0)) + foreach ( + var myhotelresult in myresult + .Elements("hotels") + .Elements("hotel") + .Where(x => x.Elements("channel").Count() > 0) + ) { //Nur wenn ein Angebot eines Channels vorhanden ist if (myhotelresult.Elements("channel").Count() > 0) @@ -247,14 +277,19 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st //Nur wenn kein Ab Preis vorhanden ist if (myhotelresult.Element("channel").Element("from_price") == null) { - - List> cheapestofferlist = new List>(); - - List> cheapestofferlist_ws = new List>(); - List> cheapestofferlist_bb = new List>(); - List> cheapestofferlist_hb = new List>(); - List> cheapestofferlist_fb = new List>(); - List> cheapestofferlist_ai = new List>(); + List> cheapestofferlist = + new List>(); + + List> cheapestofferlist_ws = + new List>(); + List> cheapestofferlist_bb = + new List>(); + List> cheapestofferlist_hb = + new List>(); + List> cheapestofferlist_fb = + new List>(); + List> cheapestofferlist_ai = + new List>(); var mychanneloffers = myhotelresult.Elements("channel"); @@ -277,7 +312,11 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st // myresp.Channellink = mychanneloffer.Element("channel_link").Value; //spezialfall Booking Südtirol Buchungslink selbst zusammenstellen - if (myresp.ChannelID == "esy" || myresp.ChannelID == "lts" || myresp.ChannelID == "hgv") + if ( + myresp.ChannelID == "esy" + || myresp.ChannelID == "lts" + || myresp.ChannelID == "hgv" + ) { //http://www.bookingsuedtirol.com/index.php?action=view&src=sinfo&id=10096&result_id=ec373a3d116ce01806a1c5f9f110c16b&room_qty_0=1&room_occ_0=18&room_rid_0=3124 //http://www.bookingsuedtirol.com/index.php?action=view&src=sinfo&id=10096&result_id=fba3a11c1a9cf7c9ce636e10188507bd&room_qty_0=1&room_occ_0=18&room_rid_0=3124&room_qty_1=1&room_occ_1=18,18&room_rid_1=3125 @@ -290,7 +329,13 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st string person = String.Join(",", room.Person.ToArray()); roomstring = roomstring + "room_qty_" + roomcounter + "=1&"; - roomstring = roomstring + "room_occ_" + roomcounter + "=" + person + "&"; + roomstring = + roomstring + + "room_occ_" + + roomcounter + + "=" + + person + + "&"; roomcounter++; } @@ -299,23 +344,48 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st if (lang.ToLower() == "it") bookingurl = "https://www.bookingaltoadige.com"; - else if (lang.ToLower() == "en" || lang.ToLower() == "nl" || lang.ToLower() == "fr" || lang.ToLower() == "ru" || lang.ToLower() == "pl" || lang.ToLower() == "cs") + else if ( + lang.ToLower() == "en" + || lang.ToLower() == "nl" + || lang.ToLower() == "fr" + || lang.ToLower() == "ru" + || lang.ToLower() == "pl" + || lang.ToLower() == "cs" + ) bookingurl = "https://www.bookingsouthtyrol.com"; - string bookinglink = bookingurl + "/index.php?action=view&src=sbalance&id=" + myresp.HotelId + "&result_id=" + resultid + "&" + roomstring; + string bookinglink = + bookingurl + + "/index.php?action=view&src=sbalance&id=" + + myresp.HotelId + + "&result_id=" + + resultid + + "&" + + roomstring; bookinglink = bookinglink.Substring(0, bookinglink.Length - 1); string myofferidforlink = ""; - if (mychanneloffer.Element("offer_description").Element("offer").Element("offer_id").Value != null) - myofferidforlink = mychanneloffer.Element("offer_description").Element("offer").Element("offer_id").Value; + if ( + mychanneloffer + .Element("offer_description") + .Element("offer") + .Element("offer_id") + .Value != null + ) + myofferidforlink = mychanneloffer + .Element("offer_description") + .Element("offer") + .Element("offer_id") + .Value; myresp.Channellink = bookinglink + "#_pid=" + myofferidforlink; } - - var myofferdescription = mychanneloffer.Element("offer_description"); + var myofferdescription = mychanneloffer.Element( + "offer_description" + ); if (myofferdescription != null) { @@ -324,21 +394,43 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st { int offershow = 0; if (myofferdetails.Element("offer_gid") != null) - myresp.OfferGid = !String.IsNullOrEmpty(myofferdetails.Element("offer_gid").Value) ? myofferdetails.Element("offer_gid").Value : ""; + myresp.OfferGid = !String.IsNullOrEmpty( + myofferdetails.Element("offer_gid").Value + ) + ? myofferdetails.Element("offer_gid").Value + : ""; if (myofferdetails.Element("offer_id") != null) - myresp.OfferId = !String.IsNullOrEmpty(myofferdetails.Element("offer_id").Value) ? myofferdetails.Element("offer_id").Value : ""; + myresp.OfferId = !String.IsNullOrEmpty( + myofferdetails.Element("offer_id").Value + ) + ? myofferdetails.Element("offer_id").Value + : ""; if (myofferdetails.Element("offer_show") != null) - myresp.OfferShow = Int32.TryParse(myofferdetails.Element("offer_show").Value, out offershow) ? offershow : 0; + myresp.OfferShow = Int32.TryParse( + myofferdetails.Element("offer_show").Value, + out offershow + ) + ? offershow + : 0; int offertyp = 0; if (myofferdetails.Element("offer_typ") != null) - myresp.OfferTyp = Int32.TryParse(myofferdetails.Element("offer_typ").Value, out offertyp) ? offertyp : 0; + myresp.OfferTyp = Int32.TryParse( + myofferdetails.Element("offer_typ").Value, + out offertyp + ) + ? offertyp + : 0; if (myofferdetails.Element("offer_id") != null) - myresp.A0RID = "Package" + myofferdetails.Element("offer_id").Value; + myresp.A0RID = + "Package" + + myofferdetails.Element("offer_id").Value; } } - var myroomdetails = mychanneloffer.Element("room_price").Elements("price"); + var myroomdetails = mychanneloffer + .Element("room_price") + .Elements("price"); foreach (var myroomdetail in myroomdetails) { RoomDetails myroom = new RoomDetails(); @@ -349,7 +441,12 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st int roomseq = 0; if (myroomdetail.Element("room_seq") != null) - myroom.RoomSeq = Int32.TryParse(myroomdetail.Element("room_seq").Value, out roomseq) ? roomseq : 0; + myroom.RoomSeq = Int32.TryParse( + myroomdetail.Element("room_seq").Value, + out roomseq + ) + ? roomseq + : 0; //Mal kucken wiamer do tian wenn olle verpflegungsorten ausgwählt sein gazzo @@ -358,56 +455,126 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st { if (requestedservice == "price_ws") { - double mycurrentpricews = myroomdetail.Element("price_total").Element(requestedservice) != null ? Convert.ToDouble(myroomdetail.Element("price_total").Element(requestedservice).Value, CultureInfo.InvariantCulture.NumberFormat) : 0; + double mycurrentpricews = + myroomdetail + .Element("price_total") + .Element(requestedservice) != null + ? Convert.ToDouble( + myroomdetail + .Element("price_total") + .Element(requestedservice) + .Value, + CultureInfo.InvariantCulture.NumberFormat + ) + : 0; myroom.Price_ws = mycurrentpricews; if (mycurrentpricews > 0) { - var mytuplews = new Tuple((int)myroom.RoomSeq, mycurrentpricews); + var mytuplews = new Tuple( + (int)myroom.RoomSeq, + mycurrentpricews + ); cheapestofferlist_ws.Add(mytuplews); } } if (requestedservice == "price_bb") { - double mycurrentpricebb = myroomdetail.Element("price_total").Element(requestedservice) != null ? Convert.ToDouble(myroomdetail.Element("price_total").Element(requestedservice).Value, CultureInfo.InvariantCulture.NumberFormat) : 0; + double mycurrentpricebb = + myroomdetail + .Element("price_total") + .Element(requestedservice) != null + ? Convert.ToDouble( + myroomdetail + .Element("price_total") + .Element(requestedservice) + .Value, + CultureInfo.InvariantCulture.NumberFormat + ) + : 0; myroom.Price_bb = mycurrentpricebb; if (mycurrentpricebb > 0) { - var mytuplebb = new Tuple((int)myroom.RoomSeq, mycurrentpricebb); + var mytuplebb = new Tuple( + (int)myroom.RoomSeq, + mycurrentpricebb + ); cheapestofferlist_bb.Add(mytuplebb); } } if (requestedservice == "price_hb") { - double mycurrentpricehb = myroomdetail.Element("price_total").Element(requestedservice) != null ? Convert.ToDouble(myroomdetail.Element("price_total").Element(requestedservice).Value, CultureInfo.InvariantCulture.NumberFormat) : 0; + double mycurrentpricehb = + myroomdetail + .Element("price_total") + .Element(requestedservice) != null + ? Convert.ToDouble( + myroomdetail + .Element("price_total") + .Element(requestedservice) + .Value, + CultureInfo.InvariantCulture.NumberFormat + ) + : 0; myroom.Price_hb = mycurrentpricehb; if (mycurrentpricehb > 0) { - var mytuplehb = new Tuple((int)myroom.RoomSeq, mycurrentpricehb); + var mytuplehb = new Tuple( + (int)myroom.RoomSeq, + mycurrentpricehb + ); cheapestofferlist_hb.Add(mytuplehb); } } if (requestedservice == "price_fb") { - double mycurrentpricefb = myroomdetail.Element("price_total").Element(requestedservice) != null ? Convert.ToDouble(myroomdetail.Element("price_total").Element(requestedservice).Value, CultureInfo.InvariantCulture.NumberFormat) : 0; + double mycurrentpricefb = + myroomdetail + .Element("price_total") + .Element(requestedservice) != null + ? Convert.ToDouble( + myroomdetail + .Element("price_total") + .Element(requestedservice) + .Value, + CultureInfo.InvariantCulture.NumberFormat + ) + : 0; myroom.Price_fb = mycurrentpricefb; if (mycurrentpricefb > 0) { - var mytuplefb = new Tuple((int)myroom.RoomSeq, mycurrentpricefb); + var mytuplefb = new Tuple( + (int)myroom.RoomSeq, + mycurrentpricefb + ); cheapestofferlist_fb.Add(mytuplefb); } } if (requestedservice == "price_ai") { - double mycurrentpriceai = myroomdetail.Element("price_total").Element(requestedservice) != null ? Convert.ToDouble(myroomdetail.Element("price_total").Element(requestedservice).Value, CultureInfo.InvariantCulture.NumberFormat) : 0; + double mycurrentpriceai = + myroomdetail + .Element("price_total") + .Element(requestedservice) != null + ? Convert.ToDouble( + myroomdetail + .Element("price_total") + .Element(requestedservice) + .Value, + CultureInfo.InvariantCulture.NumberFormat + ) + : 0; myroom.Price_ai = mycurrentpriceai; if (mycurrentpriceai > 0) { - var mytupleai = new Tuple((int)myroom.RoomSeq, mycurrentpriceai); + var mytupleai = new Tuple( + (int)myroom.RoomSeq, + mycurrentpriceai + ); cheapestofferlist_ai.Add(mytupleai); } } @@ -416,13 +583,33 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st //Spezial falls mehrere Services angefragt werden if (splittedservice.Count == 1) { - double mycurrentprice = !String.IsNullOrEmpty(myroomdetail.Element("price_total").Element(servicecode).Value) ? Convert.ToDouble(myroomdetail.Element("price_total").Element(servicecode).Value, CultureInfo.InvariantCulture.NumberFormat) : 0; - - var mytuple = new Tuple((int)myroom.RoomSeq, mycurrentprice); + double mycurrentprice = !String.IsNullOrEmpty( + myroomdetail + .Element("price_total") + .Element(servicecode) + .Value + ) + ? Convert.ToDouble( + myroomdetail + .Element("price_total") + .Element(servicecode) + .Value, + CultureInfo.InvariantCulture.NumberFormat + ) + : 0; + + var mytuple = new Tuple( + (int)myroom.RoomSeq, + mycurrentprice + ); cheapestofferlist.Add(mytuple); myroom.TotalPrice = mycurrentprice; - myroom.TotalPriceString = String.Format(culturede, "{0:0,0.00}", mycurrentprice); + myroom.TotalPriceString = String.Format( + culturede, + "{0:0,0.00}", + mycurrentprice + ); } else { @@ -430,7 +617,11 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st myroom.TotalPrice = 0; - myroom.TotalPriceString = String.Format(culturede, "{0:0,0.00}", 0); + myroom.TotalPriceString = String.Format( + culturede, + "{0:0,0.00}", + 0 + ); } //myroom.Service = servicecode; @@ -447,19 +638,36 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st // cheapestchanneloffertemp = mycurrentprice; //} - var myroomdesc = mychanneloffer.Element("room_description").Elements("room").Where(x => x.Element("room_id").Value == roomid).FirstOrDefault(); + var myroomdesc = mychanneloffer + .Element("room_description") + .Elements("room") + .Where(x => x.Element("room_id").Value == roomid) + .FirstOrDefault(); if (myroomdesc != null) { if (myroomdesc.Element("title") != null) myroom.Roomtitle = myroomdesc.Element("title").Value; if (myroomdesc.Element("description") != null) - myroom.Roomdesc = myroomdesc.Element("description").Value; - + myroom.Roomdesc = myroomdesc + .Element("description") + .Value; if (myroomdesc.Element("room_type") != null) - myroom.Roomtype = !String.IsNullOrEmpty(myroomdesc.Element("room_type").Value) ? Convert.ToInt32(myroomdesc.Element("room_type").Value) : 0; + myroom.Roomtype = !String.IsNullOrEmpty( + myroomdesc.Element("room_type").Value + ) + ? Convert.ToInt32( + myroomdesc.Element("room_type").Value + ) + : 0; if (myroomdesc.Element("room_free") != null) - myroom.Roomfree = !String.IsNullOrEmpty(myroomdesc.Element("room_free").Value) ? Convert.ToInt32(myroomdesc.Element("room_free").Value) : 0; + myroom.Roomfree = !String.IsNullOrEmpty( + myroomdesc.Element("room_free").Value + ) + ? Convert.ToInt32( + myroomdesc.Element("room_free").Value + ) + : 0; //Zimmerbilder var roompics = myroomdesc.Elements("pictures"); @@ -468,14 +676,16 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st { if (myroompic.Element("url") != null) { - RoomPictures mypicture = new RoomPictures() { Pictureurl = myroompic.Element("url").Value }; + RoomPictures mypicture = new RoomPictures() + { + Pictureurl = myroompic.Element("url").Value + }; //myroom.RoomPictures.Add(mypicture); myroompiclist.Add(mypicture); } } myroom.RoomPictures = myroompiclist.ToList(); - } //myroom.MssResponseShort = myresp; @@ -486,88 +696,110 @@ public static MssResult ResponseSpecialParser(IEnumerable myresult, st //Billigstes Angebot holen for (int i = 1; i <= rooms; i++) { - var cheapestchanneloffertemp = (from x in cheapestofferlist - where x.Item1 == i - orderby x.Item2 ascending - select x.Item2).FirstOrDefault(); + var cheapestchanneloffertemp = ( + from x in cheapestofferlist + where x.Item1 == i + orderby x.Item2 ascending + select x.Item2 + ).FirstOrDefault(); //if (cheapestchanneloffertemp == null) // cheapestchanneloffertemp = 0; - cheapestchanneloffer = cheapestchanneloffer + cheapestchanneloffertemp; + cheapestchanneloffer = + cheapestchanneloffer + cheapestchanneloffertemp; } myresp.CheapestOffer = cheapestchanneloffer; - myresp.CheapestOfferString = String.Format(culturede, "{0:0,0.00}", cheapestchanneloffer); + myresp.CheapestOfferString = String.Format( + culturede, + "{0:0,0.00}", + cheapestchanneloffer + ); //Billigstes Angebot für die einzelnen Typen double cheapestchanneloffer_ws = 0; for (int i = 1; i <= rooms; i++) { - var cheapestchanneloffertemp = (from x in cheapestofferlist_ws - where x.Item1 == i - orderby x.Item2 ascending - select x.Item2).FirstOrDefault(); - - cheapestchanneloffer_ws = cheapestchanneloffer_ws + cheapestchanneloffertemp; + var cheapestchanneloffertemp = ( + from x in cheapestofferlist_ws + where x.Item1 == i + orderby x.Item2 ascending + select x.Item2 + ).FirstOrDefault(); + + cheapestchanneloffer_ws = + cheapestchanneloffer_ws + cheapestchanneloffertemp; } myresp.CheapestOffer_ws = cheapestchanneloffer_ws; double cheapestchanneloffer_bb = 0; for (int i = 1; i <= rooms; i++) { - var cheapestchanneloffertemp = (from x in cheapestofferlist_bb - where x.Item1 == i - orderby x.Item2 ascending - select x.Item2).FirstOrDefault(); - - cheapestchanneloffer_bb = cheapestchanneloffer_bb + cheapestchanneloffertemp; + var cheapestchanneloffertemp = ( + from x in cheapestofferlist_bb + where x.Item1 == i + orderby x.Item2 ascending + select x.Item2 + ).FirstOrDefault(); + + cheapestchanneloffer_bb = + cheapestchanneloffer_bb + cheapestchanneloffertemp; } myresp.CheapestOffer_bb = cheapestchanneloffer_bb; double cheapestchanneloffer_hb = 0; for (int i = 1; i <= rooms; i++) { - var cheapestchanneloffertemp = (from x in cheapestofferlist_hb - where x.Item1 == i - orderby x.Item2 ascending - select x.Item2).FirstOrDefault(); - - cheapestchanneloffer_hb = cheapestchanneloffer_hb + cheapestchanneloffertemp; + var cheapestchanneloffertemp = ( + from x in cheapestofferlist_hb + where x.Item1 == i + orderby x.Item2 ascending + select x.Item2 + ).FirstOrDefault(); + + cheapestchanneloffer_hb = + cheapestchanneloffer_hb + cheapestchanneloffertemp; } myresp.CheapestOffer_hb = cheapestchanneloffer_hb; double cheapestchanneloffer_fb = 0; for (int i = 1; i <= rooms; i++) { - var cheapestchanneloffertemp = (from x in cheapestofferlist_fb - where x.Item1 == i - orderby x.Item2 ascending - select x.Item2).FirstOrDefault(); - - cheapestchanneloffer_fb = cheapestchanneloffer_fb + cheapestchanneloffertemp; + var cheapestchanneloffertemp = ( + from x in cheapestofferlist_fb + where x.Item1 == i + orderby x.Item2 ascending + select x.Item2 + ).FirstOrDefault(); + + cheapestchanneloffer_fb = + cheapestchanneloffer_fb + cheapestchanneloffertemp; } myresp.CheapestOffer_fb = cheapestchanneloffer_fb; double cheapestchanneloffer_ai = 0; for (int i = 1; i <= rooms; i++) { - var cheapestchanneloffertemp = (from x in cheapestofferlist_ai - where x.Item1 == i - orderby x.Item2 ascending - select x.Item2).FirstOrDefault(); - - cheapestchanneloffer_ai = cheapestchanneloffer_ai + cheapestchanneloffertemp; + var cheapestchanneloffertemp = ( + from x in cheapestofferlist_ai + where x.Item1 == i + orderby x.Item2 ascending + select x.Item2 + ).FirstOrDefault(); + + cheapestchanneloffer_ai = + cheapestchanneloffer_ai + cheapestchanneloffertemp; } myresp.CheapestOffer_ai = cheapestchanneloffer_ai; - myparsedresponselist.MssResponseShort.Add(myresp); } } } - }; + } + ; //myparsedresponselist.CheapestChannel = cheapestchannel; //myparsedresponselist.Cheapestprice = cheapestprice; @@ -582,6 +814,5 @@ orderby x.Item2 ascending return null; } } - } } diff --git a/MSS/Room.cs b/MSS/Room.cs index 5f481fc4f..cf03c6471 100644 --- a/MSS/Room.cs +++ b/MSS/Room.cs @@ -26,5 +26,5 @@ public List Person get { return person; } set { person = value; } } - } + } } diff --git a/NINJA/GetNinjaInfo.cs b/NINJA/GetNinjaInfo.cs index c303f9dce..d8bbc0142 100644 --- a/NINJA/GetNinjaInfo.cs +++ b/NINJA/GetNinjaInfo.cs @@ -7,8 +7,10 @@ namespace NINJA { public class GetNinjaData { - private const string ninjaeventserviceurl = @"https://mobility.api.opendatahub.bz.it/v2/flat/Culture/*/?limit=-1&offset=0&select=tmetadata&where=sactive.eq.true,tname.eq.1aJW6sEGo40hWeL_B2yK4N7CIGwRlmwVpAkwqxjF1ruA:1179155880&shownull=false&distinct=true"; - private const string ninjaplaceroomserviceurl = @"https://mobility.api.opendatahub.bz.it/v2/flat/Culture/?limit=-1&offset=0&where=sactive.eq.true,sorigin.eq.1aJW6sEGo40hWeL_B2yK4N7CIGwRlmwVpAkwqxjF1ruA&shownull=false&distinct=true"; + private const string ninjaeventserviceurl = + @"https://mobility.api.opendatahub.bz.it/v2/flat/Culture/*/?limit=-1&offset=0&select=tmetadata&where=sactive.eq.true,tname.eq.1aJW6sEGo40hWeL_B2yK4N7CIGwRlmwVpAkwqxjF1ruA:1179155880&shownull=false&distinct=true"; + private const string ninjaplaceroomserviceurl = + @"https://mobility.api.opendatahub.bz.it/v2/flat/Culture/?limit=-1&offset=0&where=sactive.eq.true,sorigin.eq.1aJW6sEGo40hWeL_B2yK4N7CIGwRlmwVpAkwqxjF1ruA&shownull=false&distinct=true"; /// /// Gets the Data from Ninja Api @@ -26,13 +28,14 @@ public static async Task> GetNinjaEvent() var myresponsejson = await myresponse.Content.ReadAsStringAsync(); - var btpresponseobject = JsonConvert.DeserializeObject>(myresponsejson); + var btpresponseobject = JsonConvert.DeserializeObject>( + myresponsejson + ); return btpresponseobject; } } - /// /// Gets the Data from Ninja Api /// @@ -49,12 +52,12 @@ public static async Task> GetNinjaPlaces() var myresponsejson = await myresponse.Content.ReadAsStringAsync(); - var btpresponseobject = JsonConvert.DeserializeObject>(myresponsejson); + var btpresponseobject = JsonConvert.DeserializeObject>( + myresponsejson + ); return btpresponseobject; } } - - } } diff --git a/NINJA/NinjaModels.cs b/NINJA/NinjaModels.cs index 81a4a902b..ba238a3a6 100644 --- a/NINJA/NinjaModels.cs +++ b/NINJA/NinjaModels.cs @@ -6,7 +6,6 @@ namespace NINJA { - #region Ninja classes public class NinjaObject @@ -46,16 +45,22 @@ public class NinjaEvent public IDictionary decription { get; set; } public IDictionary event_type { get; set; } public string event_type_key { get; set; } + [JsonProperty("begin_date")] public string begin_date { get; set; } + [JsonProperty("end_date")] public string end_date { get; set; } + [JsonProperty("begin_time")] public string begin_time { get; set; } + [JsonProperty("end_time")] public string end_time { get; set; } + [JsonProperty("price")] public string price { get; set; } + [JsonProperty("number_of_seats")] public string number_of_seats { get; set; } } diff --git a/NINJA/Parser/ParseNinjaData.cs b/NINJA/Parser/ParseNinjaData.cs index bd3866751..353e17439 100644 --- a/NINJA/Parser/ParseNinjaData.cs +++ b/NINJA/Parser/ParseNinjaData.cs @@ -117,13 +117,15 @@ public static List GetTopicRid(string ninjaeventtype) break; } - return new List() - { - topic - }; + return new List() { topic }; } - public static EventLinked ParseNinjaEventToODHEvent(string id, NinjaEvent ninjaevent, NinjaData place, NinjaData room) + public static EventLinked ParseNinjaEventToODHEvent( + string id, + NinjaEvent ninjaevent, + NinjaData place, + NinjaData room + ) { if (id != "------" && place != null) { @@ -134,15 +136,28 @@ public static EventLinked ParseNinjaEventToODHEvent(string id, NinjaEvent ninjae var ninjaid = new Dictionary() { { "id", id } }; myevent.Mapping.TryAddOrUpdate("culture", ninjaid); + string source = !String.IsNullOrEmpty(place.sname) + ? place.sname.ToLower() + : "ninja"; - string source = !String.IsNullOrEmpty(place.sname) ? place.sname.ToLower() : "ninja"; - - Metadata metainfo = new Metadata() { Id = id, LastUpdate = DateTime.Now, Source = source, Type = "event" }; + Metadata metainfo = new Metadata() + { + Id = id, + LastUpdate = DateTime.Now, + Source = source, + Type = "event" + }; myevent._Meta = metainfo; myevent.Source = source; - LicenseInfo licenseInfo = new LicenseInfo() { ClosedData = false, Author = "", License = "CC0", LicenseHolder = source }; + LicenseInfo licenseInfo = new LicenseInfo() + { + ClosedData = false, + Author = "", + License = "CC0", + LicenseHolder = source + }; myevent.LicenseInfo = licenseInfo; //Maybe needeed by DD Transformer @@ -158,8 +173,18 @@ public static EventLinked ParseNinjaEventToODHEvent(string id, NinjaEvent ninjae { Detail mydetail = new Detail(); mydetail.Language = language; - mydetail.Title = ninjaevent.title != null ? ninjaevent.title.ContainsKey(language) ? ninjaevent.title[language] : "no title" : "no title"; - mydetail.BaseText = ninjaevent.decription != null ? ninjaevent.decription.ContainsKey(language) ? ninjaevent.decription[language] : "" : ""; + mydetail.Title = + ninjaevent.title != null + ? ninjaevent.title.ContainsKey(language) + ? ninjaevent.title[language] + : "no title" + : "no title"; + mydetail.BaseText = + ninjaevent.decription != null + ? ninjaevent.decription.ContainsKey(language) + ? ninjaevent.decription[language] + : "" + : ""; myevent.Detail.TryAddOrUpdate(language, mydetail); } @@ -195,7 +220,6 @@ public static EventLinked ParseNinjaEventToODHEvent(string id, NinjaEvent ninjae } } - //Add Type info myevent.Topics = GetTopicRid(ninjaevent.event_type_key); myevent.TopicRIDs = myevent.Topics.Select(x => x.TopicRID).ToList(); @@ -203,17 +227,19 @@ public static EventLinked ParseNinjaEventToODHEvent(string id, NinjaEvent ninjae //Console.WriteLine("Parsing: " + ninjaevent.begin_date + " " + ninjaevent.begin_time); //TODO PARSING FAILS IF format of datetime is not exactly as described - //TODO Resolve this "exception": "String '04/04/2022 9:00' was not recognized as a valid DateTime.", - + //TODO Resolve this "exception": "String '04/04/2022 9:00' was not recognized as a valid DateTime.", + //Date Info //myevent.DateBegin = DateTime.ParseExact(ninjaevent.begin_date + " " + ninjaevent.begin_time, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture); //myevent.DateEnd = DateTime.ParseExact(ninjaevent.end_date + " " + ninjaevent.end_time, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture); - myevent.DateBegin = TryParsingToDateTime(ninjaevent.begin_date + " " + ninjaevent.begin_time); - myevent.DateEnd = TryParsingToDateTime(ninjaevent.end_date + " " + ninjaevent.end_time); - - + myevent.DateBegin = TryParsingToDateTime( + ninjaevent.begin_date + " " + ninjaevent.begin_time + ); + myevent.DateEnd = TryParsingToDateTime( + ninjaevent.end_date + " " + ninjaevent.end_time + ); //DateTime.TryParse(ninjaevent.begin_date + " " + ninjaevent.begin_time, CultureInfo.InvariantCulture, out evendatebegin); //DateTime.TryParse(ninjaevent.end_date + " " + ninjaevent.end_time, CultureInfo.InvariantCulture, out evendateend); @@ -227,17 +253,29 @@ public static EventLinked ParseNinjaEventToODHEvent(string id, NinjaEvent ninjae myevent.NextBeginDate = myevent.DateBegin; myevent.EventDate = new List() - { - new EventDate() { - Begin = TimeSpan.Parse(ninjaevent.begin_time), - From = DateTime.ParseExact(ninjaevent.begin_date, "dd/MM/yyyy", CultureInfo.InvariantCulture), - End = TimeSpan.Parse(ninjaevent.end_time), - To = DateTime.ParseExact(ninjaevent.end_date, "dd/MM/yyyy", CultureInfo.InvariantCulture), - Ticket = ticket, - MaxPersons = !String.IsNullOrEmpty(ninjaevent.number_of_seats) && int.TryParse(ninjaevent.number_of_seats, out var numberofseatsint) ? numberofseatsint : 0 - } - }; + new EventDate() + { + Begin = TimeSpan.Parse(ninjaevent.begin_time), + From = DateTime.ParseExact( + ninjaevent.begin_date, + "dd/MM/yyyy", + CultureInfo.InvariantCulture + ), + End = TimeSpan.Parse(ninjaevent.end_time), + To = DateTime.ParseExact( + ninjaevent.end_date, + "dd/MM/yyyy", + CultureInfo.InvariantCulture + ), + Ticket = ticket, + MaxPersons = + !String.IsNullOrEmpty(ninjaevent.number_of_seats) + && int.TryParse(ninjaevent.number_of_seats, out var numberofseatsint) + ? numberofseatsint + : 0 + } + }; myevent.Ticket = ticketstr; myevent.PayMet = paymet; @@ -256,20 +294,38 @@ public static EventLinked ParseNinjaEventToODHEvent(string id, NinjaEvent ninjae floor.Add(new KeyValuePair("it", "piano")); floor.Add(new KeyValuePair("en", "floor")); - //Contact Info + //Contact Info foreach (var language in languages) { if (room != null) { string floorstr = " "; - if (!String.IsNullOrEmpty(room.smetadata.floor.ToString()) && floor.ContainsKey(language)) + if ( + !String.IsNullOrEmpty(room.smetadata.floor.ToString()) + && floor.ContainsKey(language) + ) floorstr = floorstr + room.smetadata.floor + " " + floor[language]; ContactInfos mycontact = new ContactInfos(); mycontact.Language = language; - mycontact.Address = room.smetadata.address != null ? room.smetadata.address.ContainsKey(language) ? room.smetadata.address[language] + floorstr : "" : ""; - mycontact.City = room.smetadata.city != null ? room.smetadata.city.ContainsKey(language) ? room.smetadata.city[language] : "" : ""; - mycontact.CompanyName = room.smetadata.name != null ? room.smetadata.name.ContainsKey(language) ? room.smetadata.name[language] : "" : ""; + mycontact.Address = + room.smetadata.address != null + ? room.smetadata.address.ContainsKey(language) + ? room.smetadata.address[language] + floorstr + : "" + : ""; + mycontact.City = + room.smetadata.city != null + ? room.smetadata.city.ContainsKey(language) + ? room.smetadata.city[language] + : "" + : ""; + mycontact.CompanyName = + room.smetadata.name != null + ? room.smetadata.name.ContainsKey(language) + ? room.smetadata.name[language] + : "" + : ""; mycontact.Phonenumber = room.smetadata.phone; mycontact.Email = room.smetadata.email; mycontact.ZipCode = room.smetadata.zipcode; @@ -285,14 +341,32 @@ public static EventLinked ParseNinjaEventToODHEvent(string id, NinjaEvent ninjae if (place != null) { string floorstr = " "; - if (!String.IsNullOrEmpty(place.smetadata.floor.ToString()) && floor.ContainsKey(language)) + if ( + !String.IsNullOrEmpty(place.smetadata.floor.ToString()) + && floor.ContainsKey(language) + ) floorstr = floorstr + place.smetadata.floor + " " + floor[language]; ContactInfos orgcontact = new ContactInfos(); orgcontact.Language = language; - orgcontact.Address = place.smetadata.address != null ? place.smetadata.address.ContainsKey(language) ? place.smetadata.address[language] + floorstr : "" : ""; - orgcontact.City = place.smetadata.city != null ? place.smetadata.city.ContainsKey(language) ? place.smetadata.city[language] : "" : ""; - orgcontact.CompanyName = place.smetadata.name != null ? place.smetadata.name.ContainsKey(language) ? place.smetadata.name[language] : "" : ""; + orgcontact.Address = + place.smetadata.address != null + ? place.smetadata.address.ContainsKey(language) + ? place.smetadata.address[language] + floorstr + : "" + : ""; + orgcontact.City = + place.smetadata.city != null + ? place.smetadata.city.ContainsKey(language) + ? place.smetadata.city[language] + : "" + : ""; + orgcontact.CompanyName = + place.smetadata.name != null + ? place.smetadata.name.ContainsKey(language) + ? place.smetadata.name[language] + : "" + : ""; orgcontact.Phonenumber = place.smetadata.phone; orgcontact.Email = place.smetadata.email; orgcontact.ZipCode = place.smetadata.zipcode; @@ -309,21 +383,26 @@ public static EventLinked ParseNinjaEventToODHEvent(string id, NinjaEvent ninjae { EventAdditionalInfos eventadditionalinfo = new EventAdditionalInfos(); eventadditionalinfo.Language = language; - eventadditionalinfo.Location = room != null ? room.smetadata.name.ContainsKey(language) ? room.smetadata.name[language] : "" : ""; + eventadditionalinfo.Location = + room != null + ? room.smetadata.name.ContainsKey(language) + ? room.smetadata.name[language] + : "" + : ""; eventadditionalinfo.Reg = ninjaevent.link_to_ticket_info; myevent.EventAdditionalInfos.TryAddOrUpdate(language, eventadditionalinfo); } myevent.EventPublisher = new List() - { - new EventPublisher() { - Publish = 1, - PublisherRID = ninjaevent.place, - Ranc = 0 - } - }; + new EventPublisher() + { + Publish = 1, + PublisherRID = ninjaevent.place, + Ranc = 0 + } + }; myevent.HasLanguage = languages; @@ -337,9 +416,25 @@ public static EventLinked ParseNinjaEventToODHEvent(string id, NinjaEvent ninjae public static DateTime TryParsingToDateTime(string datetimetoparse) { - if (DateTime.TryParseExact(datetimetoparse, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime datetimetoreturn)) + if ( + DateTime.TryParseExact( + datetimetoparse, + "dd/MM/yyyy HH:mm", + CultureInfo.InvariantCulture, + DateTimeStyles.None, + out DateTime datetimetoreturn + ) + ) return datetimetoreturn; - else if (DateTime.TryParseExact(datetimetoparse, "dd/MM/yyyy H:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime datetimetoreturn2)) + else if ( + DateTime.TryParseExact( + datetimetoparse, + "dd/MM/yyyy H:mm", + CultureInfo.InvariantCulture, + DateTimeStyles.None, + out DateTime datetimetoreturn2 + ) + ) return datetimetoreturn2; else throw new Exception("DateTime Parsing failed input:" + datetimetoparse); diff --git a/OdhApiCore/Binders/CommaSeparatedArrayBinder.cs b/OdhApiCore/Binders/CommaSeparatedArrayBinder.cs index 41efc8732..9a823d3bf 100644 --- a/OdhApiCore/Binders/CommaSeparatedArrayBinder.cs +++ b/OdhApiCore/Binders/CommaSeparatedArrayBinder.cs @@ -9,18 +9,21 @@ public class CommaSeparatedArrayBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { - var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); + var valueProviderResult = bindingContext.ValueProvider.GetValue( + bindingContext.ModelName + ); - string[] model = - valueProviderResult - .Values - .SelectMany(value => - value?.Split(",", StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty()) - .ToArray(); + string[] model = valueProviderResult.Values + .SelectMany( + value => + value?.Split(",", StringSplitOptions.RemoveEmptyEntries) + ?? Array.Empty() + ) + .ToArray(); bindingContext.Result = ModelBindingResult.Success(model); return Task.CompletedTask; } } -} \ No newline at end of file +} diff --git a/OdhApiCore/Binders/LegacyBool.cs b/OdhApiCore/Binders/LegacyBool.cs index 9dfa6885b..0430d8089 100644 --- a/OdhApiCore/Binders/LegacyBool.cs +++ b/OdhApiCore/Binders/LegacyBool.cs @@ -30,7 +30,9 @@ public class LegacyBoolBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { - var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); + var valueProviderResult = bindingContext.ValueProvider.GetValue( + bindingContext.ModelName + ); var firstValue = valueProviderResult.FirstValue; if (firstValue == null || firstValue == "null") // "null" exists for compatibility reasons { @@ -44,7 +46,9 @@ public Task BindModelAsync(ModelBindingContext bindingContext) { bindingContext.ModelState.TryAddModelError( bindingContext.ModelName, - bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueIsInvalidAccessor(firstValue) + bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueIsInvalidAccessor( + firstValue + ) ); bindingContext.Result = ModelBindingResult.Failed(); } diff --git a/OdhApiCore/Binders/PageSize.cs b/OdhApiCore/Binders/PageSize.cs index 4c5c1b51a..3ea67a8af 100644 --- a/OdhApiCore/Binders/PageSize.cs +++ b/OdhApiCore/Binders/PageSize.cs @@ -35,13 +35,15 @@ public class PageSizeBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { - var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); + var valueProviderResult = bindingContext.ValueProvider.GetValue( + bindingContext.ModelName + ); var firstValue = valueProviderResult.FirstValue; if (firstValue == null || firstValue == "null") // "null" exists for compatibility reasons { bindingContext.Result = ModelBindingResult.Success(new PageSize(10)); } - else if (firstValue == "-1" || firstValue == "0") + else if (firstValue == "-1" || firstValue == "0") { bindingContext.Result = ModelBindingResult.Success(new PageSize(int.MaxValue)); } @@ -53,7 +55,9 @@ public Task BindModelAsync(ModelBindingContext bindingContext) { bindingContext.ModelState.TryAddModelError( bindingContext.ModelName, - bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueIsInvalidAccessor(firstValue) + bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueIsInvalidAccessor( + firstValue + ) ); bindingContext.Result = ModelBindingResult.Failed(); } diff --git a/OdhApiCore/Controllers/alpinebits/AlpineBitsApiController.cs b/OdhApiCore/Controllers/alpinebits/AlpineBitsApiController.cs index bb6941eff..0ea99fa26 100644 --- a/OdhApiCore/Controllers/alpinebits/AlpineBitsApiController.cs +++ b/OdhApiCore/Controllers/alpinebits/AlpineBitsApiController.cs @@ -22,8 +22,12 @@ public class AlpineBitsController : OdhController { private readonly ISettings settings; - public AlpineBitsController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) + public AlpineBitsController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { this.settings = settings; } @@ -36,19 +40,26 @@ public AlpineBitsController(IWebHostEnvironment env, ISettings settings, ILogger /// /// GET All InventoryBasic Objects from User - /// + /// /// AlpineBits InventoryBasicObject [ApiExplorerSettings(IgnoreApi = true)] [Authorize(Roles = "DataReader,AlpineBitsReader,AlpineBitsInventoryBasicReader")] [HttpGet, Route("AlpineBits/InventoryBasic")] - public async Task Get( - string? accoid = null, - bool last = true) + public async Task Get(string? accoid = null, bool last = true) { if (String.IsNullOrEmpty(accoid)) - return await GetAllAlpineBitsMessagesBySource(this.User.Identity?.Name, "InventoryBasicPush"); + return await GetAllAlpineBitsMessagesBySource( + this.User.Identity?.Name, + "InventoryBasicPush" + ); else - return await GetAlpineBitsMessagesByIdandSource(null, this.User.Identity?.Name, "InventoryBasicPush", accoid, last); + return await GetAlpineBitsMessagesByIdandSource( + null, + this.User.Identity?.Name, + "InventoryBasicPush", + accoid, + last + ); } /// @@ -61,7 +72,13 @@ public async Task Get( [HttpGet, Route("AlpineBits/InventoryBasic/{RequestId}")] public async Task Get(string RequestId) { - return await GetAlpineBitsMessagesByIdandSource(RequestId, this.User.Identity?.Name, "InventoryBasicPush", null, false); + return await GetAlpineBitsMessagesByIdandSource( + RequestId, + this.User.Identity?.Name, + "InventoryBasicPush", + null, + false + ); } /// @@ -82,20 +99,29 @@ public async Task PostInventoryBasicData() /// /// GET All InventoryHotelInfo Objects from User - /// + /// /// AlpineBits InventoryHotelInfoObject [ApiExplorerSettings(IgnoreApi = true)] [Authorize(Roles = "DataReader,AlpineBitsReader,AlpineBitsInventoryHotelInfoReader")] [HttpGet, Route("AlpineBits/InventoryHotelInfo")] public async Task GetInventoryHotelInfo( - string? accoid = null, - bool last = true) + string? accoid = null, + bool last = true + ) { if (String.IsNullOrEmpty(accoid)) - return await GetAllAlpineBitsMessagesBySource(this.User.Identity?.Name, "InventoryHotelInfoPush"); + return await GetAllAlpineBitsMessagesBySource( + this.User.Identity?.Name, + "InventoryHotelInfoPush" + ); else - return await GetAlpineBitsMessagesByIdandSource(null, this.User.Identity?.Name, "InventoryHotelInfoPush", accoid, last); - + return await GetAlpineBitsMessagesByIdandSource( + null, + this.User.Identity?.Name, + "InventoryHotelInfoPush", + accoid, + last + ); } /// @@ -108,7 +134,13 @@ public async Task GetInventoryHotelInfo( [HttpGet, Route("AlpineBits/InventoryHotelInfo/{RequestId}")] public async Task GetInventoryHotelInfoSingle(string RequestId) { - return await GetAlpineBitsMessagesByIdandSource(RequestId, this.User.Identity?.Name, "InventoryHotelInfoPush", null, false); + return await GetAlpineBitsMessagesByIdandSource( + RequestId, + this.User.Identity?.Name, + "InventoryHotelInfoPush", + null, + false + ); } /// @@ -116,7 +148,9 @@ public async Task GetInventoryHotelInfoSingle(string RequestId) /// /// HttpResponseMessage [ApiExplorerSettings(IgnoreApi = true)] - [Authorize(Roles = "DataWriter,DataCreate,AlpineBitsWriter,AlpineBitsInventoryHotelInfoWriter")] + [Authorize( + Roles = "DataWriter,DataCreate,AlpineBitsWriter,AlpineBitsInventoryHotelInfoWriter" + )] [HttpPost, Route("AlpineBits/InventoryHotelInfo")] public async Task PostInventoryHotelInfoData() { @@ -129,20 +163,26 @@ public async Task PostInventoryHotelInfoData() /// /// GET All FreeRooms Objects from User - /// + /// /// AlpineBits FreeRoomsObject [ApiExplorerSettings(IgnoreApi = true)] [Authorize(Roles = "DataReader,AlpineBitsReader,AlpineBitsFreeRoomsReader")] [HttpGet, Route("AlpineBits/FreeRooms")] - public async Task GetFreeRooms( - string? accoid = null, - bool last = true) + public async Task GetFreeRooms(string? accoid = null, bool last = true) { if (String.IsNullOrEmpty(accoid)) - return await GetAllAlpineBitsMessagesBySource(this.User.Identity?.Name, "FreeRoomsPush"); + return await GetAllAlpineBitsMessagesBySource( + this.User.Identity?.Name, + "FreeRoomsPush" + ); else - return await GetAlpineBitsMessagesByIdandSource(null, this.User.Identity?.Name, "FreeRoomsPush", accoid, last); - + return await GetAlpineBitsMessagesByIdandSource( + null, + this.User.Identity?.Name, + "FreeRoomsPush", + accoid, + last + ); } /// @@ -155,7 +195,13 @@ public async Task GetFreeRooms( [HttpGet, Route("AlpineBits/FreeRooms/{RequestId}")] public async Task GetFreeRoomsSingle(string RequestId) { - return await GetAlpineBitsMessagesByIdandSource(RequestId, this.User.Identity?.Name, "FreeRoomsPush", null, false); + return await GetAlpineBitsMessagesByIdandSource( + RequestId, + this.User.Identity?.Name, + "FreeRoomsPush", + null, + false + ); } /// @@ -167,14 +213,20 @@ public async Task GetFreeRoomsSingle(string RequestId) [HttpPost, Route("AlpineBits/FreeRooms")] public async Task PostFreeRoomsData() { - return await PostFreeRooms(Request); ; + return await PostFreeRooms(Request); + ; } #endregion #region Helpers - private async Task GetAllAlpineBitsMessagesBySource(string? source, string? messagetype, string? id = null, string? accoids = null) + private async Task GetAllAlpineBitsMessagesBySource( + string? source, + string? messagetype, + string? id = null, + string? accoids = null + ) { try { @@ -183,14 +235,19 @@ private async Task GetAllAlpineBitsMessagesBySource(string? sourc var messagetypelist = CommonListCreator.CreateIdList(messagetype); var accoidlist = CommonListCreator.CreateIdList(accoids); - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("alpinebits") - .AlpineBitsWhereExpression(idlist, sourcelist, accoidlist, messagetypelist, null) - //.OrderByRaw("TO_TIMESTAMP(data ->> 'RequestDate','YYYY-MM-DD T HH24:MI:SS') DESC"); - .OrderByDesc("gen_requestdate"); - + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("alpinebits") + .AlpineBitsWhereExpression( + idlist, + sourcelist, + accoidlist, + messagetypelist, + null + ) + //.OrderByRaw("TO_TIMESTAMP(data ->> 'RequestDate','YYYY-MM-DD T HH24:MI:SS') DESC"); + .OrderByDesc("gen_requestdate"); var data = await query.GetAsync(); @@ -202,7 +259,13 @@ private async Task GetAllAlpineBitsMessagesBySource(string? sourc } } - private async Task GetAlpineBitsMessagesByIdandSource(string? id, string? source, string? messagetype, string? accoids, bool last) + private async Task GetAlpineBitsMessagesByIdandSource( + string? id, + string? source, + string? messagetype, + string? accoids, + bool last + ) { try { @@ -215,18 +278,24 @@ private async Task GetAlpineBitsMessagesByIdandSource(string? id, if (last) limit = 1; - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("alpinebits") - .AlpineBitsWhereExpression(idlist, sourcelist, accoidlist, messagetypelist, null) - //.OrderByRaw("TO_TIMESTAMP(data ->> 'RequestDate','YYYY-MM-DD T HH24:MI:SS') DESC") - .OrderByDesc("gen_requestdate") - .Limit(limit); + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("alpinebits") + .AlpineBitsWhereExpression( + idlist, + sourcelist, + accoidlist, + messagetypelist, + null + ) + //.OrderByRaw("TO_TIMESTAMP(data ->> 'RequestDate','YYYY-MM-DD T HH24:MI:SS') DESC") + .OrderByDesc("gen_requestdate") + .Limit(limit); var data = await query.GetAsync(); - return Ok(data); + return Ok(data); } catch (Exception ex) { @@ -249,12 +318,14 @@ private static async Task ReadStringDataManual(HttpRequest request) private async Task PostInventoryBasic(HttpRequest request) { try - { + { string jsonContent = await ReadStringDataManual(request); if (!string.IsNullOrEmpty(jsonContent)) { - dynamic input = JsonConvert.DeserializeObject(jsonContent) ?? throw new InvalidOperationException(); + dynamic input = + JsonConvert.DeserializeObject(jsonContent) + ?? throw new InvalidOperationException(); var id = input.RequestId.Value; @@ -262,9 +333,20 @@ private async Task PostInventoryBasic(HttpRequest request) input.RequestDate = DateTime.Now; input.Source = this.User.Identity?.Name?.ToLower(); - var query = await QueryFactory.Query("alpinebits").InsertAsync(new JsonBData() { id = id, data = new JsonRaw(input) }); - - return Ok(new GenericResult() { Message = "INSERT AlpineBits InventoryBasicPush succeeded, Request Id:" + id + " username:" + this.User.Identity?.Name }); + var query = await QueryFactory + .Query("alpinebits") + .InsertAsync(new JsonBData() { id = id, data = new JsonRaw(input) }); + + return Ok( + new GenericResult() + { + Message = + "INSERT AlpineBits InventoryBasicPush succeeded, Request Id:" + + id + + " username:" + + this.User.Identity?.Name + } + ); } else throw new Exception("no Content"); @@ -283,7 +365,9 @@ private async Task PostInventoryHotelInfo(HttpRequest request) if (!string.IsNullOrEmpty(jsonContent)) { - dynamic input = JsonConvert.DeserializeObject(jsonContent) ?? throw new InvalidOperationException(); + dynamic input = + JsonConvert.DeserializeObject(jsonContent) + ?? throw new InvalidOperationException(); var id = input.RequestId.Value; @@ -291,13 +375,24 @@ private async Task PostInventoryHotelInfo(HttpRequest request) input.RequestDate = DateTime.Now; input.Source = this.User.Identity?.Name?.ToLower(); - var query = await QueryFactory.Query("alpinebits").InsertAsync(new JsonBData() { id = id, data = new JsonRaw(input) }); + var query = await QueryFactory + .Query("alpinebits") + .InsertAsync(new JsonBData() { id = id, data = new JsonRaw(input) }); //var query = QueryFactory.Query("alpinebits").AsInsert(new JsonBData() { id = id, data = JsonConvert.SerializeObject(input) }); - return Ok(new GenericResult() { Message = "INSERT AlpineBits InventoryHotelInfoPush succeeded, Request Id:" + id + " username:" + this.User.Identity?.Name }); + return Ok( + new GenericResult() + { + Message = + "INSERT AlpineBits InventoryHotelInfoPush succeeded, Request Id:" + + id + + " username:" + + this.User.Identity?.Name + } + ); } else - throw new Exception("no Content"); + throw new Exception("no Content"); } catch (Exception ex) { @@ -313,17 +408,30 @@ private async Task PostFreeRooms(HttpRequest request) if (!string.IsNullOrEmpty(jsonContent)) { - dynamic input = JsonConvert.DeserializeObject(jsonContent) ?? throw new InvalidOperationException(); + dynamic input = + JsonConvert.DeserializeObject(jsonContent) + ?? throw new InvalidOperationException(); var id = input.RequestId.Value; input.MessageType = "FreeRoomsPush"; input.RequestDate = DateTime.Now; - input.Source = this.User.Identity?.Name?.ToLower(); - - var query = await QueryFactory.Query("alpinebits").InsertAsync(new JsonBData() { id = id, data = new JsonRaw(input) }); + input.Source = this.User.Identity?.Name?.ToLower(); - return Ok(new GenericResult() { Message = "INSERT AlpineBits FreeRoomsPush succeeded, Request Id:" + id + " username:" + this.User.Identity?.Name }); + var query = await QueryFactory + .Query("alpinebits") + .InsertAsync(new JsonBData() { id = id, data = new JsonRaw(input) }); + + return Ok( + new GenericResult() + { + Message = + "INSERT AlpineBits FreeRoomsPush succeeded, Request Id:" + + id + + " username:" + + this.User.Identity?.Name + } + ); } else throw new Exception("no Content"); @@ -331,10 +439,9 @@ private async Task PostFreeRooms(HttpRequest request) catch (Exception ex) { return BadRequest(new GenericResult() { Message = ex.Message }); - } + } } - #endregion } } diff --git a/OdhApiCore/Controllers/api/AccommodationApiController.cs b/OdhApiCore/Controllers/api/AccommodationApiController.cs index 6668eda57..625561b80 100644 --- a/OdhApiCore/Controllers/api/AccommodationApiController.cs +++ b/OdhApiCore/Controllers/api/AccommodationApiController.cs @@ -23,7 +23,7 @@ namespace OdhApiCore.Controllers { /// - /// Accommodation Api (data provided by LTS / Availability Requests provided by HGV/LTS) SOME DATA Available as OPENDATA + /// Accommodation Api (data provided by LTS / Availability Requests provided by HGV/LTS) SOME DATA Available as OPENDATA /// [EnableCors("CorsPolicy")] [NullStringParameterActionFilter] @@ -32,8 +32,13 @@ public class AccommodationController : OdhController private readonly IHttpClientFactory httpClientFactory; private readonly ISettings settings; - public AccommodationController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory, IHttpClientFactory httpClientFactory) - : base(env, settings, logger, queryFactory) + public AccommodationController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory, + IHttpClientFactory httpClientFactory + ) : base(env, settings, logger, queryFactory) { this.httpClientFactory = httpClientFactory; this.settings = settings; @@ -49,7 +54,7 @@ private bool CheckAvailabilitySearch(System.Security.Claims.ClaimsPrincipal User if (User.IsInRole(role)) return true; } - + return false; } @@ -67,12 +72,12 @@ private bool CheckAvailabilitySearch(System.Security.Claims.ClaimsPrincipal User /// FeatureFilter BITMASK values: 1 = (Group-friendly), 2 = (Meeting rooms), 4 = (Swimming pool), 8 = (Sauna), 16 = (Garage), 32 = (Pick-up service), 64 = (WLAN), 128 = (Barrier-free), 256 = (Special menus for allergy sufferers), 512 = (Pets welcome), 'null' = (No Filter), (default:'null') /// Feature Id Filter, LIST filter over ALL Features available. Separator ',' List of Feature IDs, 'null' = (No Filter), (default:'null') /// Themefilter BITMASK values: 1 = (Gourmet), 2 = (At altitude), 4 = (Regional wellness offerings), 8 = (on the wheels), 16 = (With family), 32 = (Hiking), 64 = (In the vineyards), 128 = (Urban vibe), 256 = (At the ski resort), 512 = (Mediterranean), 1024 = (In the Dolomites), 2048 = (Alpine), 4096 = (Small and charming), 8192 = (Huts and mountain inns), 16384 = (Rural way of life), 32768 = (Balance), 65536 = (Christmas markets), 131072 = (Sustainability), 'null' = (No Filter), (default:'null') - /// BadgeFilter BITMASK values: 1 = (Belvita Wellness Hotel), 2 = (Familyhotel), 4 = (Bikehotel), 8 = (Red Rooster Farm), 16 = (Barrier free certificated), 32 = (Vitalpina Hiking Hotel), 64 = (Private Rooms in South Tyrol), 128 = (Vinum Hotels), 'null' = (No Filter), (default:'null') + /// BadgeFilter BITMASK values: 1 = (Belvita Wellness Hotel), 2 = (Familyhotel), 4 = (Bikehotel), 8 = (Red Rooster Farm), 16 = (Barrier free certificated), 32 = (Vitalpina Hiking Hotel), 64 = (Private Rooms in South Tyrol), 128 = (Vinum Hotels), 'null' = (No Filter), (default:'null') /// IDFilter LIST Separator ',' List of Accommodation IDs, 'null' = (No Filter), (default:'null') - /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter + /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter /// ODHTag Filter LIST (refers to Array SmgTags) (String, Separator ',' more ODHTags possible, 'null' = No Filter, available ODHTags reference to 'v1/ODHTag?validforentity=accommodation'), (default:'null') - /// ODHActive Filter BOOLEAN (refers to field SmgActive) (possible Values: 'null' Displays all Accommodations, 'true' only ODH Active Accommodations, 'false' only ODH Disabled Accommodations), (default:'null') - /// TIC Active Filter BOOLEAN (possible Values: 'null' Displays all Accommodations, 'true' only TIC Active Accommodations, 'false' only TIC Disabled Accommodations), (default:'null') + /// ODHActive Filter BOOLEAN (refers to field SmgActive) (possible Values: 'null' Displays all Accommodations, 'true' only ODH Active Accommodations, 'false' only ODH Disabled Accommodations), (default:'null') + /// TIC Active Filter BOOLEAN (possible Values: 'null' Displays all Accommodations, 'true' only TIC Active Accommodations, 'false' only TIC Disabled Accommodations), (default:'null') /// Altitude Range Filter SPECIAL (Separator ',' example Value: 500,1000 Altitude from 500 up to 1000 metres), (default:'null') /// Availability Check BOOLEAN (possible Values: 'true', 'false), (default Value: 'false') NOT AVAILABLE AS OPEN DATA, IF Availabilty Check is true certain filters are Required /// Arrival DATE (yyyy-MM-dd) REQUIRED ON Availabilitycheck = true, (default:'Today's date') @@ -88,12 +93,12 @@ private bool CheckAvailabilitySearch(System.Security.Claims.ClaimsPrincipal User /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Language field selector, displays data and fields in the selected language, possible values: 'de|it|en|nl|cs|pl|fr|ru' only one language supported (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Collection of Accommodation Objects /// List created /// Request Error @@ -101,9 +106,14 @@ private bool CheckAvailabilitySearch(System.Security.Claims.ClaimsPrincipal User [ProducesResponseType(typeof(JsonResult), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] [TypeFilter(typeof(Filters.AvailabilitySearchInterceptorAttribute))] - [OdhCacheOutput(ClientTimeSpan = 0, ServerTimeSpan = 3600, CacheKeyGenerator = typeof(CustomCacheKeyGenerator), MustRevalidate = true)] + [OdhCacheOutput( + ClientTimeSpan = 0, + ServerTimeSpan = 3600, + CacheKeyGenerator = typeof(CustomCacheKeyGenerator), + MustRevalidate = true + )] [HttpGet, Route("Accommodation", Name = "AccommodationList")] public async Task GetAccommodations( uint pagenumber = 1, @@ -128,7 +138,7 @@ public async Task GetAccommodations( string? departure = null, string? roominfo = "1-18,18", string? bokfilter = "hgv", - string? msssource = "sinfo", + string? msssource = "sinfo", string? availabilitychecklanguage = "en", string? detail = "0", LegacyBool availabilitycheck = null!, @@ -139,13 +149,13 @@ public async Task GetAccommodations( string? language = null, string? langfilter = null, string? updatefrom = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { //if availabilitysearch requested and User not logged if (availabilitycheck?.Value == true && !CheckAvailabilitySearch(User)) @@ -153,18 +163,48 @@ public async Task GetAccommodations( return Unauthorized("User not allowed for availabilitysearch"); } - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); List bokfilterlist = bokfilter?.Split(',').ToList() ?? new List(); if (availabilitycheck?.Value != true) { return await GetFiltered( - fields: fields ?? Array.Empty(), language: language, pagenumber: pagenumber, - pagesize: pagesize, idfilter: idfilter, idlist: new List(), locfilter: locfilter, categoryfilter: categoryfilter, - typefilter: typefilter, boardfilter: boardfilter, featurefilter: featurefilter, featureidfilter: featureidfilter, themefilter: themefilter, badgefilter: badgefilter, - altitudefilter: altitudefilter, active: active, smgactive: odhactive, bookablefilter: bookablefilter, smgtagfilter: odhtagfilter, sourcefilter: source, publishedon: publishedon, - seed: seed, updatefrom: updatefrom, langfilter: langfilter, searchfilter: searchfilter, geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + fields: fields ?? Array.Empty(), + language: language, + pagenumber: pagenumber, + pagesize: pagesize, + idfilter: idfilter, + idlist: new List(), + locfilter: locfilter, + categoryfilter: categoryfilter, + typefilter: typefilter, + boardfilter: boardfilter, + featurefilter: featurefilter, + featureidfilter: featureidfilter, + themefilter: themefilter, + badgefilter: badgefilter, + altitudefilter: altitudefilter, + active: active, + smgactive: odhactive, + bookablefilter: bookablefilter, + smgtagfilter: odhtagfilter, + sourcefilter: source, + publishedon: publishedon, + seed: seed, + updatefrom: updatefrom, + langfilter: langfilter, + searchfilter: searchfilter, + geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } else if (availabilitycheck?.Value == true) { @@ -174,19 +214,55 @@ public async Task GetAccommodations( var availableonlineaccos = new List(); if (accoavailabilitymss != null) - availableonlineaccos.AddRange(((MssResult?)accoavailabilitymss)?.MssResponseShort?.Select(x => x.A0RID?.ToUpper() ?? "").Distinct().ToList() ?? new List()); + availableonlineaccos.AddRange( + ((MssResult?)accoavailabilitymss) + ?.MssResponseShort?.Select(x => x.A0RID?.ToUpper() ?? "") + .Distinct() + .ToList() ?? new List() + ); if (accoavailabilitylcs != null) - availableonlineaccos.AddRange(((MssResult?)accoavailabilitylcs)?.MssResponseShort?.Select(x => x.A0RID?.ToUpper() ?? "").Distinct().ToList() ?? new List()); + availableonlineaccos.AddRange( + ((MssResult?)accoavailabilitylcs) + ?.MssResponseShort?.Select(x => x.A0RID?.ToUpper() ?? "") + .Distinct() + .ToList() ?? new List() + ); //TODO SORT ORDER??? return await GetFiltered( - fields: fields ?? Array.Empty(), language: language, pagenumber: pagenumber, - pagesize: pagesize, idfilter: idfilter, idlist: availableonlineaccos, locfilter: locfilter, categoryfilter: categoryfilter, - typefilter: typefilter, boardfilter: boardfilter, featurefilter: featurefilter, featureidfilter: featureidfilter, themefilter: themefilter, badgefilter: badgefilter, - altitudefilter: altitudefilter, active: active, smgactive: odhactive, bookablefilter: bookablefilter, smgtagfilter: odhtagfilter, sourcefilter: source, publishedon: publishedon, - seed: seed, updatefrom: updatefrom, langfilter: langfilter, searchfilter: searchfilter, geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); - } + fields: fields ?? Array.Empty(), + language: language, + pagenumber: pagenumber, + pagesize: pagesize, + idfilter: idfilter, + idlist: availableonlineaccos, + locfilter: locfilter, + categoryfilter: categoryfilter, + typefilter: typefilter, + boardfilter: boardfilter, + featurefilter: featurefilter, + featureidfilter: featureidfilter, + themefilter: themefilter, + badgefilter: badgefilter, + altitudefilter: altitudefilter, + active: active, + smgactive: odhactive, + bookablefilter: bookablefilter, + smgtagfilter: odhtagfilter, + sourcefilter: source, + publishedon: publishedon, + seed: seed, + updatefrom: updatefrom, + langfilter: langfilter, + searchfilter: searchfilter, + geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); + } else { return BadRequest("not supported!"); @@ -197,7 +273,7 @@ public async Task GetAccommodations( /// GET Accommodation Single /// /// ID of the Accommodation - /// ID Source Filter (possible values:'lts','hgv'), (default:'lts') + /// ID Source Filter (possible values:'lts','hgv'), (default:'lts') /// Boardfilter BITMASK values: 0 = (all boards), 1 = (without board), 2 = (breakfast), 4 = (half board), 8 = (full board), 16 = (All inclusive), 'null' = (No Filter), (default:'null') /// Availability Check enabled/disabled (possible Values: 'true', 'false), (default Value: 'false') NOT AVAILABLE AS OPEN DATA /// Arrival Date (yyyy-MM-dd) REQUIRED, (default:'Today') @@ -208,7 +284,7 @@ public async Task GetAccommodations( /// Detail of the Availablity check (string, 1 = full Details, 0 = basic Details (default)) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Accommodation Object /// Object created /// Request Error @@ -216,7 +292,7 @@ public async Task GetAccommodations( [ProducesResponseType(typeof(AccommodationLinked), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("Accommodation/{id}", Name = "SingleAccommodation")] [TypeFilter(typeof(Filters.AvailabilitySearchInterceptorAttribute))] public async Task GetAccommodation( @@ -231,11 +307,11 @@ public async Task GetAccommodation( string? msssource = "sinfo", LegacyBool availabilitycheck = null!, string? detail = "0", - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { //if availabilitysearch requested and User not logged if (availabilitycheck?.Value == true && !CheckAvailabilitySearch(User)) @@ -244,9 +320,21 @@ public async Task GetAccommodation( } if (idsource == "hgv") - return await GetSingleByHgvId(id, language, fields: fields ?? Array.Empty(), removenullvalues, cancellationToken); + return await GetSingleByHgvId( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues, + cancellationToken + ); else - return await GetSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues, cancellationToken); + return await GetSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues, + cancellationToken + ); } //ACCO TYPES @@ -260,26 +348,34 @@ public async Task GetAccommodation( /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of AccommodationType Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of AccommodationType Object /// List created /// Request Error /// Internal Server Error [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("AccommodationTypes")] public async Task GetAllAccommodationTypesList( string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetAccoTypeList(language, fields: fields ?? Array.Empty(), searchfilter, rawfilter, rawsort, removenullvalues, cancellationToken); + return await GetAccoTypeList( + language, + fields: fields ?? Array.Empty(), + searchfilter, + rawfilter, + rawsort, + removenullvalues, + cancellationToken + ); } /// @@ -288,8 +384,8 @@ public async Task GetAllAccommodationTypesList( /// ID of the AccommodationType /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Language field selector, displays data and fields in the selected language, possible values: 'de|it|en|nl|cs|pl|fr|ru' only one language supported (default:'null' all languages are displayed) - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// AccommodationType Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// AccommodationType Object /// List created /// Request Error /// Internal Server Error @@ -301,12 +397,18 @@ public async Task GetAllAccommodationTypesList( public async Task GetAllAccommodationTypessingle( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetAccoTypeSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues, cancellationToken); + return await GetAccoTypeSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues, + cancellationToken + ); } /// @@ -320,8 +422,8 @@ public async Task GetAllAccommodationTypessingle( /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of AccoFeatures Object / XML LTS + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of AccoFeatures Object / XML LTS /// List created /// Request Error /// Internal Server Error @@ -333,19 +435,28 @@ public async Task GetAllAccommodationTypessingle( public async Task GetAllAccommodationFeaturesList( string? language, string? ltst0idfilter = null, - string? source = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + string? source = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - if (!String.IsNullOrEmpty(source) && source == "lts") - return GetFeatureListXML(cancellationToken); + if (!String.IsNullOrEmpty(source) && source == "lts") + return GetFeatureListXML(cancellationToken); else - return await GetAccoFeatureList(language, ltst0idfilter, fields: fields ?? Array.Empty(), searchfilter, rawfilter, rawsort, removenullvalues, cancellationToken); + return await GetAccoFeatureList( + language, + ltst0idfilter, + fields: fields ?? Array.Empty(), + searchfilter, + rawfilter, + rawsort, + removenullvalues, + cancellationToken + ); } /// @@ -354,8 +465,8 @@ public async Task GetAllAccommodationFeaturesList( /// ID of the AccommodationFeature /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Language field selector, displays data and fields in the selected language, possible values: 'de|it|en|nl|cs|pl|fr|ru' only one language supported (default:'null' all languages are displayed) - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// AccoFeatures Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// AccoFeatures Object /// List created /// Request Error /// Internal Server Error @@ -367,12 +478,18 @@ public async Task GetAllAccommodationFeaturesList( public async Task GetAllAccommodationFeaturesSingle( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetAccoFeatureSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues, cancellationToken); + return await GetAccoFeatureSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues, + cancellationToken + ); } // ACCO ROOMS @@ -381,9 +498,9 @@ public async Task GetAllAccommodationFeaturesSingle( /// GET Accommodation Room Info by Accommodation /// /// Accommodation ID - /// HGV ID or LTS ID of the Accommodation (possible values:'lts','hgv'), (default:'lts') - /// Source Filter (possible values:'lts','hgv'), (default:null) - /// Get Rooms from all sources (If an accommodation is bookable on Booking Southtyrol, rooms from this source are returned, setting getall to true returns also LTS Rooms), (default:false) + /// HGV ID or LTS ID of the Accommodation (possible values:'lts','hgv'), (default:'lts') + /// Source Filter (possible values:'lts','hgv'), (default:null) + /// Get Rooms from all sources (If an accommodation is bookable on Booking Southtyrol, rooms from this source are returned, setting getall to true returns also LTS Rooms), (default:false) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) @@ -391,9 +508,12 @@ public async Task GetAllAccommodationFeaturesSingle( /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Collection of AccoRoom Objects - [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] + [ProducesResponseType( + typeof(IEnumerable), + StatusCodes.Status200OK + )] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] //[Authorize(Roles = "DataReader,AccoReader")] @@ -403,8 +523,7 @@ public async Task GetAccoRoomInfos( string? idsource = "lts", string? source = null, bool getall = false, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, string? langfilter = null, string? updatefrom = null, @@ -413,16 +532,29 @@ public async Task GetAccoRoomInfos( string? rawsort = null, bool removenullvalues = false, CancellationToken cancellationToken = default - ) + ) { string idtocheck = accoid; if (idsource == "hgv") { idtocheck = await GetAccoIdByHgvId(accoid, cancellationToken); - } + } - return await GetAccommodationRooms(idtocheck, fields: fields ?? Array.Empty(), language, getall, source, updatefrom, langfilter, searchfilter, rawfilter, rawsort, removenullvalues, cancellationToken); + return await GetAccommodationRooms( + idtocheck, + fields: fields ?? Array.Empty(), + language, + getall, + source, + updatefrom, + langfilter, + searchfilter, + rawfilter, + rawsort, + removenullvalues, + cancellationToken + ); } // ACCO ROOMS @@ -433,22 +565,28 @@ public async Task GetAccoRoomInfos( /// AccommodationRoom ID /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// AccommodationRoom Object [ProducesResponseType(typeof(AccommodationRoomLinked), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - //[Authorize(Roles = "DataReader,AccoReader")] + //[Authorize(Roles = "DataReader,AccoReader")] [HttpGet, Route("AccommodationRoom/{id}", Name = "SingleAccommodationRoom")] public async Task GetAccoRoomInfosById( string id, string? language = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) - { - return await GetSingleAccommodationRoom(id, language, fields: fields ?? Array.Empty(), removenullvalues, cancellationToken); + CancellationToken cancellationToken = default + ) + { + return await GetSingleAccommodationRoom( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues, + cancellationToken + ); } //SPECIAL GETTER @@ -460,14 +598,17 @@ public async Task GetAccoRoomInfosById( /// Boardfilter (BITMASK values: 0 = (all boards), 1 = (without board), 2 = (breakfast), 4 = (half board), 8 = (full board), 16 = (All inclusive), 'null' = No Filter) /// Arrival Date (yyyy-MM-dd) REQUIRED /// Departure Date (yyyy-MM-dd) REQUIRED - /// Roominfo Filter REQUIRED (Splitter for Rooms '|' Splitter for Persons Ages ',') (Room Types: 0=notprovided, 1=room, 2=apartment, 4=pitch/tent(onlyLTS), 8=dorm(onlyLTS)) possible Values Example 1-18,10|1-18 = 2 Rooms, Room 1 for 2 person Age 18 and Age 10, Room 2 for 1 Person Age 18), (default:'1-18,18')/// Booking Channels Filter (Separator ',' possible values: hgv = (Booking Südtirol), htl = (Hotel.de), exp = (Expedia), bok = (Booking.com), lts = (LTS Availability check), (default:hgv)) REQUIRED + /// Roominfo Filter REQUIRED (Splitter for Rooms '|' Splitter for Persons Ages ',') (Room Types: 0=notprovided, 1=room, 2=apartment, 4=pitch/tent(onlyLTS), 8=dorm(onlyLTS)) possible Values Example 1-18,10|1-18 = 2 Rooms, Room 1 for 2 person Age 18 and Age 10, Room 2 for 1 Person Age 18), (default:'1-18,18')/// Booking Channels Filter (Separator ',' possible values: hgv = (Booking Südtirol), htl = (Hotel.de), exp = (Expedia), bok = (Booking.com), lts = (LTS Availability check), (default:hgv)) REQUIRED /// Include Offer Details (String, 1 = full Details) - /// Source of the Requester (possible value: 'sinfo' = Suedtirol.info, 'sbalance' = Südtirol Balance) REQUIRED - /// Search over all bookable Accommodations (No Ids have to be provided as Post Data, when set to true, all passed Ids are omitted) (default: false) + /// Source of the Requester (possible value: 'sinfo' = Suedtirol.info, 'sbalance' = Südtirol Balance) REQUIRED + /// Search over all bookable Accommodations (No Ids have to be provided as Post Data, when set to true, all passed Ids are omitted) (default: false) /// Get only availability information without Accommodation information /// Posted Accommodation IDs (Separated by , must be specified in the POST Body as raw) - /// Result Object with Collection of Accommodation Objects - [ProducesResponseType(typeof(JsonResultWithBookingInfo), StatusCodes.Status200OK)] + /// Result Object with Collection of Accommodation Objects + [ProducesResponseType( + typeof(JsonResultWithBookingInfo), + StatusCodes.Status200OK + )] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -476,7 +617,10 @@ public async Task GetAccoRoomInfosById( [HttpPost, Route("AccommodationAvailable")] //[HttpPost, Route("AvailabilityCheck")] public async Task PostAvailableAccommodations( - [FromBody(EmptyBodyBehavior = Microsoft.AspNetCore.Mvc.ModelBinding.EmptyBodyBehavior.Allow)] string? idfilter = null, + [FromBody( + EmptyBodyBehavior = Microsoft.AspNetCore.Mvc.ModelBinding.EmptyBodyBehavior.Allow + )] + string? idfilter = null, string? availabilitychecklanguage = "en", string? boardfilter = null, string? arrival = null, @@ -485,9 +629,10 @@ public async Task PostAvailableAccommodations( string? bokfilter = "hgv", string? msssource = "sinfo", string? detail = "0", - bool withoutids = false, + bool withoutids = false, bool availabilityonly = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { bokfilter ??= "hgv"; @@ -504,15 +649,25 @@ public async Task PostAvailableAccommodations( availabilityonly = true; //If no ids in the post body, makes ure withoutids is checked (make use of cached MSS) - if((idfilter == null || String.IsNullOrEmpty(idfilter)) && withoutids == false) - return BadRequest("No Ids in the POST Body, Availability Search over all Accommodations only with withoutids set to true"); + if ((idfilter == null || String.IsNullOrEmpty(idfilter)) && withoutids == false) + return BadRequest( + "No Ids in the POST Body, Availability Search over all Accommodations only with withoutids set to true" + ); var accobooklist = Request.HttpContext.Items["accobooklist"]; var accoavailabilitymss = Request.HttpContext.Items["mssavailablity"]; var accoavailabilitylcs = Request.HttpContext.Items["lcsavailablity"]; - var accosonmss = ((MssResult?)accoavailabilitymss)?.MssResponseShort?.Select(x => x.A0RID?.ToUpper() ?? "").Distinct().ToList() ?? new List(); - var accosonlcs = ((MssResult?)accoavailabilitylcs)?.MssResponseShort?.Select(x => x.A0RID?.ToUpper() ?? "").Distinct().ToList() ?? new List(); + var accosonmss = + ((MssResult?)accoavailabilitymss) + ?.MssResponseShort?.Select(x => x.A0RID?.ToUpper() ?? "") + .Distinct() + .ToList() ?? new List(); + var accosonlcs = + ((MssResult?)accoavailabilitylcs) + ?.MssResponseShort?.Select(x => x.A0RID?.ToUpper() ?? "") + .Distinct() + .ToList() ?? new List(); var availableonlineaccos = new List(); if (accoavailabilitymss != null) @@ -533,35 +688,71 @@ public async Task PostAvailableAccommodations( var toreturn = new List(); if (bokfilter.Contains("hgv") && accoavailabilitymss != null) - toreturn.AddRange(((MssResult?)accoavailabilitymss)?.MssResponseShort?.ToList() ?? new()); + toreturn.AddRange( + ((MssResult?)accoavailabilitymss)?.MssResponseShort?.ToList() ?? new() + ); if (bokfilter.Contains("lts") && accoavailabilitylcs != null) - toreturn.AddRange(((MssResult?)accoavailabilitylcs)?.MssResponseShort?.ToList() ?? new()); + toreturn.AddRange( + ((MssResult?)accoavailabilitylcs)?.MssResponseShort?.ToList() ?? new() + ); //return immediately the mss response var result = ResponseHelpers.GetResult( - 1, - 1, - (uint)requestedtotal, - requestedtotal, - availableonline, - availableonrequest, - resultid, - "", - toreturn, - Url); + 1, + 1, + (uint)requestedtotal, + requestedtotal, + availableonline, + availableonrequest, + resultid, + "", + toreturn, + Url + ); return (Ok(result)); } else { return await GetFiltered( - fields: Array.Empty(), language: null, pagenumber: 1, - pagesize: int.MaxValue, idfilter: idfilter, idlist: availableonlineaccos, locfilter: null, categoryfilter: null, - typefilter: null, boardfilter: boardfilter, featurefilter: null, featureidfilter: null, themefilter: null, badgefilter: null, - altitudefilter: null, active: null, smgactive: null, bookablefilter: null, smgtagfilter: null, sourcefilter: null, - publishedon: null, seed: null, updatefrom: null, langfilter: null, searchfilter: null, new PGGeoSearchResult() { geosearch = false, latitude = 0, longitude = 0, radius = 0 }, - rawfilter: null, rawsort: null, removenullvalues: false, cancellationToken); - } + fields: Array.Empty(), + language: null, + pagenumber: 1, + pagesize: int.MaxValue, + idfilter: idfilter, + idlist: availableonlineaccos, + locfilter: null, + categoryfilter: null, + typefilter: null, + boardfilter: boardfilter, + featurefilter: null, + featureidfilter: null, + themefilter: null, + badgefilter: null, + altitudefilter: null, + active: null, + smgactive: null, + bookablefilter: null, + smgtagfilter: null, + sourcefilter: null, + publishedon: null, + seed: null, + updatefrom: null, + langfilter: null, + searchfilter: null, + new PGGeoSearchResult() + { + geosearch = false, + latitude = 0, + longitude = 0, + radius = 0 + }, + rawfilter: null, + rawsort: null, + removenullvalues: false, + cancellationToken + ); + } } /// @@ -571,21 +762,27 @@ public async Task PostAvailableAccommodations( /// Boardfilter (BITMASK values: 0 = (all boards), 1 = (without board), 2 = (breakfast), 4 = (half board), 8 = (full board), 16 = (All inclusive), 'null' = No Filter) /// Arrival Date (yyyy-MM-dd) REQUIRED /// Departure Date (yyyy-MM-dd) REQUIRED - /// Roominfo Filter REQUIRED (Splitter for Rooms '|' Splitter for Persons Ages ',') (Room Types: 0=notprovided, 1=room, 2=apartment, 4=pitch/tent(onlyLTS), 8=dorm(onlyLTS)) possible Values Example 1-18,10|1-18 = 2 Rooms, Room 1 for 2 person Age 18 and Age 10, Room 2 for 1 Person Age 18), (default:'1-18,18')/// Booking Channels Filter (Separator ',' possible values: hgv = (Booking Südtirol), htl = (Hotel.de), exp = (Expedia), bok = (Booking.com), lts = (LTS Availability check), (default:hgv)) REQUIRED + /// Roominfo Filter REQUIRED (Splitter for Rooms '|' Splitter for Persons Ages ',') (Room Types: 0=notprovided, 1=room, 2=apartment, 4=pitch/tent(onlyLTS), 8=dorm(onlyLTS)) possible Values Example 1-18,10|1-18 = 2 Rooms, Room 1 for 2 person Age 18 and Age 10, Room 2 for 1 Person Age 18), (default:'1-18,18')/// Booking Channels Filter (Separator ',' possible values: hgv = (Booking Südtirol), htl = (Hotel.de), exp = (Expedia), bok = (Booking.com), lts = (LTS Availability check), (default:hgv)) REQUIRED /// Include Offer Details (String, 1 = full Details) - /// Source of the Requester (possible value: 'sinfo' = Suedtirol.info, 'sbalance' = Südtirol Balance) REQUIRED - /// Search over all bookable Accommodations (No Ids have to be provided as Post Data, when set to true, all passed Ids are omitted) (default: false) - /// Posted Accommodation IDs (Separated by , must be specified in the POST Body as raw) - /// Result Object with Collection of Accommodation Objects - [ProducesResponseType(typeof(JsonResultWithBookingInfo), StatusCodes.Status200OK)] + /// Source of the Requester (possible value: 'sinfo' = Suedtirol.info, 'sbalance' = Südtirol Balance) REQUIRED + /// Search over all bookable Accommodations (No Ids have to be provided as Post Data, when set to true, all passed Ids are omitted) (default: false) + /// Posted Accommodation IDs (Separated by , must be specified in the POST Body as raw) + /// Result Object with Collection of Accommodation Objects + [ProducesResponseType( + typeof(JsonResultWithBookingInfo), + StatusCodes.Status200OK + )] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] //[Authorize(Roles = "DataReader,AccoReader,PackageReader")] - [TypeFilter(typeof(Filters.AvailabilitySearchInterceptorAttribute))] + [TypeFilter(typeof(Filters.AvailabilitySearchInterceptorAttribute))] [HttpPost, Route("AvailabilityCheck")] public async Task PostAvailableAccommodationsOnlyMssResult( - [FromBody(EmptyBodyBehavior = Microsoft.AspNetCore.Mvc.ModelBinding.EmptyBodyBehavior.Allow)] string? idfilter = null, + [FromBody( + EmptyBodyBehavior = Microsoft.AspNetCore.Mvc.ModelBinding.EmptyBodyBehavior.Allow + )] + string? idfilter = null, string? availabilitychecklanguage = "en", string? boardfilter = null, string? arrival = null, @@ -594,144 +791,272 @@ public async Task PostAvailableAccommodationsOnlyMssResult( string? bokfilter = "hgv", string? msssource = "sinfo", string? detail = "0", - bool withoutids = false, - CancellationToken cancellationToken = default) + bool withoutids = false, + CancellationToken cancellationToken = default + ) { - return await PostAvailableAccommodations(idfilter, availabilitychecklanguage, boardfilter, arrival, departure, roominfo, bokfilter, msssource, detail, withoutids, true, cancellationToken); + return await PostAvailableAccommodations( + idfilter, + availabilitychecklanguage, + boardfilter, + arrival, + departure, + roominfo, + bokfilter, + msssource, + detail, + withoutids, + true, + cancellationToken + ); } #endregion #region GETTER - private Task GetFiltered(string[] fields, string? language, uint pagenumber, int? pagesize, string? idfilter, List idlist, string? locfilter, - string? categoryfilter, string? typefilter, string? boardfilter, string? featurefilter, string? featureidfilter, string? themefilter, string? badgefilter, string? altitudefilter, - bool? active, bool? smgactive, bool? bookablefilter, string? smgtagfilter, string? sourcefilter, string? publishedon, - string? seed, string? updatefrom, string? langfilter, string? searchfilter, - PGGeoSearchResult geosearchresult, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task GetFiltered( + string[] fields, + string? language, + uint pagenumber, + int? pagesize, + string? idfilter, + List idlist, + string? locfilter, + string? categoryfilter, + string? typefilter, + string? boardfilter, + string? featurefilter, + string? featureidfilter, + string? themefilter, + string? badgefilter, + string? altitudefilter, + bool? active, + bool? smgactive, + bool? bookablefilter, + string? smgtagfilter, + string? sourcefilter, + string? publishedon, + string? seed, + string? updatefrom, + string? langfilter, + string? searchfilter, + PGGeoSearchResult geosearchresult, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { AccommodationHelper myhelper = await AccommodationHelper.CreateAsync( - QueryFactory, idfilter: idfilter, locfilter: locfilter, boardfilter: boardfilter, categoryfilter: categoryfilter, typefilter: typefilter, - featurefilter: featurefilter, featureidfilter: featureidfilter, badgefilter: badgefilter, themefilter: themefilter, altitudefilter: altitudefilter, smgtags: smgtagfilter, activefilter: active, - smgactivefilter: smgactive, bookablefilter: bookablefilter, sourcefilter: sourcefilter, lastchange: updatefrom, langfilter: langfilter, publishedonfilter: publishedon, cancellationToken); + QueryFactory, + idfilter: idfilter, + locfilter: locfilter, + boardfilter: boardfilter, + categoryfilter: categoryfilter, + typefilter: typefilter, + featurefilter: featurefilter, + featureidfilter: featureidfilter, + badgefilter: badgefilter, + themefilter: themefilter, + altitudefilter: altitudefilter, + smgtags: smgtagfilter, + activefilter: active, + smgactivefilter: smgactive, + bookablefilter: bookablefilter, + sourcefilter: sourcefilter, + lastchange: updatefrom, + langfilter: langfilter, + publishedonfilter: publishedon, + cancellationToken + ); //Fix if idlist from availabilitysearch is added use this instead of idfilter if (idlist.Count > 0) myhelper.idlist = idlist; - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("accommodations") - .AccommodationWhereExpression( - idlist: myhelper.idlist, accotypelist: myhelper.accotypelist, - categorylist: myhelper.categorylist, featurelist: myhelper.featurelist, featureidlist: myhelper.featureidlist, - badgelist: myhelper.badgelist, themelist: myhelper.themelist, - boardlist: myhelper.boardlist, smgtaglist: myhelper.smgtaglist, - districtlist: myhelper.districtlist, municipalitylist: myhelper.municipalitylist, - tourismvereinlist: myhelper.tourismvereinlist, regionlist: myhelper.regionlist, - apartmentfilter: myhelper.apartment, bookable: myhelper.bookable, altitude: myhelper.altitude, - altitudemin: myhelper.altitudemin, altitudemax: myhelper.altitudemax, - activefilter: myhelper.active, smgactivefilter: myhelper.smgactive, publishedonlist: myhelper.publishedonlist, - sourcelist: myhelper.sourcelist, - searchfilter: searchfilter, language: language, lastchange: myhelper.lastchange, languagelist: myhelper.languagelist, - filterClosedData: FilterClosedData, reducedData: ReducedData) - .ApplyRawFilter(rawfilter) - .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("accommodations") + .AccommodationWhereExpression( + idlist: myhelper.idlist, + accotypelist: myhelper.accotypelist, + categorylist: myhelper.categorylist, + featurelist: myhelper.featurelist, + featureidlist: myhelper.featureidlist, + badgelist: myhelper.badgelist, + themelist: myhelper.themelist, + boardlist: myhelper.boardlist, + smgtaglist: myhelper.smgtaglist, + districtlist: myhelper.districtlist, + municipalitylist: myhelper.municipalitylist, + tourismvereinlist: myhelper.tourismvereinlist, + regionlist: myhelper.regionlist, + apartmentfilter: myhelper.apartment, + bookable: myhelper.bookable, + altitude: myhelper.altitude, + altitudemin: myhelper.altitudemin, + altitudemax: myhelper.altitudemax, + activefilter: myhelper.active, + smgactivefilter: myhelper.smgactive, + publishedonlist: myhelper.publishedonlist, + sourcelist: myhelper.sourcelist, + searchfilter: searchfilter, + language: language, + lastchange: myhelper.lastchange, + languagelist: myhelper.languagelist, + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); uint totalpages = (uint)data.TotalPages; uint totalcount = (uint)data.Count; - var availableonline = Request.HttpContext.Items["mssavailablity"] != null ? ((MssResult?)Request.HttpContext.Items["mssavailablity"])!.MssResponseShort.Count : 0; - var availableonrequest = Request.HttpContext.Items["lcsavailablity"] != null ? ((MssResult?)Request.HttpContext.Items["lcsavailablity"])!.MssResponseShort.Count : 0; + var availableonline = + Request.HttpContext.Items["mssavailablity"] != null + ? ((MssResult?)Request.HttpContext.Items["mssavailablity"])! + .MssResponseShort + .Count + : 0; + var availableonrequest = + Request.HttpContext.Items["lcsavailablity"] != null + ? ((MssResult?)Request.HttpContext.Items["lcsavailablity"])! + .MssResponseShort + .Count + : 0; var accobooklist = Request.HttpContext.Items["accobooklist"]; var accosrequested = accobooklist != null ? ((List)accobooklist).Count : 0; - var resultid = ((MssResult?)Request.HttpContext.Items["mssavailablity"])?.ResultId ?? ""; + var resultid = + ((MssResult?)Request.HttpContext.Items["mssavailablity"])?.ResultId ?? ""; if (availableonline > 0) { return ResponseHelpers.GetResult( - pagenumber, - totalpages, - (uint)accosrequested, - accosrequested, - availableonline, - availableonrequest, - resultid, - seed, - dataTransformed, - Url); + pagenumber, + totalpages, + (uint)accosrequested, + accosrequested, + availableonline, + availableonrequest, + resultid, + seed, + dataTransformed, + Url + ); } else { return ResponseHelpers.GetResult( - pagenumber, - totalpages, - totalcount, - seed, - dataTransformed, - Url); + pagenumber, + totalpages, + totalcount, + seed, + dataTransformed, + Url + ); } }); } - private Task GetSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("accommodations") - .Select("data") - .Where("id", id.ToUpper()) - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + var query = QueryFactory + .Query("accommodations") + .Select("data") + .Where("id", id.ToUpper()) + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); - var data = await query.FirstOrDefaultAsync(cancellationToken: cancellationToken); + var data = await query.FirstOrDefaultAsync( + cancellationToken: cancellationToken + ); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } - private Task GetSingleByHgvId(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSingleByHgvId( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("accommodations") - .Select("data") - .Where("gen_hgvid", "ILIKE", id) - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + var query = QueryFactory + .Query("accommodations") + .Select("data") + .Where("gen_hgvid", "ILIKE", id) + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); - var data = await query.FirstOrDefaultAsync(cancellationToken: cancellationToken); + var data = await query.FirstOrDefaultAsync( + cancellationToken: cancellationToken + ); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } private async Task GetAccoIdByHgvId(string id, CancellationToken cancellationToken) { - var query = - QueryFactory.Query("accommodations") - .Select("id") - .Where("gen_hgvid", "ILIKE", id) - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + var query = QueryFactory + .Query("accommodations") + .Select("id") + .Where("gen_hgvid", "ILIKE", id) + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); var data = await query.FirstOrDefaultAsync(); @@ -744,39 +1069,56 @@ private Task GetAccommodationRooms( string? language, bool all, string? sourcefilter, - string? updatefrom, + string? updatefrom, string? langfilter, string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken - ) + ) { return DoAsyncReturn(async () => { var languagelist = Helper.CommonListCreator.CreateIdList(langfilter); var sourcelist = Helper.CommonListCreator.CreateIdList(sourcefilter); - var query = - QueryFactory.Query("accommodationrooms") - .Select("data") - .Where("gen_a0rid", "ILIKE", id) - .When(languagelist.Count > 0, q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist)) - .When(sourcelist.Count > 0, q => q.SourceFilter_GeneratedColumn(sourcelist)) - .When(!String.IsNullOrEmpty(updatefrom), q => q.LastChangedFilter_GeneratedColumn(updatefrom)) - .SearchFilter(PostgresSQLWhereBuilder.AccoRoomNameFieldsToSearchFor(language), searchfilter) - .ApplyRawFilter(rawfilter) - .OrderOnlyByRawSortIfNotNull(rawsort) - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + var query = QueryFactory + .Query("accommodationrooms") + .Select("data") + .Where("gen_a0rid", "ILIKE", id) + .When( + languagelist.Count > 0, + q => q.HasLanguageFilterAnd_GeneratedColumn(languagelist) + ) + .When(sourcelist.Count > 0, q => q.SourceFilter_GeneratedColumn(sourcelist)) + .When( + !String.IsNullOrEmpty(updatefrom), + q => q.LastChangedFilter_GeneratedColumn(updatefrom) + ) + .SearchFilter( + PostgresSQLWhereBuilder.AccoRoomNameFieldsToSearchFor(language), + searchfilter + ) + .ApplyRawFilter(rawfilter) + .OrderOnlyByRawSortIfNotNull(rawsort) + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); var data = await query.GetAsync(cancellationToken: cancellationToken); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.Select( - raw => raw?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); @@ -792,20 +1134,31 @@ private Task GetSingleAccommodationRoom( string? language, string[] fields, bool removenullvalues, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("accommodationrooms") - .Select("data") - .Where("id", id.ToUpper()) - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + var query = QueryFactory + .Query("accommodationrooms") + .Select("data") + .Where("id", id.ToUpper()) + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); - var data = await query.FirstOrDefaultAsync(cancellationToken: cancellationToken); + var data = await query.FirstOrDefaultAsync( + cancellationToken: cancellationToken + ); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -819,95 +1172,170 @@ private Task GetSingleAccommodationRoom( #region CATEGORIES - private Task GetAccoTypeList(string? language, string[] fields, string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task GetAccoTypeList( + string? language, + string[] fields, + string? searchfilter, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("accommodationtypes") - .SelectRaw("data") - .When(FilterClosedData, q => q.FilterClosedData()) - .SearchFilter(PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), searchfilter) - .ApplyRawFilter(rawfilter) - .OrderOnlyByRawSortIfNotNull(rawsort); + var query = QueryFactory + .Query("accommodationtypes") + .SelectRaw("data") + .When(FilterClosedData, q => q.FilterClosedData()) + .SearchFilter( + PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), + searchfilter + ) + .ApplyRawFilter(rawfilter) + .OrderOnlyByRawSortIfNotNull(rawsort); var data = await query.GetAsync(); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.Select( - raw => raw?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); } - private Task GetAccoTypeSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetAccoTypeSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("accommodationtypes") - .Select("data") - //.WhereJsonb("Key", "ilike", id) - .Where("id", id.ToLower()) - .When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query("accommodationtypes") + .Select("data") + //.WhereJsonb("Key", "ilike", id) + .Where("id", id.ToLower()) + .When(FilterClosedData, q => q.FilterClosedData()); //.Where("Key", "ILIKE", id); var data = await query.FirstOrDefaultAsync(); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } - private Task GetAccoFeatureList(string? language, string? ltst0filter, string[] fields, string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task GetAccoFeatureList( + string? language, + string? ltst0filter, + string[] fields, + string? searchfilter, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("accommodationfeatures") - .SelectRaw("data") - .When(!String.IsNullOrEmpty(ltst0filter), q => q.WhereJsonb("CustomId", "like", ltst0filter + "%")) - .When(FilterClosedData, q => q.FilterClosedData()) - .SearchFilter(PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), searchfilter) - .ApplyRawFilter(rawfilter) - .OrderOnlyByRawSortIfNotNull(rawsort); + var query = QueryFactory + .Query("accommodationfeatures") + .SelectRaw("data") + .When( + !String.IsNullOrEmpty(ltst0filter), + q => q.WhereJsonb("CustomId", "like", ltst0filter + "%") + ) + .When(FilterClosedData, q => q.FilterClosedData()) + .SearchFilter( + PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), + searchfilter + ) + .ApplyRawFilter(rawfilter) + .OrderOnlyByRawSortIfNotNull(rawsort); var data = await query.GetAsync(); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.Select( - raw => raw?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); } - private Task GetAccoFeatureSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetAccoFeatureSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("accommodationfeatures") - .Select("data") - //.WhereJsonb("Key", "ilike", id) - .Where("id", id.ToUpper()) - .When(FilterClosedData, q => q.FilterClosedData()); - + var query = QueryFactory + .Query("accommodationfeatures") + .Select("data") + //.WhereJsonb("Key", "ilike", id) + .Where("id", id.ToUpper()) + .When(FilterClosedData, q => q.FilterClosedData()); + var data = await query.FirstOrDefaultAsync(); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } private IActionResult GetFeatureListXML(CancellationToken cancellationToken) { - XDocument mytins = GetAccommodationDataCDB.GetTinfromCDB("1", settings.CDBConfig.Username, settings.CDBConfig.Password, settings.CDBConfig.Url); + XDocument mytins = GetAccommodationDataCDB.GetTinfromCDB( + "1", + settings.CDBConfig.Username, + settings.CDBConfig.Password, + settings.CDBConfig.Url + ); //return new ContentResult { Content = mytins.ToString(), ContentType = "text/xml", StatusCode = 200 }; @@ -924,13 +1352,17 @@ private IActionResult GetFeatureListXML(CancellationToken cancellationToken) /// Accommodation Object /// Http Response [ApiExplorerSettings(IgnoreApi = true)] - [Authorize(Roles = "DataWriter,DataCreate,AccoManager,AccoCreate,AccommodationWriter,AccommodationManager,AccommodationCreate")] + [Authorize( + Roles = "DataWriter,DataCreate,AccoManager,AccoCreate,AccommodationWriter,AccommodationManager,AccommodationCreate" + )] [HttpPost, Route("Accommodation")] public Task Post([FromBody] AccommodationLinked accommodation) { return DoAsyncReturn(async () => { - accommodation.Id = !String.IsNullOrEmpty(accommodation.Id) ? accommodation.Id.ToUpper() : "NOID"; + accommodation.Id = !String.IsNullOrEmpty(accommodation.Id) + ? accommodation.Id.ToUpper() + : "NOID"; return await UpsertData(accommodation, "accommodations"); }); } @@ -942,7 +1374,9 @@ public Task Post([FromBody] AccommodationLinked accommodation) /// Accommodation Object /// Http Response [ApiExplorerSettings(IgnoreApi = true)] - [Authorize(Roles = "DataWriter,DataModify,AccoManager,AccoModify,AccommodationWriter,AccommodationManager,AccommodationModify")] + [Authorize( + Roles = "DataWriter,DataModify,AccoManager,AccoModify,AccommodationWriter,AccommodationManager,AccommodationModify" + )] [HttpPut, Route("Accommodation/{id}")] public Task Put(string id, [FromBody] AccommodationLinked accommodation) { @@ -959,7 +1393,9 @@ public Task Put(string id, [FromBody] AccommodationLinked accommo /// Accommodation Id /// Http Response [ApiExplorerSettings(IgnoreApi = true)] - [Authorize(Roles = "DataWriter,DataDelete,AccoManager,AccoDelete,AccommodationWriter,AccommodationManager,AccommodationDelete")] + [Authorize( + Roles = "DataWriter,DataDelete,AccoManager,AccoDelete,AccommodationWriter,AccommodationManager,AccommodationDelete" + )] [HttpDelete, Route("Accommodation/{id}")] public Task Delete(string id) { @@ -970,7 +1406,6 @@ public Task Delete(string id) }); } - #endregion } -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/api/ActivityApiController.cs b/OdhApiCore/Controllers/api/ActivityApiController.cs index 3b9b3780b..9bcea0df7 100644 --- a/OdhApiCore/Controllers/api/ActivityApiController.cs +++ b/OdhApiCore/Controllers/api/ActivityApiController.cs @@ -16,8 +16,8 @@ using Serilog.Context; using Microsoft.AspNetCore.Authorization; using Swashbuckle.AspNetCore.Annotations; -using OdhApiCore.Filters; - +using OdhApiCore.Filters; + namespace OdhApiCore.Controllers { /// @@ -27,11 +27,13 @@ namespace OdhApiCore.Controllers [EnableCors("CorsPolicy")] [NullStringParameterActionFilter] public class ActivityController : OdhController - { - public ActivityController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + { + public ActivityController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } #region SWAGGER Exposed API @@ -44,7 +46,7 @@ public ActivityController(IWebHostEnvironment env, ISettings settings, ILoggerType of the Activity ('null' = Filter disabled, possible values: BITMASK: 'Mountains = 1','Cycling = 2','Local tours = 4','Horses = 8','Hiking = 16','Running and fitness = 32','Cross-country ski-track = 64','Tobbogan run = 128','Slopes = 256','Lifts = 512'), (default:'1023' == ALL), REFERENCE TO: GET /api/ActivityTypes /// Subtype of the Activity (BITMASK Filter = available SubTypes depends on the selected Activity Type), (default:'null') /// IDFilter (Separator ',' List of Activity IDs), (default:'null') - /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter + /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter /// AreaFilter (Separator ',' IDList of AreaIDs separated by ','), (default:'null') /// Distance Range Filter (Separator ',' example Value: 15,40 Distance from 15 up to 40 Km), (default:'null') /// Altitude Range Filter (Separator ',' example Value: 500,1000 Altitude from 500 up to 1000 metres), (default:'null') @@ -64,7 +66,7 @@ public ActivityController(IWebHostEnvironment env, ISettings settings, ILoggerString to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Collection of Activity Objects /// List created /// Request Error @@ -73,7 +75,12 @@ public ActivityController(IWebHostEnvironment env, ISettings settings, ILogger GetActivityList( string? language = null, @@ -93,30 +100,53 @@ public async Task GetActivityList( LegacyBool active = null!, LegacyBool odhactive = null!, string? updatefrom = null, - string? langfilter = null, + string? langfilter = null, string? seed = null, string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); return await GetFiltered( - fields: fields ?? Array.Empty(), language: language, pagenumber: pagenumber, - pagesize: pagesize, activitytype: activitytype, subtypefilter: subtype, idfilter: idlist, - searchfilter: searchfilter, locfilter: locfilter, areafilter: areafilter, - distancefilter: distancefilter, altitudefilter: altitudefilter, durationfilter: durationfilter, - highlightfilter: highlight, difficultyfilter: difficultyfilter, active: active, - smgactive: odhactive, smgtags: odhtagfilter, seed: seed, lastchange: updatefrom, langfilter: langfilter, - geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, - cancellationToken: cancellationToken); + fields: fields ?? Array.Empty(), + language: language, + pagenumber: pagenumber, + pagesize: pagesize, + activitytype: activitytype, + subtypefilter: subtype, + idfilter: idlist, + searchfilter: searchfilter, + locfilter: locfilter, + areafilter: areafilter, + distancefilter: distancefilter, + altitudefilter: altitudefilter, + durationfilter: durationfilter, + highlightfilter: highlight, + difficultyfilter: difficultyfilter, + active: active, + smgactive: odhactive, + smgtags: odhtagfilter, + seed: seed, + lastchange: updatefrom, + langfilter: langfilter, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken: cancellationToken + ); } /// @@ -125,7 +155,7 @@ public async Task GetActivityList( /// ID of the Activity /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// GBLTSActivity Object /// Object created /// Request Error @@ -138,12 +168,18 @@ public async Task GetActivityList( public async Task GetActivitySingle( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues, cancellationToken); + return await GetSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues, + cancellationToken + ); } /// @@ -154,7 +190,7 @@ public async Task GetActivitySingle( /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Collection of ActivityTypes Object /// List created /// Request Error @@ -167,15 +203,23 @@ public async Task GetActivitySingle( [HttpGet, Route("ActivityTypes")] public async Task GetAllActivityTypesListAsync( string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetActivityTypesListAsync(language, fields: fields ?? Array.Empty(), searchfilter, rawfilter, rawsort, removenullvalues, cancellationToken); + return await GetActivityTypesListAsync( + language, + fields: fields ?? Array.Empty(), + searchfilter, + rawfilter, + rawsort, + removenullvalues, + cancellationToken + ); } /// @@ -184,7 +228,7 @@ public async Task GetAllActivityTypesListAsync( /// ID of the Activity Type /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// ActivityTypes Object /// List created /// Request Error @@ -198,12 +242,18 @@ public async Task GetAllActivityTypesListAsync( public async Task GetAllActivityTypesSingleAsync( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetActivityTypesSingleAsync(id, language, fields: fields ?? Array.Empty(), removenullvalues, cancellationToken); + return await GetActivityTypesSingleAsync( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues, + cancellationToken + ); } #endregion @@ -231,52 +281,112 @@ public async Task GetAllActivityTypesSingleAsync( /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting /// Result Object with Collection of Activities Objects private Task GetFiltered( - string[] fields, string? language, uint pagenumber, int? pagesize, string? activitytype, string? subtypefilter, - string? idfilter, string? searchfilter, string? locfilter, string? areafilter, string? distancefilter, string? altitudefilter, - string? durationfilter, bool? highlightfilter, string? difficultyfilter, bool? active, bool? smgactive, - string? smgtags, string? seed, string? lastchange, string? langfilter, PGGeoSearchResult geosearchresult, string? rawfilter, string? rawsort, - bool removenullvalues, CancellationToken cancellationToken) + string[] fields, + string? language, + uint pagenumber, + int? pagesize, + string? activitytype, + string? subtypefilter, + string? idfilter, + string? searchfilter, + string? locfilter, + string? areafilter, + string? distancefilter, + string? altitudefilter, + string? durationfilter, + bool? highlightfilter, + string? difficultyfilter, + bool? active, + bool? smgactive, + string? smgtags, + string? seed, + string? lastchange, + string? langfilter, + PGGeoSearchResult geosearchresult, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { ActivityHelper myactivityhelper = await ActivityHelper.CreateAsync( - QueryFactory, activitytype, subtypefilter, idfilter, locfilter, areafilter, distancefilter, - altitudefilter, durationfilter, highlightfilter, difficultyfilter, active, smgactive, smgtags, lastchange, langfilter, - cancellationToken); - - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("activities") - .ActivityWhereExpression( - idlist: myactivityhelper.idlist, activitytypelist: myactivityhelper.activitytypelist, - subtypelist: myactivityhelper.subtypelist, difficultylist: myactivityhelper.difficultylist, - smgtaglist: myactivityhelper.smgtaglist, districtlist: new List(), - municipalitylist: new List(), tourismvereinlist: myactivityhelper.tourismvereinlist, - regionlist: myactivityhelper.regionlist, arealist: myactivityhelper.arealist, - distance: myactivityhelper.distance, distancemin: myactivityhelper.distancemin, - distancemax: myactivityhelper.distancemax, duration: myactivityhelper.duration, - durationmin: myactivityhelper.durationmin, durationmax: myactivityhelper.durationmax, - altitude: myactivityhelper.altitude, altitudemin: myactivityhelper.altitudemin, - altitudemax: myactivityhelper.altitudemax, highlight: myactivityhelper.highlight, - activefilter: myactivityhelper.active, smgactivefilter: myactivityhelper.smgactive, - searchfilter: searchfilter, language: language, lastchange: myactivityhelper.lastchange, - languagelist: myactivityhelper.languagelist, filterClosedData: FilterClosedData, reducedData: ReducedData) - .ApplyRawFilter(rawfilter) - .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); + QueryFactory, + activitytype, + subtypefilter, + idfilter, + locfilter, + areafilter, + distancefilter, + altitudefilter, + durationfilter, + highlightfilter, + difficultyfilter, + active, + smgactive, + smgtags, + lastchange, + langfilter, + cancellationToken + ); + + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("activities") + .ActivityWhereExpression( + idlist: myactivityhelper.idlist, + activitytypelist: myactivityhelper.activitytypelist, + subtypelist: myactivityhelper.subtypelist, + difficultylist: myactivityhelper.difficultylist, + smgtaglist: myactivityhelper.smgtaglist, + districtlist: new List(), + municipalitylist: new List(), + tourismvereinlist: myactivityhelper.tourismvereinlist, + regionlist: myactivityhelper.regionlist, + arealist: myactivityhelper.arealist, + distance: myactivityhelper.distance, + distancemin: myactivityhelper.distancemin, + distancemax: myactivityhelper.distancemax, + duration: myactivityhelper.duration, + durationmin: myactivityhelper.durationmin, + durationmax: myactivityhelper.durationmax, + altitude: myactivityhelper.altitude, + altitudemin: myactivityhelper.altitudemin, + altitudemax: myactivityhelper.altitudemax, + highlight: myactivityhelper.highlight, + activefilter: myactivityhelper.active, + smgactivefilter: myactivityhelper.smgactive, + searchfilter: searchfilter, + language: language, + lastchange: myactivityhelper.lastchange, + languagelist: myactivityhelper.languagelist, + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); uint totalpages = (uint)data.TotalPages; uint totalcount = (uint)data.Count; @@ -287,7 +397,8 @@ await query totalcount, seed, dataTransformed, - Url); + Url + ); }); } @@ -296,21 +407,35 @@ await query /// /// ID of the Activity /// Activity Object - private Task GetSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("activities") - .Select("data") - .Where("id", id.ToUpper()) - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); - //.When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query("activities") + .Select("data") + .Where("id", id.ToUpper()) + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + //.When(FilterClosedData, q => q.FilterClosedData()); var data = await query.FirstOrDefaultAsync(); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -322,25 +447,44 @@ private Task GetSingle(string id, string? language, string[] fiel /// GET Activity Types List /// /// Collection of ActivityTypes Object - private Task GetActivityTypesListAsync(string? language, string[] fields, string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task GetActivityTypesListAsync( + string? language, + string[] fields, + string? searchfilter, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("activitytypes") - .SelectRaw("data") - .When(FilterClosedData, q => q.FilterClosedData()) - .SearchFilter(PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), searchfilter) - .ApplyRawFilter(rawfilter) - .OrderOnlyByRawSortIfNotNull(rawsort); + var query = QueryFactory + .Query("activitytypes") + .SelectRaw("data") + .When(FilterClosedData, q => q.FilterClosedData()) + .SearchFilter( + PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), + searchfilter + ) + .ApplyRawFilter(rawfilter) + .OrderOnlyByRawSortIfNotNull(rawsort); var data = await query.GetAsync(); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.Select( - raw => raw?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); @@ -350,21 +494,35 @@ private Task GetActivityTypesListAsync(string? language, string[] /// GET Activity Types Single /// /// ActivityTypes Object - private Task GetActivityTypesSingleAsync(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetActivityTypesSingleAsync( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("activitytypes") - .Select("data") - //.WhereJsonb("Key", "ilike", id) - .Where("id", id.ToLower()) - .When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query("activitytypes") + .Select("data") + //.WhereJsonb("Key", "ilike", id) + .Where("id", id.ToLower()) + .When(FilterClosedData, q => q.FilterClosedData()); var data = await query.FirstOrDefaultAsync(); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -424,7 +582,6 @@ public Task Delete(string id) }); } - #endregion } -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/api/ArticleApiController.cs b/OdhApiCore/Controllers/api/ArticleApiController.cs index 4795b9a23..86efc3e9f 100644 --- a/OdhApiCore/Controllers/api/ArticleApiController.cs +++ b/OdhApiCore/Controllers/api/ArticleApiController.cs @@ -18,16 +18,18 @@ namespace OdhApiCore.Controllers.api { /// - /// Articles Api (data provided by IDM) SOME DATA Available as OPENDATA + /// Articles Api (data provided by IDM) SOME DATA Available as OPENDATA /// [EnableCors("CorsPolicy")] [NullStringParameterActionFilter] public class ArticleController : OdhController - { - public ArticleController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + { + public ArticleController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } #region SWAGGER Exposed API @@ -45,20 +47,20 @@ public ArticleController(IWebHostEnvironment env, ISettings settings, ILoggerFilter by ArticleDate Format (yyyy-MM-dd HH:mm) /// Filter by ArticleDate Format (yyyy-MM-dd HH:mm) /// Sort By Articledate ('true' sorts Articles by Articledate) - /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=article'), (default:'null') + /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=article'), (default:'null') /// Active Articles Filter (possible Values: 'true' only Active Articles, 'false' only Disabled Articles), (default:'null') - /// ODH Active (Published) Articles Filter (Refers to field OdhActive) (possible Values: 'true' only published Article, 'false' only not published Articles), (default:'null') + /// ODH Active (Published) Articles Filter (Refers to field OdhActive) (possible Values: 'true' only published Article, 'false' only not published Articles), (default:'null') /// Filter by Source (Separator ','), (Sources available 'idm','noi'...),(default: 'null') /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of Article Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of Article Objects /// List created /// Request Error /// Internal Server Error @@ -85,30 +87,49 @@ public async Task GetArticleList( string? seed = null, string? publishedon = null, string? source = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetFiltered( - fields: fields ?? Array.Empty(), language: language, pagenumber: pagenumber, pagesize: pagesize, - type: articletype, subtypefilter: articlesubtype, searchfilter: searchfilter, idfilter: idlist, languagefilter: langfilter, highlightfilter: null, - active: active?.Value, smgactive: odhactive?.Value, smgtags: odhtagfilter, seed: seed, - articledate: startdate, articledateto: enddate, source: source, lastchange: updatefrom, sortbyarticledate: sortbyarticledate?.Value, publishedon: publishedon, - rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + fields: fields ?? Array.Empty(), + language: language, + pagenumber: pagenumber, + pagesize: pagesize, + type: articletype, + subtypefilter: articlesubtype, + searchfilter: searchfilter, + idfilter: idlist, + languagefilter: langfilter, + highlightfilter: null, + active: active?.Value, + smgactive: odhactive?.Value, + smgtags: odhtagfilter, + seed: seed, + articledate: startdate, + articledateto: enddate, + source: source, + lastchange: updatefrom, + sortbyarticledate: sortbyarticledate?.Value, + publishedon: publishedon, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } /// - /// GET Article Single + /// GET Article Single /// /// ID of the Article /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Article Object /// Object created /// Request Error @@ -120,12 +141,18 @@ public async Task GetArticleList( public async Task GetArticleSingle( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues, cancellationToken); + return await GetSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues, + cancellationToken + ); } //Special GETTER @@ -138,8 +165,8 @@ public async Task GetArticleSingle( /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of ArticleTypes Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of ArticleTypes Object /// List created /// Request Error /// Internal Server Error @@ -149,15 +176,23 @@ public async Task GetArticleSingle( [HttpGet, Route("ArticleTypes")] public async Task GetAllArticleTypesList( string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetArticleTypesList(language, fields: fields ?? Array.Empty(), searchfilter, rawfilter, rawsort, removenullvalues, cancellationToken); + return await GetArticleTypesList( + language, + fields: fields ?? Array.Empty(), + searchfilter, + rawfilter, + rawsort, + removenullvalues, + cancellationToken + ); } /// @@ -166,8 +201,8 @@ public async Task GetAllArticleTypesList( /// ID of the Article Type /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// ArticleTypes Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// ArticleTypes Object /// List created /// Request Error /// Internal Server Error @@ -178,62 +213,122 @@ public async Task GetAllArticleTypesList( public async Task GetAllArticlesTypeTypesSingle( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetArticleTypeSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues, cancellationToken); + return await GetArticleTypeSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues, + cancellationToken + ); } #endregion #region GETTER - private Task GetFiltered(string[] fields, string? language, uint pagenumber, int? pagesize, - string? type, string? subtypefilter, string? searchfilter, string? idfilter, string? languagefilter, bool? highlightfilter, - bool? active, bool? smgactive, string? smgtags, string? seed, string? articledate, string? articledateto, string? source, string? lastchange, - bool? sortbyarticledate, string? publishedon, string? rawfilter, string? rawsort, bool removenullvalues, - CancellationToken cancellationToken) + private Task GetFiltered( + string[] fields, + string? language, + uint pagenumber, + int? pagesize, + string? type, + string? subtypefilter, + string? searchfilter, + string? idfilter, + string? languagefilter, + bool? highlightfilter, + bool? active, + bool? smgactive, + string? smgtags, + string? seed, + string? articledate, + string? articledateto, + string? source, + string? lastchange, + bool? sortbyarticledate, + string? publishedon, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { ArticleHelper myarticlehelper = ArticleHelper.Create( - type, subtypefilter, idfilter, languagefilter, highlightfilter, - active, smgactive, smgtags, articledate, articledateto, source, lastchange, publishedon); - - if(sortbyarticledate == true) + type, + subtypefilter, + idfilter, + languagefilter, + highlightfilter, + active, + smgactive, + smgtags, + articledate, + articledateto, + source, + lastchange, + publishedon + ); + + if (sortbyarticledate == true) rawsort = "ArticleDate"; - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("articles") - .ArticleWhereExpression( - idlist: myarticlehelper.idlist, typelist: myarticlehelper.typelist, - subtypelist: myarticlehelper.subtypelist, smgtaglist: myarticlehelper.smgtaglist, languagelist: myarticlehelper.languagelist, - highlight: myarticlehelper.highlight, activefilter: myarticlehelper.active, smgactivefilter: myarticlehelper.smgactive, - articledate: myarticlehelper.articledate, articledateto: myarticlehelper.articledateto, sourcelist: myarticlehelper.sourcelist, - publishedonlist: myarticlehelper.publishedonlist, - searchfilter: searchfilter, language: language, lastchange: myarticlehelper.lastchange, - filterClosedData: FilterClosedData, reducedData: ReducedData) - .ApplyRawFilter(rawfilter) - .ApplyOrdering_GeneratedColumns(ref seed, new PGGeoSearchResult() { geosearch = false }, rawsort); - + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("articles") + .ArticleWhereExpression( + idlist: myarticlehelper.idlist, + typelist: myarticlehelper.typelist, + subtypelist: myarticlehelper.subtypelist, + smgtaglist: myarticlehelper.smgtaglist, + languagelist: myarticlehelper.languagelist, + highlight: myarticlehelper.highlight, + activefilter: myarticlehelper.active, + smgactivefilter: myarticlehelper.smgactive, + articledate: myarticlehelper.articledate, + articledateto: myarticlehelper.articledateto, + sourcelist: myarticlehelper.sourcelist, + publishedonlist: myarticlehelper.publishedonlist, + searchfilter: searchfilter, + language: language, + lastchange: myarticlehelper.lastchange, + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering_GeneratedColumns( + ref seed, + new PGGeoSearchResult() { geosearch = false }, + rawsort + ); // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); - + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); + var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); uint totalpages = (uint)data.TotalPages; uint totalcount = (uint)data.Count; @@ -244,26 +339,41 @@ await query totalcount, seed, dataTransformed, - Url); + Url + ); }); } - private Task GetSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("articles") - .Select("data") - .Where("id", id.ToUpper()) - //.When(FilterClosedData, q => q.FilterClosedData()) - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, ReducedData); + var query = QueryFactory + .Query("articles") + .Select("data") + .Where("id", id.ToUpper()) + //.When(FilterClosedData, q => q.FilterClosedData()) + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, ReducedData); var data = await query.FirstOrDefaultAsync(); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -271,51 +381,83 @@ private Task GetSingle(string id, string? language, string[] fiel #region CATEGORIES - private Task GetArticleTypesList(string? language, string[] fields, string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task GetArticleTypesList( + string? language, + string[] fields, + string? searchfilter, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("articletypes") - .SelectRaw("data") - .When(FilterClosedData, q => q.FilterClosedData()) - .SearchFilter(PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), searchfilter) - .ApplyRawFilter(rawfilter) - .OrderOnlyByRawSortIfNotNull(rawsort); + var query = QueryFactory + .Query("articletypes") + .SelectRaw("data") + .When(FilterClosedData, q => q.FilterClosedData()) + .SearchFilter( + PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), + searchfilter + ) + .ApplyRawFilter(rawfilter) + .OrderOnlyByRawSortIfNotNull(rawsort); var data = await query.GetAsync(); - + var fieldsTohide = FieldsToHide; - var dataTransformed = - data.Select( - raw => raw?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); } - private Task GetArticleTypeSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetArticleTypeSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("articletypes") - .Select("data") - //.WhereJsonb("Key", "ilike", id) - .Where("id", id.ToLower()) - .When(FilterClosedData, q => q.FilterClosedData()); - + var query = QueryFactory + .Query("articletypes") + .Select("data") + //.WhereJsonb("Key", "ilike", id) + .Where("id", id.ToLower()) + .When(FilterClosedData, q => q.FilterClosedData()); + var fieldsTohide = FieldsToHide; var data = await query.FirstOrDefaultAsync(); - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } - #endregion #region POST PUT DELETE @@ -333,7 +475,7 @@ private Task GetArticleTypeSingle(string id, string? language, st [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpPost, Route("Article")] public Task Post([FromBody] ArticlesLinked article) - { + { return DoAsyncReturn(async () => { //GENERATE ID @@ -341,7 +483,7 @@ public Task Post([FromBody] ArticlesLinked article) article.CheckMyInsertedLanguages(new List { "de", "en", "it" }); - if(article.ArticleDateTo == null) + if (article.ArticleDateTo == null) article.ArticleDateTo = DateTime.MaxValue; return await UpsertData(article, "articles", true); @@ -362,7 +504,7 @@ public Task Post([FromBody] ArticlesLinked article) [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpPut, Route("Article/{id}")] public Task Put(string id, [FromBody] ArticlesLinked article) - { + { return DoAsyncReturn(async () => { //Check ID uppercase lowercase @@ -400,7 +542,6 @@ public Task Delete(string id) }); } - #endregion } } diff --git a/OdhApiCore/Controllers/api/CommonApiController.cs b/OdhApiCore/Controllers/api/CommonApiController.cs index 66db931a2..1e8d5b5dc 100644 --- a/OdhApiCore/Controllers/api/CommonApiController.cs +++ b/OdhApiCore/Controllers/api/CommonApiController.cs @@ -17,12 +17,14 @@ namespace OdhApiCore.Controllers.api { public class CommonController : OdhController { - public CommonController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + public CommonController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } - #region SWAGGER Exposed API + #region SWAGGER Exposed API //Standard GETTER @@ -38,15 +40,15 @@ public CommonController(IWebHostEnvironment env, ISettings settings, ILoggerRadius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting, (default:null) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of MetaRegion Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of MetaRegion Objects /// List created /// Request Error /// Internal Server Error @@ -66,8 +68,7 @@ public async Task GetMetaRegions( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, string? langfilter = null, string? updatefrom = null, @@ -77,22 +78,65 @@ public async Task GetMetaRegions( string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) - { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, idfilter: idlist, languagefilter: langfilter, null, source, active?.Value, odhactive?.Value, odhtagfilter, lastchange: updatefrom, publishedon, cancellationToken); + CancellationToken cancellationToken = default + ) + { + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + idfilter: idlist, + languagefilter: langfilter, + null, + source, + active?.Value, + odhactive?.Value, + odhtagfilter, + lastchange: updatefrom, + publishedon, + cancellationToken + ); if (pagenumber.HasValue) { - return await CommonGetPagedListHelper(pagenumber.Value, pagesize, tablename: "metaregions", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetPagedListHelper( + pagenumber.Value, + pagesize, + tablename: "metaregions", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } else { - return await CommonGetListHelper(tablename: "metaregions", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); - } + return await CommonGetListHelper( + tablename: "metaregions", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); + } } /// @@ -101,8 +145,8 @@ public async Task GetMetaRegions( /// ID of the requested data /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// MetaRegion Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// MetaRegion Object /// Object created /// Request Error /// Internal Server Error @@ -112,13 +156,20 @@ public async Task GetMetaRegions( [HttpGet, Route("MetaRegion/{id}", Name = "SingleMetaRegion")] public async Task GetMetaRegionSingle( string id, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) - { - return await CommonGetSingleHelper(id: id, tablename: "metaregions", fields: fields ?? Array.Empty(), language: language, removenullvalues: removenullvalues, cancellationToken); + CancellationToken cancellationToken = default + ) + { + return await CommonGetSingleHelper( + id: id, + tablename: "metaregions", + fields: fields ?? Array.Empty(), + language: language, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -134,15 +185,15 @@ public async Task GetMetaRegionSingle( /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting, (default:null) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of ExperienceArea Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of ExperienceArea Objects /// List created /// Request Error /// Internal Server Error @@ -152,7 +203,7 @@ public async Task GetMetaRegionSingle( [HttpGet, Route("ExperienceArea")] public async Task GetExperienceAreas( uint? pagenumber = null, - PageSize pagesize = null!, + PageSize pagesize = null!, string? idlist = null, string? odhtagfilter = null, LegacyBool active = null!, @@ -162,8 +213,7 @@ public async Task GetExperienceAreas( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, string? langfilter = null, string? updatefrom = null, @@ -173,21 +223,63 @@ public async Task GetExperienceAreas( string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) - { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, idfilter: idlist, languagefilter: langfilter, visibleinsearch, source, activefilter: active?.Value, - smgactivefilter: odhactive?.Value, smgtags: odhtagfilter, lastchange: updatefrom, publishedonfilter: publishedon, cancellationToken); + CancellationToken cancellationToken = default + ) + { + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + idfilter: idlist, + languagefilter: langfilter, + visibleinsearch, + source, + activefilter: active?.Value, + smgactivefilter: odhactive?.Value, + smgtags: odhtagfilter, + lastchange: updatefrom, + publishedonfilter: publishedon, + cancellationToken + ); if (pagenumber.HasValue) { - return await CommonGetPagedListHelper(pagenumber.Value, pagesize, tablename: "experienceareas", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetPagedListHelper( + pagenumber.Value, + pagesize, + tablename: "experienceareas", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } else { - return await CommonGetListHelper(tablename: "experienceareas", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetListHelper( + tablename: "experienceareas", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } } @@ -197,23 +289,31 @@ public async Task GetExperienceAreas( /// ID of the requested data /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// ExperienceArea Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// ExperienceArea Object /// Object created /// Request Error /// Internal Server Error [ProducesResponseType(typeof(ExperienceArea), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [HttpGet, Route("ExperienceArea/{id}", Name ="SingleExperienceArea")] - public async Task GetExperienceAreaSingle(string id, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [HttpGet, Route("ExperienceArea/{id}", Name = "SingleExperienceArea")] + public async Task GetExperienceAreaSingle( + string id, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await CommonGetSingleHelper(id: id, tablename: "experienceareas", fields: fields ?? Array.Empty(), language: language, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetSingleHelper( + id: id, + tablename: "experienceareas", + fields: fields ?? Array.Empty(), + language: language, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -228,15 +328,15 @@ public async Task GetExperienceAreaSingle(string id, /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting, (default:null) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of Region Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of Region Objects /// List created /// Request Error /// Internal Server Error @@ -246,7 +346,7 @@ public async Task GetExperienceAreaSingle(string id, [HttpGet, Route("Region")] public async Task GetRegions( uint? pagenumber = null, - PageSize pagesize = null!, + PageSize pagesize = null!, string? idlist = null, string? odhtagfilter = null, LegacyBool active = null!, @@ -255,8 +355,7 @@ public async Task GetRegions( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, string? langfilter = null, string? updatefrom = null, @@ -266,21 +365,63 @@ public async Task GetRegions( string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, idfilter: idlist, languagefilter: langfilter, null, source, - activefilter: active?.Value, smgactivefilter: odhactive?.Value, smgtags: odhtagfilter, lastchange: updatefrom, publishedonfilter: publishedon, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + idfilter: idlist, + languagefilter: langfilter, + null, + source, + activefilter: active?.Value, + smgactivefilter: odhactive?.Value, + smgtags: odhtagfilter, + lastchange: updatefrom, + publishedonfilter: publishedon, + cancellationToken + ); if (pagenumber.HasValue) { - return await CommonGetPagedListHelper(pagenumber.Value, pagesize, tablename: "regions", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetPagedListHelper( + pagenumber.Value, + pagesize, + tablename: "regions", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } else { - return await CommonGetListHelper(tablename: "regions", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetListHelper( + tablename: "regions", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } } @@ -290,23 +431,31 @@ public async Task GetRegions( /// ID of the requested data /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Region Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Region Object /// Object created /// Request Error /// Internal Server Error [ProducesResponseType(typeof(Region), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [HttpGet, Route("Region/{id}", Name ="SingleRegion")] - public async Task GetRegionSingle(string id, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [HttpGet, Route("Region/{id}", Name = "SingleRegion")] + public async Task GetRegionSingle( + string id, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await CommonGetSingleHelper(id: id, tablename: "regions", fields: fields ?? Array.Empty(), language: language, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetSingleHelper( + id: id, + tablename: "regions", + fields: fields ?? Array.Empty(), + language: language, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -321,15 +470,15 @@ public async Task GetRegionSingle(string id, /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting, (default:null) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of Tourismverein Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of Tourismverein Objects /// List created /// Request Error /// Internal Server Error @@ -339,7 +488,7 @@ public async Task GetRegionSingle(string id, [HttpGet, Route("TourismAssociation")] public async Task GetTourismverein( uint? pagenumber = null, - PageSize pagesize = null!, + PageSize pagesize = null!, string? idlist = null, string? odhtagfilter = null, LegacyBool active = null!, @@ -348,34 +497,74 @@ public async Task GetTourismverein( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, string? langfilter = null, - string? updatefrom = null, + string? updatefrom = null, string? seed = null, string? publishedon = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, idfilter: idlist, languagefilter: langfilter, null, source, - activefilter: active?.Value, smgactivefilter: odhactive?.Value, smgtags: odhtagfilter, lastchange: updatefrom, publishedonfilter: publishedon, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + idfilter: idlist, + languagefilter: langfilter, + null, + source, + activefilter: active?.Value, + smgactivefilter: odhactive?.Value, + smgtags: odhtagfilter, + lastchange: updatefrom, + publishedonfilter: publishedon, + cancellationToken + ); if (pagenumber.HasValue) { - return await CommonGetPagedListHelper(pagenumber.Value, pagesize, tablename: "tvs", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetPagedListHelper( + pagenumber.Value, + pagesize, + tablename: "tvs", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } else { - return await CommonGetListHelper(tablename: "tvs", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetListHelper( + tablename: "tvs", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } - } /// @@ -384,8 +573,8 @@ public async Task GetTourismverein( /// ID of the requested data /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Tourismverein Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Tourismverein Object /// Object created /// Request Error /// Internal Server Error @@ -393,14 +582,22 @@ public async Task GetTourismverein( [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("TourismAssociation/{id}", Name = "SingleTourismAssociation")] - public async Task GetTourismvereinSingle(string id, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + public async Task GetTourismvereinSingle( + string id, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await CommonGetSingleHelper(id: id, tablename: "tvs", fields: fields ?? Array.Empty(), language: language, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetSingleHelper( + id: id, + tablename: "tvs", + fields: fields ?? Array.Empty(), + language: language, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -416,15 +613,15 @@ public async Task GetTourismvereinSingle(string id, /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting, (default:null) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of Municipality Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of Municipality Objects /// List created /// Request Error /// Internal Server Error @@ -434,7 +631,7 @@ public async Task GetTourismvereinSingle(string id, [HttpGet, Route("Municipality")] public async Task GetMunicipality( uint? pagenumber = null, - PageSize pagesize = null!, + PageSize pagesize = null!, bool? visibleinsearch = null, string? idlist = null, string? odhtagfilter = null, @@ -444,34 +641,74 @@ public async Task GetMunicipality( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, string? langfilter = null, - string? updatefrom = null, + string? updatefrom = null, string? seed = null, string? publishedon = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, idfilter: idlist, languagefilter: langfilter, visibleinsearch, source, - active?.Value, odhactive?.Value, smgtags: odhtagfilter, lastchange: updatefrom, publishedonfilter: publishedon, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + idfilter: idlist, + languagefilter: langfilter, + visibleinsearch, + source, + active?.Value, + odhactive?.Value, + smgtags: odhtagfilter, + lastchange: updatefrom, + publishedonfilter: publishedon, + cancellationToken + ); if (pagenumber.HasValue) { - return await CommonGetPagedListHelper(pagenumber.Value, pagesize, tablename: "municipalities", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetPagedListHelper( + pagenumber.Value, + pagesize, + tablename: "municipalities", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } else { - return await CommonGetListHelper(tablename: "municipalities", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetListHelper( + tablename: "municipalities", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } - } /// @@ -480,8 +717,8 @@ public async Task GetMunicipality( /// ID of the requested data /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Municipality Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Municipality Object /// Object created /// Request Error /// Internal Server Error @@ -489,14 +726,22 @@ public async Task GetMunicipality( [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("Municipality/{id}", Name = "SingleMunicipality")] - public async Task GetMunicipalitySingle(string id, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + public async Task GetMunicipalitySingle( + string id, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await CommonGetSingleHelper(id: id, tablename: "municipalities", fields: fields ?? Array.Empty(), language: language, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetSingleHelper( + id: id, + tablename: "municipalities", + fields: fields ?? Array.Empty(), + language: language, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -512,15 +757,15 @@ public async Task GetMunicipalitySingle(string id, /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting, (default:null) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of District Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of District Objects /// List created /// Request Error /// Internal Server Error @@ -540,8 +785,7 @@ public async Task GetDistrict( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, string? langfilter = null, string? updatefrom = null, @@ -551,23 +795,64 @@ public async Task GetDistrict( string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) - { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, idfilter: idlist, languagefilter: langfilter, visibleinsearch, source, - active?.Value, odhactive?.Value, smgtags: odhtagfilter, lastchange: updatefrom, publishedonfilter: publishedon, cancellationToken); + CancellationToken cancellationToken = default + ) + { + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + idfilter: idlist, + languagefilter: langfilter, + visibleinsearch, + source, + active?.Value, + odhactive?.Value, + smgtags: odhtagfilter, + lastchange: updatefrom, + publishedonfilter: publishedon, + cancellationToken + ); if (pagenumber.HasValue) { - return await CommonGetPagedListHelper(pagenumber.Value, pagesize, tablename: "districts", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetPagedListHelper( + pagenumber.Value, + pagesize, + tablename: "districts", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } else { - return await CommonGetListHelper(tablename: "districts", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetListHelper( + tablename: "districts", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } - } /// @@ -576,8 +861,8 @@ public async Task GetDistrict( /// ID of the requested data /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// District Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// District Object /// List created /// Request Error /// Internal Server Error @@ -585,17 +870,24 @@ public async Task GetDistrict( [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("District/{id}", Name = "SingleDistrict")] - public async Task GetDistrictSingle(string id, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + public async Task GetDistrictSingle( + string id, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await CommonGetSingleHelper(id: id, tablename: "districts", fields: fields ?? Array.Empty(), language: language, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetSingleHelper( + id: id, + tablename: "districts", + fields: fields ?? Array.Empty(), + language: language, + removenullvalues: removenullvalues, + cancellationToken + ); } - /// /// GET Area List /// @@ -605,15 +897,15 @@ public async Task GetDistrictSingle(string id, /// Odhactive (Published) data Filter (possible Values: 'true' only published data, 'false' only not published data, (default:'null') /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting, (default:null) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of Area Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of Area Objects /// List created /// Request Error /// Internal Server Error @@ -623,14 +915,13 @@ public async Task GetDistrictSingle(string id, [HttpGet, Route("Area")] public async Task GetAreas( uint? pagenumber = null, - PageSize pagesize = null!, + PageSize pagesize = null!, string? idlist = null, string? odhtagfilter = null, LegacyBool active = null!, LegacyBool odhactive = null!, string? source = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, string? langfilter = null, string? updatefrom = null, @@ -640,20 +931,58 @@ public async Task GetAreas( string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, idfilter: idlist, languagefilter: langfilter, null, source, - active?.Value, odhactive?.Value, smgtags: odhtagfilter, lastchange: updatefrom, publishedonfilter: publishedon, cancellationToken); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + idfilter: idlist, + languagefilter: langfilter, + null, + source, + active?.Value, + odhactive?.Value, + smgtags: odhtagfilter, + lastchange: updatefrom, + publishedonfilter: publishedon, + cancellationToken + ); if (pagenumber.HasValue) { - return await CommonGetPagedListHelper(pagenumber.Value, pagesize, tablename: "areas", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: new PGGeoSearchResult(), rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetPagedListHelper( + pagenumber.Value, + pagesize, + tablename: "areas", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: new PGGeoSearchResult(), + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } else { - return await CommonGetListHelper(tablename: "areas", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: new PGGeoSearchResult(), rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetListHelper( + tablename: "areas", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: new PGGeoSearchResult(), + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } } @@ -663,8 +992,8 @@ public async Task GetAreas( /// ID of the requested data /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Area Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Area Object /// List created /// Request Error /// Internal Server Error @@ -672,17 +1001,24 @@ public async Task GetAreas( [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("Area/{id}", Name = "SingleArea")] - public async Task GetAreaSingle(string id, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + public async Task GetAreaSingle( + string id, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await CommonGetSingleHelper(id: id, tablename: "areas", fields: fields ?? Array.Empty(), language: language, removenullvalues : removenullvalues, cancellationToken); + return await CommonGetSingleHelper( + id: id, + tablename: "areas", + fields: fields ?? Array.Empty(), + language: language, + removenullvalues: removenullvalues, + cancellationToken + ); } - /// /// GET SkiRegion List /// @@ -695,15 +1031,15 @@ public async Task GetAreaSingle(string id, /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting, (default:null) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of SkiRegion Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of SkiRegion Objects /// List created /// Request Error /// Internal Server Error @@ -713,14 +1049,13 @@ public async Task GetAreaSingle(string id, [HttpGet, Route("SkiRegion")] public async Task GetSkiRegion( uint? pagenumber = null, - PageSize pagesize = null!, + PageSize pagesize = null!, string? idlist = null, string? odhtagfilter = null, LegacyBool active = null!, LegacyBool odhactive = null!, string? source = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, string? langfilter = null, string? updatefrom = null, @@ -730,20 +1065,58 @@ public async Task GetSkiRegion( string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, idfilter: idlist, languagefilter: langfilter, null, source, - active?.Value, odhactive?.Value, smgtags: odhtagfilter, lastchange: updatefrom, publishedonfilter: publishedon, cancellationToken); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + idfilter: idlist, + languagefilter: langfilter, + null, + source, + active?.Value, + odhactive?.Value, + smgtags: odhtagfilter, + lastchange: updatefrom, + publishedonfilter: publishedon, + cancellationToken + ); if (pagenumber.HasValue) { - return await CommonGetPagedListHelper(pagenumber.Value, pagesize, tablename: "skiregions", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: new PGGeoSearchResult(), rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetPagedListHelper( + pagenumber.Value, + pagesize, + tablename: "skiregions", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: new PGGeoSearchResult(), + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } else { - return await CommonGetListHelper(tablename: "skiregions", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: new PGGeoSearchResult(), rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetListHelper( + tablename: "skiregions", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: new PGGeoSearchResult(), + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } } @@ -753,23 +1126,31 @@ public async Task GetSkiRegion( /// ID of the requested data /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// SkiRegion Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// SkiRegion Object /// List created /// Request Error /// Internal Server Error [ProducesResponseType(typeof(SkiRegion), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [HttpGet, Route("SkiRegion/{id}", Name ="SingleSkiRegion")] - public async Task GetSkiRegionSingle(string id, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [HttpGet, Route("SkiRegion/{id}", Name = "SingleSkiRegion")] + public async Task GetSkiRegionSingle( + string id, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await CommonGetSingleHelper(id: id, tablename: "skiregions", fields: fields ?? Array.Empty(), language: language, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetSingleHelper( + id: id, + tablename: "skiregions", + fields: fields ?? Array.Empty(), + language: language, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -784,15 +1165,15 @@ public async Task GetSkiRegionSingle(string id, /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting, (default:null) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of SkiArea Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of SkiArea Objects /// List created /// Request Error /// Internal Server Error @@ -802,17 +1183,16 @@ public async Task GetSkiRegionSingle(string id, [HttpGet, Route("SkiArea")] public async Task GetSkiArea( uint? pagenumber = null, - PageSize pagesize = null!, + PageSize pagesize = null!, string? idlist = null, string? odhtagfilter = null, LegacyBool active = null!, LegacyBool odhactive = null!, string? source = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, string? langfilter = null, - string? updatefrom = null, + string? updatefrom = null, string? seed = null, string? publishedon = null, string? searchfilter = null, @@ -822,22 +1202,64 @@ public async Task GetSkiArea( string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, idfilter: idlist, languagefilter: langfilter, null, source, - active?.Value, odhactive?.Value, smgtags: odhtagfilter, lastchange: updatefrom, publishedonfilter: publishedon, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + idfilter: idlist, + languagefilter: langfilter, + null, + source, + active?.Value, + odhactive?.Value, + smgtags: odhtagfilter, + lastchange: updatefrom, + publishedonfilter: publishedon, + cancellationToken + ); if (pagenumber.HasValue) { - return await CommonGetPagedListHelper(pagenumber.Value, pagesize, tablename: "skiareas", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetPagedListHelper( + pagenumber.Value, + pagesize, + tablename: "skiareas", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } else { - return await CommonGetListHelper(tablename: "skiareas", seed: seed, publishedon: publishedon, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetListHelper( + tablename: "skiareas", + seed: seed, + publishedon: publishedon, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } } @@ -847,26 +1269,33 @@ public async Task GetSkiArea( /// ID of the requested data /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// SkiArea Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// SkiArea Object /// List created /// Request Error /// Internal Server Error [ProducesResponseType(typeof(SkiArea), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [HttpGet, Route("SkiArea/{id}", Name ="SingleSkiArea")] - public async Task GetSkiAreaSingle(string id, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [HttpGet, Route("SkiArea/{id}", Name = "SingleSkiArea")] + public async Task GetSkiAreaSingle( + string id, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await CommonGetSingleHelper(id: id, tablename: "skiareas", fields: fields ?? Array.Empty(), language: language, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetSingleHelper( + id: id, + tablename: "skiareas", + fields: fields ?? Array.Empty(), + language: language, + removenullvalues: removenullvalues, + cancellationToken + ); } - ////Special GETTER /// @@ -880,14 +1309,14 @@ public async Task GetSkiAreaSingle(string id, /// Filter by Wine Id, (default:'null') /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting, (default:null) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// List created /// Request Error /// Internal Server Error @@ -897,7 +1326,7 @@ public async Task GetSkiAreaSingle(string id, [HttpGet, Route("WineAward")] public async Task GetWineAwardsList( uint? pagenumber = null, - PageSize pagesize = null!, + PageSize pagesize = null!, string? idlist = null, string? odhtagfilter = null, LegacyBool active = null!, @@ -905,8 +1334,7 @@ public async Task GetWineAwardsList( string? source = null, string? wineid = null, string? companyid = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, string? langfilter = null, string? updatefrom = null, @@ -917,20 +1345,54 @@ public async Task GetWineAwardsList( string? searchfilter = null, bool removenullvalues = false, CancellationToken cancellationToken = default - ) + ) { - WineHelper commonhelper = await WineHelper.CreateAsync(QueryFactory, idfilter: idlist, companyid, wineid, languagefilter: langfilter, null, source, - active?.Value, odhactive?.Value, smgtags: odhtagfilter, lastchange: updatefrom, cancellationToken); + WineHelper commonhelper = await WineHelper.CreateAsync( + QueryFactory, + idfilter: idlist, + companyid, + wineid, + languagefilter: langfilter, + null, + source, + active?.Value, + odhactive?.Value, + smgtags: odhtagfilter, + lastchange: updatefrom, + cancellationToken + ); if (pagenumber.HasValue) { - return await WineGetPagedListHelper(pagenumber.Value, pagesize, tablename: "wines", seed: seed, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await WineGetPagedListHelper( + pagenumber.Value, + pagesize, + tablename: "wines", + seed: seed, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } else { - return await WineGetListHelper(tablename: "wines", seed: seed, searchfilter: searchfilter, fields: fields ?? Array.Empty(), - language: language, commonhelper, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken); + return await WineGetListHelper( + tablename: "wines", + seed: seed, + searchfilter: searchfilter, + fields: fields ?? Array.Empty(), + language: language, + commonhelper, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } } @@ -940,83 +1402,154 @@ public async Task GetWineAwardsList( /// ID of the requested data /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Wine Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Wine Object [ProducesResponseType(typeof(Wine), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [HttpGet, Route("WineAward/{id}", Name ="SingleWineAward")] - public async Task GetWineAwardsSingle(string id, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [HttpGet, Route("WineAward/{id}", Name = "SingleWineAward")] + public async Task GetWineAwardsSingle( + string id, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? language = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await CommonGetSingleHelper(id: id, tablename: "wines", fields: fields ?? Array.Empty(), language: language, removenullvalues: removenullvalues, cancellationToken); + return await CommonGetSingleHelper( + id: id, + tablename: "wines", + fields: fields ?? Array.Empty(), + language: language, + removenullvalues: removenullvalues, + cancellationToken + ); } #endregion #region GETTER - private Task CommonGetListHelper(string tablename, string? seed, string? publishedon, string? searchfilter, string[] fields, string? language, CommonHelper commonhelper, PGGeoSearchResult geosearchresult, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task CommonGetListHelper( + string tablename, + string? seed, + string? publishedon, + string? searchfilter, + string[] fields, + string? language, + CommonHelper commonhelper, + PGGeoSearchResult geosearchresult, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query() - .SelectRaw("data") - .From(tablename) - .CommonWhereExpression(idlist: commonhelper.idlist, languagelist: commonhelper.languagelist, visibleinsearch: commonhelper.visibleinsearch, commonhelper.smgtaglist, - activefilter: commonhelper.active, odhactivefilter: commonhelper.smgactive, publishedonlist: commonhelper.publishedonlist, sourcelist: commonhelper.sourcelist, searchfilter: searchfilter, language: language, - lastchange: commonhelper.lastchange, filterClosedData: FilterClosedData) - .ApplyRawFilter(rawfilter) - .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); //.ApplyOrdering(ref seed, new PGGeoSearchResult() { geosearch = false }, rawsort); + var query = QueryFactory + .Query() + .SelectRaw("data") + .From(tablename) + .CommonWhereExpression( + idlist: commonhelper.idlist, + languagelist: commonhelper.languagelist, + visibleinsearch: commonhelper.visibleinsearch, + commonhelper.smgtaglist, + activefilter: commonhelper.active, + odhactivefilter: commonhelper.smgactive, + publishedonlist: commonhelper.publishedonlist, + sourcelist: commonhelper.sourcelist, + searchfilter: searchfilter, + language: language, + lastchange: commonhelper.lastchange, + filterClosedData: FilterClosedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); //.ApplyOrdering(ref seed, new PGGeoSearchResult() { geosearch = false }, rawsort); // Get paginated data - var data = - await query - .GetAsync(); - + var data = await query.GetAsync(); + var fieldsTohide = FieldsToHide; - var dataTransformed = - data.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); } - private Task CommonGetPagedListHelper(uint pagenumber, int? pagesize, string tablename, string? seed, string? publishedon, string? searchfilter, string[] fields, string? language, CommonHelper commonhelper, PGGeoSearchResult geosearchresult, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task CommonGetPagedListHelper( + uint pagenumber, + int? pagesize, + string tablename, + string? seed, + string? publishedon, + string? searchfilter, + string[] fields, + string? language, + CommonHelper commonhelper, + PGGeoSearchResult geosearchresult, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query() - .SelectRaw("data") - .From(tablename) - .CommonWhereExpression(idlist: commonhelper.idlist, languagelist: commonhelper.languagelist, visibleinsearch: commonhelper.visibleinsearch, commonhelper.smgtaglist, - activefilter: commonhelper.active, odhactivefilter: commonhelper.smgactive, publishedonlist: commonhelper.publishedonlist, sourcelist: commonhelper.sourcelist, searchfilter: searchfilter, language: language, - lastchange: commonhelper.lastchange, filterClosedData: FilterClosedData) - .ApplyRawFilter(rawfilter) - .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); + var query = QueryFactory + .Query() + .SelectRaw("data") + .From(tablename) + .CommonWhereExpression( + idlist: commonhelper.idlist, + languagelist: commonhelper.languagelist, + visibleinsearch: commonhelper.visibleinsearch, + commonhelper.smgtaglist, + activefilter: commonhelper.active, + odhactivefilter: commonhelper.smgactive, + publishedonlist: commonhelper.publishedonlist, + sourcelist: commonhelper.sourcelist, + searchfilter: searchfilter, + language: language, + lastchange: commonhelper.lastchange, + filterClosedData: FilterClosedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); uint totalpages = (uint)data.TotalPages; uint totalcount = (uint)data.Count; @@ -1027,67 +1560,131 @@ await query totalcount, seed, dataTransformed, - Url); + Url + ); }); } - private Task WineGetListHelper(string tablename, string? seed, string? searchfilter, string[] fields, string? language, WineHelper winehelper, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task WineGetListHelper( + string tablename, + string? seed, + string? searchfilter, + string[] fields, + string? language, + WineHelper winehelper, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query() - .SelectRaw("data") - .From(tablename) - .WineWhereExpression(languagelist: new List(), lastchange: winehelper.lastchange, wineid: winehelper.wineidlist, companyid: winehelper.companyidlist, - activefilter: winehelper.active, odhactivefilter: winehelper.smgactive, sourcelist: winehelper.sourcelist, - searchfilter: searchfilter, language: language, filterClosedData: FilterClosedData) - .ApplyRawFilter(rawfilter) - .ApplyOrdering(ref seed, new PGGeoSearchResult() { geosearch = false }, rawsort); + var query = QueryFactory + .Query() + .SelectRaw("data") + .From(tablename) + .WineWhereExpression( + languagelist: new List(), + lastchange: winehelper.lastchange, + wineid: winehelper.wineidlist, + companyid: winehelper.companyidlist, + activefilter: winehelper.active, + odhactivefilter: winehelper.smgactive, + sourcelist: winehelper.sourcelist, + searchfilter: searchfilter, + language: language, + filterClosedData: FilterClosedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering( + ref seed, + new PGGeoSearchResult() { geosearch = false }, + rawsort + ); // Get paginated data - var data = - await query - .GetAsync(); - + var data = await query.GetAsync(); + var fieldsTohide = FieldsToHide; - var dataTransformed = - data.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); } - private Task WineGetPagedListHelper(uint pagenumber, int? pagesize, string tablename, string? seed, string? searchfilter, string[] fields, string? language, WineHelper winehelper, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task WineGetPagedListHelper( + uint pagenumber, + int? pagesize, + string tablename, + string? seed, + string? searchfilter, + string[] fields, + string? language, + WineHelper winehelper, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query() - .SelectRaw("data") - .From(tablename) - .WineWhereExpression(languagelist: new List(), lastchange: winehelper.lastchange, wineid: winehelper.wineidlist, companyid: winehelper.companyidlist, - activefilter: winehelper.active, odhactivefilter: winehelper.smgactive, sourcelist: winehelper.sourcelist, - searchfilter: searchfilter, language: language, filterClosedData: FilterClosedData) - .ApplyRawFilter(rawfilter) - .ApplyOrdering(ref seed, new PGGeoSearchResult() { geosearch = false }, rawsort); + var query = QueryFactory + .Query() + .SelectRaw("data") + .From(tablename) + .WineWhereExpression( + languagelist: new List(), + lastchange: winehelper.lastchange, + wineid: winehelper.wineidlist, + companyid: winehelper.companyidlist, + activefilter: winehelper.active, + odhactivefilter: winehelper.smgactive, + sourcelist: winehelper.sourcelist, + searchfilter: searchfilter, + language: language, + filterClosedData: FilterClosedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering( + ref seed, + new PGGeoSearchResult() { geosearch = false }, + rawsort + ); // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); uint totalpages = (uint)data.TotalPages; uint totalcount = (uint)data.Count; @@ -1098,26 +1695,41 @@ await query totalcount, seed, dataTransformed, - Url); + Url + ); }); } - - private Task CommonGetSingleHelper(string id, string tablename, string[] fields, string? language, bool removenullvalues, CancellationToken cancellationToken) + private Task CommonGetSingleHelper( + string id, + string tablename, + string[] fields, + string? language, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query(tablename) - .Select("data") - .Where("id", id.ToUpper()) - .When(FilterClosedData, q => q.FilterClosedData()); - + var query = QueryFactory + .Query(tablename) + .Select("data") + .Where("id", id.ToUpper()) + .When(FilterClosedData, q => q.FilterClosedData()); + var fieldsTohide = FieldsToHide; var data = await query.FirstOrDefaultAsync(); - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } diff --git a/OdhApiCore/Controllers/api/EventApiController.cs b/OdhApiCore/Controllers/api/EventApiController.cs index 2561bc6b9..e74c56970 100644 --- a/OdhApiCore/Controllers/api/EventApiController.cs +++ b/OdhApiCore/Controllers/api/EventApiController.cs @@ -19,16 +19,18 @@ namespace OdhApiCore.Controllers { /// - /// Events Api (data provided by LTS) SOME DATA Available as OPENDATA + /// Events Api (data provided by LTS) SOME DATA Available as OPENDATA /// [EnableCors("CorsPolicy")] [NullStringParameterActionFilter] public class EventController : OdhController - { - public EventController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + { + public EventController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } #region SWAGGER Exposed API @@ -39,22 +41,22 @@ public EventController(IWebHostEnvironment env, ISettings settings, ILoggerElements per Page, (default:10) /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting, (default:null) /// IDFilter (Separator ',' List of Event IDs, 'null' = No Filter), (default:'null') - /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter + /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter /// Rancfilter (Ranc 0-5 possible),(default: 'null') /// Typefilter (Type of Event: not used yet),(default: 'null') /// Topic ID Filter (Filter by Topic ID) BITMASK refers to 'v1/EventTopics',(default: 'null') /// Organization Filter (Filter by Organizer RID) - /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=event'), (default:'null') + /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=event'), (default:'null') /// BeginDate of Events (Format: yyyy-MM-dd), (default: 'null') /// EndDate of Events (Format: yyyy-MM-dd), (default: 'null') /// Sorting of Events by Next Begindate ('desc': Descending, 'asc': Ascending) /// Active Events Filter (possible Values: 'true' only Active Events, 'false' only Disabled Events), (default:'null') - /// ODH Active (Published) Events Filter (Refers to field OdhActive) Events Filter (possible Values: 'true' only published Events, 'false' only not published Events), (default:'null') + /// ODH Active (Published) Events Filter (Refers to field OdhActive) Events Filter (possible Values: 'true' only published Events, 'false' only not published Events), (default:'null') /// Filter by Source (Separator ','), (Sources available 'lts','trevilab','drin'),(default: 'null') /// GeoFilter FLOAT Latitude Format: '46.624975', 'null' = disabled, (default:'null') Wiki geosort /// GeoFilter FLOAT Longitude Format: '11.369909', 'null' = disabled, (default:'null') Wiki geosort /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) @@ -62,15 +64,20 @@ public EventController(IWebHostEnvironment env, ISettings settings, ILoggerString to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of Event Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of Event Objects /// List created /// Request Error /// Internal Server Error [ProducesResponseType(typeof(JsonResult), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [OdhCacheOutput(ClientTimeSpan = 0, ServerTimeSpan = 3600, CacheKeyGenerator = typeof(CustomCacheKeyGenerator), MustRevalidate = true)] + [OdhCacheOutput( + ClientTimeSpan = 0, + ServerTimeSpan = 3600, + CacheKeyGenerator = typeof(CustomCacheKeyGenerator), + MustRevalidate = true + )] //[Authorize] [HttpGet, Route("Event")] public async Task GetEventList( @@ -97,38 +104,62 @@ public async Task GetEventList( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); return await GetFiltered( - fields: fields ?? Array.Empty(), language: language, pagenumber: pagenumber, - pagesize: pagesize, typefilter: typefilter, idfilter: idlist, rancfilter: rancfilter, - searchfilter: searchfilter, locfilter: locfilter, topicfilter: topicfilter, orgfilter: orgfilter, - begindate: begindate, enddate: enddate, sort: sort, active: active, - smgactive: odhactive, smgtags: odhtagfilter, seed: seed, lastchange: updatefrom, - langfilter: langfilter, source: source, publishedon: publishedon, - geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, - cancellationToken: cancellationToken); + fields: fields ?? Array.Empty(), + language: language, + pagenumber: pagenumber, + pagesize: pagesize, + typefilter: typefilter, + idfilter: idlist, + rancfilter: rancfilter, + searchfilter: searchfilter, + locfilter: locfilter, + topicfilter: topicfilter, + orgfilter: orgfilter, + begindate: begindate, + enddate: enddate, + sort: sort, + active: active, + smgactive: odhactive, + smgtags: odhtagfilter, + seed: seed, + lastchange: updatefrom, + langfilter: langfilter, + source: source, + publishedon: publishedon, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken: cancellationToken + ); } /// - /// GET Event Single + /// GET Event Single /// /// ID of the Event /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Event Object /// Object created /// Request Error - /// Internal Server Error + /// Internal Server Error [ProducesResponseType(typeof(EventLinked), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -136,12 +167,18 @@ public async Task GetEventList( public async Task GetEventSingle( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -152,27 +189,35 @@ public async Task GetEventSingle( /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of EventTypes Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of EventTypes Object /// List created /// Request Error /// Internal Server Error //[OdhCacheOutputUntilToday(23, 59)] [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("EventTopics")] public async Task GetAllEventTopicListAsync( string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetEventTopicListAsync(language, fields: fields ?? Array.Empty(), searchfilter, rawfilter, rawsort, removenullvalues, cancellationToken); + return await GetEventTopicListAsync( + language, + fields: fields ?? Array.Empty(), + searchfilter, + rawfilter, + rawsort, + removenullvalues, + cancellationToken + ); } /// @@ -181,25 +226,31 @@ public async Task GetAllEventTopicListAsync( /// ID of the Event /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// EventTypes Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// EventTypes Object /// List created /// Request Error /// Internal Server Error //[OdhCacheOutputUntilToday(23, 59)] [ProducesResponseType(typeof(EventTypes), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("EventTopics/{id}", Name = "SingleEventTopics")] public async Task GetAllEventTopicSingleAsync( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetEventTopicSingleAsync(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetEventTopicSingleAsync( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } #endregion @@ -207,22 +258,61 @@ public async Task GetAllEventTopicSingleAsync( #region GETTER private Task GetFiltered( - string[] fields, string? language, uint pagenumber, int? pagesize, string? typefilter, string? idfilter, - string? rancfilter, string? searchfilter, string? locfilter, string? orgfilter, string? topicfilter, string? begindate, string? enddate, - string? sort, bool? active, bool? smgactive, string? smgtags, string? seed, string? lastchange, string? langfilter, string? source, string? publishedon, - PGGeoSearchResult geosearchresult, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + string[] fields, + string? language, + uint pagenumber, + int? pagesize, + string? typefilter, + string? idfilter, + string? rancfilter, + string? searchfilter, + string? locfilter, + string? orgfilter, + string? topicfilter, + string? begindate, + string? enddate, + string? sort, + bool? active, + bool? smgactive, + string? smgtags, + string? seed, + string? lastchange, + string? langfilter, + string? source, + string? publishedon, + PGGeoSearchResult geosearchresult, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { EventHelper myeventhelper = await EventHelper.CreateAsync( - QueryFactory, idfilter, locfilter, rancfilter, typefilter, topicfilter, orgfilter, begindate, enddate, - active, smgactive, smgtags, lastchange, langfilter, source, publishedon, - cancellationToken); + QueryFactory, + idfilter, + locfilter, + rancfilter, + typefilter, + topicfilter, + orgfilter, + begindate, + enddate, + active, + smgactive, + smgtags, + lastchange, + langfilter, + source, + publishedon, + cancellationToken + ); string? sortifseednull = null; if (sort != null) - { + { if (sort.ToLower() == "asc") sortifseednull = "gen_nextbegindate ASC"; else @@ -230,47 +320,73 @@ private Task GetFiltered( //Set seed to null seed = null; - + //Set Rawfilter to this RTHOENI rawfilter can overwrite this ;) //rawfilter = sortifseednull; } - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("events") - .EventWhereExpression( - idlist: myeventhelper.idlist, typelist: myeventhelper.typeidlist, - ranclist: myeventhelper.rancidlist, orglist: myeventhelper.orgidlist, - smgtaglist: myeventhelper.smgtaglist, districtlist: myeventhelper.districtlist, - municipalitylist: myeventhelper.municipalitylist, tourismvereinlist: myeventhelper.tourismvereinlist, - regionlist: myeventhelper.regionlist, topiclist: myeventhelper.topicrids, sourcelist: myeventhelper.sourcelist, - languagelist: myeventhelper.languagelist, begindate: myeventhelper.begin, enddate: myeventhelper.end, - activefilter: myeventhelper.active, smgactivefilter: myeventhelper.smgactive, publishedonlist: myeventhelper.publishedonlist, - searchfilter: searchfilter, language: language, lastchange: myeventhelper.lastchange, - filterClosedData: FilterClosedData, reducedData: ReducedData) - .ApplyRawFilter(rawfilter) - .OrderByRawIfNotNull(sortifseednull) - .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort, sortifseednull); - //.ApplyOrdering(ref seed, geosearchresult, rawsort, sortifseednull); + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("events") + .EventWhereExpression( + idlist: myeventhelper.idlist, + typelist: myeventhelper.typeidlist, + ranclist: myeventhelper.rancidlist, + orglist: myeventhelper.orgidlist, + smgtaglist: myeventhelper.smgtaglist, + districtlist: myeventhelper.districtlist, + municipalitylist: myeventhelper.municipalitylist, + tourismvereinlist: myeventhelper.tourismvereinlist, + regionlist: myeventhelper.regionlist, + topiclist: myeventhelper.topicrids, + sourcelist: myeventhelper.sourcelist, + languagelist: myeventhelper.languagelist, + begindate: myeventhelper.begin, + enddate: myeventhelper.end, + activefilter: myeventhelper.active, + smgactivefilter: myeventhelper.smgactive, + publishedonlist: myeventhelper.publishedonlist, + searchfilter: searchfilter, + language: language, + lastchange: myeventhelper.lastchange, + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) + .ApplyRawFilter(rawfilter) + .OrderByRawIfNotNull(sortifseednull) + .ApplyOrdering_GeneratedColumns( + ref seed, + geosearchresult, + rawsort, + sortifseednull + ); + //.ApplyOrdering(ref seed, geosearchresult, rawsort, sortifseednull); //.OrderBySeed(ref seed, sortifseednull) //.GeoSearchFilterAndOrderby(geosearchresult); //TODO Use sorting // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); uint totalpages = (uint)data.TotalPages; uint totalcount = (uint)data.Count; @@ -281,7 +397,8 @@ await query totalcount, seed, dataTransformed, - Url); + Url + ); }); } @@ -290,22 +407,36 @@ await query /// /// ID of the Event /// Event Object - private Task GetSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("events") - .Select("data") - .Where("id", id.ToUpper()) - //.When(FilterClosedData, q => q.FilterClosedData()); - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + var query = QueryFactory + .Query("events") + .Select("data") + .Where("id", id.ToUpper()) + //.When(FilterClosedData, q => q.FilterClosedData()); + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); var fieldsTohide = FieldsToHide; var data = await query.FirstOrDefaultAsync(); - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -317,26 +448,45 @@ private Task GetSingle(string id, string? language, string[] fiel /// GET Event Topics List /// /// Collection of EventTypes Object - private Task GetEventTopicListAsync(string? language, string[] fields, string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task GetEventTopicListAsync( + string? language, + string[] fields, + string? searchfilter, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("eventtypes") - .SelectRaw("data") - .When(FilterClosedData, q => q.FilterClosedData()) - .SearchFilter(PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), searchfilter) - .ApplyRawFilter(rawfilter) - .OrderOnlyByRawSortIfNotNull(rawsort); + var query = QueryFactory + .Query("eventtypes") + .SelectRaw("data") + .When(FilterClosedData, q => q.FilterClosedData()) + .SearchFilter( + PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), + searchfilter + ) + .ApplyRawFilter(rawfilter) + .OrderOnlyByRawSortIfNotNull(rawsort); var fieldsTohide = FieldsToHide; var data = await query.GetAsync(); - var dataTransformed = - data.Select( - raw => raw?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); @@ -346,21 +496,35 @@ private Task GetEventTopicListAsync(string? language, string[] fi /// GET Event Topic Single /// /// EventTypes Object - private Task GetEventTopicSingleAsync(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetEventTopicSingleAsync( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("eventtypes") - .Select("data") - .Where("id", id.ToUpper()) - .When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query("eventtypes") + .Select("data") + .Where("id", id.ToUpper()) + .When(FilterClosedData, q => q.FilterClosedData()); var fieldsTohide = FieldsToHide; var data = await query.FirstOrDefaultAsync(); - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -420,7 +584,6 @@ public Task Delete(string id) }); } - #endregion } -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/api/EventShortApiController.cs b/OdhApiCore/Controllers/api/EventShortApiController.cs index 05d29659d..fc6f76320 100644 --- a/OdhApiCore/Controllers/api/EventShortApiController.cs +++ b/OdhApiCore/Controllers/api/EventShortApiController.cs @@ -1,5 +1,5 @@ using DataModel; -using DataModel.Annotations; +using DataModel.Annotations; using Helper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; @@ -13,7 +13,7 @@ using OdhApiCore.Responses; using SqlKata; using SqlKata.Execution; -using Swashbuckle.AspNetCore.Annotations; +using Swashbuckle.AspNetCore.Annotations; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -25,16 +25,18 @@ namespace OdhApiCore.Controllers.api { /// - /// EventShort Api (data provided by NOI/EURAC) ALL DATA Available as OPENDATA + /// EventShort Api (data provided by NOI/EURAC) ALL DATA Available as OPENDATA /// [EnableCors("CorsPolicy")] [NullStringParameterActionFilter] public class EventShortController : OdhController - { - public EventShortController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + { + public EventShortController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } #region SWAGGER Exposed API @@ -49,22 +51,22 @@ public EventShortController(IWebHostEnvironment env, ISettings settings, ILogger /// not provided, use default format, for unix timestamp pass "uxtimestamp" /// Source of the data, (possible values 'Content' or 'EBMS') /// Event Location, (possible values, 'NOI' = Events at Noi Techpark, 'EC' = Eurac Events, 'OUT' = Events in other locatiosn) - /// 'true' if only Events marked as Active should be returned - /// 'true' if only Events marked as Active for noi.bz.it should be returned - /// 'true' if only Events marked as Active for Noi community should be returned + /// 'true' if only Events marked as Active should be returned + /// 'true' if only Events marked as Active for noi.bz.it should be returned + /// 'true' if only Events marked as Active for Noi community should be returned /// comma separated list of event ids /// ASC or DESC by StartDate /// Searches the webaddress /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Optimizes dates, cuts out all Rooms with Comment "x", revisits and corrects start + enddate /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Result Object with EventShort List [ProducesResponseType(typeof(Result), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] @@ -72,15 +74,17 @@ public EventShortController(IWebHostEnvironment env, ISettings settings, ILogger //[EnableCors(origins: "*", headers: "*", methods: "*")] [HttpGet, Route("EventShort")] public async Task Get( - uint pagenumber = 1, + uint pagenumber = 1, PageSize pagesize = null!, //1024 should be given as standard - string? startdate = null, - string? enddate = null, - string? datetimeformat = null, - string? source = null, + string? startdate = null, + string? enddate = null, + string? datetimeformat = null, + string? source = null, [SwaggerEnum(new[] { "NOI", "EV", "VV", "OUT" })] - [SwaggerParameter("

Members:

  • NOI - NOI Techpark
  • EC - Eurac
  • VV - Virtual Village
  • OUT - Other Location
")] - string? eventlocation = null, + [SwaggerParameter( + "

Members:

  • NOI - NOI Techpark
  • EC - Eurac
  • VV - Virtual Village
  • OUT - Other Location
" + )] + string? eventlocation = null, LegacyBool onlyactive = null!, LegacyBool websiteactive = null!, LegacyBool communityactive = null!, @@ -91,25 +95,42 @@ public async Task Get( string? language = null, string? langfilter = null, bool optimizedates = false, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? lastchange = null, string? publishedon = null, string? searchfilter = null, string? rawfilter = null, - string? rawsort = null, + string? rawsort = null, bool removenullvalues = false, CancellationToken cancellationToken = default - ) + ) { return await GetEventShortList( - fields: fields ?? Array.Empty(), language: language, pagenumber: pagenumber, pagesize: pagesize, - startdate: startdate, enddate: enddate, datetimeformat: datetimeformat, idfilter: eventids, - searchfilter: searchfilter, sourcefilter: source, eventlocationfilter: eventlocation, - webaddressfilter: webaddress, active: onlyactive.Value, websiteactive: websiteactive.Value, communityactive: communityactive.Value, optimizedates: optimizedates, - sortorder: sortorder, seed: seed, lastchange: lastchange, publishedon: publishedon, - rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, - cancellationToken: cancellationToken); + fields: fields ?? Array.Empty(), + language: language, + pagenumber: pagenumber, + pagesize: pagesize, + startdate: startdate, + enddate: enddate, + datetimeformat: datetimeformat, + idfilter: eventids, + searchfilter: searchfilter, + sourcefilter: source, + eventlocationfilter: eventlocation, + webaddressfilter: webaddress, + active: onlyactive.Value, + websiteactive: websiteactive.Value, + communityactive: communityactive.Value, + optimizedates: optimizedates, + sortorder: sortorder, + seed: seed, + lastchange: lastchange, + publishedon: publishedon, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken: cancellationToken + ); } /// @@ -119,7 +140,7 @@ public async Task Get( /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Optimizes dates, cuts out all Rooms with Comment "x", revisits and corrects start + enddate - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// EventShort Object /// Object created /// Request Error @@ -135,12 +156,19 @@ public async Task GetSingle( string id, string? language, bool optimizedates = false, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetEventShortSingle(id, language, optimizedates: optimizedates, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetEventShortSingle( + id, + language, + optimizedates: optimizedates, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -150,20 +178,20 @@ public async Task GetSingle( /// Format (yyyy-MM-dd HH:mm) default or Unix Timestamp /// not provided, use default format, for unix timestamp pass "uxtimestamp" /// Source of the data, (possible values 'Content' or 'EBMS') - /// Event Location, (possible values, 'NOI' = Events at Noi Techpark, 'EC' = Eurac Events, 'OUT' = Events in other locatiosn) - /// 'true' if only Events marked as Active should be returned - /// 'true' if only Events marked as Active for noi.bz.it should be returned - /// 'true' if only Events marked as Active for Noi community should be returned + /// Event Location, (possible values, 'NOI' = Events at Noi Techpark, 'EC' = Eurac Events, 'OUT' = Events in other locatiosn) + /// 'true' if only Events marked as Active should be returned + /// 'true' if only Events marked as Active for noi.bz.it should be returned + /// 'true' if only Events marked as Active for Noi community should be returned /// comma separated list of event ids /// Filter by WebAddress Field /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Language filter (returns only data available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// List of EventShortByRoom Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] @@ -171,35 +199,54 @@ public async Task GetSingle( //[EnableCors(origins: "*", headers: "*", methods: "*")] [HttpGet, Route("EventShort/GetbyRoomBooked")] public async Task GetbyRoomBooked( - string? startdate = null, - string? enddate = null, - string? datetimeformat = null, - string? source = null, + string? startdate = null, + string? enddate = null, + string? datetimeformat = null, + string? source = null, string? eventlocation = null, LegacyBool onlyactive = null!, LegacyBool websiteactive = null!, LegacyBool communityactive = null!, - string? eventids = null, + string? eventids = null, string? webaddress = null, string? language = null, string? langfilter = null, string? lastchange = null, string? updatefrom = null, string? publishedon = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { if (updatefrom == null && lastchange != null) updatefrom = lastchange; - return await GetEventShortListbyRoomBooked(startdate, enddate, datetimeformat, source, eventlocation, onlyactive.Value, - websiteactive.Value, communityactive.Value, eventids, webaddress, publishedon, updatefrom, language, null, - searchfilter, fields: fields ?? Array.Empty(), rawfilter, rawsort, removenullvalues, cancellationToken); + return await GetEventShortListbyRoomBooked( + startdate, + enddate, + datetimeformat, + source, + eventlocation, + onlyactive.Value, + websiteactive.Value, + communityactive.Value, + eventids, + webaddress, + publishedon, + updatefrom, + language, + null, + searchfilter, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + removenullvalues, + cancellationToken + ); } /// @@ -213,7 +260,7 @@ public async Task GetbyRoomBooked( [HttpGet, Route("EventShort/RoomMapping")] public async Task> GetBDPNoiRoomsWithLinkDictionary( string? language = null - ) + ) { return await GetBDPNoiRoomsWithLink(language); } @@ -226,23 +273,31 @@ public async Task> GetBDPNoiRoomsWithLinkDictionary( /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of EventShortType Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of EventShortType Object //[ProducesResponseType(typeof(IDictionary), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("EventShortTypes")] public async Task GetEventShortTypes( string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetEventShortTypesList(language, fields: fields ?? Array.Empty(), searchfilter, rawfilter, rawsort, removenullvalues: removenullvalues, cancellationToken); + return await GetEventShortTypesList( + language, + fields: fields ?? Array.Empty(), + searchfilter, + rawfilter, + rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -251,8 +306,8 @@ public async Task GetEventShortTypes( /// ID of the EventShort Type /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// ActivityPoiType Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// ActivityPoiType Object /// List created /// Request Error /// Internal Server Error @@ -263,12 +318,18 @@ public async Task GetEventShortTypes( public async Task GetEventShortTypesSingle( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetEventShortType(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetEventShortType( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } #endregion @@ -276,47 +337,104 @@ public async Task GetEventShortTypesSingle( #region GETTER private Task GetEventShortList( - string[] fields, string? language, string? searchfilter, uint pagenumber, int? pagesize, string? startdate, string? enddate, string? datetimeformat, - string? idfilter, string? sourcefilter, string? eventlocationfilter, string? webaddressfilter, bool? active, bool? websiteactive, bool? communityactive, bool optimizedates, string? sortorder, string? seed, - string? lastchange, string? publishedon, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + string[] fields, + string? language, + string? searchfilter, + uint pagenumber, + int? pagesize, + string? startdate, + string? enddate, + string? datetimeformat, + string? idfilter, + string? sourcefilter, + string? eventlocationfilter, + string? webaddressfilter, + bool? active, + bool? websiteactive, + bool? communityactive, + bool optimizedates, + string? sortorder, + string? seed, + string? lastchange, + string? publishedon, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - - EventShortHelper myeventshorthelper = EventShortHelper.Create(startdate, enddate, datetimeformat, - sourcefilter, eventlocationfilter, active, websiteactive, communityactive, idfilter, webaddressfilter, lastchange, sortorder, publishedon); - - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("eventeuracnoi") - .EventShortWhereExpression( - idlist: myeventshorthelper.idlist, sourcelist: myeventshorthelper.sourcelist, - eventlocationlist: myeventshorthelper.eventlocationlist, webaddresslist: myeventshorthelper.webaddresslist, - start: myeventshorthelper.start, end: myeventshorthelper.end, activefilter: myeventshorthelper.activefilter, - websiteactivefilter: myeventshorthelper.websiteactivefilter, communityactivefilter: myeventshorthelper.communityactivefilter, - publishedonlist: myeventshorthelper.publishedonlist, searchfilter: searchfilter, language: language, lastchange: myeventshorthelper.lastchange, - filterClosedData: FilterClosedData, getbyrooms: false) - .ApplyRawFilter(rawfilter) - .ApplyOrdering(ref seed, new PGGeoSearchResult() { geosearch = false }, rawsort, "data #>>'\\{StartDate\\}' " + myeventshorthelper.sortorder); + EventShortHelper myeventshorthelper = EventShortHelper.Create( + startdate, + enddate, + datetimeformat, + sourcefilter, + eventlocationfilter, + active, + websiteactive, + communityactive, + idfilter, + webaddressfilter, + lastchange, + sortorder, + publishedon + ); + + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("eventeuracnoi") + .EventShortWhereExpression( + idlist: myeventshorthelper.idlist, + sourcelist: myeventshorthelper.sourcelist, + eventlocationlist: myeventshorthelper.eventlocationlist, + webaddresslist: myeventshorthelper.webaddresslist, + start: myeventshorthelper.start, + end: myeventshorthelper.end, + activefilter: myeventshorthelper.activefilter, + websiteactivefilter: myeventshorthelper.websiteactivefilter, + communityactivefilter: myeventshorthelper.communityactivefilter, + publishedonlist: myeventshorthelper.publishedonlist, + searchfilter: searchfilter, + language: language, + lastchange: myeventshorthelper.lastchange, + filterClosedData: FilterClosedData, + getbyrooms: false + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering( + ref seed, + new PGGeoSearchResult() { geosearch = false }, + rawsort, + "data #>>'\\{StartDate\\}' " + myeventshorthelper.sortorder + ); // Get paginated data - var data = - (await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25)); + var data = ( + await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ) + ); if (optimizedates) data.List = OptimizeRoomForAppList(data.List); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); - + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); uint totalpages = (uint)data.TotalPages; uint totalcount = (uint)data.Count; @@ -327,20 +445,27 @@ private Task GetEventShortList( totalcount, seed, dataTransformed, - Url); - }); + Url + ); + }); } private Task GetEventShortSingle( - string id, string? language, bool optimizedates, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + string id, + string? language, + bool optimizedates, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("eventeuracnoi") - .Select("data") - .Where("id", id.ToLower()) - .When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query("eventeuracnoi") + .Select("data") + .Where("id", id.ToLower()) + .When(FilterClosedData, q => q.FilterClosedData()); var fieldsTohide = FieldsToHide; @@ -349,64 +474,127 @@ private Task GetEventShortSingle( if (optimizedates && data is { }) data = OptimizeRoomForApp(data); - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } #endregion - #region CUSTOM METODS + #region CUSTOM METODS private async Task GetEventShortListbyRoomBooked( - string? startdate, string? enddate, string? datetimeformat, string? sourcefilter, string? eventlocationfilter, - bool? active, bool? websiteactive, bool? communityactive, string? idfilter, string? webaddressfilter, string? publishedon, string? lastchange, string? language, string? sortorder, - string? searchfilter, string[] fields, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + string? startdate, + string? enddate, + string? datetimeformat, + string? sourcefilter, + string? eventlocationfilter, + bool? active, + bool? websiteactive, + bool? communityactive, + string? idfilter, + string? webaddressfilter, + string? publishedon, + string? lastchange, + string? language, + string? sortorder, + string? searchfilter, + string[] fields, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { - - EventShortHelper myeventshorthelper = EventShortHelper.Create(startdate, enddate, datetimeformat, - sourcefilter, eventlocationfilter, active, websiteactive, communityactive, idfilter, webaddressfilter, lastchange, sortorder, publishedon); - - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("eventeuracnoi") - .EventShortWhereExpression( - idlist: myeventshorthelper.idlist, sourcelist: myeventshorthelper.sourcelist, - eventlocationlist: myeventshorthelper.eventlocationlist, webaddresslist: myeventshorthelper.webaddresslist, - start: myeventshorthelper.start, end: myeventshorthelper.end, activefilter: myeventshorthelper.activefilter, - websiteactivefilter: myeventshorthelper.websiteactivefilter, communityactivefilter: myeventshorthelper.communityactivefilter, - publishedonlist: myeventshorthelper.publishedonlist, searchfilter: searchfilter, language: language, lastchange: myeventshorthelper.lastchange, - filterClosedData: FilterClosedData, getbyrooms: false) - .ApplyRawFilter(rawfilter); - - var data = - await query - .GetAsync(); - - var eventshortlist = data.Select(x => JsonConvert.DeserializeObject(x)!).ToList(); - - var result = TransformEventShortToRoom(eventshortlist, myeventshorthelper.start, myeventshorthelper.end); + EventShortHelper myeventshorthelper = EventShortHelper.Create( + startdate, + enddate, + datetimeformat, + sourcefilter, + eventlocationfilter, + active, + websiteactive, + communityactive, + idfilter, + webaddressfilter, + lastchange, + sortorder, + publishedon + ); + + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("eventeuracnoi") + .EventShortWhereExpression( + idlist: myeventshorthelper.idlist, + sourcelist: myeventshorthelper.sourcelist, + eventlocationlist: myeventshorthelper.eventlocationlist, + webaddresslist: myeventshorthelper.webaddresslist, + start: myeventshorthelper.start, + end: myeventshorthelper.end, + activefilter: myeventshorthelper.activefilter, + websiteactivefilter: myeventshorthelper.websiteactivefilter, + communityactivefilter: myeventshorthelper.communityactivefilter, + publishedonlist: myeventshorthelper.publishedonlist, + searchfilter: searchfilter, + language: language, + lastchange: myeventshorthelper.lastchange, + filterClosedData: FilterClosedData, + getbyrooms: false + ) + .ApplyRawFilter(rawfilter); + + var data = await query.GetAsync(); + + var eventshortlist = data.Select(x => JsonConvert.DeserializeObject(x)!) + .ToList(); + + var result = TransformEventShortToRoom( + eventshortlist, + myeventshorthelper.start, + myeventshorthelper.end + ); IEnumerable resultraw = result.Select(x => new JsonRaw(x)); var fieldsTohide = FieldsToHide; - var dataTransformed = - resultraw.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); - + var dataTransformed = resultraw.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); + return Ok(dataTransformed); } - private IEnumerable TransformEventShortToRoom(IEnumerable eventsshort, DateTime start, DateTime end) + private IEnumerable TransformEventShortToRoom( + IEnumerable eventsshort, + DateTime start, + DateTime end + ) { List eventshortlistbyroom = new List(); foreach (EventShort eventshort in eventsshort) { // 1 Event goes for more days - //Hack, if Event Room is + //Hack, if Event Room is foreach (RoomBooked room in eventshort.RoomBooked ?? new List()) { @@ -416,7 +604,6 @@ private IEnumerable TransformEventShortToRoom(IEnumerable TransformEventShortToRoom(IEnumerable TransformEventShortToRoom(IEnumerable TransformEventShortToRoom(IEnumerable(); - myeventshortbyroom.VideoUrl = eventshort.VideoUrl != null ? eventshort.VideoUrl : ""; + myeventshortbyroom.ImageGallery = + eventshort.ImageGallery != null + ? eventshort.ImageGallery + : new List(); + myeventshortbyroom.VideoUrl = + eventshort.VideoUrl != null ? eventshort.VideoUrl : ""; // Same Logic - string textde = eventshort.EventTextDE != null ? eventshort.EventTextDE : ""; + string textde = + eventshort.EventTextDE != null ? eventshort.EventTextDE : ""; myeventshortbyroom.EventTextDE = textde; myeventshortbyroom.EventTextIT = eventshort.EventTextIT; myeventshortbyroom.EventTextEN = eventshort.EventTextEN; - if (string.IsNullOrEmpty(myeventshortbyroom.EventTextIT)) myeventshortbyroom.EventTextIT = textde; if (string.IsNullOrEmpty(myeventshortbyroom.EventTextEN)) myeventshortbyroom.EventTextEN = textde; - myeventshortbyroom.TechnologyFields = eventshort.TechnologyFields != null ? eventshort.TechnologyFields : new List(); - myeventshortbyroom.CustomTagging = eventshort.CustomTagging != null ? eventshort.CustomTagging : new List(); + myeventshortbyroom.TechnologyFields = + eventshort.TechnologyFields != null + ? eventshort.TechnologyFields + : new List(); + myeventshortbyroom.CustomTagging = + eventshort.CustomTagging != null + ? eventshort.CustomTagging + : new List(); if (eventshort.EventDocument != null) { @@ -491,8 +718,15 @@ private IEnumerable TransformEventShortToRoom(IEnumerable TransformEventShortToRoom(IEnumerable TransformEventShortToRoom(IEnumerable x.RoomStartDate); } - private void AddToRoomList(List eventshortlistbyroom, EventShortByRoom roomtoadd) + private void AddToRoomList( + List eventshortlistbyroom, + EventShortByRoom roomtoadd + ) { - // Sieh nach ob bereits ein Event mit demselben namen und - var sameevent = eventshortlistbyroom.Where(x => x.Id == roomtoadd.Id - && x.RoomStartDate == roomtoadd.RoomStartDate - && x.RoomEndDate == roomtoadd.RoomEndDate).FirstOrDefault(); + // Sieh nach ob bereits ein Event mit demselben namen und + var sameevent = eventshortlistbyroom + .Where( + x => + x.Id == roomtoadd.Id + && x.RoomStartDate == roomtoadd.RoomStartDate + && x.RoomEndDate == roomtoadd.RoomEndDate + ) + .FirstOrDefault(); if (sameevent != null) { string roomname = roomtoadd.SpaceDesc ?? ""; - if (roomname.StartsWith("NOI ") || roomname.StartsWith("Noi ") || roomname.StartsWith("noi ")) + if ( + roomname.StartsWith("NOI ") + || roomname.StartsWith("Noi ") + || roomname.StartsWith("noi ") + ) roomname = roomname.Remove(0, 3).Trim(); sameevent.SpaceDescList.Add(roomname); } else eventshortlistbyroom.Add(roomtoadd); - } private IEnumerable OptimizeRoomForAppList(IEnumerable data) @@ -556,7 +800,8 @@ private IEnumerable OptimizeRoomForAppList(IEnumerable data) private JsonRaw OptimizeRoomForApp(JsonRaw eventshortraw) { //var eventshortlist = data.Select(x => JsonConvert.DeserializeObject(x.Value)!).ToList(); - var eventshort = JsonConvert.DeserializeObject(eventshortraw.Value) ?? new(); + var eventshort = + JsonConvert.DeserializeObject(eventshortraw.Value) ?? new(); // TODO: Remove all Rooms with x // Starting and ending date check with rooms remaining @@ -566,19 +811,29 @@ private JsonRaw OptimizeRoomForApp(JsonRaw eventshortraw) } // Get the lowest room start date - var firstbegindate = eventshort.RoomBooked?.OrderBy(x => x.StartDate).Select(x => x.StartDate).FirstOrDefault(); - var lastenddate = eventshort.RoomBooked?.OrderByDescending(x => x.EndDate).Select(x => x.EndDate).FirstOrDefault(); + var firstbegindate = eventshort.RoomBooked + ?.OrderBy(x => x.StartDate) + .Select(x => x.StartDate) + .FirstOrDefault(); + var lastenddate = eventshort.RoomBooked + ?.OrderByDescending(x => x.EndDate) + .Select(x => x.EndDate) + .FirstOrDefault(); if (firstbegindate.HasValue && firstbegindate != eventshort.StartDate) { eventshort.StartDate = firstbegindate.Value; - eventshort.StartDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(firstbegindate.Value); + eventshort.StartDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + firstbegindate.Value + ); } if (lastenddate.HasValue && lastenddate != eventshort.EndDate) { eventshort.EndDate = lastenddate.Value; - eventshort.EndDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(lastenddate.Value); + eventshort.EndDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + lastenddate.Value + ); } return new JsonRaw(eventshort); @@ -588,48 +843,81 @@ private JsonRaw OptimizeRoomForApp(JsonRaw eventshortraw) #region EVENTSHORT TYPES - private Task GetEventShortTypesList(string? language, string[] fields, string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task GetEventShortTypesList( + string? language, + string[] fields, + string? searchfilter, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("eventshorttypes") - .SelectRaw("data") - .When(FilterClosedData, q => q.FilterClosedData()) - .SearchFilter(PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), searchfilter) - .ApplyRawFilter(rawfilter) - .OrderOnlyByRawSortIfNotNull(rawsort); + var query = QueryFactory + .Query("eventshorttypes") + .SelectRaw("data") + .When(FilterClosedData, q => q.FilterClosedData()) + .SearchFilter( + PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), + searchfilter + ) + .ApplyRawFilter(rawfilter) + .OrderOnlyByRawSortIfNotNull(rawsort); var data = await query.GetAsync(); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.Select( - raw => raw?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); } - private Task GetEventShortType(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetEventShortType( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("eventshorttypes") - .Select("data") - //.WhereJsonb("Key", "ilike", id) - .Where("id", id.ToLower()) - .When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query("eventshorttypes") + .Select("data") + //.WhereJsonb("Key", "ilike", id) + .Where("id", id.ToLower()) + .When(FilterClosedData, q => q.FilterClosedData()); //.Where("Key", "ILIKE", id); var data = await query.FirstOrDefaultAsync(); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -640,7 +928,9 @@ private Task GetEventShortType(string id, string? language, strin // POST: api/EventShort //[ApiExplorerSettings(IgnoreApi = true)] //[EnableCors("DataBrowserCorsPolicy")] - [Authorize(Roles = "DataWriter,DataCreate,EventShortManager,EventShortCreate,VirtualVillageManager")] + [Authorize( + Roles = "DataWriter,DataCreate,EventShortManager,EventShortCreate,VirtualVillageManager" + )] [ProducesResponseType(typeof(PGCRUDResult), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -655,16 +945,44 @@ public async Task Post([FromBody] EventShortLinked eventshort) { if (eventshort.EventLocation == null) throw new Exception("Eventlocation needed"); - - eventshort.EventLocation = eventshort.EventLocation.ToUpper(); - if (CheckIfUserIsOnlyInRole("VirtualVillageManager", new List() { "DataWriter", "DataCreate", "EventShortManager", "EventShortCreate" }) && eventshort.EventLocation != "VV") - throw new Exception("VirtualVillageManager can only insert Virtual Village Events"); + eventshort.EventLocation = eventshort.EventLocation.ToUpper(); - if (CheckIfUserIsOnlyInRole("VirtualVillageManager", new List() { "DataWriter", "DataCreate", "EventShortManager", "EventShortCreate" })) - eventshort.Source = User.Identity != null ? User.Identity.Name :""; + if ( + CheckIfUserIsOnlyInRole( + "VirtualVillageManager", + new List() + { + "DataWriter", + "DataCreate", + "EventShortManager", + "EventShortCreate" + } + ) + && eventshort.EventLocation != "VV" + ) + throw new Exception( + "VirtualVillageManager can only insert Virtual Village Events" + ); + + if ( + CheckIfUserIsOnlyInRole( + "VirtualVillageManager", + new List() + { + "DataWriter", + "DataCreate", + "EventShortManager", + "EventShortCreate" + } + ) + ) + eventshort.Source = User.Identity != null ? User.Identity.Name : ""; - if (eventshort.StartDate == DateTime.MinValue || eventshort.EndDate == DateTime.MinValue) + if ( + eventshort.StartDate == DateTime.MinValue + || eventshort.EndDate == DateTime.MinValue + ) throw new Exception("Start + End Time not set correctly"); eventshort.ChangedOn = DateTime.Now; @@ -678,8 +996,14 @@ public async Task Post([FromBody] EventShortLinked eventshort) //eventshort.StartDate = DateTime.SpecifyKind(eventshort.StartDate, DateTimeKind.Utc); //eventshort.EndDate = DateTime.SpecifyKind(eventshort.EndDate, DateTimeKind.Utc); - eventshort.EndDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(eventshort.EndDate); - eventshort.StartDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(eventshort.StartDate); + eventshort.EndDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + eventshort.EndDate + ); + eventshort.StartDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + eventshort.StartDate + ); bool addroomautomatically = false; @@ -698,8 +1022,14 @@ public async Task Post([FromBody] EventShortLinked eventshort) RoomBooked myroom = new RoomBooked(); myroom.StartDate = eventshort.StartDate; myroom.EndDate = eventshort.EndDate; - myroom.EndDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(eventshort.EndDate); - myroom.StartDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(eventshort.StartDate); + myroom.EndDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + eventshort.EndDate + ); + myroom.StartDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + eventshort.StartDate + ); myroom.Comment = ""; myroom.Space = eventshort.AnchorVenueShort; myroom.SpaceAbbrev = eventshort.AnchorVenue; @@ -718,7 +1048,7 @@ public async Task Post([FromBody] EventShortLinked eventshort) } else { - if(eventshort.RoomBooked != null) + if (eventshort.RoomBooked != null) { foreach (var room in eventshort.RoomBooked) { @@ -726,8 +1056,14 @@ public async Task Post([FromBody] EventShortLinked eventshort) //room.StartDate = DateTime.SpecifyKind(room.StartDate, DateTimeKind.Utc); //room.EndDate = DateTime.SpecifyKind(room.EndDate, DateTimeKind.Utc); - room.EndDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(room.EndDate); - room.StartDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(room.StartDate); + room.EndDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + room.EndDate + ); + room.StartDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + room.StartDate + ); } } } @@ -741,13 +1077,19 @@ public async Task Post([FromBody] EventShortLinked eventshort) //TraceSource tracesource = new TraceSource("CustomData"); //tracesource.TraceEvent(TraceEventType.Information, 0, "Event Start Date:" + String.Format("{0:dd/MM/yyyy hh:mm}", eventshort.StartDate)); - + string author = "unknown"; if (User.Identity != null && User.Identity.Name != null) author = User.Identity.Name; //LicenseInfo - eventshort.LicenseInfo = new LicenseInfo() { Author = author, ClosedData = false, LicenseHolder = "https://noi.bz.it/", License = "CC0" }; + eventshort.LicenseInfo = new LicenseInfo() + { + Author = author, + ClosedData = false, + LicenseHolder = "https://noi.bz.it/", + License = "CC0" + }; //eventshort._Meta = MetadataHelper.GetMetadataobject(eventshort, MetadataHelper.GetMetadataforEventShort); //eventshort._Meta.LastUpdate = eventshort.LastChange; @@ -776,7 +1118,9 @@ public async Task Post([FromBody] EventShortLinked eventshort) // PUT: api/EventShort/5 //[ApiExplorerSettings(IgnoreApi = true)] - [Authorize(Roles = "DataWriter,DataCreate,EventShortManager,EventShortModify,VirtualVillageManager")] + [Authorize( + Roles = "DataWriter,DataCreate,EventShortManager,EventShortModify,VirtualVillageManager" + )] [ProducesResponseType(typeof(PGCRUDResult), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -794,10 +1138,35 @@ public async Task Put(string id, [FromBody] EventShortLinked even eventshort.EventLocation = eventshort.EventLocation.ToUpper(); - if (CheckIfUserIsOnlyInRole("VirtualVillageManager", new List() { "DataWriter", "DataCreate", "EventShortManager", "EventShortModify" }) && eventshort.EventLocation != "VV") - throw new Exception("VirtualVillageManager can only insert Virtual Village Events"); - - if(CheckIfUserIsOnlyInRole("VirtualVillageManager", new List() { "DataWriter", "DataCreate", "EventShortManager", "EventShortModify" })) + if ( + CheckIfUserIsOnlyInRole( + "VirtualVillageManager", + new List() + { + "DataWriter", + "DataCreate", + "EventShortManager", + "EventShortModify" + } + ) + && eventshort.EventLocation != "VV" + ) + throw new Exception( + "VirtualVillageManager can only insert Virtual Village Events" + ); + + if ( + CheckIfUserIsOnlyInRole( + "VirtualVillageManager", + new List() + { + "DataWriter", + "DataCreate", + "EventShortManager", + "EventShortModify" + } + ) + ) eventshort.Source = User.Identity != null ? User.Identity.Name : ""; eventshort.ChangedOn = DateTime.Now; @@ -807,16 +1176,28 @@ public async Task Put(string id, [FromBody] EventShortLinked even eventshort.AnchorVenueShort = eventshort.AnchorVenue; - eventshort.EndDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(eventshort.EndDate); - eventshort.StartDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(eventshort.StartDate); + eventshort.EndDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + eventshort.EndDate + ); + eventshort.StartDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + eventshort.StartDate + ); //TODO on rooms if (eventshort.RoomBooked != null) { foreach (var room in eventshort.RoomBooked) { - room.EndDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(room.EndDate); - room.StartDateUTC = Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds(room.StartDate); + room.EndDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + room.EndDate + ); + room.StartDateUTC = + Helper.DateTimeHelper.DateTimeToUnixTimestampMilliseconds( + room.StartDate + ); } } @@ -827,7 +1208,7 @@ public async Task Put(string id, [FromBody] EventShortLinked even if (string.IsNullOrEmpty(eventshort.EventDescriptionEN)) eventshort.EventDescriptionEN = eventshort.EventDescriptionDE; - //TODO CHECK IF THIS WORKS + //TODO CHECK IF THIS WORKS //var updatequery = await QueryFactory.Query("eventeuracnoi").Where("id", id) // .UpdateAsync(new JsonBData() { id = eventshort.Id ?? "", data = eventshort != null ? new JsonRaw(eventshort) : null }); @@ -835,7 +1216,12 @@ public async Task Put(string id, [FromBody] EventShortLinked even //Check ID uppercase lowercase eventshort.Id = Helper.IdGenerator.CheckIdFromType(id); - return await UpsertData(eventshort, "eventeuracnoi", false, true); + return await UpsertData( + eventshort, + "eventeuracnoi", + false, + true + ); } else { @@ -850,25 +1236,27 @@ public async Task Put(string id, [FromBody] EventShortLinked even // DELETE: api/EventShort/5 //[ApiExplorerSettings(IgnoreApi = true)] - [Authorize(Roles = "DataWriter,DataCreate,EventShortManager,EventShortDelete,VirtualVillageManager")] + [Authorize( + Roles = "DataWriter,DataCreate,EventShortManager,EventShortDelete,VirtualVillageManager" + )] [ProducesResponseType(typeof(PGCRUDResult), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] //[OdhAuthorizeAttribute("DataWriter,DataCreate,EventShortManager,EventShortModify,VirtualVillageManager")] [HttpDelete, Route("EventShort/{id}")] - //[InvalidateCacheOutput("GetReducedAsync")] + //[InvalidateCacheOutput("GetReducedAsync")] public async Task Delete(string id) { try { if (id != null) { - var query = - QueryFactory.Query("eventeuracnoi") - .Select("data") - .Where("id", id.ToLower()); + var query = QueryFactory + .Query("eventeuracnoi") + .Select("data") + .Where("id", id.ToLower()); - //var myeventraw = await query.FirstOrDefaultAsync(); + //var myeventraw = await query.FirstOrDefaultAsync(); //var myevent = JsonConvert.DeserializeObject(myeventraw.Value); var myevent = await query.GetFirstOrDefaultAsObject(); @@ -877,10 +1265,24 @@ public async Task Delete(string id) { if (myevent.Source != "EBMS") { - if (CheckIfUserIsOnlyInRole("VirtualVillageManager", new List() { "DataWriter", "DataDelete", "EventShortManager", "EventShortDelete" }) && myevent.EventLocation != "VV") - throw new Exception("VirtualVillageManager can only delete Virtual Village Events"); - - //TODO CHECK IF THIS WORKS + if ( + CheckIfUserIsOnlyInRole( + "VirtualVillageManager", + new List() + { + "DataWriter", + "DataDelete", + "EventShortManager", + "EventShortDelete" + } + ) + && myevent.EventLocation != "VV" + ) + throw new Exception( + "VirtualVillageManager can only delete Virtual Village Events" + ); + + //TODO CHECK IF THIS WORKS //var deletequery = await QueryFactory.Query("eventeuracnoi").Where("id", id).DeleteAsync(); //return Ok(new GenericResult() { Message = "DELETE EventShort succeeded, Id:" + id }); @@ -889,9 +1291,12 @@ public async Task Delete(string id) } else { - if (User.IsInRole("VirtualVillageManager") && myevent.EventLocation == "VV") + if ( + User.IsInRole("VirtualVillageManager") + && myevent.EventLocation == "VV" + ) { - //TODO CHECK IF THIS WORKS + //TODO CHECK IF THIS WORKS //var deletequery = await QueryFactory.Query("eventeuracnoi").Where("id", id).DeleteAsync(); //return Ok(new GenericResult() { Message = "DELETE EventShort succeeded, Id:" + id }); @@ -1161,9 +1566,9 @@ private bool CheckIfUserIsOnlyInRole(string role, List rolestocheck) if (User.IsInRole(role)) returnbool = true; - foreach(string roletocheck in rolestocheck) + foreach (string roletocheck in rolestocheck) { - if(User.IsInRole(roletocheck)) + if (User.IsInRole(roletocheck)) returnbool = false; } @@ -1174,7 +1579,8 @@ private bool CheckIfUserIsOnlyInRole(string role, List rolestocheck) #region BDPRooms - private const string bdpserviceurl = @"https://mobility.api.opendatahub.bz.it/v2/flat/NOI-Place?select=smetadata&where=sactive.eq.true&limit=-1"; + private const string bdpserviceurl = + @"https://mobility.api.opendatahub.bz.it/v2/flat/NOI-Place?select=smetadata&where=sactive.eq.true&limit=-1"; private async Task> GetBDPNoiRoomsWithLink(string? language) { @@ -1183,7 +1589,10 @@ private async Task> GetBDPNoiRoomsWithLink(string? l var langtoinsert = ""; //Temporary workaround - if (!String.IsNullOrEmpty(language) && (language == "en" || language == "de" || language == "it")) + if ( + !String.IsNullOrEmpty(language) + && (language == "en" || language == "de" || language == "it") + ) langtoinsert = language + "/"; var bdprooms = await GetBDPNoiRooms(); @@ -1194,7 +1603,11 @@ private async Task> GetBDPNoiRoomsWithLink(string? l //var noimaproomlist = new List(); var noimaproomlist = new Dictionary(); - foreach (var room in bdprooms.data.Where(x => !String.IsNullOrEmpty(x.smetadata.todaynoibzit))) + foreach ( + var room in bdprooms.data.Where( + x => !String.IsNullOrEmpty(x.smetadata.todaynoibzit) + ) + ) { var maplink = ""; @@ -1205,11 +1618,18 @@ private async Task> GetBDPNoiRoomsWithLink(string? l var nametodisplay = room.smetadata.todaynoibzit; - if (nametodisplay.StartsWith("NOI ") || nametodisplay.StartsWith("Noi ") || nametodisplay.StartsWith("noi ")) + if ( + nametodisplay.StartsWith("NOI ") + || nametodisplay.StartsWith("Noi ") + || nametodisplay.StartsWith("noi ") + ) nametodisplay = nametodisplay.Remove(0, 3).Trim(); if (!noimaproomlist.ContainsKey(nametodisplay)) - noimaproomlist.Add(nametodisplay, "https://maps.noi.bz.it/" + langtoinsert + "?shared=" + maplink); + noimaproomlist.Add( + nametodisplay, + "https://maps.noi.bz.it/" + langtoinsert + "?shared=" + maplink + ); } return noimaproomlist; @@ -1232,7 +1652,9 @@ private async Task> GetBDPNoiRoomsWithLink(string? l var myresponsejson = await myresponse.Content.ReadAsStringAsync(); - var btpresponseobject = JsonConvert.DeserializeObject(myresponsejson); + var btpresponseobject = JsonConvert.DeserializeObject( + myresponsejson + ); return btpresponseobject; } diff --git a/OdhApiCore/Controllers/api/GastronomyApiController.cs b/OdhApiCore/Controllers/api/GastronomyApiController.cs index 7df1251df..dc7b57fe3 100644 --- a/OdhApiCore/Controllers/api/GastronomyApiController.cs +++ b/OdhApiCore/Controllers/api/GastronomyApiController.cs @@ -7,7 +7,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; -using OdhApiCore.Filters; +using OdhApiCore.Filters; using OdhApiCore.Responses; using SqlKata.Execution; using System; @@ -25,11 +25,13 @@ namespace OdhApiCore.Controllers [EnableCors("CorsPolicy")] [NullStringParameterActionFilter] public class GastronomyController : OdhController - { - public GastronomyController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + { + public GastronomyController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } #region SWAGGER Exposed API @@ -40,15 +42,15 @@ public GastronomyController(IWebHostEnvironment env, ISettings settings, ILogger /// Elements per Page, (default:10) /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting, (default:null) /// IDFilter (Separator ',' List of Gastronomy IDs), (default:'null') - /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter + /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter /// Dish Code Filter (BITMASK values: 1 = (Speisen), 2 = (Vorspeise), 4 = (Hauptspeise), 8 = (Nachspeise), 16 = (Tagesgericht), 32 = (Menü), 64 = (Degustationsmenü), 128 = (Kindermenüs), 256 = (Mittagsmenüs) /// Ceremony Code Filter (BITMASK values: 1 = (Familienfeiern), 2 = (Hochzeiten), 4 = (Geburtstagsfeiern), 8 = (Firmenessen), 16 = (Weihnachtsessen), 32 = (Sylvestermenü), 64 = (Seminare / Tagungen), 128 = (Versammlungen) /// Category Code Filter (BITMASK values: 1 = (Restaurant), 2 = (Bar / Café / Bistro), 4 = (Pub / Disco), 8 = (Apres Ski), 16 = (Jausenstation), 32 = (Pizzeria), 64 = (Bäuerlicher Schankbetrieb), 128 = (Buschenschank), 256 = (Hofschank), 512 = (Törggele Lokale), 1024 = (Schnellimbiss), 2048 = (Mensa), 4096 = (Vinothek /Weinhaus / Taverne), 8192 = (Eisdiele), 16348 = (Gasthaus), 32768 = (Gasthof), 65536 = (Braugarten), 131072 = (Schutzhütte), 262144 = (Alm), 524288 = (Skihütte) - /// Facility Code Filter (BITMASK values: 1 = (American Express), 2 = (Diners Club), 4 = (Eurocard / Mastercard), 8 = (Visa), 16 = (Hunde erlaubt), 32 = (Geeignet für Busse), 64 = (Garten), 128 = (Garagen), 256 = (Bierbar), 512 = (Kinderspielplatz), 1024 = (Spielzimmer), 2048 = (Spielplatz), 4096 = (Parkplätze), 8192 = (Raucherräume), 16348 = (Terrasse), 32768 = (Behindertengerecht), 65536 = (Biergarten), 131072 = (Aussichtsterrasse), 262144 = (Wintergarten), 524288 = (Gault Millau Südtirol), 1048576 = (Guida Espresso), 2097152 = (Gambero Rosso), 4194304 = (Feinschmecker), 8388608 = (Aral Schlemmer Atlas), 16777216 = (Varta Führer), 33554432 = (Bertelsmann), 67108864 = (Preis für Südtiroler Weinkultur), 134217728 = (Michelin), 268435456 = (Roter Hahn), 536870912 = (Tafelspitz)) - /// Cuisine Code Filter (BITMASK values: 1 = (Vegetarische Küche), 2 = (Glutenfreie Küche), 4 = (Laktosefreie Kost), 8 = (Warme Küche), 16 = (Südtiroler Spezialitäten), 32 = (Gourmet Küche), 64 = (Italienische Küche), 128 = (Internationale Küche), 256 = (Pizza), 512 = (Fischspezialitäten), 1024 = (Asiatische Küche), 2048 = (Wildspezialitäten), 4096 = (Produkte eigener Erzeugung), 8192 = (Diätküche), 16348 = (Grillspezialitäten), 32768 = (Ladinische Küche), 65536 = (Kleine Karte), 131072 = (Fischwochen), 262144 = (Spargelwochen), 524288 = (Lammwochen), 1048576 = (Wildwochen), 2097152 = (Vorspeisewochen), 4194304 = (Nudelwochen), 8388608 = (Kräuterwochen), 16777216 = (Kindermenüs), 33554432 = (Mittagsmenüs)) - /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=gastronomy'), (default:'null') + /// Facility Code Filter (BITMASK values: 1 = (American Express), 2 = (Diners Club), 4 = (Eurocard / Mastercard), 8 = (Visa), 16 = (Hunde erlaubt), 32 = (Geeignet für Busse), 64 = (Garten), 128 = (Garagen), 256 = (Bierbar), 512 = (Kinderspielplatz), 1024 = (Spielzimmer), 2048 = (Spielplatz), 4096 = (Parkplätze), 8192 = (Raucherräume), 16348 = (Terrasse), 32768 = (Behindertengerecht), 65536 = (Biergarten), 131072 = (Aussichtsterrasse), 262144 = (Wintergarten), 524288 = (Gault Millau Südtirol), 1048576 = (Guida Espresso), 2097152 = (Gambero Rosso), 4194304 = (Feinschmecker), 8388608 = (Aral Schlemmer Atlas), 16777216 = (Varta Führer), 33554432 = (Bertelsmann), 67108864 = (Preis für Südtiroler Weinkultur), 134217728 = (Michelin), 268435456 = (Roter Hahn), 536870912 = (Tafelspitz)) + /// Cuisine Code Filter (BITMASK values: 1 = (Vegetarische Küche), 2 = (Glutenfreie Küche), 4 = (Laktosefreie Kost), 8 = (Warme Küche), 16 = (Südtiroler Spezialitäten), 32 = (Gourmet Küche), 64 = (Italienische Küche), 128 = (Internationale Küche), 256 = (Pizza), 512 = (Fischspezialitäten), 1024 = (Asiatische Küche), 2048 = (Wildspezialitäten), 4096 = (Produkte eigener Erzeugung), 8192 = (Diätküche), 16348 = (Grillspezialitäten), 32768 = (Ladinische Küche), 65536 = (Kleine Karte), 131072 = (Fischwochen), 262144 = (Spargelwochen), 524288 = (Lammwochen), 1048576 = (Wildwochen), 2097152 = (Vorspeisewochen), 4194304 = (Nudelwochen), 8388608 = (Kräuterwochen), 16777216 = (Kindermenüs), 33554432 = (Mittagsmenüs)) + /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=gastronomy'), (default:'null') /// Active Gastronomies Filter (possible Values: 'true' only Active Gastronomies, 'false' only Disabled Gastronomies), (default:'null' - /// ODH Active (Published) Gastronomies Filter (Refers to field OdhActive) (possible Values: 'true' only published Gastronomies, 'false' only not published Gastronomies), (default:'null') + /// ODH Active (Published) Gastronomies Filter (Refers to field OdhActive) (possible Values: 'true' only published Gastronomies, 'false' only not published Gastronomies), (default:'null') /// GeoFilter FLOAT Latitude Format: '46.624975', 'null' = disabled, (default:'null') Wiki geosort /// GeoFilter FLOAT Longitude Format: '11.369909', 'null' = disabled, (default:'null') Wiki geosort /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort @@ -59,15 +61,20 @@ public GastronomyController(IWebHostEnvironment env, ISettings settings, ILogger /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of Gastronomy Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of Gastronomy Objects /// List created /// Request Error /// Internal Server Error [ProducesResponseType(typeof(JsonResult), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [OdhCacheOutput(ClientTimeSpan = 0, ServerTimeSpan = 3600, CacheKeyGenerator = typeof(CustomCacheKeyGenerator), MustRevalidate = true)] + [OdhCacheOutput( + ClientTimeSpan = 0, + ServerTimeSpan = 3600, + CacheKeyGenerator = typeof(CustomCacheKeyGenerator), + MustRevalidate = true + )] [HttpGet, Route("Gastronomy")] public async Task GetGastronomyList( string? language = null, @@ -89,33 +96,54 @@ public async Task GetGastronomyList( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); return await GetFiltered( - fields: fields ?? Array.Empty(), language: language, pagenumber: pagenumber, - pagesize: pagesize, dishcodefilter: dishcodefilter, categorycodefilter: categorycodefilter, - facilitycodefilter: facilitycodefilter, cuisinecodefilter: cuisinecodefilter, ceremonycodefilter: ceremonycodefilter, idfilter: idlist, - searchfilter: searchfilter, locfilter: locfilter, active: active,smgactive: odhactive, langfilter: langfilter, - smgtags: odhtagfilter, seed: seed, lastchange: updatefrom, - geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, - cancellationToken: cancellationToken); + fields: fields ?? Array.Empty(), + language: language, + pagenumber: pagenumber, + pagesize: pagesize, + dishcodefilter: dishcodefilter, + categorycodefilter: categorycodefilter, + facilitycodefilter: facilitycodefilter, + cuisinecodefilter: cuisinecodefilter, + ceremonycodefilter: ceremonycodefilter, + idfilter: idlist, + searchfilter: searchfilter, + locfilter: locfilter, + active: active, + smgactive: odhactive, + langfilter: langfilter, + smgtags: odhtagfilter, + seed: seed, + lastchange: updatefrom, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken: cancellationToken + ); } /// - /// GET Gastronomy Single + /// GET Gastronomy Single /// /// ID of the Gastronomy /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Gastronomy Object [ProducesResponseType(typeof(GastronomyLinked), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] @@ -124,12 +152,18 @@ public async Task GetGastronomyList( public async Task GetGastronomySingle( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -140,24 +174,32 @@ public async Task GetGastronomySingle( /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of GastronomyTypes Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of GastronomyTypes Object [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - //[Authorize(Roles = "DataReader,GastroReader")] + //[Authorize(Roles = "DataReader,GastroReader")] [HttpGet, Route("GastronomyTypes")] public async Task GetAllGastronomyTypesList( string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetGastronomyTypesListAsync(language, fields: fields ?? Array.Empty(), searchfilter, rawfilter, rawsort, removenullvalues: removenullvalues, cancellationToken); + return await GetGastronomyTypesListAsync( + language, + fields: fields ?? Array.Empty(), + searchfilter, + rawfilter, + rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -166,22 +208,28 @@ public async Task GetAllGastronomyTypesList( /// ID of the Gastronomy Type /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// GastronomyTypes Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// GastronomyTypes Object [ProducesResponseType(typeof(GastronomyTypes), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - //[Authorize(Roles = "DataReader,GastroReader")] + //[Authorize(Roles = "DataReader,GastroReader")] [HttpGet, Route("GastronomyTypes/{id}", Name = "SingleGastronomyTypes")] public async Task GetAllGastronomyTypesList( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetGastronomyTypesSingleAsync(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetGastronomyTypesSingleAsync( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } #endregion @@ -189,48 +237,97 @@ public async Task GetAllGastronomyTypesList( #region GETTER private Task GetFiltered( - string[] fields, string? language, uint pagenumber, int? pagesize, - string? categorycodefilter, string? dishcodefilter, string? ceremonycodefilter, string? facilitycodefilter, string? cuisinecodefilter, - string? idfilter, string? searchfilter, string? locfilter, bool? active, bool? smgactive, string? langfilter, - string? smgtags, string? seed, string? lastchange, PGGeoSearchResult geosearchresult, - string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + string[] fields, + string? language, + uint pagenumber, + int? pagesize, + string? categorycodefilter, + string? dishcodefilter, + string? ceremonycodefilter, + string? facilitycodefilter, + string? cuisinecodefilter, + string? idfilter, + string? searchfilter, + string? locfilter, + bool? active, + bool? smgactive, + string? langfilter, + string? smgtags, + string? seed, + string? lastchange, + PGGeoSearchResult geosearchresult, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { GastronomyHelper mygastronomyhelper = await GastronomyHelper.CreateAsync( - QueryFactory, idfilter, locfilter, categorycodefilter, - dishcodefilter, ceremonycodefilter, facilitycodefilter, cuisinecodefilter, - active, smgactive, smgtags, lastchange, langfilter, cancellationToken); - - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("gastronomies") - .GastronomyWhereExpression( - idlist: mygastronomyhelper.idlist, dishcodeslist: mygastronomyhelper.dishcodesids, ceremonycodeslist: mygastronomyhelper.ceremonycodesids, - categorycodeslist: mygastronomyhelper.categorycodesids, facilitycodeslist: mygastronomyhelper.facilitycodesids, - smgtaglist: mygastronomyhelper.smgtaglist, districtlist: mygastronomyhelper.districtlist, - municipalitylist: mygastronomyhelper.municipalitylist, tourismvereinlist: mygastronomyhelper.tourismvereinlist, - regionlist: mygastronomyhelper.regionlist, activefilter: mygastronomyhelper.active, - smgactivefilter: mygastronomyhelper.smgactive, - searchfilter: searchfilter, language: language, lastchange: mygastronomyhelper.lastchange, languagelist: mygastronomyhelper.languagelist, - filterClosedData: FilterClosedData, reducedData: ReducedData) - .ApplyRawFilter(rawfilter) - .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); + QueryFactory, + idfilter, + locfilter, + categorycodefilter, + dishcodefilter, + ceremonycodefilter, + facilitycodefilter, + cuisinecodefilter, + active, + smgactive, + smgtags, + lastchange, + langfilter, + cancellationToken + ); + + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("gastronomies") + .GastronomyWhereExpression( + idlist: mygastronomyhelper.idlist, + dishcodeslist: mygastronomyhelper.dishcodesids, + ceremonycodeslist: mygastronomyhelper.ceremonycodesids, + categorycodeslist: mygastronomyhelper.categorycodesids, + facilitycodeslist: mygastronomyhelper.facilitycodesids, + smgtaglist: mygastronomyhelper.smgtaglist, + districtlist: mygastronomyhelper.districtlist, + municipalitylist: mygastronomyhelper.municipalitylist, + tourismvereinlist: mygastronomyhelper.tourismvereinlist, + regionlist: mygastronomyhelper.regionlist, + activefilter: mygastronomyhelper.active, + smgactivefilter: mygastronomyhelper.smgactive, + searchfilter: searchfilter, + language: language, + lastchange: mygastronomyhelper.lastchange, + languagelist: mygastronomyhelper.languagelist, + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); uint totalpages = (uint)data.TotalPages; uint totalcount = (uint)data.Count; @@ -241,25 +338,40 @@ await query totalcount, seed, dataTransformed, - Url); + Url + ); }); } - private Task GetSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("gastronomies") - .Select("data") - .Where("id", id.ToUpper()) - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + var query = QueryFactory + .Query("gastronomies") + .Select("data") + .Where("id", id.ToUpper()) + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); var data = await query.FirstOrDefaultAsync(); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -271,26 +383,45 @@ private Task GetSingle(string id, string? language, string[] fiel /// GET Gastronomy Types List /// /// Collection of GastronomyTypes Object - private Task GetGastronomyTypesListAsync(string? language, string[] fields, string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task GetGastronomyTypesListAsync( + string? language, + string[] fields, + string? searchfilter, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("gastronomytypes") - .SelectRaw("data") - .When(FilterClosedData, q => q.FilterClosedData()) - .SearchFilter(PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), searchfilter) - .ApplyRawFilter(rawfilter) - .OrderOnlyByRawSortIfNotNull(rawsort); + var query = QueryFactory + .Query("gastronomytypes") + .SelectRaw("data") + .When(FilterClosedData, q => q.FilterClosedData()) + .SearchFilter( + PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), + searchfilter + ) + .ApplyRawFilter(rawfilter) + .OrderOnlyByRawSortIfNotNull(rawsort); var data = await query.GetAsync(); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.Select( - raw => raw?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); @@ -300,14 +431,20 @@ private Task GetGastronomyTypesListAsync(string? language, string /// GET Gastronomy Types Single /// /// GastronomyTypes Object - private Task GetGastronomyTypesSingleAsync(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetGastronomyTypesSingleAsync( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("gastronomytypes") - .Select("data") - .Where("id", id.ToUpper()); + var query = QueryFactory + .Query("gastronomytypes") + .Select("data") + .Where("id", id.ToUpper()); //.WhereJsonb("Key", id.ToUpper()); //.Where("data#>>'\\{Key\\}'", "ILIKE", id); @@ -315,7 +452,15 @@ private Task GetGastronomyTypesSingleAsync(string id, string? lan var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -335,7 +480,9 @@ public Task Post([FromBody] GastronomyLinked gastronomy) { return DoAsyncReturn(async () => { - gastronomy.Id = !String.IsNullOrEmpty(gastronomy.Id) ? gastronomy.Id.ToUpper() : "noId"; + gastronomy.Id = !String.IsNullOrEmpty(gastronomy.Id) + ? gastronomy.Id.ToUpper() + : "noId"; return await UpsertData(gastronomy, "gastronomies"); }); } @@ -375,7 +522,6 @@ public Task Delete(string id) }); } - #endregion } -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/api/ODHActivityPoiController.cs b/OdhApiCore/Controllers/api/ODHActivityPoiController.cs index 415381a15..737213f44 100644 --- a/OdhApiCore/Controllers/api/ODHActivityPoiController.cs +++ b/OdhApiCore/Controllers/api/ODHActivityPoiController.cs @@ -7,7 +7,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; -using OdhApiCore.Filters; +using OdhApiCore.Filters; using OdhApiCore.Responses; using SqlKata.Execution; using System; @@ -24,11 +24,13 @@ namespace OdhApiCore.Controllers.api [EnableCors("CorsPolicy")] [NullStringParameterActionFilter] public class ODHActivityPoiController : OdhController - { - public ODHActivityPoiController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + { + public ODHActivityPoiController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } #region SWAGGER Exposed API @@ -46,7 +48,7 @@ public ODHActivityPoiController(IWebHostEnvironment env, ISettings settings, ILo /// Subtype of the ODHActivityPoi ('null' = Filter disabled, BITMASK Filter, available SubTypes depends on the selected Maintype) ODHActivityPoi SubTypes, or Activity SubTypes, or Poi SubTypes, Type: SubType /// Additional Type of Level 3 the ODHActivityPoi ('null' = Filter disabled, BITMASK Filter, available SubTypes depends on the selected Maintype, SubType reference to ODHActivityPoiTypes) /// IDFilter (Separator ',' List of ODHActivityPoi IDs), (default:'null') - /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter + /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter /// AreaFilter (Alternate Locfilter, can be combined with locfilter) (Separator ',' possible values: reg + REGIONID = (Filter by Region), tvs + TOURISMASSOCIATIONID = (Filter by Tourismassociation), skr + SKIREGIONID = (Filter by Skiregion), ska + SKIAREAID = (Filter by Skiarea), are + AREAID = (Filter by LTS Area), 'null' = No Filter), (default:'null') /// ODHActivityPoi Langfilter (returns only SmgPois available in the selected Language, Separator ',' possible values: 'de,it,en,nl,sc,pl,fr,ru', 'null': Filter disabled) /// Hightlight Filter (possible values: 'false' = only ODHActivityPoi with Highlight false, 'true' = only ODHActivityPoi with Highlight true), (default:'null') @@ -54,29 +56,29 @@ public ODHActivityPoiController(IWebHostEnvironment env, ISettings settings, ILo /// GeoFilter FLOAT Latitude Format: '46.624975', 'null' = disabled, (default:'null') Wiki geosort /// GeoFilter FLOAT Longitude Format: '11.369909', 'null' = disabled, (default:'null') Wiki geosort /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort - /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible (OR FILTER), available Tags reference to 'v1/ODHTag?validforentity=odhactivitypoi'), (default:'null') - /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible (AND FILTER), available Tags reference to 'v1/ODHTag?validforentity=odhactivitypoi'), (default:'null') - /// Active ODHActivityPoi Filter (possible Values: 'true' only active ODHActivityPoi, 'false' only not active ODHActivityPoi), (default:'null') - /// ODH Active (Published) ODHActivityPoi Filter (Refers to field OdhActive) (possible Values: 'true' only published ODHActivityPoi, 'false' only not published ODHActivityPoi), (default:'null') + /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible (OR FILTER), available Tags reference to 'v1/ODHTag?validforentity=odhactivitypoi'), (default:'null') + /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible (AND FILTER), available Tags reference to 'v1/ODHTag?validforentity=odhactivitypoi'), (default:'null') + /// Active ODHActivityPoi Filter (possible Values: 'true' only active ODHActivityPoi, 'false' only not active ODHActivityPoi), (default:'null') + /// ODH Active (Published) ODHActivityPoi Filter (Refers to field OdhActive) (possible Values: 'true' only published ODHActivityPoi, 'false' only not published ODHActivityPoi), (default:'null') /// CategoryCode Filter (Only for ODHActivityTypes of type Gastronomy) (BITMASK) refers to GastronomyTypes, Type: CategoryCodes /// DishCode Filter (Only for ODHActivityTypes of type Gastronomy) (BITMASK) refers to GastronomyTypes, Type: DishCodes /// CeremonyCode Filter (Only for ODHActivityTypes of type Gastronomy) (BITMASK) refers to GastronomyTypes, Type: CeremonyCodes - /// FacilityCode Filter (Only for ODHActivityTypes of type Gastronomy) (BITMASK) refers to GastronomyTypes, Type: with FacilityCodes_ prefix - /// CuisineCode Filter (Only for ODHActivityTypes of type Gastronomy) (BITMASK) refers to GastronomyTypes, Type: CuisineCodes + /// FacilityCode Filter (Only for ODHActivityTypes of type Gastronomy) (BITMASK) refers to GastronomyTypes, Type: with FacilityCodes_ prefix + /// CuisineCode Filter (Only for ODHActivityTypes of type Gastronomy) (BITMASK) refers to GastronomyTypes, Type: CuisineCodes /// Distance Range Filter (Separator ',' example Value: 15,40 Distance from 15 up to 40 Km), (default:'null') /// Altitude Range Filter (Separator ',' example Value: 500,1000 Altitude from 500 up to 1000 metres), (default:'null') /// Duration Range Filter (Separator ',' example Value: 1,3 Duration from 1 to 3 hours), (default:'null') /// Difficulty Filter (possible values: '1' = easy, '2' = medium, '3' = difficult), (default:'null') /// Filter on Tags. Syntax =and/or(TagSource.TagId,TagSource.TagId) example or(idm.summer,lts.hiking) and(idm.themed hikes,lts.family hikings), default: 'null') - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of ODH Activity Poi Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of ODH Activity Poi Objects /// List created /// Request Error /// Internal Server Error @@ -84,7 +86,12 @@ public ODHActivityPoiController(IWebHostEnvironment env, ISettings settings, ILo [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [TypeFilter(typeof(Filters.RequestInterceptorAttribute))] - [OdhCacheOutput(ClientTimeSpan = 0, ServerTimeSpan = 3600, CacheKeyGenerator = typeof(CustomCacheKeyGenerator), MustRevalidate = true)] + [OdhCacheOutput( + ClientTimeSpan = 0, + ServerTimeSpan = 3600, + CacheKeyGenerator = typeof(CustomCacheKeyGenerator), + MustRevalidate = true + )] [HttpGet, Route("ODHActivityPoi")] public async Task GetODHActivityPoiList( string? language = null, @@ -107,7 +114,7 @@ public async Task GetODHActivityPoiList( LegacyBool active = null!, string? categorycodefilter = null, string? dishcodefilter = null, - string? ceremonycodefilter = null, + string? ceremonycodefilter = null, string? facilitycodefilter = null, string? cuisinecodefilter = null, string? difficultyfilter = null, @@ -115,40 +122,75 @@ public async Task GetODHActivityPoiList( string? altitudefilter = null, string? durationfilter = null, string? tagfilter = null, - string? publishedon = null, + string? publishedon = null, string? updatefrom = null, string? seed = null, string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); return await GetFiltered( - fields: fields ?? Array.Empty(), language: language, pagenumber: pagenumber, pagesize: pagesize, - type: type, subtypefilter: subtype, level3typefilter: level3type, searchfilter: searchfilter, idfilter: idlist, languagefilter: langfilter, - sourcefilter: source, locfilter: locfilter, areafilter: areafilter, highlightfilter: highlight?.Value, active: active?.Value, - smgactive: odhactive?.Value, smgtags: odhtagfilter, smgtagsand: odhtagfilter_and, - categorycodefilter: categorycodefilter, dishcodefilter: dishcodefilter, ceremonycodefilter: ceremonycodefilter, facilitycodefilter: facilitycodefilter, cuisinecodefilter: cuisinecodefilter, - activitytypefilter: activitytype, poitypefilter: poitype, difficultyfilter: difficultyfilter, distancefilter: distancefilter, altitudefilter: altitudefilter, durationfilter: durationfilter, - tagfilter: tagfilter, publishedon: publishedon, seed: seed, lastchange: updatefrom, geosearchresult, rawfilter: rawfilter, rawsort: rawsort, - removenullvalues: removenullvalues, cancellationToken); + fields: fields ?? Array.Empty(), + language: language, + pagenumber: pagenumber, + pagesize: pagesize, + type: type, + subtypefilter: subtype, + level3typefilter: level3type, + searchfilter: searchfilter, + idfilter: idlist, + languagefilter: langfilter, + sourcefilter: source, + locfilter: locfilter, + areafilter: areafilter, + highlightfilter: highlight?.Value, + active: active?.Value, + smgactive: odhactive?.Value, + smgtags: odhtagfilter, + smgtagsand: odhtagfilter_and, + categorycodefilter: categorycodefilter, + dishcodefilter: dishcodefilter, + ceremonycodefilter: ceremonycodefilter, + facilitycodefilter: facilitycodefilter, + cuisinecodefilter: cuisinecodefilter, + activitytypefilter: activitytype, + poitypefilter: poitype, + difficultyfilter: difficultyfilter, + distancefilter: distancefilter, + altitudefilter: altitudefilter, + durationfilter: durationfilter, + tagfilter: tagfilter, + publishedon: publishedon, + seed: seed, + lastchange: updatefrom, + geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } /// - /// GET ODHActivityPoi Single + /// GET ODHActivityPoi Single /// /// ID of the Poi /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// ODHActivityPoi Object /// Object created /// Request Error @@ -160,12 +202,18 @@ public async Task GetODHActivityPoiList( public async Task GetODHActivityPoiSingle( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } //Special GETTER @@ -178,8 +226,8 @@ public async Task GetODHActivityPoiSingle( /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of ActivityPoiType Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of ActivityPoiType Object /// List created /// Request Error /// Internal Server Error @@ -189,15 +237,23 @@ public async Task GetODHActivityPoiSingle( [HttpGet, Route("ODHActivityPoiTypes")] public async Task GetAllODHActivityPoiTypesList( string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetSmgPoiTypesList(language, fields: fields ?? Array.Empty(), searchfilter, rawfilter, rawsort, removenullvalues: removenullvalues, cancellationToken); + return await GetSmgPoiTypesList( + language, + fields: fields ?? Array.Empty(), + searchfilter, + rawfilter, + rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -206,8 +262,8 @@ public async Task GetAllODHActivityPoiTypesList( /// ID of the ODHActivityPoi Type /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// ActivityPoiType Object + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// ActivityPoiType Object /// List created /// Request Error /// Internal Server Error @@ -218,77 +274,169 @@ public async Task GetAllODHActivityPoiTypesList( public async Task GetAllODHActivityPoiTypesSingle( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetSmgPoiTypesSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetSmgPoiTypesSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } - #endregion #region GETTER - private Task GetFiltered(string[] fields, string? language, uint pagenumber, int? pagesize, - string? type, string? subtypefilter, string? level3typefilter, string? searchfilter, string? idfilter, string? languagefilter, string? sourcefilter, string? locfilter, - string? areafilter, bool? highlightfilter, bool? active, bool? smgactive, string? smgtags, string? smgtagsand, - string? categorycodefilter, string? dishcodefilter, string? ceremonycodefilter, string? facilitycodefilter, string? cuisinecodefilter, - string? activitytypefilter, string? poitypefilter, string? difficultyfilter, string? distancefilter, string? altitudefilter, string? durationfilter, - string? tagfilter, string? publishedon, - string? seed, string? lastchange, PGGeoSearchResult geosearchresult, - string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task GetFiltered( + string[] fields, + string? language, + uint pagenumber, + int? pagesize, + string? type, + string? subtypefilter, + string? level3typefilter, + string? searchfilter, + string? idfilter, + string? languagefilter, + string? sourcefilter, + string? locfilter, + string? areafilter, + bool? highlightfilter, + bool? active, + bool? smgactive, + string? smgtags, + string? smgtagsand, + string? categorycodefilter, + string? dishcodefilter, + string? ceremonycodefilter, + string? facilitycodefilter, + string? cuisinecodefilter, + string? activitytypefilter, + string? poitypefilter, + string? difficultyfilter, + string? distancefilter, + string? altitudefilter, + string? durationfilter, + string? tagfilter, + string? publishedon, + string? seed, + string? lastchange, + PGGeoSearchResult geosearchresult, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - ODHActivityPoiHelper myodhactivitypoihelper = await ODHActivityPoiHelper.CreateAsync( - queryFactory: QueryFactory,typefilter: type, subtypefilter: subtypefilter, level3typefilter: level3typefilter, - idfilter: idfilter, locfilter: locfilter, areafilter: areafilter, languagefilter: languagefilter, sourcefilter: sourcefilter, - highlightfilter: highlightfilter, activefilter: active, smgactivefilter: smgactive, smgtags: smgtags, smgtagsand: smgtagsand, lastchange: lastchange, - categorycodefilter : categorycodefilter, dishcodefilter: dishcodefilter, ceremonycodefilter: ceremonycodefilter, facilitycodefilter: facilitycodefilter, cuisinecodefilter: cuisinecodefilter, - activitytypefilter: activitytypefilter, poitypefilter: poitypefilter, distancefilter: distancefilter, altitudefilter: altitudefilter, durationfilter: durationfilter, difficultyfilter: difficultyfilter, - tagfilter: tagfilter, publishedonfilter: publishedon, - cancellationToken); - - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("smgpois") - .ODHActivityPoiWhereExpression( - idlist: myodhactivitypoihelper.idlist, typelist: myodhactivitypoihelper.typelist, - subtypelist: myodhactivitypoihelper.subtypelist, level3typelist: myodhactivitypoihelper.level3typelist, - smgtaglist: myodhactivitypoihelper.smgtaglist, smgtaglistand: myodhactivitypoihelper.smgtaglistand, districtlist: myodhactivitypoihelper.districtlist, - municipalitylist: myodhactivitypoihelper.municipalitylist, tourismvereinlist: myodhactivitypoihelper.tourismvereinlist, - regionlist: myodhactivitypoihelper.regionlist, arealist: myodhactivitypoihelper.arealist, - sourcelist: myodhactivitypoihelper.sourcelist, languagelist: myodhactivitypoihelper.languagelist, - highlight: myodhactivitypoihelper.highlight, - activefilter: myodhactivitypoihelper.active, smgactivefilter: myodhactivitypoihelper.smgactive, - categorycodeslist: myodhactivitypoihelper.categorycodesids, dishcodeslist: myodhactivitypoihelper.dishcodesids, ceremonycodeslist: myodhactivitypoihelper.ceremonycodesids, - facilitycodeslist: myodhactivitypoihelper.facilitycodesids, - activitytypelist: myodhactivitypoihelper.activitytypelist, poitypelist: myodhactivitypoihelper.poitypelist, - difficultylist: myodhactivitypoihelper.difficultylist, distance: myodhactivitypoihelper.distance, - distancemin: myodhactivitypoihelper.distancemin, distancemax: myodhactivitypoihelper.distancemax, duration: myodhactivitypoihelper.duration, durationmin: myodhactivitypoihelper.durationmin, - durationmax: myodhactivitypoihelper.durationmax, altitude: myodhactivitypoihelper.altitude, altitudemin: myodhactivitypoihelper.altitudemin, altitudemax: myodhactivitypoihelper.altitudemax, - tagbehaviour: myodhactivitypoihelper.tagfilterbehaviour, tagdict: myodhactivitypoihelper.tagdict, publishedonlist: myodhactivitypoihelper.publishedonlist, - searchfilter: searchfilter, language: language, lastchange: myodhactivitypoihelper.lastchange, - filterClosedData: FilterClosedData, reducedData: ReducedData) - .ApplyRawFilter(rawfilter) - .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); + ODHActivityPoiHelper myodhactivitypoihelper = + await ODHActivityPoiHelper.CreateAsync( + queryFactory: QueryFactory, + typefilter: type, + subtypefilter: subtypefilter, + level3typefilter: level3typefilter, + idfilter: idfilter, + locfilter: locfilter, + areafilter: areafilter, + languagefilter: languagefilter, + sourcefilter: sourcefilter, + highlightfilter: highlightfilter, + activefilter: active, + smgactivefilter: smgactive, + smgtags: smgtags, + smgtagsand: smgtagsand, + lastchange: lastchange, + categorycodefilter: categorycodefilter, + dishcodefilter: dishcodefilter, + ceremonycodefilter: ceremonycodefilter, + facilitycodefilter: facilitycodefilter, + cuisinecodefilter: cuisinecodefilter, + activitytypefilter: activitytypefilter, + poitypefilter: poitypefilter, + distancefilter: distancefilter, + altitudefilter: altitudefilter, + durationfilter: durationfilter, + difficultyfilter: difficultyfilter, + tagfilter: tagfilter, + publishedonfilter: publishedon, + cancellationToken + ); + + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("smgpois") + .ODHActivityPoiWhereExpression( + idlist: myodhactivitypoihelper.idlist, + typelist: myodhactivitypoihelper.typelist, + subtypelist: myodhactivitypoihelper.subtypelist, + level3typelist: myodhactivitypoihelper.level3typelist, + smgtaglist: myodhactivitypoihelper.smgtaglist, + smgtaglistand: myodhactivitypoihelper.smgtaglistand, + districtlist: myodhactivitypoihelper.districtlist, + municipalitylist: myodhactivitypoihelper.municipalitylist, + tourismvereinlist: myodhactivitypoihelper.tourismvereinlist, + regionlist: myodhactivitypoihelper.regionlist, + arealist: myodhactivitypoihelper.arealist, + sourcelist: myodhactivitypoihelper.sourcelist, + languagelist: myodhactivitypoihelper.languagelist, + highlight: myodhactivitypoihelper.highlight, + activefilter: myodhactivitypoihelper.active, + smgactivefilter: myodhactivitypoihelper.smgactive, + categorycodeslist: myodhactivitypoihelper.categorycodesids, + dishcodeslist: myodhactivitypoihelper.dishcodesids, + ceremonycodeslist: myodhactivitypoihelper.ceremonycodesids, + facilitycodeslist: myodhactivitypoihelper.facilitycodesids, + activitytypelist: myodhactivitypoihelper.activitytypelist, + poitypelist: myodhactivitypoihelper.poitypelist, + difficultylist: myodhactivitypoihelper.difficultylist, + distance: myodhactivitypoihelper.distance, + distancemin: myodhactivitypoihelper.distancemin, + distancemax: myodhactivitypoihelper.distancemax, + duration: myodhactivitypoihelper.duration, + durationmin: myodhactivitypoihelper.durationmin, + durationmax: myodhactivitypoihelper.durationmax, + altitude: myodhactivitypoihelper.altitude, + altitudemin: myodhactivitypoihelper.altitudemin, + altitudemax: myodhactivitypoihelper.altitudemax, + tagbehaviour: myodhactivitypoihelper.tagfilterbehaviour, + tagdict: myodhactivitypoihelper.tagdict, + publishedonlist: myodhactivitypoihelper.publishedonlist, + searchfilter: searchfilter, + language: language, + lastchange: myodhactivitypoihelper.lastchange, + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); uint totalpages = (uint)data.TotalPages; uint totalcount = (uint)data.Count; @@ -299,25 +447,41 @@ await query totalcount, seed, dataTransformed, - Url); + Url + ); }); } - private Task GetSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("smgpois") - .Select("data") - .Where("id", id.ToLower()) - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); ; + var query = QueryFactory + .Query("smgpois") + .Select("data") + .Where("id", id.ToLower()) + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + ; var data = await query.FirstOrDefaultAsync(); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -325,52 +489,84 @@ private Task GetSingle(string id, string? language, string[] fiel #region CATEGORIES - private Task GetSmgPoiTypesList(string? language, string[] fields, string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSmgPoiTypesList( + string? language, + string[] fields, + string? searchfilter, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("smgpoitypes") - .SelectRaw("data") - .When(FilterClosedData, q => q.FilterClosedData()) - .SearchFilter(PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), searchfilter) - .ApplyRawFilter(rawfilter) - .OrderOnlyByRawSortIfNotNull(rawsort); + var query = QueryFactory + .Query("smgpoitypes") + .SelectRaw("data") + .When(FilterClosedData, q => q.FilterClosedData()) + .SearchFilter( + PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), + searchfilter + ) + .ApplyRawFilter(rawfilter) + .OrderOnlyByRawSortIfNotNull(rawsort); var data = await query.GetAsync(); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.Select( - raw => raw?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); } - private Task GetSmgPoiTypesSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSmgPoiTypesSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("smgpoitypes") - .Select("data") - //.WhereJsonb("Key", "ilike", id) - .Where("id", id.ToLower()) - .When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query("smgpoitypes") + .Select("data") + //.WhereJsonb("Key", "ilike", id) + .Where("id", id.ToLower()) + .When(FilterClosedData, q => q.FilterClosedData()); //.Where("Key", "ILIKE", id); var data = await query.FirstOrDefaultAsync(); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } - #endregion #region POST PUT DELETE @@ -381,17 +577,20 @@ private Task GetSmgPoiTypesSingle(string id, string? language, st /// ODHActivityPoi Object /// Http Response [ApiExplorerSettings(IgnoreApi = true)] - [Authorize(Roles = "DataWriter,DataCreate,ODHActivityPoiWriter,ODHActivityPoiManager,ODHActivityPoiCreate,SmgPoiManager,SmgPoiCreate")] + [Authorize( + Roles = "DataWriter,DataCreate,ODHActivityPoiWriter,ODHActivityPoiManager,ODHActivityPoiCreate,SmgPoiManager,SmgPoiCreate" + )] [HttpPost, Route("ODHActivityPoi")] public Task Post([FromBody] ODHActivityPoiLinked odhactivitypoi) { return DoAsyncReturn(async () => - { - //GENERATE ID - odhactivitypoi.Id = Helper.IdGenerator.GenerateIDFromType(odhactivitypoi); - - odhactivitypoi.CheckMyInsertedLanguages(new List { "de", "en", "it","nl","cs","pl","ru","fr" }); + { + //GENERATE ID + odhactivitypoi.Id = Helper.IdGenerator.GenerateIDFromType(odhactivitypoi); + odhactivitypoi.CheckMyInsertedLanguages( + new List { "de", "en", "it", "nl", "cs", "pl", "ru", "fr" } + ); //odhactivitypoi.Id = !String.IsNullOrEmpty(odhactivitypoi.Id) ? odhactivitypoi.Id.ToLower() : "noid"; return await UpsertData(odhactivitypoi, "smgpois", true); @@ -405,19 +604,28 @@ public Task Post([FromBody] ODHActivityPoiLinked odhactivitypoi) /// ODHActivityPoi Object /// Http Response [ApiExplorerSettings(IgnoreApi = true)] - [Authorize(Roles = "DataWriter,DataModify,ODHActivityPoiWriter,ODHActivityPoiManager,ODHActivityPoiModify,SmgPoiManager,SmgPoiModify")] + [Authorize( + Roles = "DataWriter,DataModify,ODHActivityPoiWriter,ODHActivityPoiManager,ODHActivityPoiModify,SmgPoiManager,SmgPoiModify" + )] [HttpPut, Route("ODHActivityPoi/{id}")] public Task Put(string id, [FromBody] ODHActivityPoiLinked odhactivitypoi) { return DoAsyncReturn(async () => - { - //Check ID uppercase lowercase - Helper.IdGenerator.CheckIdFromType(odhactivitypoi); - - odhactivitypoi.CheckMyInsertedLanguages(new List { "de", "en", "it", "nl", "cs", "pl", "ru", "fr" }); + { + //Check ID uppercase lowercase + Helper.IdGenerator.CheckIdFromType(odhactivitypoi); + + odhactivitypoi.CheckMyInsertedLanguages( + new List { "de", "en", "it", "nl", "cs", "pl", "ru", "fr" } + ); //odhactivitypoi.Id = id.ToLower(); - return await UpsertData(odhactivitypoi, "smgpois", false, true); + return await UpsertData( + odhactivitypoi, + "smgpois", + false, + true + ); }); } @@ -427,20 +635,21 @@ public Task Put(string id, [FromBody] ODHActivityPoiLinked odhact /// ODHActivityPoi Id /// Http Response [ApiExplorerSettings(IgnoreApi = true)] - [Authorize(Roles = "DataWriter,DataDelete,ODHActivityPoiWriter,ODHActivityPoiManager,ODHActivityPoiDelete,SmgPoiManager,SmgPoiDelete")] + [Authorize( + Roles = "DataWriter,DataDelete,ODHActivityPoiWriter,ODHActivityPoiManager,ODHActivityPoiDelete,SmgPoiManager,SmgPoiDelete" + )] [HttpDelete, Route("ODHActivityPoi/{id}")] public Task Delete(string id) { return DoAsyncReturn(async () => - { - //Check ID uppercase lowercase - id = Helper.IdGenerator.CheckIdFromType(id); + { + //Check ID uppercase lowercase + id = Helper.IdGenerator.CheckIdFromType(id); return await DeleteData(id, "smgpois"); }); } - #endregion } } diff --git a/OdhApiCore/Controllers/api/OdhTagController.cs b/OdhApiCore/Controllers/api/OdhTagController.cs index 064c5b07b..e6b648db0 100644 --- a/OdhApiCore/Controllers/api/OdhTagController.cs +++ b/OdhApiCore/Controllers/api/OdhTagController.cs @@ -8,8 +8,8 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Newtonsoft.Json; -using OdhApiCore.Filters; -using OdhApiCore.Responses; +using OdhApiCore.Filters; +using OdhApiCore.Responses; using SqlKata.Execution; using System; using System.Collections.Generic; @@ -24,13 +24,15 @@ namespace OdhApiCore.Controllers [NullStringParameterActionFilter] public class ODHTagController : OdhController { - public ODHTagController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } - + public ODHTagController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } + #region SWAGGER Exposed API - + /// /// GET ODHTag List /// @@ -44,42 +46,57 @@ public ODHTagController(IWebHostEnvironment env, ISettings settings, ILoggerString to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of ODHTag Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of ODHTag Objects /// List created /// Request Error /// Internal Server Error [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [OdhCacheOutput(ClientTimeSpan = 0, ServerTimeSpan = 3600, CacheKeyGenerator = typeof(CustomCacheKeyGenerator))] + [OdhCacheOutput( + ClientTimeSpan = 0, + ServerTimeSpan = 3600, + CacheKeyGenerator = typeof(CustomCacheKeyGenerator) + )] [HttpGet, Route("ODHTag")] //[Authorize(Roles = "DataReader,CommonReader,AccoReader,ActivityReader,PoiReader,ODHPoiReader,PackageReader,GastroReader,EventReader,ArticleReader")] public async Task GetODHTagsAsync( - uint? pagenumber = null, - PageSize pagesize = null!, + uint? pagenumber = null, + PageSize pagesize = null!, string? language = null, string? validforentity = null, string? mainentity = null, bool? displayascategory = null, string? source = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - string? localizationlanguage = null, //TODO ignore this in swagger + string? localizationlanguage = null, //TODO ignore this in swagger bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { //Compatibility if (String.IsNullOrEmpty(language) && !String.IsNullOrEmpty(localizationlanguage)) language = localizationlanguage; - - return await Get(pagenumber, pagesize, language, mainentity, validforentity, displayascategory, source, fields: fields ?? Array.Empty(), - searchfilter, rawfilter, rawsort, removenullvalues: removenullvalues, - cancellationToken); + return await Get( + pagenumber, + pagesize, + language, + mainentity, + validforentity, + displayascategory, + source, + fields: fields ?? Array.Empty(), + searchfilter, + rawfilter, + rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -88,7 +105,7 @@ public async Task GetODHTagsAsync( /// ID of the Odhtags /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// ODHTag Object /// Object created /// Request Error @@ -98,19 +115,26 @@ public async Task GetODHTagsAsync( [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("ODHTag/{id}", Name = "SingleODHTag")] //[Authorize(Roles = "DataReader,CommonReader,AccoReader,ActivityReader,PoiReader,ODHPoiReader,PackageReader,GastroReader,EventReader,ArticleReader")] - public async Task GetODHTagSingle(string id, + public async Task GetODHTagSingle( + string id, string? language = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, - string? localizationlanguage = null, //TODO ignore this in swagger + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, + string? localizationlanguage = null, //TODO ignore this in swagger bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { //Compatibility if (String.IsNullOrEmpty(language) && !String.IsNullOrEmpty(localizationlanguage)) language = localizationlanguage; - return await GetSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } #endregion @@ -118,10 +142,20 @@ public async Task GetODHTagSingle(string id, #region GETTER private Task Get( - uint? pagenumber, int? pagesize, string? language, string? maintype, - string? validforentity, bool? displayascategory, string? source, string[] fields, - string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, - CancellationToken cancellationToken) + uint? pagenumber, + int? pagesize, + string? language, + string? maintype, + string? validforentity, + bool? displayascategory, + string? source, + string[] fields, + string? searchfilter, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { @@ -135,69 +169,104 @@ private Task Get( // maintype = maintype.Replace("odhactivitypoi", "smgpoi"); //} - var validforentitytypeslist = (validforentity ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries); - var maintypeslist = (maintype ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries); + var validforentitytypeslist = (validforentity ?? "").Split( + ',', + StringSplitOptions.RemoveEmptyEntries + ); + var maintypeslist = (maintype ?? "").Split( + ',', + StringSplitOptions.RemoveEmptyEntries + ); var sourcelist = Helper.CommonListCreator.CreateIdList(source); - var query = - QueryFactory.Query() + var query = QueryFactory + .Query() .SelectRaw("data") .From("smgtags") .ODHTagWhereExpression( - languagelist: new List(), + languagelist: new List(), mainentitylist: maintypeslist, validforentitylist: validforentitytypeslist, sourcelist: sourcelist, displayascategory: displayascategory, searchfilter: searchfilter, - language: language, + language: language, filterClosedData: FilterClosedData - ) + ) .ApplyRawFilter(rawfilter) - .ApplyOrdering(new PGGeoSearchResult() { geosearch = false }, rawsort, "data #>>'\\{MainEntity\\}', data#>>'\\{Shortname\\}'"); + .ApplyOrdering( + new PGGeoSearchResult() { geosearch = false }, + rawsort, + "data #>>'\\{MainEntity\\}', data#>>'\\{Shortname\\}'" + ); var fieldsTohide = FieldsToHide; - if (pagenumber != null) - { - - // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); - - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); - - uint totalpages = (uint)data.TotalPages; - uint totalcount = (uint)data.Count; - - return ResponseHelpers.GetResult( - (uint)pagenumber, - totalpages, - totalcount, - null, - dataTransformed, - Url); + if (pagenumber != null) + { + // Get paginated data + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); + + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); + + uint totalpages = (uint)data.TotalPages; + uint totalcount = (uint)data.Count; + + return ResponseHelpers.GetResult( + (uint)pagenumber, + totalpages, + totalcount, + null, + dataTransformed, + Url + ); + } + else + { + var data = await query.GetAsync(); + + return data.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); } - else - { - var data = await query.GetAsync(); - - return data.Select(raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide)); - } }); - } + } - private Task GetSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var data = await QueryFactory.Query("smgtags") + var data = await QueryFactory + .Query("smgtags") .Select("data") .Where("id", id.ToLower()) .When(FilterClosedData, q => q.FilterClosedData()) @@ -205,7 +274,15 @@ private Task GetSingle(string id, string? language, string[] fiel var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -265,9 +342,6 @@ public Task Delete(string id) }); } - #endregion } - - -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/api/PoiApiController.cs b/OdhApiCore/Controllers/api/PoiApiController.cs index 30865c75d..a1b157fe6 100644 --- a/OdhApiCore/Controllers/api/PoiApiController.cs +++ b/OdhApiCore/Controllers/api/PoiApiController.cs @@ -26,11 +26,13 @@ namespace OdhApiCore.Controllers.api [EnableCors("CorsPolicy")] [NullStringParameterActionFilter] public class PoiController : OdhController - { - public PoiController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + { + public PoiController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } #region SWAGGER Exposed API @@ -43,7 +45,7 @@ public PoiController(IWebHostEnvironment env, ISettings settings, ILoggerType of the Poi ('null' = Filter disabled, possible values: BITMASK 'Doctors, Pharmacies = 1','Shops = 2','Culture and sights= 4','Nightlife and entertainment = 8','Public institutions = 16','Sports and leisure = 32','Traffic and transport = 64', 'Service providers' = 128, 'Craft' = 256), (default:'511' == ALL), REFERENCE TO: GET /api/PoiTypes /// Subtype of the Poi ('null' = Filter disabled, available Subtypes depends on the poitype BITMASK), (default:'null') /// IDFilter (Separator ',' List of Activity IDs, 'null' = No Filter), (default:'null') - /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter + /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter /// AreaFilter (Alternate Locfilter, can be combined with locfilter) (Separator ',' possible values: reg + REGIONID = (Filter by Region), tvs + TOURISMASSOCIATIONID = (Filter by Tourismassociation), skr + SKIREGIONID = (Filter by Skiregion), ska + SKIAREAID = (Filter by Skiarea), are + AREAID = (Filter by LTS Area), 'null' = No Filter), (default:'null') /// Highlight Filter (Show only Highlights possible values: 'true' : show only Highlight Pois, 'null' Filter disabled), (default:'null') /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=poi'), (default:'null') @@ -59,7 +61,7 @@ public PoiController(IWebHostEnvironment env, ISettings settings, ILoggerString to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Collection of LTSPoi Objects /// List created /// Request Error @@ -67,7 +69,12 @@ public PoiController(IWebHostEnvironment env, ISettings settings, ILogger), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [OdhCacheOutput(ClientTimeSpan = 0, ServerTimeSpan = 3600, CacheKeyGenerator = typeof(CustomCacheKeyGenerator), MustRevalidate = true)] + [OdhCacheOutput( + ClientTimeSpan = 0, + ServerTimeSpan = 3600, + CacheKeyGenerator = typeof(CustomCacheKeyGenerator), + MustRevalidate = true + )] [HttpGet, Route("Poi")] public async Task GetPoiList( string? language = null, @@ -88,25 +95,47 @@ public async Task GetPoiList( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { //TODO //CheckOpenData(User); - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); return await GetFiltered( - fields: fields ?? Array.Empty(), language: language, pagenumber: pagenumber, pagesize: pagesize, - activitytype: poitype, subtypefilter: subtype, idfilter: idlist, searchfilter: searchfilter, - locfilter: locfilter, areafilter: areafilter, highlightfilter: highlight, active: active, smgactive: odhactive, - smgtags: odhtagfilter, seed: seed, lastchange: updatefrom, langfilter: langfilter, geosearchresult: geosearchresult, - rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, cancellationToken: cancellationToken); + fields: fields ?? Array.Empty(), + language: language, + pagenumber: pagenumber, + pagesize: pagesize, + activitytype: poitype, + subtypefilter: subtype, + idfilter: idlist, + searchfilter: searchfilter, + locfilter: locfilter, + areafilter: areafilter, + highlightfilter: highlight, + active: active, + smgactive: odhactive, + smgtags: odhtagfilter, + seed: seed, + lastchange: updatefrom, + langfilter: langfilter, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken: cancellationToken + ); } /// @@ -115,7 +144,7 @@ public async Task GetPoiList( /// ID of the Poi /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// GBLTSPoi Object /// Object created /// Request Error @@ -128,12 +157,18 @@ public async Task GetPoiList( public async Task GetPoiSingle( string id, string? language = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -144,7 +179,7 @@ public async Task GetPoiSingle( /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Collection of PoiType Object /// List created /// Request Error @@ -157,15 +192,23 @@ public async Task GetPoiSingle( [HttpGet, Route("PoiTypes")] public async Task GetAllPoiTypesList( string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetPoiTypesList(language, fields: fields ?? Array.Empty(), searchfilter, rawfilter, rawsort, removenullvalues: removenullvalues, cancellationToken); + return await GetPoiTypesList( + language, + fields: fields ?? Array.Empty(), + searchfilter, + rawfilter, + rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -174,7 +217,7 @@ public async Task GetAllPoiTypesList( /// ID of the Poi Type /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// PoiType Object /// List created /// Request Error @@ -187,12 +230,18 @@ public async Task GetAllPoiTypesList( public async Task GetAllPoiTypesSingle( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetPoiTypesSingleAsync(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetPoiTypesSingleAsync( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } #endregion @@ -216,49 +265,95 @@ public async Task GetAllPoiTypesSingle( /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, 'null' disables Random Sorting /// Result Object with Collection of Pois private Task GetFiltered( - string[] fields, string? language, uint pagenumber, int? pagesize, string? activitytype, string? subtypefilter, - string? idfilter, string? searchfilter, string? locfilter, string? areafilter, bool? highlightfilter, bool? active, - bool? smgactive, string? smgtags, string? seed, string? lastchange, string? langfilter, PGGeoSearchResult geosearchresult, string? rawfilter, string? rawsort, bool removenullvalues, - CancellationToken cancellationToken) + string[] fields, + string? language, + uint pagenumber, + int? pagesize, + string? activitytype, + string? subtypefilter, + string? idfilter, + string? searchfilter, + string? locfilter, + string? areafilter, + bool? highlightfilter, + bool? active, + bool? smgactive, + string? smgtags, + string? seed, + string? lastchange, + string? langfilter, + PGGeoSearchResult geosearchresult, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { - return DoAsyncReturn(async () => { PoiHelper myactivityhelper = await PoiHelper.CreateAsync( - QueryFactory, poitype: activitytype, subtypefilter: subtypefilter, idfilter: idfilter, - locfilter: locfilter, areafilter: areafilter, highlightfilter: highlightfilter, activefilter: active, - smgactivefilter: smgactive, smgtags: smgtags, lastchange: lastchange, langfilter: langfilter, cancellationToken: cancellationToken); - - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("pois") - .PoiWhereExpression( - idlist: myactivityhelper.idlist, poitypelist: myactivityhelper.poitypelist, - subtypelist: myactivityhelper.subtypelist, smgtaglist: myactivityhelper.smgtaglist, - districtlist: new List(), municipalitylist: new List(), - tourismvereinlist: myactivityhelper.tourismvereinlist, regionlist: myactivityhelper.regionlist, - arealist: myactivityhelper.arealist, highlight: myactivityhelper.highlight, - activefilter: myactivityhelper.active, smgactivefilter: myactivityhelper.smgactive, - searchfilter: searchfilter, language: language, lastchange: myactivityhelper.lastchange, languagelist: myactivityhelper.languagelist, - filterClosedData: FilterClosedData, reducedData: ReducedData - ) - .ApplyRawFilter(rawfilter) - .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); + QueryFactory, + poitype: activitytype, + subtypefilter: subtypefilter, + idfilter: idfilter, + locfilter: locfilter, + areafilter: areafilter, + highlightfilter: highlightfilter, + activefilter: active, + smgactivefilter: smgactive, + smgtags: smgtags, + lastchange: lastchange, + langfilter: langfilter, + cancellationToken: cancellationToken + ); + + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("pois") + .PoiWhereExpression( + idlist: myactivityhelper.idlist, + poitypelist: myactivityhelper.poitypelist, + subtypelist: myactivityhelper.subtypelist, + smgtaglist: myactivityhelper.smgtaglist, + districtlist: new List(), + municipalitylist: new List(), + tourismvereinlist: myactivityhelper.tourismvereinlist, + regionlist: myactivityhelper.regionlist, + arealist: myactivityhelper.arealist, + highlight: myactivityhelper.highlight, + activefilter: myactivityhelper.active, + smgactivefilter: myactivityhelper.smgactive, + searchfilter: searchfilter, + language: language, + lastchange: myactivityhelper.lastchange, + languagelist: myactivityhelper.languagelist, + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); uint totalpages = (uint)data.TotalPages; uint totalcount = (uint)data.Count; @@ -269,7 +364,8 @@ await query totalcount, seed, dataTransformed, - Url); + Url + ); }); } @@ -278,26 +374,36 @@ await query /// /// ID of Poi /// Poi Object - private Task GetSingle(string id, - string? language, + private Task GetSingle( + string id, + string? language, string[] fields, bool removenullvalues, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("pois") - .Select("data") - .Where("id", id.ToUpper()) - //.When(FilterClosedData, q => q.FilterClosedData()); - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + var query = QueryFactory + .Query("pois") + .Select("data") + .Where("id", id.ToUpper()) + //.When(FilterClosedData, q => q.FilterClosedData()); + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); var data = await query.FirstOrDefaultAsync(); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -309,26 +415,45 @@ private Task GetSingle(string id, /// GET Poi Types List /// /// Collection of PoiTypes Object - private Task GetPoiTypesList(string? language, string[] fields, string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task GetPoiTypesList( + string? language, + string[] fields, + string? searchfilter, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("poitypes") - .SelectRaw("data") - .When(FilterClosedData, q => q.FilterClosedData()) - .SearchFilter(PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), searchfilter) - .ApplyRawFilter(rawfilter) - .OrderOnlyByRawSortIfNotNull(rawsort); + var query = QueryFactory + .Query("poitypes") + .SelectRaw("data") + .When(FilterClosedData, q => q.FilterClosedData()) + .SearchFilter( + PostgresSQLWhereBuilder.TypeDescFieldsToSearchFor(language), + searchfilter + ) + .ApplyRawFilter(rawfilter) + .OrderOnlyByRawSortIfNotNull(rawsort); var data = await query.GetAsync(); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.Select( - raw => raw?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); @@ -338,23 +463,37 @@ private Task GetPoiTypesList(string? language, string[] fields, s /// GET Poi Types Single /// /// PoiTypes Object - private Task GetPoiTypesSingleAsync(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetPoiTypesSingleAsync( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("poitypes") - .Select("data") - //.WhereJsonb("Key", "ilike", id) - .Where("id", id.ToLower()) - .When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query("poitypes") + .Select("data") + //.WhereJsonb("Key", "ilike", id) + .Where("id", id.ToLower()) + .When(FilterClosedData, q => q.FilterClosedData()); //.Where("Key", "ILIKE", id); var data = await query.FirstOrDefaultAsync(); var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -415,7 +554,5 @@ public Task Delete(string id) } #endregion - } - } diff --git a/OdhApiCore/Controllers/api/SearchController.cs b/OdhApiCore/Controllers/api/SearchController.cs index 468e26ae3..68d71f8d8 100644 --- a/OdhApiCore/Controllers/api/SearchController.cs +++ b/OdhApiCore/Controllers/api/SearchController.cs @@ -21,16 +21,18 @@ namespace OdhApiCore.Controllers [EnableCors("CorsPolicy")] [NullStringParameterActionFilter] public class SearchController : OdhController - { - public SearchController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + { + public SearchController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } #region SWAGGER Exposed API /// - /// GET Search over all Entities + /// GET Search over all Entities /// /// Restrict search to Entities (accommodation, odhactivitypoi, event, webcam, measuringpoint, ltsactivity, ltspoi, ltsgastronomy, article ..... ) /// Term to Search for Wiki @@ -38,12 +40,12 @@ public SearchController(IWebHostEnvironment env, ISettings settings, ILoggerLimit search to n items per entity /// Search also trough base text (true/false), caution can slow down the search significantly /// Search also on this fields, syntax analog to the fields filter - /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter + /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of ODHTag Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of ODHTag Objects /// List created /// Request Error /// Internal Server Error @@ -52,30 +54,40 @@ public SearchController(IWebHostEnvironment env, ISettings settings, ILogger GetSearchAsync( - string term, + string term, string? language = "en", string? odhtype = null, bool searchbasetext = false, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? filteronfields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? filteronfields = null, string? locfilter = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? rawfilter = null, string? rawsort = null, int? limitto = 5, bool removenullvalues = false, - CancellationToken cancellationToken = default) - { + CancellationToken cancellationToken = default + ) + { var fieldstodisplay = fields ?? Array.Empty(); var fieldstosearchon = filteronfields ?? Array.Empty(); - return await Get(language: language ?? "en", validforentity: odhtype, fields: fieldstodisplay, - searchfilter: term, searchontext: searchbasetext, passedfieldstosearchon: fieldstosearchon, locfilter: locfilter, - rawfilter: rawfilter, rawsort: rawsort, limitto: limitto, removenullvalues: removenullvalues, cancellationToken); + return await Get( + language: language ?? "en", + validforentity: odhtype, + fields: fieldstodisplay, + searchfilter: term, + searchontext: searchbasetext, + passedfieldstosearchon: fieldstosearchon, + locfilter: locfilter, + rawfilter: rawfilter, + rawsort: rawsort, + limitto: limitto, + removenullvalues: removenullvalues, + cancellationToken + ); } //TODO EXTEND THE FILTER with the possibility to add fields for search @@ -84,35 +96,71 @@ public async Task GetSearchAsync( #region GETTER - private Task Get(string language, string? validforentity, string[] fields, - string? searchfilter, bool searchontext, string[] passedfieldstosearchon, string? locfilter, string? rawfilter, string? rawsort, int? limitto, bool removenullvalues, CancellationToken cancellationToken) + private Task Get( + string language, + string? validforentity, + string[] fields, + string? searchfilter, + bool searchontext, + string[] passedfieldstosearchon, + string? locfilter, + string? rawfilter, + string? rawsort, + int? limitto, + bool removenullvalues, + CancellationToken cancellationToken + ) { - var myentitytypelist = (validforentity ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries); + var myentitytypelist = (validforentity ?? "").Split( + ',', + StringSplitOptions.RemoveEmptyEntries + ); if (myentitytypelist.Count() == 0) - myentitytypelist = ODHTypeHelper.GetAllSearchableODHTypes(false); + myentitytypelist = ODHTypeHelper.GetAllSearchableODHTypes(false); var searchresult = new List(); var searchresultpertype = new Dictionary(); return DoAsyncReturn(async () => - { + { foreach (var entitytype in myentitytypelist) { - var customfields = new string[] { "Id", ODHTypeHelper.TranslateTypeToTitleField(entitytype, language), "_Meta.Type", "Self" }; + var customfields = new string[] + { + "Id", + ODHTypeHelper.TranslateTypeToTitleField(entitytype, language), + "_Meta.Type", + "Self" + }; - foreach(var field in fields) + foreach (var field in fields) { customfields = customfields.AddToStringArray(field); } - - var result = await SearchTroughEntity(entitytype, ODHTypeHelper.TranslateTypeToSearchField(entitytype), ODHTypeHelper.TranslateTypeString2Table(entitytype), language, customfields, searchfilter, searchontext, passedfieldstosearchon, locfilter, rawfilter, rawsort, limitto, removenullvalues, cancellationToken); + + var result = await SearchTroughEntity( + entitytype, + ODHTypeHelper.TranslateTypeToSearchField(entitytype), + ODHTypeHelper.TranslateTypeString2Table(entitytype), + language, + customfields, + searchfilter, + searchontext, + passedfieldstosearchon, + locfilter, + rawfilter, + rawsort, + limitto, + removenullvalues, + cancellationToken + ); if (result != null) { searchresult.AddRange(result); searchresultpertype.Add(entitytype, (uint)result.Count()); - } + } } return new SearchResult @@ -121,19 +169,36 @@ private Task Get(string language, string? validforentity, string[ searchTerm = searchfilter, totalResults = (uint)searchresult.Count, detailedResults = searchresultpertype - }; + }; }); } - private async Task> SearchTroughEntity(string entitytype, Func fieldsearchfunc, string table, string language, string[] fields, - string? searchfilter, bool searchontext, string[] passedfieldstosearchon, string? locfilter, string? rawfilter, string? rawsort, int? limitto, bool removenullvalues, CancellationToken cancellationToken) + private async Task> SearchTroughEntity( + string entitytype, + Func fieldsearchfunc, + string table, + string language, + string[] fields, + string? searchfilter, + bool searchontext, + string[] passedfieldstosearchon, + string? locfilter, + string? rawfilter, + string? rawsort, + int? limitto, + bool removenullvalues, + CancellationToken cancellationToken + ) { var searchonfields = fieldsearchfunc(language); //Add Textfields to search on if searchontext = true - if(searchontext) + if (searchontext) { - var textsearchfields = ODHTypeHelper.TranslateTypeToBaseTextField(entitytype, language); + var textsearchfields = ODHTypeHelper.TranslateTypeToBaseTextField( + entitytype, + language + ); searchonfields = searchonfields.AddToStringArray(textsearchfields); } @@ -143,7 +208,7 @@ private async Task> SearchTroughEntity(string entitytype, F searchonfields = searchonfields.AddToStringArray(passedfieldstosearchon); } - //Locfilter extensions + //Locfilter extensions var tourismvereinlist = new List(); var regionlist = new List(); var municipalitylist = new List(); @@ -159,13 +224,22 @@ private async Task> SearchTroughEntity(string entitytype, F districtlist = Helper.CommonListCreator.CreateDistrictIdList(locfilter, "fra"); if (locfilter != null && locfilter.Contains("mta")) { - List metaregionlist = CommonListCreator.CreateDistrictIdList(locfilter, "mta"); - tourismvereinlist.AddRange(await GenericHelper.RetrieveLocFilterDataAsync(QueryFactory, metaregionlist, cancellationToken)); + List metaregionlist = CommonListCreator.CreateDistrictIdList( + locfilter, + "mta" + ); + tourismvereinlist.AddRange( + await GenericHelper.RetrieveLocFilterDataAsync( + QueryFactory, + metaregionlist, + cancellationToken + ) + ); } //end locfilter extensions - var query = - QueryFactory.Query() + var query = QueryFactory + .Query() .SelectRaw("data") .From(table) .SearchFilter(searchonfields, searchfilter) @@ -176,19 +250,33 @@ private async Task> SearchTroughEntity(string entitytype, F //.When(FilterClosedData, q => q.FilterClosedData_GeneratedColumn()) .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData) .ApplyRawFilter(rawfilter) - .ApplyOrdering(new PGGeoSearchResult() { geosearch = false }, rawsort, "data#>>'\\{Shortname\\}'") + .ApplyOrdering( + new PGGeoSearchResult() { geosearch = false }, + rawsort, + "data#>>'\\{Shortname\\}'" + ) .Limit(limitto ?? int.MaxValue); - var data = await query.GetAsync(); - + var fieldsTohide = FieldsToHide; - - return data.Select(raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide)) - .Where(json => json != null) - .Select(json => json!); + + return data.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ) + .Where(json => json != null) + .Select(json => json!); } #endregion } -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/api/TagController.cs b/OdhApiCore/Controllers/api/TagController.cs index 9c725ce11..0f14e8293 100644 --- a/OdhApiCore/Controllers/api/TagController.cs +++ b/OdhApiCore/Controllers/api/TagController.cs @@ -8,8 +8,8 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Newtonsoft.Json; -using OdhApiCore.Filters; -using OdhApiCore.Responses; +using OdhApiCore.Filters; +using OdhApiCore.Responses; using SqlKata.Execution; using System; using System.Collections.Generic; @@ -18,20 +18,22 @@ using System.Threading.Tasks; namespace OdhApiCore.Controllers -{ +{ [EnableCors("CorsPolicy")] //Do not show in Swagger for now [ApiExplorerSettings(IgnoreApi = true)] [NullStringParameterActionFilter] public class TagController : OdhController { - public TagController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } - + public TagController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } + #region SWAGGER Exposed API - + /// /// GET Tag List /// @@ -45,42 +47,57 @@ public TagController(IWebHostEnvironment env, ISettings settings, ILoggerString to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of Tag Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of Tag Objects /// List created /// Request Error /// Internal Server Error [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [OdhCacheOutput(ClientTimeSpan = 0, ServerTimeSpan = 3600, CacheKeyGenerator = typeof(CustomCacheKeyGenerator))] + [OdhCacheOutput( + ClientTimeSpan = 0, + ServerTimeSpan = 3600, + CacheKeyGenerator = typeof(CustomCacheKeyGenerator) + )] [HttpGet, Route("Tag")] //[Authorize(Roles = "DataReader,CommonReader,AccoReader,ActivityReader,PoiReader,ODHPoiReader,PackageReader,GastroReader,EventReader,ArticleReader")] public async Task GetTagAsync( - uint? pagenumber = null, - PageSize pagesize = null!, + uint? pagenumber = null, + PageSize pagesize = null!, string? language = null, string? validforentity = null, string? mainentity = null, bool? displayascategory = null, string? source = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - string? localizationlanguage = null, //TODO ignore this in swagger + string? localizationlanguage = null, //TODO ignore this in swagger bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { //Compatibility if (String.IsNullOrEmpty(language) && !String.IsNullOrEmpty(localizationlanguage)) language = localizationlanguage; - - return await Get(pagenumber, pagesize, language, mainentity, validforentity, displayascategory, source, fields: fields ?? Array.Empty(), - searchfilter, rawfilter, rawsort, removenullvalues: removenullvalues, - cancellationToken); + return await Get( + pagenumber, + pagesize, + language, + mainentity, + validforentity, + displayascategory, + source, + fields: fields ?? Array.Empty(), + searchfilter, + rawfilter, + rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -89,7 +106,7 @@ public async Task GetTagAsync( /// ID of the Tag /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// TagLinked Object /// Object created /// Request Error @@ -99,19 +116,28 @@ public async Task GetTagAsync( [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("Tag/{id}", Name = "SingleTag")] //[Authorize(Roles = "DataReader,CommonReader,AccoReader,ActivityReader,PoiReader,ODHPoiReader,PackageReader,GastroReader,EventReader,ArticleReader")] - public async Task GetTagSingle(uint? pagenumber, int? pagesize, string id, + public async Task GetTagSingle( + uint? pagenumber, + int? pagesize, + string id, string? language = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, - string? localizationlanguage = null, //TODO ignore this in swagger + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, + string? localizationlanguage = null, //TODO ignore this in swagger bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { //Compatibility if (String.IsNullOrEmpty(language) && !String.IsNullOrEmpty(localizationlanguage)) language = localizationlanguage; - return await GetSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } #endregion @@ -119,23 +145,39 @@ public async Task GetTagSingle(uint? pagenumber, int? pagesize, s #region GETTER private Task Get( - uint? pagenumber, int? pagesize, - string? language, string? maintype, string? validforentity, bool? displayascategory, string? source, string[] fields, - string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, - CancellationToken cancellationToken) + uint? pagenumber, + int? pagesize, + string? language, + string? maintype, + string? validforentity, + bool? displayascategory, + string? source, + string[] fields, + string? searchfilter, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var validforentitytypeslist = (validforentity ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries); - var maintypeslist = (maintype ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries); + var validforentitytypeslist = (validforentity ?? "").Split( + ',', + StringSplitOptions.RemoveEmptyEntries + ); + var maintypeslist = (maintype ?? "").Split( + ',', + StringSplitOptions.RemoveEmptyEntries + ); var sourcelist = Helper.CommonListCreator.CreateIdList(source); - var query = - QueryFactory.Query() + var query = QueryFactory + .Query() .SelectRaw("data") .From("tags") .ODHTagWhereExpression( - languagelist: new List(), + languagelist: new List(), mainentitylist: maintypeslist, validforentitylist: validforentitytypeslist, sourcelist: sourcelist, @@ -143,52 +185,81 @@ private Task Get( searchfilter: searchfilter, language: language, filterClosedData: FilterClosedData - ) + ) .ApplyRawFilter(rawfilter) - .ApplyOrdering(new PGGeoSearchResult() { geosearch = false }, rawsort, "data #>>'\\{MainEntity\\}', data#>>'\\{Shortname\\}'"); - - var fieldsTohide = FieldsToHide; - - if (pagenumber != null) - { - - // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); - - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); - - uint totalpages = (uint)data.TotalPages; - uint totalcount = (uint)data.Count; - - return ResponseHelpers.GetResult( - (uint)pagenumber, - totalpages, - totalcount, - null, - dataTransformed, - Url); - } - else - { - var data = await query.GetAsync(); - - return data.Select(raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide)); + .ApplyOrdering( + new PGGeoSearchResult() { geosearch = false }, + rawsort, + "data #>>'\\{MainEntity\\}', data#>>'\\{Shortname\\}'" + ); + + var fieldsTohide = FieldsToHide; + + if (pagenumber != null) + { + // Get paginated data + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); + + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); + + uint totalpages = (uint)data.TotalPages; + uint totalcount = (uint)data.Count; + + return ResponseHelpers.GetResult( + (uint)pagenumber, + totalpages, + totalcount, + null, + dataTransformed, + Url + ); + } + else + { + var data = await query.GetAsync(); + + return data.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); } }); - } + } - private Task GetSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var data = await QueryFactory.Query("tags") + var data = await QueryFactory + .Query("tags") .Select("data") .Where("id", id.ToLower()) .When(FilterClosedData, q => q.FilterClosedData()) @@ -196,7 +267,15 @@ private Task GetSingle(string id, string? language, string[] fiel var fieldsTohide = FieldsToHide; - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -256,9 +335,6 @@ public Task Delete(string id) }); } - #endregion } - - -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/api/VenueApiController.cs b/OdhApiCore/Controllers/api/VenueApiController.cs index 743229af4..a5fca4b0a 100644 --- a/OdhApiCore/Controllers/api/VenueApiController.cs +++ b/OdhApiCore/Controllers/api/VenueApiController.cs @@ -23,11 +23,13 @@ namespace OdhApiCore.Controllers [EnableCors("CorsPolicy")] [NullStringParameterActionFilter] public class VenueController : OdhController - { - public VenueController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + { + public VenueController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } #region SWAGGER Exposed API @@ -38,20 +40,20 @@ public VenueController(IWebHostEnvironment env, ISettings settings, ILoggerElements per Page (max 1024), (default:10) /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, not provided disables Random Sorting, (default:'null') /// IDFilter (Separator ',' List of Venue IDs), (default:'null') - /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter + /// Locfilter SPECIAL Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') Wiki locfilter /// Venue Category Filter (BITMASK) (Separator ',' List of Venuetype Bitmasks, refer to api/VenueTypes type:category), (default:'null') /// Venue Features Filter (BITMASK) (Separator ',' List of Venuetype Bitmasks, refer to api/VenueTypes type:feature), (default:'null') /// Venue SetupType Filter (BITMASK) (Separator ',' List of Venuetype Bitmasks, refer to api/VenueTypes type:seatType), (default:'null') - /// Source Filter(String, ), (default:'null') + /// Source Filter(String, ), (default:'null') /// Capacity Range Filter (Separator ',' example Value: 50,100 All Venues with rooms from 50 to 100 people), (default:'null') /// Room Count Range Filter (Separator ',' example Value: 2,5 All Venues with 2 to 5 rooms), (default:'null') /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=venue'), (default:'null') /// Active Venue Filter (possible Values: 'true' only Active Venues, 'false' only Disabled Venues), (default:'null') - /// ODH Active (Published) Venue Filter (possible Values: 'true' only published Venue, 'false' only not published Venue), (default:'null') + /// ODH Active (Published) Venue Filter (possible Values: 'true' only published Venue, 'false' only not published Venue), (default:'null') /// GeoFilter FLOAT Latitude Format: '46.624975', 'null' = disabled, (default:'null') Wiki geosort /// GeoFilter FLOAT Longitude Format: '11.369909', 'null' = disabled, (default:'null') Wiki geosort /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Language field selector, displays data and fields in the selected language (default:'null' all languages are displayed) @@ -59,15 +61,20 @@ public VenueController(IWebHostEnvironment env, ISettings settings, ILoggerString to search for, Title in all languages are searched, (default: null)Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of DDVenue Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of DDVenue Objects /// List created /// Request Error /// Internal Server Error [ProducesResponseType(typeof(JsonResult), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [OdhCacheOutput(ClientTimeSpan = 0, ServerTimeSpan = 3600, CacheKeyGenerator = typeof(CustomCacheKeyGenerator), MustRevalidate = true)] + [OdhCacheOutput( + ClientTimeSpan = 0, + ServerTimeSpan = 3600, + CacheKeyGenerator = typeof(CustomCacheKeyGenerator), + MustRevalidate = true + )] //[Authorize(Roles = "DataReader,VenueReader")] //[Authorize] [HttpGet, Route("Venue")] @@ -93,25 +100,47 @@ public async Task GetVenueList( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); return await GetFiltered( - fields: fields ?? Array.Empty(), language: language, pagenumber: pagenumber, - pagesize: pagesize, idfilter: idlist, categoryfilter: categoryfilter, capacityfilter: capacityfilter, - searchfilter: searchfilter, locfilter: locfilter, roomcountfilter: roomcountfilter, - featurefilter: featurefilter, setuptypefilter: setuptypefilter, sourcefilter: source, - active: active, smgactive: odhactive, smgtags: odhtagfilter, seed: seed, lastchange: updatefrom, langfilter: langfilter, - publishedon: publishedon, - geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, removenullvalues: removenullvalues, - cancellationToken: cancellationToken); + fields: fields ?? Array.Empty(), + language: language, + pagenumber: pagenumber, + pagesize: pagesize, + idfilter: idlist, + categoryfilter: categoryfilter, + capacityfilter: capacityfilter, + searchfilter: searchfilter, + locfilter: locfilter, + roomcountfilter: roomcountfilter, + featurefilter: featurefilter, + setuptypefilter: setuptypefilter, + sourcefilter: source, + active: active, + smgactive: odhactive, + smgtags: odhtagfilter, + seed: seed, + lastchange: updatefrom, + langfilter: langfilter, + publishedon: publishedon, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken: cancellationToken + ); } /// @@ -120,7 +149,7 @@ public async Task GetVenueList( /// ID of the Venue /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// DDVenue Object /// Object created /// Request Error @@ -133,12 +162,18 @@ public async Task GetVenueList( public async Task GetVenueSingle( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -149,7 +184,7 @@ public async Task GetVenueSingle( /// String to search for, Title in all languages are searched, (default: null)Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Collection of VenueTypes Object /// List created /// Request Error @@ -162,15 +197,23 @@ public async Task GetVenueSingle( [HttpGet, Route("VenueTypes")] public async Task GetAllVenueTypesListAsync( string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetVenueTypesListAsync(language, fields: fields ?? Array.Empty(), searchfilter, rawfilter, rawsort, removenullvalues: removenullvalues, cancellationToken); + return await GetVenueTypesListAsync( + language, + fields: fields ?? Array.Empty(), + searchfilter, + rawfilter, + rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } /// @@ -179,7 +222,7 @@ public async Task GetAllVenueTypesListAsync( /// ID of the VenueType /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname. Select also Dictionary fields, example Detail.de.Title, or Elements of Arrays example ImageGallery[0].ImageUrl. (default:'null' all fields are displayed) /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// VenueTypes Object /// List created /// Request Error @@ -193,12 +236,18 @@ public async Task GetAllVenueTypesListAsync( public async Task GetAllVenueTypesSingleAsync( string id, string? language, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetVenueTypesSingleAsync(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return await GetVenueTypesSingleAsync( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } #endregion @@ -206,50 +255,108 @@ public async Task GetAllVenueTypesSingleAsync( #region GETTER private Task GetFiltered( - string[] fields, string? language, uint pagenumber, int? pagesize, string? idfilter, string? categoryfilter, string? capacityfilter, - string? searchfilter, string? locfilter, string? roomcountfilter, string? featurefilter, string? setuptypefilter, - string? sourcefilter, bool? active, bool? smgactive, string? smgtags, string? seed, string? lastchange, string? langfilter, string? publishedon, - PGGeoSearchResult geosearchresult, string? rawfilter, string? rawsort, bool removenullvalues, - CancellationToken cancellationToken) + string[] fields, + string? language, + uint pagenumber, + int? pagesize, + string? idfilter, + string? categoryfilter, + string? capacityfilter, + string? searchfilter, + string? locfilter, + string? roomcountfilter, + string? featurefilter, + string? setuptypefilter, + string? sourcefilter, + bool? active, + bool? smgactive, + string? smgtags, + string? seed, + string? lastchange, + string? langfilter, + string? publishedon, + PGGeoSearchResult geosearchresult, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { VenueHelper myvenuehelper = await VenueHelper.CreateAsync( - QueryFactory, idfilter, categoryfilter, featurefilter, setuptypefilter, locfilter, capacityfilter, roomcountfilter, - langfilter, sourcefilter, active, smgactive, smgtags, lastchange, publishedon, - cancellationToken); - - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("venues") - .VenueWhereExpression( - languagelist: myvenuehelper.languagelist, idlist: myvenuehelper.idlist, categorylist: myvenuehelper.categorylist, - featurelist: myvenuehelper.featurelist, setuptypelist: myvenuehelper.setuptypelist, - smgtaglist: myvenuehelper.odhtaglist, districtlist: myvenuehelper.districtlist, - municipalitylist: myvenuehelper.municipalitylist, tourismvereinlist: myvenuehelper.tourismvereinlist, - regionlist: myvenuehelper.regionlist, sourcelist: myvenuehelper.sourcelist, - capacity: myvenuehelper.capacity, capacitymin: myvenuehelper.capacitymin, capacitymax: myvenuehelper.capacitymax, - roomcount: myvenuehelper.roomcount, roomcountmin: myvenuehelper.roomcountmin, roomcountmax: myvenuehelper.roomcountmax, - activefilter: myvenuehelper.active, smgactivefilter: myvenuehelper.smgactive, publishedonlist: myvenuehelper.publishedonlist, - searchfilter: searchfilter, language: language, lastchange: myvenuehelper.lastchange, - filterClosedData: FilterClosedData, reducedData: ReducedData) - .ApplyRawFilter(rawfilter) - .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); //.ApplyOrdering(ref seed, geosearchresult, rawsort); + QueryFactory, + idfilter, + categoryfilter, + featurefilter, + setuptypefilter, + locfilter, + capacityfilter, + roomcountfilter, + langfilter, + sourcefilter, + active, + smgactive, + smgtags, + lastchange, + publishedon, + cancellationToken + ); + + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("venues") + .VenueWhereExpression( + languagelist: myvenuehelper.languagelist, + idlist: myvenuehelper.idlist, + categorylist: myvenuehelper.categorylist, + featurelist: myvenuehelper.featurelist, + setuptypelist: myvenuehelper.setuptypelist, + smgtaglist: myvenuehelper.odhtaglist, + districtlist: myvenuehelper.districtlist, + municipalitylist: myvenuehelper.municipalitylist, + tourismvereinlist: myvenuehelper.tourismvereinlist, + regionlist: myvenuehelper.regionlist, + sourcelist: myvenuehelper.sourcelist, + capacity: myvenuehelper.capacity, + capacitymin: myvenuehelper.capacitymin, + capacitymax: myvenuehelper.capacitymax, + roomcount: myvenuehelper.roomcount, + roomcountmin: myvenuehelper.roomcountmin, + roomcountmax: myvenuehelper.roomcountmax, + activefilter: myvenuehelper.active, + smgactivefilter: myvenuehelper.smgactive, + publishedonlist: myvenuehelper.publishedonlist, + searchfilter: searchfilter, + language: language, + lastchange: myvenuehelper.lastchange, + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); //.ApplyOrdering(ref seed, geosearchresult, rawsort); // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); uint totalpages = (uint)data.TotalPages; uint totalcount = (uint)data.Count; @@ -260,26 +367,41 @@ await query totalcount, seed, dataTransformed, - Url); + Url + ); }); } - private Task GetSingle(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSingle( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("venues") - .Select("data") - .Where("id", id.ToUpper()) - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + var query = QueryFactory + .Query("venues") + .Select("data") + .Where("id", id.ToUpper()) + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); //.When(FilterClosedData, q => q.FilterClosedData()); var fieldsTohide = FieldsToHide; var data = await query.FirstOrDefaultAsync(); - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -287,26 +409,45 @@ private Task GetSingle(string id, string? language, string[] fiel #region CATEGORIES - private Task GetVenueTypesListAsync(string? language, string[] fields, string? searchfilter, string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + private Task GetVenueTypesListAsync( + string? language, + string[] fields, + string? searchfilter, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("venuetypes") - .SelectRaw("data") - .When(FilterClosedData, q => q.FilterClosedData()) - .SearchFilter(PostgresSQLWhereBuilder.VenueTitleFieldsToSearchFor(language), searchfilter) - .ApplyRawFilter(rawfilter) - .OrderOnlyByRawSortIfNotNull(rawsort); + var query = QueryFactory + .Query("venuetypes") + .SelectRaw("data") + .When(FilterClosedData, q => q.FilterClosedData()) + .SearchFilter( + PostgresSQLWhereBuilder.VenueTitleFieldsToSearchFor(language), + searchfilter + ) + .ApplyRawFilter(rawfilter) + .OrderOnlyByRawSortIfNotNull(rawsort); var data = await query.GetAsync(); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.Select( - raw => raw?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.Select( + raw => + raw?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); return dataTransformed; }); @@ -316,23 +457,37 @@ private Task GetVenueTypesListAsync(string? language, string[] fi /// GET Venue Types Single /// /// VenueTypes Object - private Task GetVenueTypesSingleAsync(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetVenueTypesSingleAsync( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("venuetypes") - .Select("data") - //.WhereJsonb("Key", "ilike", id) - .Where("id", id.ToUpper()) - .When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query("venuetypes") + .Select("data") + //.WhereJsonb("Key", "ilike", id) + .Where("id", id.ToUpper()) + .When(FilterClosedData, q => q.FilterClosedData()); //.Where("Key", "ILIKE", id); var fieldsTohide = FieldsToHide; var data = await query.FirstOrDefaultAsync(); - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } @@ -342,4 +497,4 @@ private Task GetVenueTypesSingleAsync(string id, string? language #endregion } -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/api/WeatherApiController.cs b/OdhApiCore/Controllers/api/WeatherApiController.cs index 18ca9a7ae..2b62e3925 100644 --- a/OdhApiCore/Controllers/api/WeatherApiController.cs +++ b/OdhApiCore/Controllers/api/WeatherApiController.cs @@ -9,7 +9,7 @@ using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Npgsql; -using OdhApiCore.Filters; +using OdhApiCore.Filters; using OdhApiCore.Responses; using SIAG; using SqlKata.Execution; @@ -29,11 +29,15 @@ namespace OdhApiCore.Controllers public class WeatherController : OdhController { private readonly ISettings settings; - - public WeatherController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) + + public WeatherController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { - this.settings = settings; + this.settings = settings; } #region SwaggerExposed API @@ -49,20 +53,31 @@ public WeatherController(IWebHostEnvironment env, ISettings settings, ILogger GetWeather( - uint? pagenumber = null, + uint? pagenumber = null, PageSize pagesize = null!, - string? language = "en", + string? language = "en", string? locfilter = null, bool extended = true, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { try { - return await Get(pagenumber, pagesize, language ?? "en", locfilter, extended, cancellationToken); + return await Get( + pagenumber, + pagesize, + language ?? "en", + locfilter, + extended, + cancellationToken + ); } catch (Exception ex) { - return StatusCode(StatusCodes.Status500InternalServerError, new { error = ex.Message }); + return StatusCode( + StatusCodes.Status500InternalServerError, + new { error = ex.Message } + ); } } @@ -81,7 +96,7 @@ public async Task GetWeather( [HttpGet, Route("WeatherHistory")] public async Task GetWeatherHistory( uint pagenumber = 1, - PageSize pagesize = null!, + PageSize pagesize = null!, string? language = null, string? idlist = null, string? locfilter = null, @@ -91,26 +106,42 @@ public async Task GetWeatherHistory( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? lastchange = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { try - { + { return await GetWeatherHistoryList( - pagenumber: pagenumber, pagesize: pagesize, language: language, - idfilter: idlist, locfilter: locfilter, datefrom: datefrom, dateto: dateto, - lastchange: lastchange, searchfilter: searchfilter, seed: seed, - fields: fields ?? Array.Empty(), new PGGeoSearchResult(), rawfilter, rawsort, removenullvalues, cancellationToken); + pagenumber: pagenumber, + pagesize: pagesize, + language: language, + idfilter: idlist, + locfilter: locfilter, + datefrom: datefrom, + dateto: dateto, + lastchange: lastchange, + searchfilter: searchfilter, + seed: seed, + fields: fields ?? Array.Empty(), + new PGGeoSearchResult(), + rawfilter, + rawsort, + removenullvalues, + cancellationToken + ); } catch (Exception ex) { - return StatusCode(StatusCodes.Status500InternalServerError, new { error = ex.Message }); + return StatusCode( + StatusCodes.Status500InternalServerError, + new { error = ex.Message } + ); } } @@ -119,50 +150,69 @@ public async Task GetWeatherHistory( /// /// Language /// Locfilter (possible values: filter by District 1 = Etschtal/Überetsch/Unterland, 2 = Burggrafenamt, 3 = Vinschgau, 4 = Eisacktal und Sarntal, 5 = Wipptal, 6 = Pustertal/Dolomiten, 7 = Ladinien-Dolomiten | filter nearest DistrictWeather to Region,TV,Municipality,Fraction tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction)) - /// Bezirks Weather Object + /// Bezirks Weather Object [ProducesResponseType(typeof(BezirksWeather), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("Weather/District")] public async Task GetDistrictWeather( - uint? pagenumber = null, + uint? pagenumber = null, PageSize pagesize = null!, string? locfilter = null, - string? language = "en", - CancellationToken cancellationToken = default) + string? language = "en", + CancellationToken cancellationToken = default + ) { try { - return await GetBezirksWetter(pagenumber, pagesize, language ?? "en", locfilter, cancellationToken); + return await GetBezirksWetter( + pagenumber, + pagesize, + language ?? "en", + locfilter, + cancellationToken + ); } catch (Exception ex) { - return StatusCode(StatusCodes.Status500InternalServerError, new { error = ex.Message }); + return StatusCode( + StatusCodes.Status500InternalServerError, + new { error = ex.Message } + ); } } - + /// /// GET Current Realtime Weather LIVE /// - /// Language + /// Language /// WeatherRealTime Object [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [HttpGet, Route("Weather/Realtime")] public async Task GetRealtimeWeather( - uint? pagenumber = null, - PageSize pagesize = null!, + uint? pagenumber = null, + PageSize pagesize = null!, string? language = "en", - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { try { - return await GetRealTimeWeather(pagenumber, pagesize, language ?? "en", cancellationToken); + return await GetRealTimeWeather( + pagenumber, + pagesize, + language ?? "en", + cancellationToken + ); } catch (Exception ex) { - return StatusCode(StatusCodes.Status500InternalServerError, new { error = ex.Message }); + return StatusCode( + StatusCodes.Status500InternalServerError, + new { error = ex.Message } + ); } } @@ -171,34 +221,39 @@ public async Task GetRealtimeWeather( /// /// IDFilter (Separator ',' List of Gastronomy IDs), (default:'null') /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, not provided disables Random Sorting, (default:'null') - /// Locfilter (Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') + /// Locfilter (Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = (No Filter), (default:'null') /// Area ID (multiple IDs possible, separated by ",") /// Skiarea ID /// Active Filter (possible Values: 'true' only Active Measuringpoints, 'false' only Disabled Measuringpoints), (default:'null') - /// ODH Active Filter Measuringpoints Filter (possible Values: 'true' only published Measuringpoints, 'false' only not published Measuringpoints), (default:'null') + /// ODH Active Filter Measuringpoints Filter (possible Values: 'true' only published Measuringpoints, 'false' only not published Measuringpoints), (default:'null') /// GeoFilter FLOAT Latitude Format: '46.624975', 'null' = disabled, (default:'null') Wiki geosort /// GeoFilter FLOAT Longitude Format: '11.369909', 'null' = disabled, (default:'null') Wiki geosort /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null) Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// List of Measuringpoint Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [OdhCacheOutput(ClientTimeSpan = 0, ServerTimeSpan = 3600, CacheKeyGenerator = typeof(CustomCacheKeyGenerator), MustRevalidate = true)] + [OdhCacheOutput( + ClientTimeSpan = 0, + ServerTimeSpan = 3600, + CacheKeyGenerator = typeof(CustomCacheKeyGenerator), + MustRevalidate = true + )] [HttpGet, Route("Weather/Measuringpoint")] public async Task GetMeasuringPoints( - uint? pagenumber = null, - PageSize pagesize = null!, + uint? pagenumber = null, + PageSize pagesize = null!, string? idlist = null, - string? locfilter = null, - string? areafilter = null, + string? locfilter = null, + string? areafilter = null, string? skiareafilter = null, string? language = null, string? source = null, @@ -210,23 +265,42 @@ public async Task GetMeasuringPoints( string? longitude = null, string? radius = null, string? seed = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - - return await GetMeasuringPointList(pagenumber, pagesize, - fields: fields ?? Array.Empty(), language: language, idfilter: idlist, - searchfilter: searchfilter, locfilter: locfilter, areafilter: areafilter, - skiareafilter: skiareafilter, source: source, active: active, publishedon: publishedon, - smgactive: odhactive, seed: seed, lastchange: updatefrom, - geosearchresult: geosearchresult, rawfilter: rawfilter, rawsort: rawsort, - removenullvalues: removenullvalues, cancellationToken: cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + + return await GetMeasuringPointList( + pagenumber, + pagesize, + fields: fields ?? Array.Empty(), + language: language, + idfilter: idlist, + searchfilter: searchfilter, + locfilter: locfilter, + areafilter: areafilter, + skiareafilter: skiareafilter, + source: source, + active: active, + publishedon: publishedon, + smgactive: odhactive, + seed: seed, + lastchange: updatefrom, + geosearchresult: geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken: cancellationToken + ); } /// @@ -235,7 +309,7 @@ public async Task GetMeasuringPoints( /// Measuringpoint ID /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// Measuringpoint Object [ProducesResponseType(typeof(Measuringpoint), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] @@ -244,12 +318,18 @@ public async Task GetMeasuringPoints( public async Task GetMeasuringPoint( string id, string? language = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetMeasuringPointSingle(id, language, fields: fields ?? Array.Empty(), removenullvalues, cancellationToken); + return await GetMeasuringPointSingle( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues, + cancellationToken + ); } /// @@ -261,76 +341,100 @@ public async Task GetMeasuringPoint( [ProducesResponseType(typeof(SnowReportBaseData), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [OdhCacheOutput(ClientTimeSpan = 0, ServerTimeSpan = 3600, CacheKeyGenerator = typeof(CustomCacheKeyGenerator))] + [OdhCacheOutput( + ClientTimeSpan = 0, + ServerTimeSpan = 3600, + CacheKeyGenerator = typeof(CustomCacheKeyGenerator) + )] [HttpGet, Route("Weather/SnowReport")] public async Task GetSnowReportBase( - uint? pagenumber = null, + uint? pagenumber = null, PageSize pagesize = null!, string? skiareaid = null, - string? lang = "en", - CancellationToken cancellationToken = default) + string? lang = "en", + CancellationToken cancellationToken = default + ) { try { - if(!String.IsNullOrEmpty(skiareaid)) + if (!String.IsNullOrEmpty(skiareaid)) { - var snowreport = await GetSnowReportBaseData(lang, skiareaid, cancellationToken); - - if(pagenumber != null) - { - return Ok(ResponseHelpers.GetResult( - pagenumber.Value, - 1, - 1, - null, - new List() { snowreport }, - Url)); + var snowreport = await GetSnowReportBaseData( + lang, + skiareaid, + cancellationToken + ); + + if (pagenumber != null) + { + return Ok( + ResponseHelpers.GetResult( + pagenumber.Value, + 1, + 1, + null, + new List() { snowreport }, + Url + ) + ); } - else + else { return Ok(snowreport); - } + } } else - { + { //Get all skiareaids - var query = QueryFactory.Query() + var query = QueryFactory + .Query() .Select("id") .From("skiareas") .Where("gen_active", true); var skiareaids = await query.GetAsync(); - List snowreportbasedatalist = new List(); + List snowreportbasedatalist = + new List(); //Fall 1 Getter auf ALL foreach (var myskiareaid in skiareaids) { - var result = await GetSnowReportBaseData(lang, myskiareaid, cancellationToken); + var result = await GetSnowReportBaseData( + lang, + myskiareaid, + cancellationToken + ); if (result != null) snowreportbasedatalist.Add(result); } - if (pagenumber != null) - { - return Ok(ResponseHelpers.GetResult( - pagenumber.Value, - 1, - (uint)snowreportbasedatalist.Count, - null, - snowreportbasedatalist, - Url)); + if (pagenumber != null) + { + return Ok( + ResponseHelpers.GetResult( + pagenumber.Value, + 1, + (uint)snowreportbasedatalist.Count, + null, + snowreportbasedatalist, + Url + ) + ); } - else - { - return Ok(snowreportbasedatalist); + else + { + return Ok(snowreportbasedatalist); } } } catch (Exception ex) { - return StatusCode(StatusCodes.Status500InternalServerError, new { error = ex.Message }); + return StatusCode( + StatusCodes.Status500InternalServerError, + new { error = ex.Message } + ); } } @@ -340,20 +444,31 @@ public async Task GetSnowReportBase( /// GET Current Suedtirol Weather LIVE Request private async Task Get( - uint? pagenumber, - int? pagesize, - string language, - string? locfilter, - bool extended, - CancellationToken cancellationToken) + uint? pagenumber, + int? pagesize, + string language, + string? locfilter, + bool extended, + CancellationToken cancellationToken + ) { var weatherresult = default(Weather); - if(String.IsNullOrEmpty(locfilter)) + if (String.IsNullOrEmpty(locfilter)) { //Get Weather General from Siag and Parse it to ODH Format - var weatherresponsetask = await SIAG.GetWeatherData.GetSiagWeatherData(language, settings.SiagConfig.Username, settings.SiagConfig.Password, extended); - weatherresult = await SIAG.GetWeatherData.ParseSiagWeatherDataToODHWeather(language, settings.XmlConfig.XmldirWeather, weatherresponsetask, extended); + var weatherresponsetask = await SIAG.GetWeatherData.GetSiagWeatherData( + language, + settings.SiagConfig.Username, + settings.SiagConfig.Password, + extended + ); + weatherresult = await SIAG.GetWeatherData.ParseSiagWeatherDataToODHWeather( + language, + settings.XmlConfig.XmldirWeather, + weatherresponsetask, + extended + ); } else { @@ -386,171 +501,222 @@ private async Task Get( } } - weatherresult = await SIAG.GetWeatherData.GetCurrentStationWeatherAsync(language, locfilter, stationidtype, settings.XmlConfig.XmldirWeather, settings.SiagConfig.Username, settings.SiagConfig.Password); + weatherresult = await SIAG.GetWeatherData.GetCurrentStationWeatherAsync( + language, + locfilter, + stationidtype, + settings.XmlConfig.XmldirWeather, + settings.SiagConfig.Username, + settings.SiagConfig.Password + ); } - if (pagenumber != null) + if (pagenumber != null) { - return Ok(ResponseHelpers.GetResult( - pagenumber.Value, - 1, - 1, - null, - new List() { weatherresult }, - Url)); + return Ok( + ResponseHelpers.GetResult( + pagenumber.Value, + 1, + 1, + null, + new List() { weatherresult }, + Url + ) + ); } - else - { - return Ok(weatherresult); + else + { + return Ok(weatherresult); } } - + /// GET Bezirkswetter by LocFilter LIVE Request private async Task GetBezirksWetter( - uint? pagenumber, - int? pagesize, - string language, - string? locfilter, - CancellationToken cancellationToken) + uint? pagenumber, + int? pagesize, + string language, + string? locfilter, + CancellationToken cancellationToken + ) { string bezirksid = ""; string tvrid = ""; string regid = ""; - if(!String.IsNullOrEmpty(locfilter)) - { - int n; - if (int.TryParse(locfilter, out n)) - bezirksid = n.ToString(); - else - { - //Locfilter kann hier sein Region TV, Municipality und Fraktion - if (locfilter.Contains("reg")) - { - regid = locfilter.Replace("reg", ""); - } - - if (locfilter.Contains("tvs")) - { - tvrid = locfilter.Replace("tvs", ""); - } - if (locfilter.Contains("mun")) - { - var query = - QueryFactory.Query() - .SelectRaw("data ->>'TourismvereinId'") - .From("municipalities") - .Where("id", locfilter.Replace("mun", "").ToUpper()); - - tvrid = await query.FirstOrDefaultAsync(); - } - if (locfilter.Contains("fra")) - { - var query = - QueryFactory.Query() - .SelectRaw("data ->>'TourismvereinId'") - .From("districts") - .Where("id", locfilter.Replace("fra", "").ToUpper()); - - tvrid = await query.FirstOrDefaultAsync(); - } - } - } - - var weatherresult = await GetWeatherData.GetCurrentBezirkWeatherAsync(language, bezirksid, tvrid, regid, settings.XmlConfig.XmldirWeather, settings.SiagConfig.Username, settings.SiagConfig.Password); - - if(pagenumber != null) - { - return Ok(ResponseHelpers.GetResult( - pagenumber.Value, - 1, - (uint)weatherresult.Count(), - null, - weatherresult, - Url)); + if (!String.IsNullOrEmpty(locfilter)) + { + int n; + if (int.TryParse(locfilter, out n)) + bezirksid = n.ToString(); + else + { + //Locfilter kann hier sein Region TV, Municipality und Fraktion + if (locfilter.Contains("reg")) + { + regid = locfilter.Replace("reg", ""); + } + + if (locfilter.Contains("tvs")) + { + tvrid = locfilter.Replace("tvs", ""); + } + if (locfilter.Contains("mun")) + { + var query = QueryFactory + .Query() + .SelectRaw("data ->>'TourismvereinId'") + .From("municipalities") + .Where("id", locfilter.Replace("mun", "").ToUpper()); + + tvrid = await query.FirstOrDefaultAsync(); + } + if (locfilter.Contains("fra")) + { + var query = QueryFactory + .Query() + .SelectRaw("data ->>'TourismvereinId'") + .From("districts") + .Where("id", locfilter.Replace("fra", "").ToUpper()); + + tvrid = await query.FirstOrDefaultAsync(); + } + } + } + + var weatherresult = await GetWeatherData.GetCurrentBezirkWeatherAsync( + language, + bezirksid, + tvrid, + regid, + settings.XmlConfig.XmldirWeather, + settings.SiagConfig.Username, + settings.SiagConfig.Password + ); + + if (pagenumber != null) + { + return Ok( + ResponseHelpers.GetResult( + pagenumber.Value, + 1, + (uint)weatherresult.Count(), + null, + weatherresult, + Url + ) + ); + } + else + { + //Compatibility Hack + if (weatherresult.Count() == 1) + return Ok(weatherresult.FirstOrDefault()); + else + return Ok(weatherresult); } - else - { - //Compatibility Hack - if (weatherresult.Count() == 1) - return Ok(weatherresult.FirstOrDefault()); - else - return Ok(weatherresult); - } } /// GET Current Suedtirol Weather Realtime LIVE Request private async Task GetRealTimeWeather( - uint? pagenumber, - int? pagesize, - string language, - CancellationToken cancellationToken) + uint? pagenumber, + int? pagesize, + string language, + CancellationToken cancellationToken + ) { var weatherresult = await GetWeatherData.GetCurrentRealTimeWEatherAsync(language); - if (pagenumber != null) - { - return Ok(ResponseHelpers.GetResult( - pagenumber.Value, - 1, - (uint)weatherresult.Count(), - null, - weatherresult, - Url)); + if (pagenumber != null) + { + return Ok( + ResponseHelpers.GetResult( + pagenumber.Value, + 1, + (uint)weatherresult.Count(), + null, + weatherresult, + Url + ) + ); } - else - { - return Ok(weatherresult); + else + { + return Ok(weatherresult); } } /// GET Suedtirol Weather from History Table private Task GetWeatherHistoryList( - uint pagenumber, int? pagesize, - string? language, - string? idfilter, - string? locfilter, - string? datefrom, - string? dateto, - string? lastchange, - string? searchfilter, - string? seed, - string[] fields, - PGGeoSearchResult geosearchresult, - string? rawfilter, - string? rawsort, - bool removenullvalues, - CancellationToken cancellationToken) + uint pagenumber, + int? pagesize, + string? language, + string? idfilter, + string? locfilter, + string? datefrom, + string? dateto, + string? lastchange, + string? searchfilter, + string? seed, + string[] fields, + PGGeoSearchResult geosearchresult, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => - { - WeatherHelper myweatherhelper = await WeatherHelper.CreateAsync(QueryFactory, idfilter, locfilter, language, datefrom, dateto, lastchange, cancellationToken); - - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("weatherdatahistory") - .WeatherHistoryWhereExpression( - languagelist: myweatherhelper.languagelist, idlist: myweatherhelper.idlist, sourcelist: new List(), begindate: myweatherhelper.datefrom, - enddate: myweatherhelper.dateto, searchfilter: searchfilter, language: language, lastchange: myweatherhelper.lastchange, - filterClosedData: false) - .ApplyRawFilter(rawfilter) - .ApplyOrdering(ref seed, geosearchresult, rawsort); + { + WeatherHelper myweatherhelper = await WeatherHelper.CreateAsync( + QueryFactory, + idfilter, + locfilter, + language, + datefrom, + dateto, + lastchange, + cancellationToken + ); + + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("weatherdatahistory") + .WeatherHistoryWhereExpression( + languagelist: myweatherhelper.languagelist, + idlist: myweatherhelper.idlist, + sourcelist: new List(), + begindate: myweatherhelper.datefrom, + enddate: myweatherhelper.dateto, + searchfilter: searchfilter, + language: language, + lastchange: myweatherhelper.lastchange, + filterClosedData: false + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering(ref seed, geosearchresult, rawsort); //.ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort);// - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: false, filterClosedData: false, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: false, + filterClosedData: false, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); //return dataTransformed; @@ -563,7 +729,8 @@ await query totalcount, seed, dataTransformed, - Url); + Url + ); }); } @@ -573,8 +740,8 @@ await query /// GET Measuringpoints LIST private Task GetMeasuringPointList( - uint? pagenumber, - int? pagesize, + uint? pagenumber, + int? pagesize, string? language, string? idfilter, string? locfilter, @@ -592,101 +759,148 @@ private Task GetMeasuringPointList( string? rawfilter, string? rawsort, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { return DoAsyncReturn(async () => { //Fix add are to every arefilter item - string? arefilterwithprefix = String.IsNullOrEmpty(areafilter) ? "" : "are" + areafilter; - string? skiarefilterwithprefix = String.IsNullOrEmpty(skiareafilter) ? "" : "ska" + skiareafilter; - - MeasuringPointsHelper mymeasuringpointshelper = await MeasuringPointsHelper.Create(QueryFactory, idfilter, locfilter, - arefilterwithprefix, skiarefilterwithprefix, source, active, smgactive, lastchange, publishedon, cancellationToken); - - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("measuringpoints") - .MeasuringpointWhereExpression( - idlist: mymeasuringpointshelper.idlist, districtlist: mymeasuringpointshelper.districtlist, municipalitylist: mymeasuringpointshelper.municipalitylist, - tourismvereinlist: mymeasuringpointshelper.tourismvereinlist, regionlist: mymeasuringpointshelper.regionlist, arealist: mymeasuringpointshelper.arealist, - activefilter: mymeasuringpointshelper.active, smgactivefilter: mymeasuringpointshelper.smgactive, publishedonlist: mymeasuringpointshelper.publishedonlist, - sourcelist: mymeasuringpointshelper.sourcelist, - searchfilter: searchfilter, language: language, lastchange: mymeasuringpointshelper.lastchange, - filterClosedData: FilterClosedData, reducedData: ReducedData) - .ApplyRawFilter(rawfilter) - .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort);//.ApplyOrdering(ref seed, geosearchresult, rawsort); - + string? arefilterwithprefix = String.IsNullOrEmpty(areafilter) + ? "" + : "are" + areafilter; + string? skiarefilterwithprefix = String.IsNullOrEmpty(skiareafilter) + ? "" + : "ska" + skiareafilter; + + MeasuringPointsHelper mymeasuringpointshelper = await MeasuringPointsHelper.Create( + QueryFactory, + idfilter, + locfilter, + arefilterwithprefix, + skiarefilterwithprefix, + source, + active, + smgactive, + lastchange, + publishedon, + cancellationToken + ); + + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("measuringpoints") + .MeasuringpointWhereExpression( + idlist: mymeasuringpointshelper.idlist, + districtlist: mymeasuringpointshelper.districtlist, + municipalitylist: mymeasuringpointshelper.municipalitylist, + tourismvereinlist: mymeasuringpointshelper.tourismvereinlist, + regionlist: mymeasuringpointshelper.regionlist, + arealist: mymeasuringpointshelper.arealist, + activefilter: mymeasuringpointshelper.active, + smgactivefilter: mymeasuringpointshelper.smgactive, + publishedonlist: mymeasuringpointshelper.publishedonlist, + sourcelist: mymeasuringpointshelper.sourcelist, + searchfilter: searchfilter, + language: language, + lastchange: mymeasuringpointshelper.lastchange, + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); //.ApplyOrdering(ref seed, geosearchresult, rawsort); //Hack Paging on Measuringpoints - if (pagenumber != null) - { - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); - - var fieldsTohide = FieldsToHide; - - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: false, filterClosedData: false, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); - - uint totalpages = (uint)data.TotalPages; - uint totalcount = (uint)data.Count; - - return ResponseHelpers.GetResult( - pagenumber.Value, - totalpages, - totalcount, - seed, - dataTransformed, - Url); + if (pagenumber != null) + { + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); + + var fieldsTohide = FieldsToHide; + + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: false, + filterClosedData: false, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); + + uint totalpages = (uint)data.TotalPages; + uint totalcount = (uint)data.Count; + + return ResponseHelpers.GetResult( + pagenumber.Value, + totalpages, + totalcount, + seed, + dataTransformed, + Url + ); } - else - { - var data = - await query - .GetAsync(); - - var fieldsTohide = FieldsToHide; - - var dataTransformed = - data.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); - - return dataTransformed; + else + { + var data = await query.GetAsync(); + + var fieldsTohide = FieldsToHide; + + var dataTransformed = data.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); + + return dataTransformed; } }); } /// GET Measuringpoint SINGLE by ID private Task GetMeasuringPointSingle( - string id, - string? language, + string id, + string? language, string[] fields, bool removenullvalues, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("measuringpoints") - .Select("data") - .Where("id", id.ToUpper()) - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); - //.When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query("measuringpoints") + .Select("data") + .Where("id", id.ToUpper()) + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + //.When(FilterClosedData, q => q.FilterClosedData()); var fieldsTohide = FieldsToHide; var data = await query.FirstOrDefaultAsync(); - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); - } #endregion @@ -694,20 +908,21 @@ private Task GetMeasuringPointSingle( #region SnowReport /// GET Snowreport Data by SkiareaID LIVE - private async Task GetSnowReportBaseData( - string? lang, - string skiareaid, - CancellationToken cancellationToken) + private async Task GetSnowReportBaseData( + string? lang, + string skiareaid, + CancellationToken cancellationToken + ) { - - if(lang == null) + if (lang == null) throw new Exception("parameter lang is null"); - var query = QueryFactory.Query() - .SelectRaw("data") - .From("skiareas") - .Where("id", skiareaid); - + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("skiareas") + .Where("id", skiareaid); + var skiarearaw = await query.FirstOrDefaultAsync(); if (skiarearaw == null) @@ -722,12 +937,18 @@ private async Task GetSnowReportBaseData( //var skiareastring = await query.FirstOrDefaultAsync(); //var skiareaobject = JsonConvert.DeserializeObject(skiareastring); - var mysnowreport = GetSnowReport.GetLiveSnowReport(lang, skiarea!, "SMG", settings.LcsConfig.Username, settings.LcsConfig.Password, settings.LcsConfig.MessagePassword); + var mysnowreport = GetSnowReport.GetLiveSnowReport( + lang, + skiarea!, + "SMG", + settings.LcsConfig.Username, + settings.LcsConfig.Password, + settings.LcsConfig.MessagePassword + ); return mysnowreport; } - - #endregion + #endregion } -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/api/WebcamInfoApiController.cs b/OdhApiCore/Controllers/api/WebcamInfoApiController.cs index c80344400..af5545d75 100644 --- a/OdhApiCore/Controllers/api/WebcamInfoApiController.cs +++ b/OdhApiCore/Controllers/api/WebcamInfoApiController.cs @@ -7,7 +7,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; -using OdhApiCore.Filters; +using OdhApiCore.Filters; using OdhApiCore.Responses; using SqlKata.Execution; using System; @@ -24,11 +24,13 @@ namespace OdhApiCore.Controllers [EnableCors("CorsPolicy")] [NullStringParameterActionFilter] public class WebcamInfoController : OdhController - { - public WebcamInfoController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + { + public WebcamInfoController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } #region SWAGGER Exposed API @@ -39,27 +41,32 @@ public WebcamInfoController(IWebHostEnvironment env, ISettings settings, ILogger /// Elements per Page (default:10) /// Seed '1 - 10' for Random Sorting, '0' generates a Random Seed, not provided disables Random Sorting, (default:'null') /// IDFilter (Separator ',' List of Gastronomy IDs), (default:'null') - /// Source Filter (Separator ',' available sources 'lts','content'), (default:'null') + /// Source Filter (Separator ',' available sources 'lts','content'), (default:'null') /// Active Webcam Filter (possible Values: 'true' only Active data, 'false' only Disabled data), (default:'null') - /// ODH Active (Published) Webcam Filter (possible Values: 'true' only published data, 'false' only not published data), (default:'null') + /// ODH Active (Published) Webcam Filter (possible Values: 'true' only published data, 'false' only not published data), (default:'null') /// GeoFilter FLOAT Latitude Format: '46.624975', 'null' = disabled, (default:'null') Wiki geosort /// GeoFilter FLOAT Longitude Format: '11.369909', 'null' = disabled, (default:'null') Wiki geosort /// Radius INTEGER to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') Wiki geosort - /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') + /// Published On Filter (Separator ',' List of publisher IDs), (default:'null') /// Returns data changed after this date Format (yyyy-MM-dd), (default: 'null') /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// String to search for, Title in all languages are searched, (default: null)Wiki searchfilter /// Wiki rawfilter /// Wiki rawsort /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Collection of WebcamInfo Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Collection of WebcamInfo Objects /// List created /// Request Error /// Internal Server Error [ProducesResponseType(typeof(JsonResult), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] - [OdhCacheOutput(ClientTimeSpan = 0, ServerTimeSpan = 3600, CacheKeyGenerator = typeof(CustomCacheKeyGenerator), MustRevalidate = true)] + [OdhCacheOutput( + ClientTimeSpan = 0, + ServerTimeSpan = 3600, + CacheKeyGenerator = typeof(CustomCacheKeyGenerator), + MustRevalidate = true + )] [HttpGet, Route("WebcamInfo")] public async Task Get( string? language = null, @@ -75,30 +82,48 @@ public async Task Get( string? radius = null, string? updatefrom = null, string? publishedon = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); return await GetFilteredAsync( - fields: fields ?? Array.Empty(), language, pagenumber, pagesize, - source, idlist, searchfilter, active?.Value, odhactive?.Value, publishedon, - seed, updatefrom, geosearchresult, rawfilter: rawfilter, rawsort: rawsort, - removenullvalues: removenullvalues, cancellationToken); + fields: fields ?? Array.Empty(), + language, + pagenumber, + pagesize, + source, + idlist, + searchfilter, + active?.Value, + odhactive?.Value, + publishedon, + seed, + updatefrom, + geosearchresult, + rawfilter: rawfilter, + rawsort: rawsort, + removenullvalues: removenullvalues, + cancellationToken + ); } /// - /// GET Webcam Single + /// GET Webcam Single /// /// ID of the Webcam /// Language field selector, displays data and fields available in the selected language (default:'null' all languages are displayed) /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki /// WebcamInfo Object [ProducesResponseType(typeof(WebcamInfo), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] @@ -107,12 +132,18 @@ public async Task Get( public Task Get( string id, string? language = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, bool removenullvalues = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return GetSingleAsync(id, language, fields: fields ?? Array.Empty(), removenullvalues: removenullvalues, cancellationToken); + return GetSingleAsync( + id, + language, + fields: fields ?? Array.Empty(), + removenullvalues: removenullvalues, + cancellationToken + ); } #endregion @@ -120,41 +151,76 @@ public Task Get( #region GETTER private Task GetFilteredAsync( - string[] fields, string? language, uint pagenumber, int? pagesize, string? source, - string? idfilter, string? searchfilter, bool? active, bool? smgactive, string? publishedon, - string? seed, string? lastchange, PGGeoSearchResult geosearchresult, - string? rawfilter, string? rawsort, bool removenullvalues, CancellationToken cancellationToken) + string[] fields, + string? language, + uint pagenumber, + int? pagesize, + string? source, + string? idfilter, + string? searchfilter, + bool? active, + bool? smgactive, + string? publishedon, + string? seed, + string? lastchange, + PGGeoSearchResult geosearchresult, + string? rawfilter, + string? rawsort, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { WebcamInfoHelper mywebcaminfohelper = WebcamInfoHelper.Create( - source, idfilter, active, smgactive, lastchange, publishedon); + source, + idfilter, + active, + smgactive, + lastchange, + publishedon + ); - var query = - QueryFactory.Query() - .SelectRaw("data") - .From("webcams") - .WebCamInfoWhereExpression( - idlist: mywebcaminfohelper.idlist, sourcelist: mywebcaminfohelper.sourcelist, - activefilter: mywebcaminfohelper.active, smgactivefilter: mywebcaminfohelper.smgactive, publishedonlist: mywebcaminfohelper.publishedonlist, - searchfilter: searchfilter, language: language, lastchange: mywebcaminfohelper.lastchange, - languagelist: new List(), filterClosedData: FilterClosedData, reducedData: ReducedData) - .ApplyRawFilter(rawfilter) - .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); //.ApplyOrdering(ref seed, geosearchresult, rawsort); + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("webcams") + .WebCamInfoWhereExpression( + idlist: mywebcaminfohelper.idlist, + sourcelist: mywebcaminfohelper.sourcelist, + activefilter: mywebcaminfohelper.active, + smgactivefilter: mywebcaminfohelper.smgactive, + publishedonlist: mywebcaminfohelper.publishedonlist, + searchfilter: searchfilter, + language: language, + lastchange: mywebcaminfohelper.lastchange, + languagelist: new List(), + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering_GeneratedColumns(ref seed, geosearchresult, rawsort); //.ApplyOrdering(ref seed, geosearchresult, rawsort); // Get paginated data - var data = - await query - .PaginateAsync( - page: (int)pagenumber, - perPage: pagesize ?? 25); + var data = await query.PaginateAsync( + page: (int)pagenumber, + perPage: pagesize ?? 25 + ); var fieldsTohide = FieldsToHide; - var dataTransformed = - data.List.Select( - raw => raw.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide) - ); + var dataTransformed = data.List.Select( + raw => + raw.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ) + ); uint totalpages = (uint)data.TotalPages; uint totalcount = (uint)data.Count; @@ -165,30 +231,45 @@ await query totalcount, seed, dataTransformed, - Url); + Url + ); }); } - private Task GetSingleAsync(string id, string? language, string[] fields, bool removenullvalues, CancellationToken cancellationToken) + private Task GetSingleAsync( + string id, + string? language, + string[] fields, + bool removenullvalues, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - var query = - QueryFactory.Query("webcams") - .Select("data") - .Where("id", id.ToUpper()) - //.When(FilterClosedData, q => q.FilterClosedData()); - .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); + var query = QueryFactory + .Query("webcams") + .Select("data") + .Where("id", id.ToUpper()) + //.When(FilterClosedData, q => q.FilterClosedData()); + .Anonymous_Logged_UserRule_GeneratedColumn(FilterClosedData, !ReducedData); var fieldsTohide = FieldsToHide; var data = await query.FirstOrDefaultAsync(); - return data?.TransformRawData(language, fields, checkCC0: FilterCC0License, filterClosedData: FilterClosedData, filteroutNullValues: removenullvalues, urlGenerator: UrlGenerator, fieldstohide: fieldsTohide); + return data?.TransformRawData( + language, + fields, + checkCC0: FilterCC0License, + filterClosedData: FilterClosedData, + filteroutNullValues: removenullvalues, + urlGenerator: UrlGenerator, + fieldstohide: fieldsTohide + ); }); } - #endregion + #endregion #region POST PUT DELETE @@ -258,7 +339,6 @@ public Task Delete(string id) }); } - #endregion } -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/base/MainController.cs b/OdhApiCore/Controllers/base/MainController.cs index 42e8f0844..1b07d963d 100644 --- a/OdhApiCore/Controllers/base/MainController.cs +++ b/OdhApiCore/Controllers/base/MainController.cs @@ -18,12 +18,12 @@ public class MainController : ControllerBase { private readonly IWebHostEnvironment env; private readonly ISettings settings; - private static string absoluteUri = ""; + private static string absoluteUri = ""; public MainController(IWebHostEnvironment env, ISettings settings) { this.env = env; - this.settings = settings; + this.settings = settings; } public static string GetAbsoluteUri() @@ -55,9 +55,9 @@ private async Task> GetMainApi() { string json = await r.ReadToEndAsync(); - tourismdatalist = JsonConvert.DeserializeObject>(json); - } - + tourismdatalist = JsonConvert.DeserializeObject>(json); + } + return tourismdatalist; } } @@ -72,7 +72,7 @@ public class TourismData //private string ApplicationURL { get; set; } public string ApiIdentifier { get; set; } = default!; - + public string ApiFilter { get; set; } public string Id { get; set; } = default!; @@ -82,7 +82,12 @@ public class TourismData private string swaggerUrl = default!; public string SwaggerUrl { - get { return Uri.EscapeUriString(MainController.GetAbsoluteUri() + "swagger/index.html#/" + swaggerUrl); } + get + { + return Uri.EscapeUriString( + MainController.GetAbsoluteUri() + "swagger/index.html#/" + swaggerUrl + ); + } set { swaggerUrl = value; } } @@ -90,7 +95,9 @@ public string Self { get { - return Uri.EscapeUriString(MainController.GetAbsoluteUri() + "v1/") + this.ApiIdentifier + this.ApiFilter; + return Uri.EscapeUriString(MainController.GetAbsoluteUri() + "v1/") + + this.ApiIdentifier + + this.ApiFilter; } } diff --git a/OdhApiCore/Controllers/base/OdhController.cs b/OdhApiCore/Controllers/base/OdhController.cs index 3b92405d1..16a083d81 100644 --- a/OdhApiCore/Controllers/base/OdhController.cs +++ b/OdhApiCore/Controllers/base/OdhController.cs @@ -16,14 +16,19 @@ namespace OdhApiCore.Controllers { [ApiController] - [Route("v1")] + [Route("v1")] [FormatFilter] public abstract class OdhController : ControllerBase { private readonly IWebHostEnvironment env; private readonly ISettings settings; - public OdhController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) + public OdhController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) { this.env = env; this.settings = settings; @@ -39,10 +44,7 @@ protected bool FilterCC0License { get { - var roles = new[] { - "IDM", - "AllImages" - }; + var roles = new[] { "IDM", "AllImages" }; return !roles.Any(User.IsInRole); } } @@ -55,7 +57,8 @@ protected bool FilterClosedData { get { - var roles = new[] { + var roles = new[] + { "IDM" //"DataReader", //$"{this.ControllerContext.ActionDescriptor.ControllerName}Reader" @@ -72,20 +75,22 @@ protected bool FiltertoReduced { get { - var roles = new[] { - "IDM", - "LTS" - }; + var roles = new[] { "IDM", "LTS" }; return !roles.Any(User.IsInRole); } } - protected IEnumerable UserRolesList { get { - var roleclaims = User.Claims.Where(x => x.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").Select(claim => claim.Value).ToList(); + var roleclaims = User.Claims + .Where( + x => + x.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" + ) + .Select(claim => claim.Value) + .ToList(); return roleclaims ?? new List(); } @@ -98,7 +103,7 @@ protected IEnumerable UserRolesList // foreach(var role in roles) // { // if (User.IsInRole(role)) - // return true; + // return true; // } // return false; @@ -110,16 +115,25 @@ protected IEnumerable FieldsToHide { List fieldstohide = new(); - var roleclaims = User.Claims.Where(x => x.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").Select(claim => claim.Value).ToList(); + var roleclaims = User.Claims + .Where( + x => + x.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" + ) + .Select(claim => claim.Value) + .ToList(); //Search all settings with Entity = Controllername - var fields = settings.Field2HideConfig - .Where(x => x.Entity == this.ControllerContext.RouteData.Values["controller"]?.ToString() || - string.IsNullOrEmpty(x.Entity)); - - foreach(var field in fields) + var fields = settings.Field2HideConfig.Where( + x => + x.Entity + == this.ControllerContext.RouteData.Values["controller"]?.ToString() + || string.IsNullOrEmpty(x.Entity) + ); + + foreach (var field in fields) { - if(roleclaims.Intersect(field.DisplayOnRoles ?? new()).Count() == 0) + if (roleclaims.Intersect(field.DisplayOnRoles ?? new()).Count() == 0) { fieldstohide.AddRange(field.Fields ?? new()); } @@ -140,16 +154,16 @@ protected Func UrlGenerator return self; //Hack if there is another / in the route to check if it is not generating side effects - if(chunks[1].Split('/').Count() > 1) + if (chunks[1].Split('/').Count() > 1) { chunks[1] = chunks[1].Split('/')[1]; - } + } var (controller, id) = (chunks[0], chunks[1]); return Url.Link($"Single{controller}", new { id })!; }; } - } + } protected async Task DoAsync(Func> f) { @@ -159,25 +173,38 @@ protected async Task DoAsync(Func> f) } catch (PostGresSQLHelperException ex) { - return this.StatusCode(StatusCodes.Status500InternalServerError, new { error = ex.Message }); + return this.StatusCode( + StatusCodes.Status500InternalServerError, + new { error = ex.Message } + ); } catch (JsonPathException ex) { - return this.BadRequest(new - { - error = "Invalid JSONPath selection", - path = ex.Path, - details = env.IsDevelopment() ? ex.ToString() : ex.Message - }); + return this.BadRequest( + new + { + error = "Invalid JSONPath selection", + path = ex.Path, + details = env.IsDevelopment() ? ex.ToString() : ex.Message + } + ); } catch (Exception ex) { if (ex.Message == "Request Error") - return this.BadRequest(new { error = env.IsDevelopment() ? ex.ToString() : ex.Message }); + return this.BadRequest( + new { error = env.IsDevelopment() ? ex.ToString() : ex.Message } + ); else if (ex.Message == "No data") - return this.StatusCode(StatusCodes.Status404NotFound, new { error = env.IsDevelopment() ? ex.ToString() : ex.Message }); + return this.StatusCode( + StatusCodes.Status404NotFound, + new { error = env.IsDevelopment() ? ex.ToString() : ex.Message } + ); else - return this.StatusCode(StatusCodes.Status500InternalServerError, new { error = env.IsDevelopment() ? ex.ToString() : ex.Message }); + return this.StatusCode( + StatusCodes.Status500InternalServerError, + new { error = env.IsDevelopment() ? ex.ToString() : ex.Message } + ); } } @@ -195,14 +222,26 @@ protected Task DoAsyncReturn(Func> f) //Provide Methods for POST, PUT, DELETE passing DataType etc... - protected async Task UpsertData(T data, string table, bool errorwhendataexists = false, bool errorwhendataisnew = false) where T : IIdentifiable, IImportDateassigneable, IMetaData + protected async Task UpsertData( + T data, + string table, + bool errorwhendataexists = false, + bool errorwhendataisnew = false + ) where T : IIdentifiable, IImportDateassigneable, IMetaData { - return Ok(await QueryFactory.UpsertData(data, table, errorwhendataexists, errorwhendataisnew)); + return Ok( + await QueryFactory.UpsertData( + data, + table, + errorwhendataexists, + errorwhendataisnew + ) + ); } protected async Task DeleteData(string id, string table) { - return Ok(await QueryFactory.DeleteData(id, table)); + return Ok(await QueryFactory.DeleteData(id, table)); } - } -} \ No newline at end of file + } +} diff --git a/OdhApiCore/Controllers/helper/AccommodationHelper.cs b/OdhApiCore/Controllers/helper/AccommodationHelper.cs index 85a853a78..a88463f38 100644 --- a/OdhApiCore/Controllers/helper/AccommodationHelper.cs +++ b/OdhApiCore/Controllers/helper/AccommodationHelper.cs @@ -35,48 +35,107 @@ public class AccommodationHelper public bool? active; public bool? smgactive; public string? lastchange; + //New Publishedonlist public List publishedonlist; public static async Task CreateAsync( - QueryFactory queryFactory, string? idfilter, string? locfilter, string? boardfilter, - string? categoryfilter, string? typefilter, string? featurefilter, string? featureidfilter, - string? badgefilter, string? themefilter, string? altitudefilter, string? smgtags, - bool? activefilter, bool? smgactivefilter, bool? bookablefilter, string? sourcefilter, string? lastchange, string? langfilter, - string? publishedonfilter, CancellationToken cancellationToken) + QueryFactory queryFactory, + string? idfilter, + string? locfilter, + string? boardfilter, + string? categoryfilter, + string? typefilter, + string? featurefilter, + string? featureidfilter, + string? badgefilter, + string? themefilter, + string? altitudefilter, + string? smgtags, + bool? activefilter, + bool? smgactivefilter, + bool? bookablefilter, + string? sourcefilter, + string? lastchange, + string? langfilter, + string? publishedonfilter, + CancellationToken cancellationToken + ) { IEnumerable? tourismusvereinids = null; if (locfilter != null && locfilter.Contains("mta")) { - List metaregionlist = CommonListCreator.CreateDistrictIdList(locfilter, "mta"); - tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync(queryFactory, metaregionlist, cancellationToken); + List metaregionlist = CommonListCreator.CreateDistrictIdList( + locfilter, + "mta" + ); + tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync( + queryFactory, + metaregionlist, + cancellationToken + ); } return new AccommodationHelper( - idfilter: idfilter, locfilter: locfilter, boardfilter: boardfilter, categoryfilter: categoryfilter, typefilter: typefilter, - featurefilter: featurefilter, featureidfilter: featureidfilter, badgefilter: badgefilter, themefilter: themefilter, altitudefilter: altitudefilter, bookablefilter: bookablefilter, - activefilter: activefilter, smgactivefilter: smgactivefilter, smgtags: smgtags, sourcefilter: sourcefilter, lastchange: lastchange, languagefilter: langfilter, publishedonfilter: publishedonfilter, - tourismusvereinids: tourismusvereinids); + idfilter: idfilter, + locfilter: locfilter, + boardfilter: boardfilter, + categoryfilter: categoryfilter, + typefilter: typefilter, + featurefilter: featurefilter, + featureidfilter: featureidfilter, + badgefilter: badgefilter, + themefilter: themefilter, + altitudefilter: altitudefilter, + bookablefilter: bookablefilter, + activefilter: activefilter, + smgactivefilter: smgactivefilter, + smgtags: smgtags, + sourcefilter: sourcefilter, + lastchange: lastchange, + languagefilter: langfilter, + publishedonfilter: publishedonfilter, + tourismusvereinids: tourismusvereinids + ); } private AccommodationHelper( - string? idfilter, string? locfilter, string? boardfilter, string? categoryfilter, string? typefilter, - string? featurefilter, string? featureidfilter, string? badgefilter, string? themefilter, string? altitudefilter, bool? bookablefilter, - bool? activefilter, bool? smgactivefilter, string? smgtags, string? sourcefilter, string? lastchange, string? languagefilter, string? publishedonfilter, - IEnumerable? tourismusvereinids) + string? idfilter, + string? locfilter, + string? boardfilter, + string? categoryfilter, + string? typefilter, + string? featurefilter, + string? featureidfilter, + string? badgefilter, + string? themefilter, + string? altitudefilter, + bool? bookablefilter, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? sourcefilter, + string? lastchange, + string? languagefilter, + string? publishedonfilter, + IEnumerable? tourismusvereinids + ) { - boardlist = AccoListCreator.CreateBoardListFromFlag(boardfilter); categorylist = AccoListCreator.CreateCategoryListfromFlag(categoryfilter); accotypelist = AccoListCreator.CreateAccoTypeListfromFlag(typefilter); featurelist = AccoListCreator.CreateFeatureListDictfromFlag(featurefilter); badgelist = AccoListCreator.CreateBadgeListfromFlag(badgefilter); themelist = AccoListCreator.CreateThemeListDictfromFlag(themefilter); - idlist = String.IsNullOrEmpty(idfilter) ? new List() : CommonListCreator.CreateIdList(idfilter.ToUpper()); + idlist = String.IsNullOrEmpty(idfilter) + ? new List() + : CommonListCreator.CreateIdList(idfilter.ToUpper()); smgtaglist = CommonListCreator.CreateIdList(smgtags); sourcelist = Helper.CommonListCreator.CreateSmgPoiSourceList(sourcefilter); - featureidlist = String.IsNullOrEmpty(featureidfilter) ? new List() : CommonListCreator.CreateIdList(featureidfilter.ToUpper()); + featureidlist = String.IsNullOrEmpty(featureidfilter) + ? new List() + : CommonListCreator.CreateIdList(featureidfilter.ToUpper()); districtlist = new List(); municipalitylist = new List(); @@ -121,7 +180,5 @@ private AccommodationHelper( publishedonlist = Helper.CommonListCreator.CreateIdList(publishedonfilter?.ToLower()); } - - } } diff --git a/OdhApiCore/Controllers/helper/ActivityHelper.cs b/OdhApiCore/Controllers/helper/ActivityHelper.cs index 5f65da735..adbbb6b64 100644 --- a/OdhApiCore/Controllers/helper/ActivityHelper.cs +++ b/OdhApiCore/Controllers/helper/ActivityHelper.cs @@ -35,34 +35,83 @@ public class ActivityHelper public string? lastchange; public static async Task CreateAsync( - QueryFactory queryFactory, string? activitytype, string? subtypefilter, - string? idfilter, string? locfilter, string? areafilter, string? distancefilter, - string? altitudefilter, string? durationfilter, bool? highlightfilter, string? difficultyfilter, - bool? activefilter, bool? smgactivefilter, string? smgtags, string? lastchange, string? langfilter, - CancellationToken cancellationToken) + QueryFactory queryFactory, + string? activitytype, + string? subtypefilter, + string? idfilter, + string? locfilter, + string? areafilter, + string? distancefilter, + string? altitudefilter, + string? durationfilter, + bool? highlightfilter, + string? difficultyfilter, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? lastchange, + string? langfilter, + CancellationToken cancellationToken + ) { - var arealist = await GenericHelper.RetrieveAreaFilterDataAsync(queryFactory, areafilter, cancellationToken); + var arealist = await GenericHelper.RetrieveAreaFilterDataAsync( + queryFactory, + areafilter, + cancellationToken + ); IEnumerable? tourismusvereinids = null; if (locfilter != null && locfilter.Contains("mta")) { - List metaregionlist = CommonListCreator.CreateDistrictIdList(locfilter, "mta"); - tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync(queryFactory, metaregionlist, cancellationToken); + List metaregionlist = CommonListCreator.CreateDistrictIdList( + locfilter, + "mta" + ); + tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync( + queryFactory, + metaregionlist, + cancellationToken + ); } return new ActivityHelper( - activitytype: activitytype, subtypefilter: subtypefilter, idfilter: idfilter, locfilter: locfilter, - arealist: arealist, distancefilter: distancefilter, altitudefilter: altitudefilter, - durationfilter: durationfilter, highlightfilter: highlightfilter, difficultyfilter: difficultyfilter, - activefilter: activefilter, smgactivefilter: smgactivefilter, smgtags: smgtags, lastchange: lastchange, languagefilter: langfilter, - tourismusvereinids: tourismusvereinids); + activitytype: activitytype, + subtypefilter: subtypefilter, + idfilter: idfilter, + locfilter: locfilter, + arealist: arealist, + distancefilter: distancefilter, + altitudefilter: altitudefilter, + durationfilter: durationfilter, + highlightfilter: highlightfilter, + difficultyfilter: difficultyfilter, + activefilter: activefilter, + smgactivefilter: smgactivefilter, + smgtags: smgtags, + lastchange: lastchange, + languagefilter: langfilter, + tourismusvereinids: tourismusvereinids + ); } private ActivityHelper( - string? activitytype, string? subtypefilter, string? idfilter, string? locfilter, IEnumerable arealist, - string? distancefilter, string? altitudefilter, string? durationfilter, bool? highlightfilter, - string? difficultyfilter, bool? activefilter, bool? smgactivefilter, string? smgtags, string? lastchange, string? languagefilter, - IEnumerable? tourismusvereinids) + string? activitytype, + string? subtypefilter, + string? idfilter, + string? locfilter, + IEnumerable arealist, + string? distancefilter, + string? altitudefilter, + string? durationfilter, + bool? highlightfilter, + string? difficultyfilter, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? lastchange, + string? languagefilter, + IEnumerable? tourismusvereinids + ) { activitytypelist = new List(); if (activitytype != null) @@ -70,7 +119,9 @@ private ActivityHelper( if (int.TryParse(activitytype, out int typeinteger)) { if (typeinteger != 1023) - activitytypelist = Helper.ActivityPoiListCreator.CreateActivityTypefromFlag(activitytype); + activitytypelist = Helper.ActivityPoiListCreator.CreateActivityTypefromFlag( + activitytype + ); } else { @@ -79,7 +130,9 @@ private ActivityHelper( } if (activitytypelist.Count > 0) subtypelist = Helper.ActivityPoiListCreator.CreateActivitySubTypefromFlag( - activitytypelist.FirstOrDefault(), subtypefilter); + activitytypelist.FirstOrDefault(), + subtypefilter + ); else subtypelist = new List(); @@ -132,7 +185,5 @@ private ActivityHelper( this.lastchange = lastchange; } - - } } diff --git a/OdhApiCore/Controllers/helper/ArticleHelper.cs b/OdhApiCore/Controllers/helper/ArticleHelper.cs index c8db16c7a..2c4860554 100644 --- a/OdhApiCore/Controllers/helper/ArticleHelper.cs +++ b/OdhApiCore/Controllers/helper/ArticleHelper.cs @@ -20,23 +20,59 @@ public class ArticleHelper public string? lastchange; public DateTime? articledate; public DateTime? articledateto; + //New Publishedonlist public List publishedonlist; public List sourcelist; public static ArticleHelper Create( - string? typefilter, string? subtypefilter, string? idfilter, - string? languagefilter, bool? highlightfilter, bool? activefilter, bool? smgactivefilter, - string? smgtags, string? articledate, string? articledateto, string? source, string? lastchange, string? publishedonfilter) + string? typefilter, + string? subtypefilter, + string? idfilter, + string? languagefilter, + bool? highlightfilter, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? articledate, + string? articledateto, + string? source, + string? lastchange, + string? publishedonfilter + ) { - return new ArticleHelper(typefilter, subtypefilter, idfilter, languagefilter, highlightfilter, activefilter, smgactivefilter, - smgtags, articledate, articledateto, source, lastchange, publishedonfilter); + return new ArticleHelper( + typefilter, + subtypefilter, + idfilter, + languagefilter, + highlightfilter, + activefilter, + smgactivefilter, + smgtags, + articledate, + articledateto, + source, + lastchange, + publishedonfilter + ); } private ArticleHelper( - string? typefilter, string? subtypefilter, string? idfilter, string? languagefilter, - bool? highlightfilter, bool? activefilter, bool? smgactivefilter, string? smgtags, - string? articledate, string? articledateto, string? source, string? lastchange, string? publishedonfilter) + string? typefilter, + string? subtypefilter, + string? idfilter, + string? languagefilter, + bool? highlightfilter, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? articledate, + string? articledateto, + string? source, + string? lastchange, + string? publishedonfilter + ) { typelist = new List(); int typeinteger = 0; @@ -63,11 +99,17 @@ private ArticleHelper( { if (int.TryParse(subtypefilter, out subtypeinteger)) { - subtypelist = Helper.ArticleListCreator.CreateArticleSubTypefromFlag(typelist.FirstOrDefault(), subtypefilter); + subtypelist = Helper.ArticleListCreator.CreateArticleSubTypefromFlag( + typelist.FirstOrDefault(), + subtypefilter + ); } else { - subtypelist = Helper.ArticleListCreator.CreateArticleSubTypeList(typelist.FirstOrDefault(), subtypefilter); + subtypelist = Helper.ArticleListCreator.CreateArticleSubTypeList( + typelist.FirstOrDefault(), + subtypefilter + ); } } else @@ -76,7 +118,6 @@ private ArticleHelper( else subtypelist = new List(); - idlist = Helper.CommonListCreator.CreateIdList(idfilter?.ToUpper()); languagelist = Helper.CommonListCreator.CreateIdList(languagefilter); sourcelist = Helper.CommonListCreator.CreateSmgPoiSourceList(source); diff --git a/OdhApiCore/Controllers/helper/CommonHelper.cs b/OdhApiCore/Controllers/helper/CommonHelper.cs index c471c46ac..e31af595a 100644 --- a/OdhApiCore/Controllers/helper/CommonHelper.cs +++ b/OdhApiCore/Controllers/helper/CommonHelper.cs @@ -19,24 +19,51 @@ public class CommonHelper public string? lastchange; public bool? active; public bool? smgactive; + //New Publishedonlist public List publishedonlist; public static Task CreateAsync( - QueryFactory queryFactory, string? idfilter, string? languagefilter, bool? visibleinsearch, string? sourcefilter, - bool? activefilter, bool? smgactivefilter, string? smgtags, string? lastchange, string? publishedonfilter, - CancellationToken cancellationToken) - { - return Task.FromResult(new CommonHelper( - idfilter: idfilter, languagefilter: languagefilter, - activefilter: activefilter, smgactivefilter: smgactivefilter, visibleinsearch: visibleinsearch, sourcefilter: sourcefilter, - smgtags: smgtags, lastchange: lastchange, publishedonfilter: publishedonfilter)); + QueryFactory queryFactory, + string? idfilter, + string? languagefilter, + bool? visibleinsearch, + string? sourcefilter, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? lastchange, + string? publishedonfilter, + CancellationToken cancellationToken + ) + { + return Task.FromResult( + new CommonHelper( + idfilter: idfilter, + languagefilter: languagefilter, + activefilter: activefilter, + smgactivefilter: smgactivefilter, + visibleinsearch: visibleinsearch, + sourcefilter: sourcefilter, + smgtags: smgtags, + lastchange: lastchange, + publishedonfilter: publishedonfilter + ) + ); } private CommonHelper( - string? idfilter, string? languagefilter, bool? activefilter, bool? smgactivefilter, bool? visibleinsearch, string? sourcefilter, - string? smgtags, string? lastchange, string? publishedonfilter) - { + string? idfilter, + string? languagefilter, + bool? activefilter, + bool? smgactivefilter, + bool? visibleinsearch, + string? sourcefilter, + string? smgtags, + string? lastchange, + string? publishedonfilter + ) + { idlist = Helper.CommonListCreator.CreateIdList(idfilter?.ToUpper()); languagelist = Helper.CommonListCreator.CreateIdList(languagefilter?.ToLower()); @@ -56,7 +83,5 @@ private CommonHelper( publishedonlist = Helper.CommonListCreator.CreateIdList(publishedonfilter?.ToLower()); } - - } } diff --git a/OdhApiCore/Controllers/helper/EventHelper.cs b/OdhApiCore/Controllers/helper/EventHelper.cs index 505ed348b..1abb8d18e 100644 --- a/OdhApiCore/Controllers/helper/EventHelper.cs +++ b/OdhApiCore/Controllers/helper/EventHelper.cs @@ -29,36 +29,82 @@ public class EventHelper public DateTime? begin; public DateTime? end; public string? lastchange; + //New Publishedonlist public List publishedonlist; public static async Task CreateAsync( - QueryFactory queryFactory, string? idfilter, string? locfilter, string? rancfilter, - string? typefilter, string? topicfilter, string? orgfilter, string? begindate, string? enddate, - bool? activefilter, bool? smgactivefilter, string? smgtags, string? lastchange, string? langfilter, string? source, + QueryFactory queryFactory, + string? idfilter, + string? locfilter, + string? rancfilter, + string? typefilter, + string? topicfilter, + string? orgfilter, + string? begindate, + string? enddate, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? lastchange, + string? langfilter, + string? source, string? publishedonfilter, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { IEnumerable? tourismusvereinids = null; if (locfilter != null && locfilter.Contains("mta")) { - List metaregionlist = CommonListCreator.CreateDistrictIdList(locfilter, "mta"); - tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync(queryFactory, metaregionlist, cancellationToken); + List metaregionlist = CommonListCreator.CreateDistrictIdList( + locfilter, + "mta" + ); + tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync( + queryFactory, + metaregionlist, + cancellationToken + ); } return new EventHelper( - idfilter: idfilter, locfilter: locfilter, rancfilter: rancfilter, typefilter: typefilter, - topicfilter: topicfilter, orgfilter: orgfilter, begindate: begindate, enddate: enddate, - activefilter: activefilter, smgactivefilter: smgactivefilter, smgtags: smgtags, lastchange: lastchange, sourcefilter: source, - languagefilter: langfilter, publishedonfilter: publishedonfilter, tourismusvereinids: tourismusvereinids); + idfilter: idfilter, + locfilter: locfilter, + rancfilter: rancfilter, + typefilter: typefilter, + topicfilter: topicfilter, + orgfilter: orgfilter, + begindate: begindate, + enddate: enddate, + activefilter: activefilter, + smgactivefilter: smgactivefilter, + smgtags: smgtags, + lastchange: lastchange, + sourcefilter: source, + languagefilter: langfilter, + publishedonfilter: publishedonfilter, + tourismusvereinids: tourismusvereinids + ); } private EventHelper( - string? idfilter, string? locfilter, string? rancfilter, - string? typefilter, string? topicfilter, string? orgfilter, - string? begindate, string? enddate, bool? activefilter, bool? smgactivefilter, - string? smgtags, string? lastchange, string? languagefilter, string? sourcefilter, string? publishedonfilter, - IEnumerable? tourismusvereinids) + string? idfilter, + string? locfilter, + string? rancfilter, + string? typefilter, + string? topicfilter, + string? orgfilter, + string? begindate, + string? enddate, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? lastchange, + string? languagefilter, + string? sourcefilter, + string? publishedonfilter, + IEnumerable? tourismusvereinids + ) { idlist = CommonListCreator.CreateIdList(idfilter?.ToUpper()); @@ -109,7 +155,5 @@ private EventHelper( publishedonlist = Helper.CommonListCreator.CreateIdList(publishedonfilter?.ToLower()); } - - } } diff --git a/OdhApiCore/Controllers/helper/EventShortHelper.cs b/OdhApiCore/Controllers/helper/EventShortHelper.cs index 875a09327..fe0172011 100644 --- a/OdhApiCore/Controllers/helper/EventShortHelper.cs +++ b/OdhApiCore/Controllers/helper/EventShortHelper.cs @@ -21,25 +21,61 @@ public class EventShortHelper public bool? communityactivefilter; public string? lastchange; public string? sortorder; + //New Publishedonlist public List publishedonlist; public static EventShortHelper Create( - string? startdate, string? enddate, string? datetimeformat, string? source, - string? eventlocation, bool? onlyactive, bool? websiteactive, bool? communityactive, - string? eventids, string? webaddress, string? lastchange, string? sortorder, string? publishedonfilter) + string? startdate, + string? enddate, + string? datetimeformat, + string? source, + string? eventlocation, + bool? onlyactive, + bool? websiteactive, + bool? communityactive, + string? eventids, + string? webaddress, + string? lastchange, + string? sortorder, + string? publishedonfilter + ) { - return new EventShortHelper(startdate, enddate, datetimeformat, source, eventlocation, onlyactive, websiteactive, - communityactive, eventids, webaddress, lastchange, sortorder, publishedonfilter); + return new EventShortHelper( + startdate, + enddate, + datetimeformat, + source, + eventlocation, + onlyactive, + websiteactive, + communityactive, + eventids, + webaddress, + lastchange, + sortorder, + publishedonfilter + ); } private EventShortHelper( - string? startdate, string? enddate, string? datetimeformat, string? source, - string? eventlocation, bool? onlyactive, bool? websiteactive, bool? communityactive, string? eventids, string? webaddress, - string? lastchange, string? sortorder, string? publishedonfilter) - { + string? startdate, + string? enddate, + string? datetimeformat, + string? source, + string? eventlocation, + bool? onlyactive, + bool? websiteactive, + bool? communityactive, + string? eventids, + string? webaddress, + string? lastchange, + string? sortorder, + string? publishedonfilter + ) + { idlist = Helper.CommonListCreator.CreateIdList(eventids); - var sourcelisttemp = Helper.CommonListCreator.CreateIdList(source); + var sourcelisttemp = Helper.CommonListCreator.CreateIdList(source); sourcelist = ExtendSourceFilterEventShort(sourcelisttemp); @@ -64,7 +100,6 @@ private EventShortHelper( } else if (datetimeformat == "uxtimestamp") { - if (!String.IsNullOrEmpty(startdate)) { double startdatedb = Convert.ToDouble(startdate); @@ -95,17 +130,16 @@ private EventShortHelper( this.sortorder = sortorder; - if(sortorder != null) + if (sortorder != null) { sortorder = sortorder.ToUpper(); if (sortorder != "ASC" && sortorder != "DESC") sortorder = ""; } - + this.lastchange = lastchange; publishedonlist = Helper.CommonListCreator.CreateIdList(publishedonfilter?.ToLower()); - } private List ExtendSourceFilterEventShort(List sourcelist) @@ -119,13 +153,13 @@ private List ExtendSourceFilterEventShort(List sourcelist) if (source == "noi") { if (!sourcelistnew.Contains("Content")) - sourcelistnew.Add("Content"); + sourcelistnew.Add("Content"); } else if (source == "eurac") { if (!sourcelistnew.Contains("EBMS")) - sourcelistnew.Add("EBMS"); - } + sourcelistnew.Add("EBMS"); + } } return sourcelistnew; diff --git a/OdhApiCore/Controllers/helper/GastronomyHelper.cs b/OdhApiCore/Controllers/helper/GastronomyHelper.cs index fd36538a0..efde29376 100644 --- a/OdhApiCore/Controllers/helper/GastronomyHelper.cs +++ b/OdhApiCore/Controllers/helper/GastronomyHelper.cs @@ -28,45 +28,90 @@ public class GastronomyHelper public string? lastchange; public static async Task CreateAsync( - QueryFactory queryFactory, string? idfilter, string? locfilter, string? categorycodefilter, string? dishcodefilter, - string? ceremonycodefilter, string? facilitycodefilter, string? cuisinecodefilter, - bool? activefilter, bool? smgactivefilter, string? smgtags, string? lastchange, string? langfilter, - CancellationToken cancellationToken) + QueryFactory queryFactory, + string? idfilter, + string? locfilter, + string? categorycodefilter, + string? dishcodefilter, + string? ceremonycodefilter, + string? facilitycodefilter, + string? cuisinecodefilter, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? lastchange, + string? langfilter, + CancellationToken cancellationToken + ) { IEnumerable? tourismusvereinids = null; if (locfilter != null && locfilter.Contains("mta")) { - List metaregionlist = CommonListCreator.CreateDistrictIdList(locfilter, "mta"); - tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync(queryFactory, metaregionlist, cancellationToken); + List metaregionlist = CommonListCreator.CreateDistrictIdList( + locfilter, + "mta" + ); + tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync( + queryFactory, + metaregionlist, + cancellationToken + ); } return new GastronomyHelper( - idfilter: idfilter, locfilter: locfilter, dishcodefilter: dishcodefilter, ceremonycodefilter: ceremonycodefilter, - categorycodefilter: categorycodefilter, facilitycodefilter: facilitycodefilter, cuisinecodefilter: cuisinecodefilter, - activefilter: activefilter, smgactivefilter: smgactivefilter, smgtags: smgtags, lastchange: lastchange, languagefilter: langfilter, - tourismusvereinids: tourismusvereinids); + idfilter: idfilter, + locfilter: locfilter, + dishcodefilter: dishcodefilter, + ceremonycodefilter: ceremonycodefilter, + categorycodefilter: categorycodefilter, + facilitycodefilter: facilitycodefilter, + cuisinecodefilter: cuisinecodefilter, + activefilter: activefilter, + smgactivefilter: smgactivefilter, + smgtags: smgtags, + lastchange: lastchange, + languagefilter: langfilter, + tourismusvereinids: tourismusvereinids + ); } private GastronomyHelper( - string? idfilter, string? locfilter, string? dishcodefilter, - string? ceremonycodefilter, string? categorycodefilter, string? facilitycodefilter, - string? cuisinecodefilter, bool? activefilter, bool? smgactivefilter, string? smgtags, - string? lastchange, string? languagefilter, IEnumerable? tourismusvereinids) + string? idfilter, + string? locfilter, + string? dishcodefilter, + string? ceremonycodefilter, + string? categorycodefilter, + string? facilitycodefilter, + string? cuisinecodefilter, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? lastchange, + string? languagefilter, + IEnumerable? tourismusvereinids + ) { idlist = CommonListCreator.CreateIdList(idfilter?.ToUpper()); smgtaglist = CommonListCreator.CreateIdList(smgtags); dishcodesids = GastronomyListCreator.CreateGastroDishCodeListfromFlag(dishcodefilter); - ceremonycodesids = GastronomyListCreator.CreateGastroCeremonyCodeListfromFlag(ceremonycodefilter); - categorycodesids = GastronomyListCreator.CreateGastroCategoryCodeListfromFlag(categorycodefilter); - facilitycodesids = GastronomyListCreator.CreateGastroFacilityCodeListfromFlag(facilitycodefilter); - cuisinecodesids = GastronomyListCreator.CreateGastroCusineCodeListfromFlag(cuisinecodefilter); + ceremonycodesids = GastronomyListCreator.CreateGastroCeremonyCodeListfromFlag( + ceremonycodefilter + ); + categorycodesids = GastronomyListCreator.CreateGastroCategoryCodeListfromFlag( + categorycodefilter + ); + facilitycodesids = GastronomyListCreator.CreateGastroFacilityCodeListfromFlag( + facilitycodefilter + ); + cuisinecodesids = GastronomyListCreator.CreateGastroCusineCodeListfromFlag( + cuisinecodefilter + ); facilitycodesids.AddRange(cuisinecodesids); languagelist = Helper.CommonListCreator.CreateIdList(languagefilter); - tourismvereinlist = new List(); regionlist = new List(); municipalitylist = new List(); @@ -92,7 +137,5 @@ private GastronomyHelper( this.lastchange = lastchange; } - - } } diff --git a/OdhApiCore/Controllers/helper/GenericHelper.cs b/OdhApiCore/Controllers/helper/GenericHelper.cs index 0000dc7b6..6bf9d1a38 100644 --- a/OdhApiCore/Controllers/helper/GenericHelper.cs +++ b/OdhApiCore/Controllers/helper/GenericHelper.cs @@ -16,12 +16,20 @@ namespace OdhApiCore.Controllers public static class GenericHelper { public static async Task> RetrieveAreaFilterDataAsync( - QueryFactory queryFactory, string? areafilter, CancellationToken cancellationToken) + QueryFactory queryFactory, + string? areafilter, + CancellationToken cancellationToken + ) { if (areafilter != null) { - return (await LocationListCreator.CreateActivityAreaListPGAsync( - queryFactory, areafilter, cancellationToken)).ToList(); + return ( + await LocationListCreator.CreateActivityAreaListPGAsync( + queryFactory, + areafilter, + cancellationToken + ) + ).ToList(); } else { @@ -30,24 +38,36 @@ public static async Task> RetrieveAreaFilterDataAsync( } public static async Task> RetrieveLocFilterDataAsync( - QueryFactory queryFactory, IReadOnlyCollection metaregionlist, CancellationToken cancellationToken) + QueryFactory queryFactory, + IReadOnlyCollection metaregionlist, + CancellationToken cancellationToken + ) { - var data = await queryFactory.Query() - .From("metaregions") - .Select("data") - .MetaRegionFilter(metaregionlist) - .GetAsync(); - var mymetaregion = data.Select(raw => JsonConvert.DeserializeObject(raw.Value)); - return (from region in mymetaregion - where region.TourismvereinIds != null - from tid in region.TourismvereinIds ?? Enumerable.Empty() - select tid).Distinct().ToList(); + var data = await queryFactory + .Query() + .From("metaregions") + .Select("data") + .MetaRegionFilter(metaregionlist) + .GetAsync(); + var mymetaregion = data.Select( + raw => JsonConvert.DeserializeObject(raw.Value) + ); + return ( + from region in mymetaregion + where region.TourismvereinIds != null + from tid in region.TourismvereinIds ?? Enumerable.Empty() + select tid + ) + .Distinct() + .ToList(); } #region Tag Filter - public static IDictionary> RetrieveTagFilter(string? tagfilter) - { + public static IDictionary> RetrieveTagFilter( + string? tagfilter + ) + { try { if (tagfilter == null) @@ -66,7 +86,7 @@ public static IDictionary> RetrieveTagFilter(s //Get data inside brackets var bracketdatalist = GetSubStrings(tagfilter, "(", ")"); - foreach(var bracketdata in bracketdatalist) + foreach (var bracketdata in bracketdatalist) { var splittedelements = bracketdata.Split(","); @@ -77,15 +97,13 @@ public static IDictionary> RetrieveTagFilter(s var splittedtag = splittedelement.Split("."); if (splittedtag.Length > 1) { - splitdict.Add(splittedtag[1], splittedtag[0]); + splitdict.Add(splittedtag[1], splittedtag[0]); } } tagstofilter.Add(tagoperator, splitdict); } - - return tagstofilter; } catch (Exception) diff --git a/OdhApiCore/Controllers/helper/LcsHelper.cs b/OdhApiCore/Controllers/helper/LcsHelper.cs index f43dd1dde..5568930a0 100644 --- a/OdhApiCore/Controllers/helper/LcsHelper.cs +++ b/OdhApiCore/Controllers/helper/LcsHelper.cs @@ -8,33 +8,49 @@ namespace OdhApiCore.Controllers.helper { public class LcsHelper { - public readonly string lcsrequestlanguage; - public readonly List accoidlist; - public readonly List myroomdata; + public readonly string lcsrequestlanguage; + public readonly List accoidlist; + public readonly List myroomdata; public readonly string arrival; public readonly string departure; public readonly List service; public readonly int rooms; public readonly string source; - + public static LcsHelper Create( - List accoidlist, string language, string roominfo, string boardfilter, - string arrival, string departure, string source) + List accoidlist, + string language, + string roominfo, + string boardfilter, + string arrival, + string departure, + string source + ) { return new LcsHelper( - accoidlist: accoidlist, language: language, - roominfo: roominfo, boardfilter: boardfilter, arrival: arrival, - departure: departure, source: source); + accoidlist: accoidlist, + language: language, + roominfo: roominfo, + boardfilter: boardfilter, + arrival: arrival, + departure: departure, + source: source + ); } private LcsHelper( - List accoidlist, string language, string roominfo, string boardfilter, - string arrival, string departure, string source) + List accoidlist, + string language, + string roominfo, + string boardfilter, + string arrival, + string departure, + string source + ) { - service = Helper.AccoListCreator.CreateBoardListLCSfromFlag(boardfilter); myroomdata = LCS.GetAccommodationDataLCS.RoomstayTransformer(roominfo); - + rooms = myroomdata.Count; this.arrival = arrival; @@ -42,13 +58,21 @@ private LcsHelper( this.source = source; - if (language.ToLower() == "nl" || language.ToLower() == "cs" || language.ToLower() == "pl" || language.ToLower() == "fr" || language.ToLower() == "ru") + if ( + language.ToLower() == "nl" + || language.ToLower() == "cs" + || language.ToLower() == "pl" + || language.ToLower() == "fr" + || language.ToLower() == "ru" + ) lcsrequestlanguage = "en"; else lcsrequestlanguage = language.ToLower(); - this.accoidlist = accoidlist != null && accoidlist.Count > 0 ? accoidlist.Select(x => x.ToUpper()).ToList() : accoidlist ?? new(); + this.accoidlist = + accoidlist != null && accoidlist.Count > 0 + ? accoidlist.Select(x => x.ToUpper()).ToList() + : accoidlist ?? new(); } - } } diff --git a/OdhApiCore/Controllers/helper/MeasuringPointsHelper.cs b/OdhApiCore/Controllers/helper/MeasuringPointsHelper.cs index 89ecc692e..8bb5fdfd5 100644 --- a/OdhApiCore/Controllers/helper/MeasuringPointsHelper.cs +++ b/OdhApiCore/Controllers/helper/MeasuringPointsHelper.cs @@ -21,42 +21,82 @@ public class MeasuringPointsHelper public bool? active; public bool? smgactive; public string? lastchange; + //New Publishedonlist public List publishedonlist; public static async Task Create( - QueryFactory queryFactory, string? idfilter, string? locfilter, string? areafilter, string? skiareafilter, string? sourcefilter, - bool? activefilter, bool? smgactivefilter, string? lastchange, string? publishedonfilter, - CancellationToken cancellationToken) + QueryFactory queryFactory, + string? idfilter, + string? locfilter, + string? areafilter, + string? skiareafilter, + string? sourcefilter, + bool? activefilter, + bool? smgactivefilter, + string? lastchange, + string? publishedonfilter, + CancellationToken cancellationToken + ) { //TODO SKIAREAFILTER AND AREAFILTER not like on Activity Endpoint! - var arealistfromskiarea = await GenericHelper.RetrieveAreaFilterDataAsync(queryFactory, skiareafilter, cancellationToken); - var arealistfromarea = await GenericHelper.RetrieveAreaFilterDataAsync(queryFactory, areafilter, cancellationToken); + var arealistfromskiarea = await GenericHelper.RetrieveAreaFilterDataAsync( + queryFactory, + skiareafilter, + cancellationToken + ); + var arealistfromarea = await GenericHelper.RetrieveAreaFilterDataAsync( + queryFactory, + areafilter, + cancellationToken + ); IEnumerable? tourismusvereinids = null; if (locfilter != null && locfilter.Contains("mta")) { - List metaregionlist = CommonListCreator.CreateDistrictIdList(locfilter, "mta"); - tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync(queryFactory, metaregionlist, cancellationToken); + List metaregionlist = CommonListCreator.CreateDistrictIdList( + locfilter, + "mta" + ); + tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync( + queryFactory, + metaregionlist, + cancellationToken + ); } return new MeasuringPointsHelper( - idfilter: idfilter, locfilter: locfilter, areafilterlist: arealistfromarea, skiareafilterlist: arealistfromskiarea, sourcefilter: sourcefilter, - activefilter: activefilter, smgactivefilter: smgactivefilter, - lastchange: lastchange, publishedonfilter: publishedonfilter, - tourismusvereinids: tourismusvereinids); + idfilter: idfilter, + locfilter: locfilter, + areafilterlist: arealistfromarea, + skiareafilterlist: arealistfromskiarea, + sourcefilter: sourcefilter, + activefilter: activefilter, + smgactivefilter: smgactivefilter, + lastchange: lastchange, + publishedonfilter: publishedonfilter, + tourismusvereinids: tourismusvereinids + ); } private MeasuringPointsHelper( - string? idfilter, string? locfilter, IEnumerable areafilterlist, IEnumerable skiareafilterlist, string? sourcefilter, - bool? activefilter, bool? smgactivefilter, string? lastchange, string? publishedonfilter, IEnumerable? tourismusvereinids) + string? idfilter, + string? locfilter, + IEnumerable areafilterlist, + IEnumerable skiareafilterlist, + string? sourcefilter, + bool? activefilter, + bool? smgactivefilter, + string? lastchange, + string? publishedonfilter, + IEnumerable? tourismusvereinids + ) { idlist = Helper.CommonListCreator.CreateIdList(idfilter?.ToUpper()); sourcelist = Helper.CommonListCreator.CreateIdList(sourcefilter); - arealist = new List(); if (areafilterlist != null) @@ -90,7 +130,5 @@ private MeasuringPointsHelper( this.lastchange = lastchange; publishedonlist = Helper.CommonListCreator.CreateIdList(publishedonfilter?.ToLower()); } - - } } diff --git a/OdhApiCore/Controllers/helper/MssHelper.cs b/OdhApiCore/Controllers/helper/MssHelper.cs index 3277f8578..9f98ef691 100644 --- a/OdhApiCore/Controllers/helper/MssHelper.cs +++ b/OdhApiCore/Controllers/helper/MssHelper.cs @@ -13,7 +13,7 @@ public class MssHelper public readonly string[] mybokchannels; public readonly List accoidlist; public readonly string idsofchannel; - public readonly List>> myroomdata; + public readonly List>> myroomdata; public readonly XElement xoffertype; public readonly XElement xhoteldetails; public readonly DateTime arrival; @@ -25,23 +25,47 @@ public class MssHelper public readonly string mssversion; public static MssHelper Create( - List accoidlist, string idsofchannel, - string bokfilter, string language, string roominfo, string boardfilter, - string arrival, string departure, int? detail, - string requestsource, string mssversion) + List accoidlist, + string idsofchannel, + string bokfilter, + string language, + string roominfo, + string boardfilter, + string arrival, + string departure, + int? detail, + string requestsource, + string mssversion + ) { return new MssHelper( - accoidlist: accoidlist, idsofchannel: idsofchannel, bokfilter: bokfilter, language: language, - roominfo: roominfo, boardfilter: boardfilter, arrival: arrival, - departure: departure, detail: detail, - requestsource: requestsource, mssversion: mssversion); + accoidlist: accoidlist, + idsofchannel: idsofchannel, + bokfilter: bokfilter, + language: language, + roominfo: roominfo, + boardfilter: boardfilter, + arrival: arrival, + departure: departure, + detail: detail, + requestsource: requestsource, + mssversion: mssversion + ); } private MssHelper( - List accoidlist, string idsofchannel, - string bokfilter, string language, string roominfo, string boardfilter, - string arrival, string departure, int? detail, string requestsource, - string mssversion) + List accoidlist, + string idsofchannel, + string bokfilter, + string language, + string roominfo, + string boardfilter, + string arrival, + string departure, + int? detail, + string requestsource, + string mssversion + ) { if (bokfilter.EndsWith(",")) bokfilter = bokfilter.Substring(0, bokfilter.Length - 1); @@ -78,15 +102,23 @@ private MssHelper( this.requestsource = requestsource; this.mssversion = mssversion; - if (language.ToLower() == "nl" || language.ToLower() == "cs" || language.ToLower() == "pl" || language.ToLower() == "fr" || language.ToLower() == "ru") + if ( + language.ToLower() == "nl" + || language.ToLower() == "cs" + || language.ToLower() == "pl" + || language.ToLower() == "fr" + || language.ToLower() == "ru" + ) mssrequestlanguage = "en"; else mssrequestlanguage = language.ToLower(); - this.accoidlist = accoidlist != null && accoidlist.Count > 0 ? accoidlist.Select(x => x.ToUpper()).ToList() : accoidlist ?? new(); + this.accoidlist = + accoidlist != null && accoidlist.Count > 0 + ? accoidlist.Select(x => x.ToUpper()).ToList() + : accoidlist ?? new(); this.idsofchannel = idsofchannel; } - } } diff --git a/OdhApiCore/Controllers/helper/ODHActivityPoiHelper.cs b/OdhApiCore/Controllers/helper/ODHActivityPoiHelper.cs index 502ff6f7f..986d88588 100644 --- a/OdhApiCore/Controllers/helper/ODHActivityPoiHelper.cs +++ b/OdhApiCore/Controllers/helper/ODHActivityPoiHelper.cs @@ -27,12 +27,14 @@ public class ODHActivityPoiHelper public bool? active; public bool? smgactive; public string? lastchange; + //Gastronomy public List dishcodesids; public List ceremonycodesids; public List categorycodesids; public List facilitycodesids; public List cuisinecodesids; + //Activity public List activitytypelist; public List poitypelist; @@ -50,72 +52,126 @@ public class ODHActivityPoiHelper public string tagfilterbehaviour = ""; public List taglist; - - public IDictionary> tagdict; + + public IDictionary> tagdict; //New Publishedonlist public List publishedonlist; - public static async Task CreateAsync( - QueryFactory queryFactory, - string? typefilter, - string? subtypefilter, - string? level3typefilter, - string? idfilter, + QueryFactory queryFactory, + string? typefilter, + string? subtypefilter, + string? level3typefilter, + string? idfilter, string? locfilter, - string? areafilter, - string? languagefilter, - string? sourcefilter, - bool? highlightfilter, - bool? activefilter, + string? areafilter, + string? languagefilter, + string? sourcefilter, + bool? highlightfilter, + bool? activefilter, bool? smgactivefilter, string? smgtags, string? smgtagsand, string? lastchange, - string? categorycodefilter, string? dishcodefilter, string? ceremonycodefilter, string? facilitycodefilter, string? cuisinecodefilter, - string? activitytypefilter, string? poitypefilter, - string? distancefilter, string? altitudefilter, string? durationfilter, string? difficultyfilter, + string? categorycodefilter, + string? dishcodefilter, + string? ceremonycodefilter, + string? facilitycodefilter, + string? cuisinecodefilter, + string? activitytypefilter, + string? poitypefilter, + string? distancefilter, + string? altitudefilter, + string? durationfilter, + string? difficultyfilter, string? tagfilter, string? publishedonfilter, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { - var arealist = await GenericHelper.RetrieveAreaFilterDataAsync(queryFactory, areafilter, cancellationToken); + var arealist = await GenericHelper.RetrieveAreaFilterDataAsync( + queryFactory, + areafilter, + cancellationToken + ); IEnumerable? tourismusvereinids = null; if (locfilter != null && locfilter.Contains("mta")) { - List metaregionlist = CommonListCreator.CreateDistrictIdList(locfilter, "mta"); - tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync(queryFactory, metaregionlist, cancellationToken); + List metaregionlist = CommonListCreator.CreateDistrictIdList( + locfilter, + "mta" + ); + tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync( + queryFactory, + metaregionlist, + cancellationToken + ); } - return new ODHActivityPoiHelper(typefilter, subtypefilter, level3typefilter, idfilter, locfilter, arealist, languagefilter, sourcefilter, - highlightfilter, activefilter, smgactivefilter, smgtags, smgtagsand, - categorycodefilter, dishcodefilter, ceremonycodefilter, facilitycodefilter, cuisinecodefilter, - activitytypefilter, poitypefilter, distancefilter, altitudefilter, durationfilter, difficultyfilter, - tagfilter, publishedonfilter, - lastchange, tourismusvereinids); + return new ODHActivityPoiHelper( + typefilter, + subtypefilter, + level3typefilter, + idfilter, + locfilter, + arealist, + languagefilter, + sourcefilter, + highlightfilter, + activefilter, + smgactivefilter, + smgtags, + smgtagsand, + categorycodefilter, + dishcodefilter, + ceremonycodefilter, + facilitycodefilter, + cuisinecodefilter, + activitytypefilter, + poitypefilter, + distancefilter, + altitudefilter, + durationfilter, + difficultyfilter, + tagfilter, + publishedonfilter, + lastchange, + tourismusvereinids + ); } private ODHActivityPoiHelper( - string? typefilter, - string? subtypefilter, - string? level3typefilter, - string? idfilter, - string? locfilter, - IEnumerable arealist, - string? languagefilter, + string? typefilter, + string? subtypefilter, + string? level3typefilter, + string? idfilter, + string? locfilter, + IEnumerable arealist, + string? languagefilter, string? sourcefilter, - bool? highlightfilter, - bool? activefilter, - bool? smgactivefilter, + bool? highlightfilter, + bool? activefilter, + bool? smgactivefilter, string? smgtags, string? smgtagsand, - string? categorycodefilter, string? dishcodefilter, string? ceremonycodefilter, string? facilitycodefilter, string? cuisinecodefilter, - string? activitytypefilter, string? poitypefilter, string? distancefilter, string? altitudefilter, string? durationfilter, string? difficultyfilter, - string? tagfilter, string? publishedonfilter, - string? lastchange, - IEnumerable? tourismusvereinids) + string? categorycodefilter, + string? dishcodefilter, + string? ceremonycodefilter, + string? facilitycodefilter, + string? cuisinecodefilter, + string? activitytypefilter, + string? poitypefilter, + string? distancefilter, + string? altitudefilter, + string? durationfilter, + string? difficultyfilter, + string? tagfilter, + string? publishedonfilter, + string? lastchange, + IEnumerable? tourismusvereinids + ) { typelist = new(); @@ -125,7 +181,9 @@ private ODHActivityPoiHelper( { //Sonderfall wenn alles abgefragt wird um keine unnötige Where zu erzeugen if (typeinteger != 255) - typelist = Helper.ActivityPoiListCreator.CreateSmgPoiTypefromFlag(typefilter); + typelist = Helper.ActivityPoiListCreator.CreateSmgPoiTypefromFlag( + typefilter + ); } else { @@ -139,16 +197,20 @@ private ODHActivityPoiHelper( } if (typelist.Count > 0) - subtypelist = Helper.ActivityPoiListCreator.CreateSmgPoiSubTypefromFlag(typelist.FirstOrDefault(), subtypefilter); + subtypelist = Helper.ActivityPoiListCreator.CreateSmgPoiSubTypefromFlag( + typelist.FirstOrDefault(), + subtypefilter + ); else subtypelist = new(); if (subtypelist.Count > 0) - level3typelist = Helper.ActivityPoiListCreator.CreateSmgPoiPoiTypefromFlag(subtypelist.FirstOrDefault(), level3typefilter); + level3typelist = Helper.ActivityPoiListCreator.CreateSmgPoiPoiTypefromFlag( + subtypelist.FirstOrDefault(), + level3typefilter + ); else level3typelist = new(); - - idlist = Helper.CommonListCreator.CreateIdList(idfilter?.ToUpper()); var sourcelisttemp = Helper.CommonListCreator.CreateSmgPoiSourceList(sourcefilter); @@ -188,10 +250,18 @@ private ODHActivityPoiHelper( //Using Gastronomy Filters dishcodesids = GastronomyListCreator.CreateGastroDishCodeListfromFlag(dishcodefilter); - ceremonycodesids = GastronomyListCreator.CreateGastroCeremonyCodeListfromFlag(ceremonycodefilter); - categorycodesids = GastronomyListCreator.CreateGastroCategoryCodeListfromFlag(categorycodefilter); - facilitycodesids = GastronomyListCreator.CreateGastroFacilityCodeListfromFlag(facilitycodefilter); - cuisinecodesids = GastronomyListCreator.CreateGastroCusineCodeListfromFlag(cuisinecodefilter); + ceremonycodesids = GastronomyListCreator.CreateGastroCeremonyCodeListfromFlag( + ceremonycodefilter + ); + categorycodesids = GastronomyListCreator.CreateGastroCategoryCodeListfromFlag( + categorycodefilter + ); + facilitycodesids = GastronomyListCreator.CreateGastroFacilityCodeListfromFlag( + facilitycodefilter + ); + cuisinecodesids = GastronomyListCreator.CreateGastroCusineCodeListfromFlag( + cuisinecodefilter + ); facilitycodesids.AddRange(cuisinecodesids); //using Activity Filters @@ -204,7 +274,9 @@ private ODHActivityPoiHelper( if (int.TryParse(activitytypefilter, out int typeintegeractivity)) { if (typeintegeractivity != 1023) - activitytypelist = Helper.ActivityPoiListCreator.CreateActivityTypefromFlag(activitytypefilter); + activitytypelist = Helper.ActivityPoiListCreator.CreateActivityTypefromFlag( + activitytypefilter + ); } else { @@ -214,7 +286,10 @@ private ODHActivityPoiHelper( //ODHActivityPoi Typelist has priority if (typelist.Count == 0 && poitypelist.Count == 0 && activitytypelist.Count > 0) - subtypelist = Helper.ActivityPoiListCreator.CreateActivitySubTypefromFlag(activitytypelist.FirstOrDefault(), subtypefilter); + subtypelist = Helper.ActivityPoiListCreator.CreateActivitySubTypefromFlag( + activitytypelist.FirstOrDefault(), + subtypefilter + ); //using Poi Filters poitypelist = new(); @@ -223,7 +298,9 @@ private ODHActivityPoiHelper( if (int.TryParse(poitypefilter, out int typeintegerpoi)) { if (typeintegerpoi != 511) - poitypelist = Helper.ActivityPoiListCreator.CreatePoiTypefromFlag(poitypefilter); + poitypelist = Helper.ActivityPoiListCreator.CreatePoiTypefromFlag( + poitypefilter + ); } else { @@ -233,9 +310,15 @@ private ODHActivityPoiHelper( //ODHActivityPoi Typelist has priority if (typelist.Count == 0 && activitytypelist.Count == 0 && poitypelist.Count > 0) - subtypelist = Helper.ActivityPoiListCreator.CreatePoiSubTypefromFlag(poitypelist.FirstOrDefault(), subtypefilter); - - difficultylist = CommonListCreator.CreateDifficultyList(difficultyfilter, activitytypefilter); + subtypelist = Helper.ActivityPoiListCreator.CreatePoiSubTypefromFlag( + poitypelist.FirstOrDefault(), + subtypefilter + ); + + difficultylist = CommonListCreator.CreateDifficultyList( + difficultyfilter, + activitytypefilter + ); //Distance distance = distancefilter != null; if (distance) @@ -255,7 +338,6 @@ private ODHActivityPoiHelper( if (duration) (durationmin, durationmax) = CommonListCreator.CreateRangeString(durationfilter); - publishedonlist = Helper.CommonListCreator.CreateIdList(publishedonfilter?.ToLower()); if (!String.IsNullOrEmpty(tagfilter)) @@ -280,7 +362,7 @@ private List ExtendSourceFilterODHActivityPois(List sourcelist) { List sourcelistnew = new(); - foreach(var source in sourcelist) + foreach (var source in sourcelist) { sourcelistnew.Add(source); @@ -291,9 +373,9 @@ private List ExtendSourceFilterODHActivityPois(List sourcelist) if (!sourcelistnew.Contains("magnolia")) sourcelistnew.Add("magnolia"); if (!sourcelistnew.Contains("common")) - sourcelistnew.Add("common"); + sourcelistnew.Add("common"); } - else if(source == "lts") + else if (source == "lts") { if (!sourcelistnew.Contains("activitydata")) sourcelistnew.Add("activitydata"); @@ -306,7 +388,7 @@ private List ExtendSourceFilterODHActivityPois(List sourcelist) if (!sourcelistnew.Contains("beacondata")) sourcelistnew.Add("beacondata"); } - else if(source == "siag") + else if (source == "siag") { if (!sourcelistnew.Contains("museumdata")) sourcelistnew.Add("museumdata"); @@ -323,5 +405,4 @@ private List ExtendSourceFilterODHActivityPois(List sourcelist) return sourcelistnew; } } - } diff --git a/OdhApiCore/Controllers/helper/PoiHelper.cs b/OdhApiCore/Controllers/helper/PoiHelper.cs index 2df1056e1..4b4e91dbb 100644 --- a/OdhApiCore/Controllers/helper/PoiHelper.cs +++ b/OdhApiCore/Controllers/helper/PoiHelper.cs @@ -24,26 +24,71 @@ public class PoiHelper public string? lastchange; public static async Task CreateAsync( - QueryFactory queryFactory, string? poitype, string? subtypefilter, string? idfilter, string? locfilter, - string? areafilter, bool? highlightfilter, bool? activefilter, bool? smgactivefilter, - string? smgtags, string? lastchange, string? langfilter, CancellationToken cancellationToken) + QueryFactory queryFactory, + string? poitype, + string? subtypefilter, + string? idfilter, + string? locfilter, + string? areafilter, + bool? highlightfilter, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? lastchange, + string? langfilter, + CancellationToken cancellationToken + ) { - var arealist = await GenericHelper.RetrieveAreaFilterDataAsync(queryFactory, areafilter, cancellationToken); + var arealist = await GenericHelper.RetrieveAreaFilterDataAsync( + queryFactory, + areafilter, + cancellationToken + ); IEnumerable? tourismusvereinids = null; if (locfilter != null && locfilter.Contains("mta")) { - List metaregionlist = CommonListCreator.CreateDistrictIdList(locfilter, "mta"); - tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync(queryFactory, metaregionlist, cancellationToken); + List metaregionlist = CommonListCreator.CreateDistrictIdList( + locfilter, + "mta" + ); + tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync( + queryFactory, + metaregionlist, + cancellationToken + ); } return new PoiHelper( - poitype, subtypefilter, idfilter, locfilter, arealist, highlightfilter, activefilter, smgactivefilter, smgtags, lastchange, langfilter, tourismusvereinids); + poitype, + subtypefilter, + idfilter, + locfilter, + arealist, + highlightfilter, + activefilter, + smgactivefilter, + smgtags, + lastchange, + langfilter, + tourismusvereinids + ); } private PoiHelper( - string? poitype, string? subtypefilter, string? idfilter, string? locfilter, IEnumerable arealist, - bool? highlightfilter, bool? activefilter, bool? smgactivefilter, string? smgtags, string? lastchange, string? languagefilter, IEnumerable? tourismusvereinids) + string? poitype, + string? subtypefilter, + string? idfilter, + string? locfilter, + IEnumerable arealist, + bool? highlightfilter, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? lastchange, + string? languagefilter, + IEnumerable? tourismusvereinids + ) { poitypelist = new List(); if (poitype != null) @@ -61,11 +106,13 @@ private PoiHelper( } if (poitypelist.Count > 0) - subtypelist = Helper.ActivityPoiListCreator.CreatePoiSubTypefromFlag(poitypelist.FirstOrDefault(), subtypefilter); + subtypelist = Helper.ActivityPoiListCreator.CreatePoiSubTypefromFlag( + poitypelist.FirstOrDefault(), + subtypefilter + ); else subtypelist = new List(); - idlist = Helper.CommonListCreator.CreateIdList(idfilter?.ToUpper()); languagelist = Helper.CommonListCreator.CreateIdList(languagefilter); diff --git a/OdhApiCore/Controllers/helper/VenueHelper.cs b/OdhApiCore/Controllers/helper/VenueHelper.cs index 5b82e85dc..133cfa9a0 100644 --- a/OdhApiCore/Controllers/helper/VenueHelper.cs +++ b/OdhApiCore/Controllers/helper/VenueHelper.cs @@ -24,7 +24,7 @@ public class VenueHelper public bool? active; public bool? smgactive; public string? lastchange; - + public bool capacity; public int capacitymin; public int capacitymax; @@ -32,38 +32,88 @@ public class VenueHelper public bool roomcount; public int roomcountmin; public int roomcountmax; + //New Publishedonlist public List publishedonlist; public static async Task CreateAsync( - QueryFactory queryFactory, string? idfilter, string? categoryfilter, string? featurefilter, string? setuptypefilter, string? locfilter, - string? capacityfilter, string? roomcountfilter, string? languagefilter, string? sourcefilter, bool? activefilter, bool? smgactivefilter, - string? odhtags, string? lastchange, string? publishedonfilter, CancellationToken cancellationToken) + QueryFactory queryFactory, + string? idfilter, + string? categoryfilter, + string? featurefilter, + string? setuptypefilter, + string? locfilter, + string? capacityfilter, + string? roomcountfilter, + string? languagefilter, + string? sourcefilter, + bool? activefilter, + bool? smgactivefilter, + string? odhtags, + string? lastchange, + string? publishedonfilter, + CancellationToken cancellationToken + ) { IEnumerable? tourismusvereinids = null; if (locfilter != null && locfilter.Contains("mta")) { - List metaregionlist = CommonListCreator.CreateDistrictIdList(locfilter, "mta"); - tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync(queryFactory, metaregionlist, cancellationToken); + List metaregionlist = CommonListCreator.CreateDistrictIdList( + locfilter, + "mta" + ); + tourismusvereinids = await GenericHelper.RetrieveLocFilterDataAsync( + queryFactory, + metaregionlist, + cancellationToken + ); } - return new VenueHelper(idfilter, categoryfilter, featurefilter, setuptypefilter, locfilter, capacityfilter, roomcountfilter, - languagefilter, sourcefilter, activefilter, smgactivefilter, odhtags, lastchange, publishedonfilter, tourismusvereinids); + return new VenueHelper( + idfilter, + categoryfilter, + featurefilter, + setuptypefilter, + locfilter, + capacityfilter, + roomcountfilter, + languagefilter, + sourcefilter, + activefilter, + smgactivefilter, + odhtags, + lastchange, + publishedonfilter, + tourismusvereinids + ); } private VenueHelper( - string? idfilter, string? categoryfilter, string? featurefilter, string? setuptypefilter, string? locfilter, - string? capacityfilter, string? roomcountfilter, string? languagefilter, string? sourcefilter, - bool? activefilter, bool? smgactivefilter, string? odhtags, string? lastchange, string? publishedonfilter, IEnumerable? tourismusvereinids) + string? idfilter, + string? categoryfilter, + string? featurefilter, + string? setuptypefilter, + string? locfilter, + string? capacityfilter, + string? roomcountfilter, + string? languagefilter, + string? sourcefilter, + bool? activefilter, + bool? smgactivefilter, + string? odhtags, + string? lastchange, + string? publishedonfilter, + IEnumerable? tourismusvereinids + ) { - sourcelist = Helper.CommonListCreator.CreateSmgPoiSourceList(sourcefilter); - setuptypelist = Helper.VenueListCreator.CreateVenueSeatTypeListfromFlag(setuptypefilter); + setuptypelist = Helper.VenueListCreator.CreateVenueSeatTypeListfromFlag( + setuptypefilter + ); featurelist = Helper.VenueListCreator.CreateVenueFeatureListfromFlag(featurefilter); categorylist = Helper.VenueListCreator.CreateVenueCategoryListfromFlag(categoryfilter); - idlist = Helper.CommonListCreator.CreateIdList(idfilter?.ToUpper()); sourcelist = Helper.CommonListCreator.CreateSmgPoiSourceList(sourcefilter); languagelist = Helper.CommonListCreator.CreateIdList(languagefilter); @@ -87,10 +137,9 @@ private VenueHelper( if (tourismusvereinids != null) tourismvereinlist.AddRange(tourismusvereinids); - //Capacity capacity = capacityfilter != null; - if(capacity) + if (capacity) (capacitymin, capacitymax) = CommonListCreator.CreateRangeString(capacityfilter); //Altitude diff --git a/OdhApiCore/Controllers/helper/WeatherHelper.cs b/OdhApiCore/Controllers/helper/WeatherHelper.cs index ddcc2b8a4..69432a107 100644 --- a/OdhApiCore/Controllers/helper/WeatherHelper.cs +++ b/OdhApiCore/Controllers/helper/WeatherHelper.cs @@ -19,16 +19,37 @@ public class WeatherHelper public DateTime? dateto; public static Task CreateAsync( - QueryFactory queryFactory, string? idfilter, string? locfilter, string? languagefilter, string? datefrom, string? dateto, string? lastchange, - CancellationToken cancellationToken) - { - return Task.FromResult(new WeatherHelper( - idfilter: idfilter, languagefilter: languagefilter, locfilter: locfilter, datefromstr: datefrom, datetostr: dateto, lastchange: lastchange)); + QueryFactory queryFactory, + string? idfilter, + string? locfilter, + string? languagefilter, + string? datefrom, + string? dateto, + string? lastchange, + CancellationToken cancellationToken + ) + { + return Task.FromResult( + new WeatherHelper( + idfilter: idfilter, + languagefilter: languagefilter, + locfilter: locfilter, + datefromstr: datefrom, + datetostr: dateto, + lastchange: lastchange + ) + ); } private WeatherHelper( - string? idfilter, string? languagefilter, string? locfilter, string? datefromstr, string? datetostr, string? lastchange) - { + string? idfilter, + string? languagefilter, + string? locfilter, + string? datefromstr, + string? datetostr, + string? lastchange + ) + { idlist = Helper.CommonListCreator.CreateIdList(idfilter?.ToUpper()); languagelist = Helper.CommonListCreator.CreateIdList(languagefilter?.ToLower()); @@ -43,7 +64,5 @@ private WeatherHelper( if (datetostr != "null") dateto = Convert.ToDateTime(datetostr); } - - } } diff --git a/OdhApiCore/Controllers/helper/WebcamInfoHelper.cs b/OdhApiCore/Controllers/helper/WebcamInfoHelper.cs index 308d69656..8d3483cb0 100644 --- a/OdhApiCore/Controllers/helper/WebcamInfoHelper.cs +++ b/OdhApiCore/Controllers/helper/WebcamInfoHelper.cs @@ -15,25 +15,41 @@ public class WebcamInfoHelper public bool? active; public bool? smgactive; public string? lastchange; + //New Publishedonlist public List publishedonlist; public static WebcamInfoHelper Create( string? sourcefilter, - string? idfilter, bool? activefilter, bool? smgactivefilter, string? lastchange, string? publishedonfilter) + string? idfilter, + bool? activefilter, + bool? smgactivefilter, + string? lastchange, + string? publishedonfilter + ) { return new WebcamInfoHelper( - idfilter: idfilter, sourcefilter: sourcefilter, - activefilter: activefilter, smgactivefilter: smgactivefilter, - lastchange: lastchange, publishedonfilter: publishedonfilter); + idfilter: idfilter, + sourcefilter: sourcefilter, + activefilter: activefilter, + smgactivefilter: smgactivefilter, + lastchange: lastchange, + publishedonfilter: publishedonfilter + ); } private WebcamInfoHelper( - string? sourcefilter, string? idfilter, bool? activefilter, bool? smgactivefilter, string? lastchange, string? publishedonfilter) + string? sourcefilter, + string? idfilter, + bool? activefilter, + bool? smgactivefilter, + string? lastchange, + string? publishedonfilter + ) { idlist = Helper.CommonListCreator.CreateIdList(idfilter?.ToUpper()); var sourcelisttemp = Helper.CommonListCreator.CreateIdList(sourcefilter?.ToLower()); - + sourcelist = ExtendSourceFilterWebcamInfo(sourcelisttemp); //active @@ -58,8 +74,8 @@ private List ExtendSourceFilterWebcamInfo(List sourcelist) if (source == "idm") { if (!sourcelistnew.Contains("content")) - sourcelistnew.Add("content"); - } + sourcelistnew.Add("content"); + } } return sourcelistnew; diff --git a/OdhApiCore/Controllers/helper/WineHelper.cs b/OdhApiCore/Controllers/helper/WineHelper.cs index ab7c7b346..5fd99f5fa 100644 --- a/OdhApiCore/Controllers/helper/WineHelper.cs +++ b/OdhApiCore/Controllers/helper/WineHelper.cs @@ -23,18 +23,49 @@ public class WineHelper public bool? smgactive; public static Task CreateAsync( - QueryFactory queryFactory, string? idfilter, string? companyidfilter, string? wineidfilter, string? languagefilter, bool? visibleinsearch, string? sourcefilter, - bool? activefilter, bool? smgactivefilter, string? smgtags, string? lastchange, - CancellationToken cancellationToken) - { - return Task.FromResult(new WineHelper( - idfilter: idfilter, languagefilter: languagefilter, companyidfilter: companyidfilter, wineidfilter: wineidfilter, - activefilter: activefilter, smgactivefilter: smgactivefilter, visibleinsearch: visibleinsearch, sourcefilter: sourcefilter, smgtags: smgtags, lastchange: lastchange)); + QueryFactory queryFactory, + string? idfilter, + string? companyidfilter, + string? wineidfilter, + string? languagefilter, + bool? visibleinsearch, + string? sourcefilter, + bool? activefilter, + bool? smgactivefilter, + string? smgtags, + string? lastchange, + CancellationToken cancellationToken + ) + { + return Task.FromResult( + new WineHelper( + idfilter: idfilter, + languagefilter: languagefilter, + companyidfilter: companyidfilter, + wineidfilter: wineidfilter, + activefilter: activefilter, + smgactivefilter: smgactivefilter, + visibleinsearch: visibleinsearch, + sourcefilter: sourcefilter, + smgtags: smgtags, + lastchange: lastchange + ) + ); } private WineHelper( - string? idfilter, string? languagefilter, string? companyidfilter, string? wineidfilter, bool? activefilter, bool? smgactivefilter, bool? visibleinsearch, string? sourcefilter, string? smgtags, string? lastchange) - { + string? idfilter, + string? languagefilter, + string? companyidfilter, + string? wineidfilter, + bool? activefilter, + bool? smgactivefilter, + bool? visibleinsearch, + string? sourcefilter, + string? smgtags, + string? lastchange + ) + { idlist = Helper.CommonListCreator.CreateIdList(idfilter?.ToUpper()); companyidlist = Helper.CommonListCreator.CreateIdList(companyidfilter?.ToLower()); wineidlist = Helper.CommonListCreator.CreateIdList(wineidfilter?.ToLower()); @@ -54,7 +85,5 @@ private WineHelper( this.lastchange = lastchange; } - - } } diff --git a/OdhApiCore/Controllers/other/CompatiblityApiController.cs b/OdhApiCore/Controllers/other/CompatiblityApiController.cs index 9def3d0df..f9f529fc6 100644 --- a/OdhApiCore/Controllers/other/CompatiblityApiController.cs +++ b/OdhApiCore/Controllers/other/CompatiblityApiController.cs @@ -28,10 +28,12 @@ namespace OdhApiCore.Controllers.api [NullStringParameterActionFilter] public class CompatiblityApiController : OdhController { - public CompatiblityApiController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + public CompatiblityApiController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } #region PoiController @@ -46,13 +48,13 @@ public CompatiblityApiController(IWebHostEnvironment env, ISettings settings, IL /// Locfilter (Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMASSOCIATIONID = (Filter by Tourismassociation), 'null' = No Filter), (default:'null') /// AreaFilter (Alternate Locfilter, can be combined with locfilter) (Separator ',' possible values: reg + REGIONID = (Filter by Region), tvs + TOURISMASSOCIATIONID = (Filter by Tourismassociation), skr + SKIREGIONID = (Filter by Skiregion), ska + SKIAREAID = (Filter by Skiarea), are + AREAID = (Filter by LTS Area), 'null' = No Filter), (default:'null') /// Hightlight Filter (possible values: 'false' = only Pois with Highlight false, 'true' = only Pois with Highlight true), (default:'null') - /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=poi'), (default:'null') + /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=poi'), (default:'null') /// Active Pois Filter (possible Values: 'true' only Active Pois, 'false' only Disabled Pois - /// ODH Active (Published) Pois Filter (Refers to field SmgActive) Pois Filter (possible Values: 'true' only published Pois, 'false' only not published Pois, (default:'null') + /// ODH Active (Published) Pois Filter (Refers to field SmgActive) Pois Filter (possible Values: 'true' only published Pois, 'false' only not published Pois, (default:'null') /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// Collection of Poi Reduced Objects + /// Collection of Poi Reduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -71,32 +73,47 @@ public async Task GetPoiReduced( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { //TODO //CheckOpenData(User); - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); return await GetPoiReduced( - language?.ToLower(), poitype, subtype, locfilter, areafilter, - highlight, active, odhactive, odhtagfilter, - fields: fields ?? Array.Empty(), rawfilter, rawsort, searchfilter, - geosearchresult, cancellationToken); + language?.ToLower(), + poitype, + subtype, + locfilter, + areafilter, + highlight, + active, + odhactive, + odhtagfilter, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + searchfilter, + geosearchresult, + cancellationToken + ); } - /// /// GET Reduced POI List /// /// Localization Language /// Type of the Poi (possible values: STRINGS: 'Ärtze, Apotheken','Geschäfte und Dienstleister','Kultur und Sehenswürdigkeiten','Nachtleben und Unterhaltung','Öffentliche Einrichtungen','Sport und Freizeit','Verkehr und Transport' : BITMASK also possible: 'Ärtze, Apotheken = 1','Geschäfte und Dienstleister = 2','Kultur und Sehenswürdigkeiten = 4','Nachtleben und Unterhaltung = 8','Öffentliche Einrichtungen = 16','Sport und Freizeit = 32','Verkehr und Transport = 64') - /// Subtype of the Poi ('null' = Filter disabled, available Subtypes depends on the activitytype BITMASK) + /// Subtype of the Poi ('null' = Filter disabled, available Subtypes depends on the activitytype BITMASK) /// Locfilter (Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), 'null' = No Filter) /// AreaFilter (Separator ',' IDList of AreaIDs separated by ',', 'null' : Filter disabled) /// Highlight Filter (Show only Highlights possible values: 'true' : show only Highlight Pois, 'null' Filter disabled) @@ -105,41 +122,90 @@ public async Task GetPoiReduced( /// SMGTag Filter (String, Separator ',' more SMGTags possible, 'null' = No Filter) /// Collection of Reduced Poi Objects private Task GetPoiReduced( - string? language, string? poitype, string? subtypefilter, string? locfilter, - string? areafilter, bool? highlightfilter, bool? active, bool? smgactive, - string? smgtags, string[] fields, string? rawfilter, string? rawsort, string? searchfilter, - PGGeoSearchResult geosearchresult, CancellationToken cancellationToken) + string? language, + string? poitype, + string? subtypefilter, + string? locfilter, + string? areafilter, + bool? highlightfilter, + bool? active, + bool? smgactive, + string? smgtags, + string[] fields, + string? rawfilter, + string? rawsort, + string? searchfilter, + PGGeoSearchResult geosearchresult, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { PoiHelper mypoihelper = await PoiHelper.CreateAsync( - QueryFactory, poitype: poitype, subtypefilter: subtypefilter, idfilter: null, locfilter: locfilter, areafilter: areafilter, - highlightfilter: highlightfilter, activefilter: active, smgactivefilter: smgactive, smgtags: smgtags, lastchange: null, langfilter: language, cancellationToken); - - string select = $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Detail,{language},Title\\}}' as \"Name\""; + QueryFactory, + poitype: poitype, + subtypefilter: subtypefilter, + idfilter: null, + locfilter: locfilter, + areafilter: areafilter, + highlightfilter: highlightfilter, + activefilter: active, + smgactivefilter: smgactive, + smgtags: smgtags, + lastchange: null, + langfilter: language, + cancellationToken + ); + + string select = + $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Detail,{language},Title\\}}' as \"Name\""; //Custom Fields filter if (fields.Length > 0) - select += string.Join("", fields.Where(x => x != "Id").Select(field => $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"")); + select += string.Join( + "", + fields + .Where(x => x != "Id") + .Select( + field => + $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"" + ) + ); - var query = - (XQuery)QueryFactory.Query() - .SelectRaw(select) + var query = (XQuery) + QueryFactory + .Query() + .SelectRaw(select) .From("pois") .PoiWhereExpression( - idlist: mypoihelper.idlist, poitypelist: mypoihelper.poitypelist, subtypelist: mypoihelper.subtypelist, - smgtaglist: mypoihelper.smgtaglist, districtlist: new List(), municipalitylist: new List(), - tourismvereinlist: mypoihelper.tourismvereinlist, regionlist: mypoihelper.regionlist, - arealist: mypoihelper.arealist, highlight: mypoihelper.highlight, activefilter: mypoihelper.active, - smgactivefilter: mypoihelper.smgactive, searchfilter: searchfilter, language: language, lastchange: null, languagelist: new List(), - filterClosedData: FilterClosedData, reducedData: ReducedData + idlist: mypoihelper.idlist, + poitypelist: mypoihelper.poitypelist, + subtypelist: mypoihelper.subtypelist, + smgtaglist: mypoihelper.smgtaglist, + districtlist: new List(), + municipalitylist: new List(), + tourismvereinlist: mypoihelper.tourismvereinlist, + regionlist: mypoihelper.regionlist, + arealist: mypoihelper.arealist, + highlight: mypoihelper.highlight, + activefilter: mypoihelper.active, + smgactivefilter: mypoihelper.smgactive, + searchfilter: searchfilter, + language: language, + lastchange: null, + languagelist: new List(), + filterClosedData: FilterClosedData, + reducedData: ReducedData ) .ApplyRawFilter(rawfilter) .ApplyOrdering_GeneratedColumns(geosearchresult, rawsort); var compiled = query.Compiler.Compile(query); - var reader = await query.Connection.ExecuteReaderAsync(compiled.Sql, compiled.NamedBindings); + var reader = await query.Connection.ExecuteReaderAsync( + compiled.Sql, + compiled.NamedBindings + ); return reader.ReadAndParseTOJson(); }); @@ -154,22 +220,26 @@ public RedirectToActionResult GetAllPoisChanged( string? seed = null, string? updatefrom = null, CancellationToken cancellationToken = default - ) + ) { updatefrom ??= String.Format("{0:yyyy-MM-dd}", DateTime.Now.AddDays(-1)); - return RedirectToAction("Poi", "v1", new RouteValueDictionary - { - {"pagenumber", pagenumber}, - {"pagesize", pagesize}, - {"seed", seed}, - {"updatefrom", updatefrom} - }); + return RedirectToAction( + "Poi", + "v1", + new RouteValueDictionary + { + { "pagenumber", pagenumber }, + { "pagesize", pagesize }, + { "seed", seed }, + { "updatefrom", updatefrom } + } + ); } #endregion - #region ActivityController + #region ActivityController /// /// GET Activity List Reduced @@ -183,14 +253,14 @@ public RedirectToActionResult GetAllPoisChanged( /// Altitude Range Filter (Separator ',' example Value: 500,1000 Altitude from 500 up to 1000 metres), (default:'null') /// Duration Range Filter (Separator ',' example Value: 1,3 Duration from 1 to 3 hours), (default:'null') /// Hightlight Filter (possible values: 'false' = only Activities with Highlight false, 'true' = only Activities with Highlight true), (default:'null') - /// Difficulty Filter (possible values: '1' = easy, '2' = medium, '3' = difficult), (default:'null') - /// Taglist Filter (String, Separator ',' more Tags possible, available Tags reference to 'api/SmgTag/ByMainEntity/Activity'), (default:'null') + /// Difficulty Filter (possible values: '1' = easy, '2' = medium, '3' = difficult), (default:'null') + /// Taglist Filter (String, Separator ',' more Tags possible, available Tags reference to 'api/SmgTag/ByMainEntity/Activity'), (default:'null') /// Active Activities Filter (possible Values: 'true' only Active Activities, 'false' only Disabled Activities - /// odhactive (Published) Activities Filter (possible Values: 'true' only published Activities, 'false' only not published Activities, (default:'null') + /// odhactive (Published) Activities Filter (possible Values: 'true' only published Activities, 'false' only not published Activities, (default:'null') /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// Collection of Activity Reduced Objects + /// Collection of Activity Reduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -213,74 +283,150 @@ public async Task GetActivityReduced( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); return await GetActivityReduced( - language?.ToLower(), activitytype, subtype, locfilter, areafilter, distancefilter, altitudefilter, durationfilter, - highlight, difficultyfilter, active, odhactive, odhtagfilter, - fields: fields ?? Array.Empty(), rawfilter, rawsort, searchfilter, - geosearchresult, cancellationToken); + language?.ToLower(), + activitytype, + subtype, + locfilter, + areafilter, + distancefilter, + altitudefilter, + durationfilter, + highlight, + difficultyfilter, + active, + odhactive, + odhtagfilter, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + searchfilter, + geosearchresult, + cancellationToken + ); } private Task GetActivityReduced( - string? language, string? activitytype, string? subtypefilter, string? locfilter, string? areafilter, - string? distancefilter, string? altitudefilter, string? durationfilter, bool? highlightfilter, - string? difficultyfilter, bool? active, bool? smgactive, string? smgtags, - string[] fields, string? rawfilter, string? rawsort, string? searchfilter, - PGGeoSearchResult geosearchresult, CancellationToken cancellationToken) + string? language, + string? activitytype, + string? subtypefilter, + string? locfilter, + string? areafilter, + string? distancefilter, + string? altitudefilter, + string? durationfilter, + bool? highlightfilter, + string? difficultyfilter, + bool? active, + bool? smgactive, + string? smgtags, + string[] fields, + string? rawfilter, + string? rawsort, + string? searchfilter, + PGGeoSearchResult geosearchresult, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { ActivityHelper myactivityhelper = await ActivityHelper.CreateAsync( - QueryFactory, activitytype: activitytype, subtypefilter: subtypefilter, idfilter: null, - locfilter: locfilter, areafilter: areafilter, distancefilter: distancefilter, - altitudefilter: altitudefilter, durationfilter: durationfilter, highlightfilter: highlightfilter, - difficultyfilter: difficultyfilter, activefilter: active, smgactivefilter: smgactive, - smgtags: smgtags, lastchange: null, langfilter: language, cancellationToken: cancellationToken); - - string select = $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Detail,{language},Title\\}}' as \"Name\""; + QueryFactory, + activitytype: activitytype, + subtypefilter: subtypefilter, + idfilter: null, + locfilter: locfilter, + areafilter: areafilter, + distancefilter: distancefilter, + altitudefilter: altitudefilter, + durationfilter: durationfilter, + highlightfilter: highlightfilter, + difficultyfilter: difficultyfilter, + activefilter: active, + smgactivefilter: smgactive, + smgtags: smgtags, + lastchange: null, + langfilter: language, + cancellationToken: cancellationToken + ); + + string select = + $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Detail,{language},Title\\}}' as \"Name\""; //Custom Fields filter if (fields.Length > 0) - select += string.Join("", fields.Where(x => x != "Id").Select(field => $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"")); + select += string.Join( + "", + fields + .Where(x => x != "Id") + .Select( + field => + $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"" + ) + ); - var query = - (XQuery)QueryFactory.Query() + var query = (XQuery) + QueryFactory + .Query() .SelectRaw(select) .From("activities") .ActivityWhereExpression( - idlist: myactivityhelper.idlist, activitytypelist: myactivityhelper.activitytypelist, - subtypelist: myactivityhelper.subtypelist, difficultylist: myactivityhelper.difficultylist, - smgtaglist: myactivityhelper.smgtaglist, districtlist: new List(), - municipalitylist: new List(), tourismvereinlist: myactivityhelper.tourismvereinlist, - regionlist: myactivityhelper.regionlist, arealist: myactivityhelper.arealist, - distance: myactivityhelper.distance, distancemin: myactivityhelper.distancemin, - distancemax: myactivityhelper.distancemax, duration: myactivityhelper.duration, - durationmin: myactivityhelper.durationmin, durationmax: myactivityhelper.durationmax, - altitude: myactivityhelper.altitude, altitudemin: myactivityhelper.altitudemin, - altitudemax: myactivityhelper.altitudemax, highlight: myactivityhelper.highlight, - activefilter: myactivityhelper.active, smgactivefilter: myactivityhelper.smgactive, - searchfilter: null, language: language, lastchange: null, languagelist: new List(), - filterClosedData: FilterClosedData, reducedData: ReducedData) + idlist: myactivityhelper.idlist, + activitytypelist: myactivityhelper.activitytypelist, + subtypelist: myactivityhelper.subtypelist, + difficultylist: myactivityhelper.difficultylist, + smgtaglist: myactivityhelper.smgtaglist, + districtlist: new List(), + municipalitylist: new List(), + tourismvereinlist: myactivityhelper.tourismvereinlist, + regionlist: myactivityhelper.regionlist, + arealist: myactivityhelper.arealist, + distance: myactivityhelper.distance, + distancemin: myactivityhelper.distancemin, + distancemax: myactivityhelper.distancemax, + duration: myactivityhelper.duration, + durationmin: myactivityhelper.durationmin, + durationmax: myactivityhelper.durationmax, + altitude: myactivityhelper.altitude, + altitudemin: myactivityhelper.altitudemin, + altitudemax: myactivityhelper.altitudemax, + highlight: myactivityhelper.highlight, + activefilter: myactivityhelper.active, + smgactivefilter: myactivityhelper.smgactive, + searchfilter: null, + language: language, + lastchange: null, + languagelist: new List(), + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) .ApplyRawFilter(rawfilter) .ApplyOrdering_GeneratedColumns(geosearchresult, rawsort); var compiled = query.Compiler.Compile(query); - var reader = await query.Connection.ExecuteReaderAsync(compiled.Sql, compiled.NamedBindings); + var reader = await query.Connection.ExecuteReaderAsync( + compiled.Sql, + compiled.NamedBindings + ); return reader.ReadAndParseTOJson(); }); } - [Obsolete("Deprecated, use the Activity Endpoint")] [ApiExplorerSettings(IgnoreApi = true)] [HttpGet, Route("ActivityChanged")] @@ -289,17 +435,21 @@ public RedirectToActionResult GetAllActivityChanged( uint pagesize = 10, string? seed = null, string? updatefrom = null - ) + ) { updatefrom ??= String.Format("{0:yyyy-MM-dd}", DateTime.Now.AddDays(-1)); - return RedirectToAction("Activity", "v1", new RouteValueDictionary - { - {"pagenumber", pagenumber}, - {"pagesize", pagesize}, - {"seed", seed}, - {"updatefrom", updatefrom} - }); + return RedirectToAction( + "Activity", + "v1", + new RouteValueDictionary + { + { "pagenumber", pagenumber }, + { "pagesize", pagesize }, + { "seed", seed }, + { "updatefrom", updatefrom } + } + ); } #endregion @@ -314,15 +464,15 @@ public RedirectToActionResult GetAllActivityChanged( /// Dish Code Filter (BITMASK values: 1 = (Speisen), 2 = (Vorspeise), 4 = (Hauptspeise), 8 = (Nachspeise), 16 = (Tagesgericht), 32 = (Menü), 64 = (Degustationsmenü), 128 = (Kindermenüs), 256 = (Mittagsmenüs) /// Ceremony Code Filter (BITMASK values: 1 = (Familienfeiern), 2 = (Hochzeiten), 4 = (Geburtstagsfeiern), 8 = (Firmenessen), 16 = (Weihnachtsessen), 32 = (Sylvestermenü), 64 = (Seminare / Tagungen), 128 = (Versammlungen) /// Category Code Filter (BITMASK values: 1 = (Restaurant), 2 = (Bar / Café / Bistro), 4 = (Pub / Disco), 8 = (Apres Ski), 16 = (Jausenstation), 32 = (Pizzeria), 64 = (Bäuerlicher Schankbetrieb), 128 = (Buschenschank), 256 = (Hofschank), 512 = (Törggele Lokale), 1024 = (Schnellimbiss), 2048 = (Mensa), 4096 = (Vinothek /Weinhaus / Taverne), 8192 = (Eisdiele), 16348 = (Gasthaus), 32768 = (Gasthof), 65536 = (Braugarten), 131072 = (Schutzhütte), 262144 = (Alm), 524288 = (Skihütte) - /// Facility Code Filter (BITMASK values: 1 = (American Express), 2 = (Diners Club), 4 = (Eurocard / Mastercard), 8 = (Visa), 16 = (Hunde erlaubt), 32 = (Geeignet für Busse), 64 = (Garten), 128 = (Garagen), 256 = (Bierbar), 512 = (Kinderspielplatz), 1024 = (Spielzimmer), 2048 = (Spielplatz), 4096 = (Parkplätze), 8192 = (Raucherräume), 16348 = (Terrasse), 32768 = (Behindertengerecht), 65536 = (Biergarten), 131072 = (Aussichtsterrasse), 262144 = (Wintergarten), 524288 = (Gault Millau Südtirol), 1048576 = (Guida Espresso), 2097152 = (Gambero Rosso), 4194304 = (Feinschmecker), 8388608 = (Aral Schlemmer Atlas), 16777216 = (Varta Führer), 33554432 = (Bertelsmann), 67108864 = (Preis für Südtiroler Weinkultur), 134217728 = (Michelin), 268435456 = (Roter Hahn), 536870912 = (Tafelspitz)) - /// Cuisine Code Filter (BITMASK values: 1 = (Vegetarische Küche), 2 = (Glutenfreie Küche), 4 = (Laktosefreie Kost), 8 = (Warme Küche), 16 = (Südtiroler Spezialitäten), 32 = (Gourmet Küche), 64 = (Italienische Küche), 128 = (Internationale Küche), 256 = (Pizza), 512 = (Fischspezialitäten), 1024 = (Asiatische Küche), 2048 = (Wildspezialitäten), 4096 = (Produkte eigener Erzeugung), 8192 = (Diätküche), 16348 = (Grillspezialitäten), 32768 = (Ladinische Küche), 65536 = (Kleine Karte), 131072 = (Fischwochen), 262144 = (Spargelwochen), 524288 = (Lammwochen), 1048576 = (Wildwochen), 2097152 = (Vorspeisewochen), 4194304 = (Nudelwochen), 8388608 = (Kräuterwochen), 16777216 = (Kindermenüs), 33554432 = (Mittagsmenüs)) - /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=gastronomy'), (default:'null') + /// Facility Code Filter (BITMASK values: 1 = (American Express), 2 = (Diners Club), 4 = (Eurocard / Mastercard), 8 = (Visa), 16 = (Hunde erlaubt), 32 = (Geeignet für Busse), 64 = (Garten), 128 = (Garagen), 256 = (Bierbar), 512 = (Kinderspielplatz), 1024 = (Spielzimmer), 2048 = (Spielplatz), 4096 = (Parkplätze), 8192 = (Raucherräume), 16348 = (Terrasse), 32768 = (Behindertengerecht), 65536 = (Biergarten), 131072 = (Aussichtsterrasse), 262144 = (Wintergarten), 524288 = (Gault Millau Südtirol), 1048576 = (Guida Espresso), 2097152 = (Gambero Rosso), 4194304 = (Feinschmecker), 8388608 = (Aral Schlemmer Atlas), 16777216 = (Varta Führer), 33554432 = (Bertelsmann), 67108864 = (Preis für Südtiroler Weinkultur), 134217728 = (Michelin), 268435456 = (Roter Hahn), 536870912 = (Tafelspitz)) + /// Cuisine Code Filter (BITMASK values: 1 = (Vegetarische Küche), 2 = (Glutenfreie Küche), 4 = (Laktosefreie Kost), 8 = (Warme Küche), 16 = (Südtiroler Spezialitäten), 32 = (Gourmet Küche), 64 = (Italienische Küche), 128 = (Internationale Küche), 256 = (Pizza), 512 = (Fischspezialitäten), 1024 = (Asiatische Küche), 2048 = (Wildspezialitäten), 4096 = (Produkte eigener Erzeugung), 8192 = (Diätküche), 16348 = (Grillspezialitäten), 32768 = (Ladinische Küche), 65536 = (Kleine Karte), 131072 = (Fischwochen), 262144 = (Spargelwochen), 524288 = (Lammwochen), 1048576 = (Wildwochen), 2097152 = (Vorspeisewochen), 4194304 = (Nudelwochen), 8388608 = (Kräuterwochen), 16777216 = (Kindermenüs), 33554432 = (Mittagsmenüs)) + /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=gastronomy'), (default:'null') /// Active Gastronomies Filter (possible Values: 'true' only Active Gastronomies, 'false' only Disabled Gastronomies - /// ODH Active (Published) Gastronomies Filter (Refers to field SmgActive) Gastronomies Filter (possible Values: 'true' only published Gastronomies, 'false' only not published Gastronomies, (default:'null') + /// ODH Active (Published) Gastronomies Filter (Refers to field SmgActive) Gastronomies Filter (possible Values: 'true' only published Gastronomies, 'false' only not published Gastronomies, (default:'null') /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// Collection of GastronomyReduced Objects + /// Collection of GastronomyReduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -341,63 +491,126 @@ public async Task GetGastronomyListReduced( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); return await GetGastronomyReduced( - language?.ToLower(), locfilter, dishcodefilter, ceremonycodefilter, categorycodefilter, facilitycodefilter, - cuisinecodefilter, active?.Value, odhactive?.Value, odhtagfilter, - fields: fields ?? Array.Empty(), rawfilter, rawsort, searchfilter, - geosearchresult, cancellationToken); + language?.ToLower(), + locfilter, + dishcodefilter, + ceremonycodefilter, + categorycodefilter, + facilitycodefilter, + cuisinecodefilter, + active?.Value, + odhactive?.Value, + odhtagfilter, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + searchfilter, + geosearchresult, + cancellationToken + ); } private Task GetGastronomyReduced( - string? language, string? locfilter, string? dishcodefilter, - string? ceremonycodefilter, string? categorycodefilter, string? facilitycodefilter, - string? cuisinecodefilter, bool? active, bool? smgactive, string? smgtagfilter, - string[] fields, string? rawfilter, string? rawsort, string? searchfilter, - PGGeoSearchResult geosearchresult, CancellationToken cancellationToken) + string? language, + string? locfilter, + string? dishcodefilter, + string? ceremonycodefilter, + string? categorycodefilter, + string? facilitycodefilter, + string? cuisinecodefilter, + bool? active, + bool? smgactive, + string? smgtagfilter, + string[] fields, + string? rawfilter, + string? rawsort, + string? searchfilter, + PGGeoSearchResult geosearchresult, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { GastronomyHelper mygastronomyhelper = await GastronomyHelper.CreateAsync( - QueryFactory, idfilter: null, locfilter: locfilter, categorycodefilter: categorycodefilter, - dishcodefilter: dishcodefilter, ceremonycodefilter: ceremonycodefilter, facilitycodefilter: facilitycodefilter, - cuisinecodefilter: cuisinecodefilter, activefilter: active, smgactivefilter: smgactive, smgtags: smgtagfilter, - lastchange: null, langfilter: language, cancellationToken); - - string select = $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Detail,{language},Title\\}}' as \"Name\""; + QueryFactory, + idfilter: null, + locfilter: locfilter, + categorycodefilter: categorycodefilter, + dishcodefilter: dishcodefilter, + ceremonycodefilter: ceremonycodefilter, + facilitycodefilter: facilitycodefilter, + cuisinecodefilter: cuisinecodefilter, + activefilter: active, + smgactivefilter: smgactive, + smgtags: smgtagfilter, + lastchange: null, + langfilter: language, + cancellationToken + ); + + string select = + $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Detail,{language},Title\\}}' as \"Name\""; //Custom Fields filter if (fields.Length > 0) - select += string.Join("", fields.Where(x => x != "Id").Select(field => $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"")); + select += string.Join( + "", + fields + .Where(x => x != "Id") + .Select( + field => + $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"" + ) + ); - var query = - (XQuery)QueryFactory.Query() - .SelectRaw(select) + var query = (XQuery) + QueryFactory + .Query() + .SelectRaw(select) .From("gastronomies") .GastronomyWhereExpression( - idlist: mygastronomyhelper.idlist, dishcodeslist: mygastronomyhelper.dishcodesids, ceremonycodeslist: mygastronomyhelper.ceremonycodesids, - categorycodeslist: mygastronomyhelper.categorycodesids, facilitycodeslist: mygastronomyhelper.facilitycodesids, - smgtaglist: mygastronomyhelper.smgtaglist, districtlist: mygastronomyhelper.districtlist, - municipalitylist: mygastronomyhelper.municipalitylist, tourismvereinlist: mygastronomyhelper.tourismvereinlist, - regionlist: mygastronomyhelper.regionlist, activefilter: mygastronomyhelper.active, + idlist: mygastronomyhelper.idlist, + dishcodeslist: mygastronomyhelper.dishcodesids, + ceremonycodeslist: mygastronomyhelper.ceremonycodesids, + categorycodeslist: mygastronomyhelper.categorycodesids, + facilitycodeslist: mygastronomyhelper.facilitycodesids, + smgtaglist: mygastronomyhelper.smgtaglist, + districtlist: mygastronomyhelper.districtlist, + municipalitylist: mygastronomyhelper.municipalitylist, + tourismvereinlist: mygastronomyhelper.tourismvereinlist, + regionlist: mygastronomyhelper.regionlist, + activefilter: mygastronomyhelper.active, smgactivefilter: mygastronomyhelper.smgactive, - searchfilter: searchfilter, language: language, lastchange: null, languagelist: new List(), - filterClosedData: FilterClosedData, reducedData: ReducedData + searchfilter: searchfilter, + language: language, + lastchange: null, + languagelist: new List(), + filterClosedData: FilterClosedData, + reducedData: ReducedData ) .ApplyRawFilter(rawfilter) .ApplyOrdering_GeneratedColumns(geosearchresult, rawsort); var compiled = query.Compiler.Compile(query); - var reader = await query.Connection.ExecuteReaderAsync(compiled.Sql, compiled.NamedBindings); + var reader = await query.Connection.ExecuteReaderAsync( + compiled.Sql, + compiled.NamedBindings + ); return reader.ReadAndParseTOJson(); }); @@ -411,17 +624,21 @@ public RedirectToActionResult GetAllGastronomyChanged( int pagesize = 10, string? seed = null, string? updatefrom = null - ) + ) { updatefrom ??= String.Format("{0:yyyy-MM-dd}", DateTime.Now.AddDays(-1)); - return RedirectToAction("Gastronomy", "v1", new RouteValueDictionary - { - {"pagenumber", pagenumber}, - {"pagesize", pagesize}, - {"seed", seed}, - {"updatefrom", updatefrom} - }); + return RedirectToAction( + "Gastronomy", + "v1", + new RouteValueDictionary + { + { "pagenumber", pagenumber }, + { "pagesize", pagesize }, + { "seed", seed }, + { "updatefrom", updatefrom } + } + ); } #endregion @@ -441,49 +658,72 @@ public async Task GetODHTagsReduced( string? language = "en", string? localizationlanguage = null, string? validforentity = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { //Compatibility if (!String.IsNullOrEmpty(localizationlanguage)) language = localizationlanguage; - return await GetODHTagReduced(language?.ToLower(), validforentity, searchfilter, - fields: fields ?? Array.Empty(), rawfilter, - rawsort, cancellationToken); + return await GetODHTagReduced( + language?.ToLower(), + validforentity, + searchfilter, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + cancellationToken + ); } private Task GetODHTagReduced( - string? language, string? validforentity, - string? searchfilter, string[] fields, - string? rawfilter, string? rawsort, - CancellationToken cancellationToken) + string? language, + string? validforentity, + string? searchfilter, + string[] fields, + string? rawfilter, + string? rawsort, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - string select = $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{TagName,{language}\\}}' as \"Name\""; + string select = + $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{TagName,{language}\\}}' as \"Name\""; - //Hack - if (validforentity == "odhactivitypoi") - { - validforentity.Replace("odhactivitypoi", "smgpoi"); - } + //Hack + if (validforentity == "odhactivitypoi") + { + validforentity.Replace("odhactivitypoi", "smgpoi"); + } - var validforentitytypeslist = (validforentity ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries); - //var maintypeslist = (validforentity ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries); + var validforentitytypeslist = (validforentity ?? "").Split( + ',', + StringSplitOptions.RemoveEmptyEntries + ); + //var maintypeslist = (validforentity ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries); - //Custom Fields filter - if (fields.Length > 0) - select += string.Join("", fields.Where(x => x != "Id").Select(field => $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"")); + //Custom Fields filter + if (fields.Length > 0) + select += string.Join( + "", + fields + .Where(x => x != "Id") + .Select( + field => + $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"" + ) + ); - var query = - (XQuery)QueryFactory.Query() - .SelectRaw(select) - .From("smgtags") + var query = (XQuery) + QueryFactory + .Query() + .SelectRaw(select) + .From("smgtags") .ODHTagWhereExpression( languagelist: new List(), mainentitylist: new List(), @@ -493,13 +733,20 @@ private Task GetODHTagReduced( searchfilter: searchfilter, language: language, filterClosedData: FilterClosedData - ) - .ApplyRawFilter(rawfilter) - .ApplyOrdering(new PGGeoSearchResult() { geosearch = false }, rawsort, "data #>>'\\{MainEntity\\}', data#>>'\\{Shortname\\}'"); + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering( + new PGGeoSearchResult() { geosearch = false }, + rawsort, + "data #>>'\\{MainEntity\\}', data#>>'\\{Shortname\\}'" + ); var compiled = query.Compiler.Compile(query); - var reader = await query.Connection.ExecuteReaderAsync(compiled.Sql, compiled.NamedBindings); + var reader = await query.Connection.ExecuteReaderAsync( + compiled.Sql, + compiled.NamedBindings + ); return reader.ReadAndParseTOJson(); }); @@ -525,10 +772,10 @@ private Task GetODHTagReduced( /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=smgpoi'), (default:'null') - /// Active ODHActivityPoi Filter (possible Values: 'true' only active ODHActivityPoi, 'false' only not active ODHActivityPoi, (default:'null') - /// ODH Active (Published) ODHActivityPoi Filter (Refers to field SmgActive) (possible Values: 'true' only published ODHActivityPoi, 'false' only not published ODHActivityPoi, (default:'null') - /// Collection of ActivityPoiReduced Objects + /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=smgpoi'), (default:'null') + /// Active ODHActivityPoi Filter (possible Values: 'true' only active ODHActivityPoi, 'false' only not active ODHActivityPoi, (default:'null') + /// ODH Active (Published) ODHActivityPoi Filter (Refers to field SmgActive) (possible Values: 'true' only published ODHActivityPoi, 'false' only not published ODHActivityPoi, (default:'null') + /// Collection of ActivityPoiReduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -549,18 +796,38 @@ public async Task GetODHActivityPoiListReduced( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - - return await GetODHActivityPoiReduced(language, type, subtype, level3type, locfilter, areafilter, highlight?.Value, active?.Value, odhactive?.Value, - source, odhtagfilter, fields: fields ?? Array.Empty(), rawfilter, rawsort, searchfilter, - geosearchresult, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + + return await GetODHActivityPoiReduced( + language, + type, + subtype, + level3type, + locfilter, + areafilter, + highlight?.Value, + active?.Value, + odhactive?.Value, + source, + odhtagfilter, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + searchfilter, + geosearchresult, + cancellationToken + ); } /// @@ -568,7 +835,7 @@ public async Task GetODHActivityPoiListReduced( /// /// Localization Language /// Type of the Poi (possible values: STRINGS: 'Ärtze, Apotheken','Geschäfte und Dienstleister','Kultur und Sehenswürdigkeiten','Nachtleben und Unterhaltung','Öffentliche Einrichtungen','Sport und Freizeit','Verkehr und Transport' : BITMASK also possible: 'Ärtze, Apotheken = 1','Geschäfte und Dienstleister = 2','Kultur und Sehenswürdigkeiten = 4','Nachtleben und Unterhaltung = 8','Öffentliche Einrichtungen = 16','Sport und Freizeit = 32','Verkehr und Transport = 64') - /// Subtype of the Poi ('null' = Filter disabled, available Subtypes depends on the activitytype BITMASK) + /// Subtype of the Poi ('null' = Filter disabled, available Subtypes depends on the activitytype BITMASK) /// Locfilter (Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), 'null' = No Filter) /// AreaFilter (Separator ',' IDList of AreaIDs separated by ',', 'null' : Filter disabled) /// Highlight Filter (Show only Highlights possible values: 'true' : show only Highlight Pois, 'null' Filter disabled) @@ -577,50 +844,131 @@ public async Task GetODHActivityPoiListReduced( /// SMGTag Filter (String, Separator ',' more SMGTags possible, 'null' = No Filter) /// Collection of Reduced Poi Objects private Task GetODHActivityPoiReduced( - string? language, string? type, string? subtype, string? level3type, string? locfilter, - string? areafilter, bool? highlightfilter, bool? active, bool? smgactive, string? source, - string? smgtags, string[] fields, string? rawfilter, string? rawsort, string? searchfilter, - PGGeoSearchResult geosearchresult, CancellationToken cancellationToken) + string? language, + string? type, + string? subtype, + string? level3type, + string? locfilter, + string? areafilter, + bool? highlightfilter, + bool? active, + bool? smgactive, + string? source, + string? smgtags, + string[] fields, + string? rawfilter, + string? rawsort, + string? searchfilter, + PGGeoSearchResult geosearchresult, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { ODHActivityPoiHelper helper = await ODHActivityPoiHelper.CreateAsync( - queryFactory: QueryFactory, typefilter: type, subtypefilter: subtype, level3typefilter: level3type, idfilter: null, locfilter: locfilter, areafilter: areafilter, - languagefilter: language, sourcefilter: source, highlightfilter: highlightfilter, activefilter: active, smgactivefilter: smgactive, smgtags: smgtags, smgtagsand: null, lastchange: null, - categorycodefilter: null, dishcodefilter: null, ceremonycodefilter: null, facilitycodefilter: null, cuisinecodefilter: null, activitytypefilter: null, poitypefilter: null, distancefilter: null, - altitudefilter: null, durationfilter: null, difficultyfilter: null, null, publishedonfilter: null, cancellationToken); - - string select = $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Detail,{language},Title\\}}' as \"Name\""; + queryFactory: QueryFactory, + typefilter: type, + subtypefilter: subtype, + level3typefilter: level3type, + idfilter: null, + locfilter: locfilter, + areafilter: areafilter, + languagefilter: language, + sourcefilter: source, + highlightfilter: highlightfilter, + activefilter: active, + smgactivefilter: smgactive, + smgtags: smgtags, + smgtagsand: null, + lastchange: null, + categorycodefilter: null, + dishcodefilter: null, + ceremonycodefilter: null, + facilitycodefilter: null, + cuisinecodefilter: null, + activitytypefilter: null, + poitypefilter: null, + distancefilter: null, + altitudefilter: null, + durationfilter: null, + difficultyfilter: null, + null, + publishedonfilter: null, + cancellationToken + ); + + string select = + $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Detail,{language},Title\\}}' as \"Name\""; //string orderby = "data#>>'\\{Shortname\\}' ASC"; //Custom Fields filter Removes a twice selected Id Field if (fields.Length > 0) - select += string.Join("", fields.Where(x => x != "Id").Select(field => $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"")); + select += string.Join( + "", + fields + .Where(x => x != "Id") + .Select( + field => + $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"" + ) + ); - var query = - (XQuery)QueryFactory.Query() + var query = (XQuery) + QueryFactory + .Query() .SelectRaw(select) .From("smgpois") .ODHActivityPoiWhereExpression( - idlist: helper.idlist, typelist: helper.typelist, subtypelist: helper.subtypelist, level3typelist: helper.level3typelist, - smgtaglist: helper.smgtaglist, smgtaglistand: helper.smgtaglistand, districtlist: helper.districtlist, municipalitylist: helper.municipalitylist, - tourismvereinlist: helper.tourismvereinlist, regionlist: helper.regionlist, - arealist: helper.arealist, highlight: helper.highlight, activefilter: helper.active, - smgactivefilter: helper.smgactive, sourcelist: helper.sourcelist, languagelist: helper.languagelist, - categorycodeslist: helper.categorycodesids, dishcodeslist: helper.dishcodesids, ceremonycodeslist: helper.ceremonycodesids, + idlist: helper.idlist, + typelist: helper.typelist, + subtypelist: helper.subtypelist, + level3typelist: helper.level3typelist, + smgtaglist: helper.smgtaglist, + smgtaglistand: helper.smgtaglistand, + districtlist: helper.districtlist, + municipalitylist: helper.municipalitylist, + tourismvereinlist: helper.tourismvereinlist, + regionlist: helper.regionlist, + arealist: helper.arealist, + highlight: helper.highlight, + activefilter: helper.active, + smgactivefilter: helper.smgactive, + sourcelist: helper.sourcelist, + languagelist: helper.languagelist, + categorycodeslist: helper.categorycodesids, + dishcodeslist: helper.dishcodesids, + ceremonycodeslist: helper.ceremonycodesids, facilitycodeslist: helper.facilitycodesids, - activitytypelist: helper.activitytypelist, poitypelist: helper.poitypelist, difficultylist: helper.difficultylist, distance: helper.distance, - distancemin: helper.distancemin, distancemax: helper.distancemax, duration: helper.duration, durationmin: helper.durationmin, - durationmax: helper.durationmax, altitude: helper.altitude, altitudemin: helper.altitudemin, altitudemax: helper.altitudemax, - tagbehaviour: helper.tagfilterbehaviour, tagdict: helper.tagdict, publishedonlist: helper.publishedonlist, - searchfilter: searchfilter, language: language, lastchange: null, filterClosedData: FilterClosedData, reducedData: ReducedData + activitytypelist: helper.activitytypelist, + poitypelist: helper.poitypelist, + difficultylist: helper.difficultylist, + distance: helper.distance, + distancemin: helper.distancemin, + distancemax: helper.distancemax, + duration: helper.duration, + durationmin: helper.durationmin, + durationmax: helper.durationmax, + altitude: helper.altitude, + altitudemin: helper.altitudemin, + altitudemax: helper.altitudemax, + tagbehaviour: helper.tagfilterbehaviour, + tagdict: helper.tagdict, + publishedonlist: helper.publishedonlist, + searchfilter: searchfilter, + language: language, + lastchange: null, + filterClosedData: FilterClosedData, + reducedData: ReducedData ) .ApplyRawFilter(rawfilter) .ApplyOrdering_GeneratedColumns(geosearchresult, rawsort); var compiled = query.Compiler.Compile(query); - var reader = await query.Connection.ExecuteReaderAsync(compiled.Sql, compiled.NamedBindings); + var reader = await query.Connection.ExecuteReaderAsync( + compiled.Sql, + compiled.NamedBindings + ); return reader.ReadAndParseTOJson(); }); @@ -635,17 +983,21 @@ public RedirectToActionResult GetAllODHActivityPoiChanged( string? seed = null, string? updatefrom = null, CancellationToken cancellationToken = default - ) + ) { updatefrom ??= String.Format("{0:yyyy-MM-dd}", DateTime.Now.AddDays(-1)); - return RedirectToAction("ODHActivityPoi", "v1", new RouteValueDictionary - { - {"pagenumber", pagenumber}, - {"pagesize", pagesize}, - {"seed", seed}, - {"updatefrom", updatefrom} - }); + return RedirectToAction( + "ODHActivityPoi", + "v1", + new RouteValueDictionary + { + { "pagenumber", pagenumber }, + { "pagesize", pagesize }, + { "seed", seed }, + { "updatefrom", updatefrom } + } + ); } #endregion @@ -656,20 +1008,20 @@ public RedirectToActionResult GetAllODHActivityPoiChanged( /// GET Event List Reduced /// /// Localization Language, (default:'en') - /// Locfilter (Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = No Filter), (default:'null') + /// Locfilter (Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = No Filter), (default:'null') /// Rancfilter (Ranc 0-5 possible) /// Typefilter (Type of Event: not used yet) /// Topic ID Filter (Filter by Topic ID) BITMASK /// Organization Filter (Filter by Organizer RID) - /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=event'), (default:'null') + /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=event'), (default:'null') /// Active Events Filter (possible Values: 'true' only Active Events, 'false' only Disabled Events, (default:'null') - /// ODH Active (Published) Events Filter (Refers to field SmgActive) Events Filter (possible Values: 'true' only published Events, 'false' only not published Events, (default:'null') + /// ODH Active (Published) Events Filter (Refers to field SmgActive) Events Filter (possible Values: 'true' only published Events, 'false' only not published Events, (default:'null') /// BeginDate of Events (Format: yyyy-MM-dd) /// EndDate of Events (Format: yyyy-MM-dd) /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// Collection of EventReduced Objects + /// Collection of EventReduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -691,58 +1043,140 @@ public async Task GetEventsReduced( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - - return await GetEventReduced(language, locfilter, rancfilter, typefilter, - topicfilter, orgfilter, odhactive?.Value, active?.Value, - source, langfilter, begindate, enddate, odhtagfilter, - fields: fields ?? Array.Empty(), rawfilter, rawsort, searchfilter, - geosearchresult, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + + return await GetEventReduced( + language, + locfilter, + rancfilter, + typefilter, + topicfilter, + orgfilter, + odhactive?.Value, + active?.Value, + source, + langfilter, + begindate, + enddate, + odhtagfilter, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + searchfilter, + geosearchresult, + cancellationToken + ); } - private Task GetEventReduced(string? language, string? locfilter, string? rancfilter, - string? typefilter, string? topicfilter, string? orgfilter, bool? smgactive, bool? active, string? source, string? langfilter, - string? begindate, string? enddate, string? smgtagfilter, string[] fields, string? rawfilter, string? rawsort, string? searchfilter, - PGGeoSearchResult geosearchresult, CancellationToken cancellationToken) + private Task GetEventReduced( + string? language, + string? locfilter, + string? rancfilter, + string? typefilter, + string? topicfilter, + string? orgfilter, + bool? smgactive, + bool? active, + string? source, + string? langfilter, + string? begindate, + string? enddate, + string? smgtagfilter, + string[] fields, + string? rawfilter, + string? rawsort, + string? searchfilter, + PGGeoSearchResult geosearchresult, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { EventHelper helper = await EventHelper.CreateAsync( - QueryFactory, null, locfilter, rancfilter, typefilter, topicfilter, orgfilter, begindate, - enddate, active, smgactive, smgtagfilter, null, langfilter, source, null, cancellationToken); - - string select = $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Detail,{language},Title\\}}' as \"Name\""; + QueryFactory, + null, + locfilter, + rancfilter, + typefilter, + topicfilter, + orgfilter, + begindate, + enddate, + active, + smgactive, + smgtagfilter, + null, + langfilter, + source, + null, + cancellationToken + ); + + string select = + $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Detail,{language},Title\\}}' as \"Name\""; //string orderby = "data#>>'\\{Shortname\\}' ASC"; //Custom Fields filter if (fields.Length > 0) - select += string.Join("", fields.Where(x => x != "Id").Select(field => $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"")); + select += string.Join( + "", + fields + .Where(x => x != "Id") + .Select( + field => + $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"" + ) + ); - var query = - (XQuery)QueryFactory.Query() + var query = (XQuery) + QueryFactory + .Query() .SelectRaw(select) .From("events") .EventWhereExpression( - idlist: helper.idlist, topiclist: helper.topicrids, typelist: helper.typeidlist, ranclist: helper.rancidlist, - smgtaglist: helper.smgtaglist, districtlist: helper.districtlist, municipalitylist: helper.municipalitylist, - tourismvereinlist: helper.tourismvereinlist, regionlist: helper.regionlist, - orglist: helper.orgidlist, sourcelist: helper.sourcelist, begindate: helper.begin, enddate: helper.end, activefilter: helper.active, - smgactivefilter: helper.smgactive, languagelist: helper.languagelist, publishedonlist: helper.publishedonlist, - searchfilter: searchfilter, language: language, lastchange: null, filterClosedData: FilterClosedData, reducedData: ReducedData + idlist: helper.idlist, + topiclist: helper.topicrids, + typelist: helper.typeidlist, + ranclist: helper.rancidlist, + smgtaglist: helper.smgtaglist, + districtlist: helper.districtlist, + municipalitylist: helper.municipalitylist, + tourismvereinlist: helper.tourismvereinlist, + regionlist: helper.regionlist, + orglist: helper.orgidlist, + sourcelist: helper.sourcelist, + begindate: helper.begin, + enddate: helper.end, + activefilter: helper.active, + smgactivefilter: helper.smgactive, + languagelist: helper.languagelist, + publishedonlist: helper.publishedonlist, + searchfilter: searchfilter, + language: language, + lastchange: null, + filterClosedData: FilterClosedData, + reducedData: ReducedData ) .ApplyRawFilter(rawfilter) .ApplyOrdering_GeneratedColumns(geosearchresult, rawsort); var compiled = query.Compiler.Compile(query); - var reader = await query.Connection.ExecuteReaderAsync(compiled.Sql, compiled.NamedBindings); + var reader = await query.Connection.ExecuteReaderAsync( + compiled.Sql, + compiled.NamedBindings + ); return reader.ReadAndParseTOJson(); }); @@ -757,17 +1191,21 @@ public RedirectToActionResult GetAllEventChanged( string? seed = null, string? updatefrom = null, CancellationToken cancellationToken = default - ) + ) { updatefrom ??= String.Format("{0:yyyy-MM-dd}", DateTime.Now.AddDays(-1)); - return RedirectToAction("Event", "v1", new RouteValueDictionary - { - {"pagenumber", pagenumber}, - {"pagesize", pagesize}, - {"seed", seed}, - {"updatefrom", updatefrom} - }); + return RedirectToAction( + "Event", + "v1", + new RouteValueDictionary + { + { "pagenumber", pagenumber }, + { "pagesize", pagesize }, + { "seed", seed }, + { "updatefrom", updatefrom } + } + ); } #endregion @@ -780,14 +1218,14 @@ public RedirectToActionResult GetAllEventChanged( /// Localization Language, (default:'en') /// Type of the Article ('null' = Filter disabled, possible values: BITMASK values: 1 = basearticle, 2 = book article, 4 = contentarticle, 8 = eventarticle, 16 = pressarticle, 32 = recipe, 64 = touroperator , 128 = b2b), (also possible for compatibily reasons: basisartikel, buchtippartikel, contentartikel, veranstaltungsartikel, presseartikel, rezeptartikel, reiseveranstalter, b2bartikel ) (default:'255' == ALL), REFERENCE TO: GET /api/ArticleTypes /// Sub Type of the Article (depends on the Maintype of the Article 'null' = Filter disabled) - /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=article'), (default:'null') + /// ODH Taglist Filter (refers to Array SmgTags) (String, Separator ',' more Tags possible, available Tags reference to 'v1/ODHTag?validforentity=article'), (default:'null') /// Filter by ArticleDate Format (yyyy-MM-dd HH:mm) /// Filter by ArticleDate Format (yyyy-MM-dd HH:mm) /// Sort By Articledate ('true' sorts Articles by Articledate) /// Active Articles Filter (possible Values: 'true' only Active Articles, 'false' only Disabled Articles - /// ODH Active (Published) Activities Filter (Refers to field SmgActive) Article Filter (possible Values: 'true' only published Article, 'false' only not published Articles, (default:'null') + /// ODH Active (Published) Activities Filter (Refers to field SmgActive) Article Filter (possible Values: 'true' only published Article, 'false' only not published Articles, (default:'null') /// Filter by Source (Separator ','), (Sources available 'idm','noi'...),(default: 'null') - /// Collection of Article Objects + /// Collection of Article Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -803,57 +1241,119 @@ public Task GetArticleReducedList( string? odhtagfilter = null, LegacyBool active = null!, LegacyBool odhactive = null!, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, CancellationToken cancellationToken = default - ) + ) { - return GetArticleReduced(language, articletype, articlesubtype, - startdate, enddate, source, null, publishedon, - active?.Value, odhactive?.Value, odhtagfilter, - fields: fields ?? Array.Empty(), rawfilter, - rawsort, searchfilter, - cancellationToken); + return GetArticleReduced( + language, + articletype, + articlesubtype, + startdate, + enddate, + source, + null, + publishedon, + active?.Value, + odhactive?.Value, + odhtagfilter, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + searchfilter, + cancellationToken + ); } - private Task GetArticleReduced(string? language, string? articletype, string? articlesubtype, - string? articledate, string? articledateto, string? source, bool? sortbyarticledate, string? publishedon, - bool? active, bool? smgactive, string? smgtags, - string[] fields, string? rawfilter, string? rawsort, string? searchfilter, - CancellationToken cancellationToken) + private Task GetArticleReduced( + string? language, + string? articletype, + string? articlesubtype, + string? articledate, + string? articledateto, + string? source, + bool? sortbyarticledate, + string? publishedon, + bool? active, + bool? smgactive, + string? smgtags, + string[] fields, + string? rawfilter, + string? rawsort, + string? searchfilter, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { ArticleHelper helper = ArticleHelper.Create( - articletype, articlesubtype, null, language, null, active, smgactive, smgtags, articledate, articledateto, source, null, publishedon); - - string select = $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Detail,{language},Title\\}}' as \"Name\""; + articletype, + articlesubtype, + null, + language, + null, + active, + smgactive, + smgtags, + articledate, + articledateto, + source, + null, + publishedon + ); + + string select = + $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Detail,{language},Title\\}}' as \"Name\""; //string orderby = "data#>>'\\{Shortname\\}' ASC"; //Custom Fields filter if (fields.Length > 0) - select += string.Join("", fields.Where(x => x != "Id").Select(field => $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"")); + select += string.Join( + "", + fields + .Where(x => x != "Id") + .Select( + field => + $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"" + ) + ); - var query = - (XQuery)QueryFactory.Query() + var query = (XQuery) + QueryFactory + .Query() .SelectRaw(select) .From("articles") .ArticleWhereExpression( - idlist: helper.idlist, typelist: helper.typelist, subtypelist: helper.subtypelist, languagelist: helper.languagelist, - smgtaglist: helper.smgtaglist, highlight: helper.highlight, activefilter: helper.active, - smgactivefilter: helper.smgactive, articledate: helper.articledate, articledateto: helper.articledateto, sourcelist: helper.sourcelist, + idlist: helper.idlist, + typelist: helper.typelist, + subtypelist: helper.subtypelist, + languagelist: helper.languagelist, + smgtaglist: helper.smgtaglist, + highlight: helper.highlight, + activefilter: helper.active, + smgactivefilter: helper.smgactive, + articledate: helper.articledate, + articledateto: helper.articledateto, + sourcelist: helper.sourcelist, publishedonlist: helper.publishedonlist, - searchfilter: searchfilter, language: language, lastchange: null, filterClosedData: FilterClosedData, reducedData: ReducedData + searchfilter: searchfilter, + language: language, + lastchange: null, + filterClosedData: FilterClosedData, + reducedData: ReducedData ) .ApplyRawFilter(rawfilter) .ApplyOrdering(new PGGeoSearchResult() { geosearch = false }, rawsort); var compiled = query.Compiler.Compile(query); - var reader = await query.Connection.ExecuteReaderAsync(compiled.Sql, compiled.NamedBindings); + var reader = await query.Connection.ExecuteReaderAsync( + compiled.Sql, + compiled.NamedBindings + ); return reader.ReadAndParseTOJson(); }); @@ -863,22 +1363,26 @@ private Task GetArticleReduced(string? language, string? articlet [ApiExplorerSettings(IgnoreApi = true)] [HttpGet, Route("ArticleChanged")] public RedirectToActionResult GetAllArticleChanged( - uint pagenumber = 1, - uint pagesize = 10, - string? seed = null, - string? updatefrom = null, - CancellationToken cancellationToken = default - ) + uint pagenumber = 1, + uint pagesize = 10, + string? seed = null, + string? updatefrom = null, + CancellationToken cancellationToken = default + ) { updatefrom ??= String.Format("{0:yyyy-MM-dd}", DateTime.Now.AddDays(-1)); - return RedirectToAction("Article", "v1", new RouteValueDictionary - { - {"pagenumber", pagenumber}, - {"pagesize", pagesize}, - {"seed", seed}, - {"updatefrom", updatefrom} - }); + return RedirectToAction( + "Article", + "v1", + new RouteValueDictionary + { + { "pagenumber", pagenumber }, + { "pagesize", pagesize }, + { "seed", seed }, + { "updatefrom", updatefrom } + } + ); } #endregion @@ -895,16 +1399,16 @@ public RedirectToActionResult GetAllArticleChanged( /// FeatureFilter (BITMASK values: 1 = (Group-friendly), 2 = (Meeting rooms), 4 = (Swimming pool), 8 = (Sauna), 16 = (Garage), 32 = (Pick-up service), 64 = (WLAN), 128 = (Barrier-free), 256 = (Special menus for allergy sufferers), 512 = (Pets welcome), 'null' = No Filter), (default:'null') /// Feature Id Filter, filter over ALL Features vailable (Separator ',' List of Feature IDs, 'null' = No Filter), (default:'null') /// Themefilter (BITMASK values: 1 = (Gourmet), 2 = (At altitude), 4 = (Regional wellness offerings), 8 = (on the wheels), 16 = (With family), 32 = (Hiking), 64 = (In the vineyards), 128 = (Urban vibe), 256 = (At the ski resort), 512 = (Mediterranean), 1024 = (In the Dolomites), 2048 = (Alpine), 4096 = (Small and charming), 8192 = (Huts and mountain inns), 16384 = (Rural way of life), 32768 = (Balance), 65536 = (Christmas markets), 'null' = No Filter), (default:'null') - /// BadgeFilter (BITMASK values: 1 = (Belvita Wellness Hotel), 2 = (Familyhotel), 4 = (Bikehotel), 8 = (Red Rooster Farm), 16 = (Barrier free certificated), 32 = (Vitalpina Hiking Hotel), 64 = (Private Rooms in South Tyrol), 128 = (Vinum Hotels), 'null' = No Filter), (default:'null') - /// Locfilter (Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = No Filter), (default:'null') + /// BadgeFilter (BITMASK values: 1 = (Belvita Wellness Hotel), 2 = (Familyhotel), 4 = (Bikehotel), 8 = (Red Rooster Farm), 16 = (Barrier free certificated), 32 = (Vitalpina Hiking Hotel), 64 = (Private Rooms in South Tyrol), 128 = (Vinum Hotels), 'null' = No Filter), (default:'null') + /// Locfilter (Separator ',' possible values: reg + REGIONID = (Filter by Region), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), 'null' = No Filter), (default:'null') /// ODHTag Filter (refers to Array SmgTags) (String, Separator ',' more ODHTags possible, 'null' = No Filter, available ODHTags reference to 'v1/ODHTag?validforentity=accommodation'), (default:'null') - /// ODHActive Filter (refers to field SmgActive) (possible Values: 'null' Displays all Accommodations, 'true' only ODH Active Accommodations, 'false' only ODH Disabled Accommodations, (default:'null') - /// TIC Active Filter (possible Values: 'null' Displays all Accommodations, 'true' only TIC Active Accommodations, 'false' only TIC Disabled Accommodations, (default:'null') + /// ODHActive Filter (refers to field SmgActive) (possible Values: 'null' Displays all Accommodations, 'true' only ODH Active Accommodations, 'false' only ODH Disabled Accommodations, (default:'null') + /// TIC Active Filter (possible Values: 'null' Displays all Accommodations, 'true' only TIC Active Accommodations, 'false' only TIC Disabled Accommodations, (default:'null') /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') /// Select fields to display, by Default Title and Id are selected if fields filter is null More fields are indicated by separator ',' example fields=Id,Active,Shortname. Select also Dictionary fields, example Detail.de.Title, or Elements of Arrays example ImageGallery[0].ImageUrl. (default:'null' all fields are displayed) - /// Collection with Accommodation Reduced Objects + /// Collection with Accommodation Reduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -925,62 +1429,150 @@ public async Task GetReducedAccosAsync( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool suedtirolmobil = false, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - - return await GetAccommodationReduced(language, categoryfilter, typefilter, boardfilter, featurefilter, themefilter, badgefilter, locfilter, active?.Value, odhactive?.Value, - odhtagfilter, featureidfilter, geosearchresult, fields: fields ?? Array.Empty(), rawfilter, rawsort, searchfilter, suedtirolmobil, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + + return await GetAccommodationReduced( + language, + categoryfilter, + typefilter, + boardfilter, + featurefilter, + themefilter, + badgefilter, + locfilter, + active?.Value, + odhactive?.Value, + odhtagfilter, + featureidfilter, + geosearchresult, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + searchfilter, + suedtirolmobil, + cancellationToken + ); } private Task GetAccommodationReduced( - string? language, string? categoryfilter, string? typefilter, string? boardfilter, string? featurefilter, string? themefilter, - string? badgefilter, string? locfilter, bool? active, bool? smgactive, string? smgtagfilter, string? featureridfilter, - PGGeoSearchResult geosearchresult, string[] fields, string? rawfilter, string? rawsort, string? searchfilter, - bool stahack, CancellationToken cancellationToken) + string? language, + string? categoryfilter, + string? typefilter, + string? boardfilter, + string? featurefilter, + string? themefilter, + string? badgefilter, + string? locfilter, + bool? active, + bool? smgactive, + string? smgtagfilter, + string? featureridfilter, + PGGeoSearchResult geosearchresult, + string[] fields, + string? rawfilter, + string? rawsort, + string? searchfilter, + bool stahack, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { AccommodationHelper myhelper = await AccommodationHelper.CreateAsync( - QueryFactory, idfilter: null, locfilter: locfilter, boardfilter: boardfilter, categoryfilter: categoryfilter, typefilter: typefilter, - featurefilter: featurefilter, featureidfilter: featureridfilter, badgefilter: badgefilter, themefilter: themefilter, altitudefilter: null, smgtags: smgtagfilter, activefilter: active, - smgactivefilter: smgactive, bookablefilter: null, sourcefilter: null, lastchange: null, langfilter: language, publishedonfilter: null, cancellationToken); - - string select = $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{AccoDetail,{language},Name\\}}' as \"Name\""; + QueryFactory, + idfilter: null, + locfilter: locfilter, + boardfilter: boardfilter, + categoryfilter: categoryfilter, + typefilter: typefilter, + featurefilter: featurefilter, + featureidfilter: featureridfilter, + badgefilter: badgefilter, + themefilter: themefilter, + altitudefilter: null, + smgtags: smgtagfilter, + activefilter: active, + smgactivefilter: smgactive, + bookablefilter: null, + sourcefilter: null, + lastchange: null, + langfilter: language, + publishedonfilter: null, + cancellationToken + ); + + string select = + $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{AccoDetail,{language},Name\\}}' as \"Name\""; //string orderby = "data#>>'\\{Shortname\\}' ASC"; //Custom Fields filter if (fields.Length > 0) - select += string.Join("", fields.Where(x => x != "Id").Select(field => $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"")); + select += string.Join( + "", + fields + .Where(x => x != "Id") + .Select( + field => + $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"" + ) + ); - var query = - (XQuery)QueryFactory.Query() + var query = (XQuery) + QueryFactory + .Query() .SelectRaw(select) .From("accommodations") .AccommodationWhereExpression( - idlist: myhelper.idlist, accotypelist: myhelper.accotypelist, - categorylist: myhelper.categorylist, featurelist: myhelper.featurelist, featureidlist: myhelper.featureidlist, - badgelist: myhelper.badgelist, themelist: myhelper.themelist, - boardlist: myhelper.boardlist, smgtaglist: myhelper.smgtaglist, - districtlist: myhelper.districtlist, municipalitylist: myhelper.municipalitylist, - tourismvereinlist: myhelper.tourismvereinlist, regionlist: myhelper.regionlist, - apartmentfilter: myhelper.apartment, bookable: myhelper.bookable, altitude: myhelper.altitude, - altitudemin: myhelper.altitudemin, altitudemax: myhelper.altitudemax, - activefilter: myhelper.active, smgactivefilter: myhelper.smgactive, publishedonlist: myhelper.publishedonlist, sourcelist: new List(), - searchfilter: searchfilter, language: language, lastchange: myhelper.lastchange, languagelist: new List(), - filterClosedData: FilterClosedData, reducedData: ReducedData) + idlist: myhelper.idlist, + accotypelist: myhelper.accotypelist, + categorylist: myhelper.categorylist, + featurelist: myhelper.featurelist, + featureidlist: myhelper.featureidlist, + badgelist: myhelper.badgelist, + themelist: myhelper.themelist, + boardlist: myhelper.boardlist, + smgtaglist: myhelper.smgtaglist, + districtlist: myhelper.districtlist, + municipalitylist: myhelper.municipalitylist, + tourismvereinlist: myhelper.tourismvereinlist, + regionlist: myhelper.regionlist, + apartmentfilter: myhelper.apartment, + bookable: myhelper.bookable, + altitude: myhelper.altitude, + altitudemin: myhelper.altitudemin, + altitudemax: myhelper.altitudemax, + activefilter: myhelper.active, + smgactivefilter: myhelper.smgactive, + publishedonlist: myhelper.publishedonlist, + sourcelist: new List(), + searchfilter: searchfilter, + language: language, + lastchange: myhelper.lastchange, + languagelist: new List(), + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) .ApplyRawFilter(rawfilter) .ApplyOrdering_GeneratedColumns(geosearchresult, rawsort); var compiled = query.Compiler.Compile(query); - var reader = await query.Connection.ExecuteReaderAsync(compiled.Sql, compiled.NamedBindings); + var reader = await query.Connection.ExecuteReaderAsync( + compiled.Sql, + compiled.NamedBindings + ); return reader.ReadAndParseTOJson(); }); @@ -990,22 +1582,26 @@ private Task GetAccommodationReduced( [ApiExplorerSettings(IgnoreApi = true)] [HttpGet, Route("AccommodationChanged")] public RedirectToActionResult GetAllAccommodationChanged( - uint pagenumber = 1, - uint pagesize = 10, - string? seed = null, - string? updatefrom = null, - CancellationToken cancellationToken = default - ) + uint pagenumber = 1, + uint pagesize = 10, + string? seed = null, + string? updatefrom = null, + CancellationToken cancellationToken = default + ) { updatefrom ??= String.Format("{0:yyyy-MM-dd}", DateTime.Now.AddDays(-1)); - return RedirectToAction("Accommodation", "v1", new RouteValueDictionary - { - {"pagenumber", pagenumber}, - {"pagesize", pagesize}, - {"seed", seed}, - {"updatefrom", updatefrom} - }); + return RedirectToAction( + "Accommodation", + "v1", + new RouteValueDictionary + { + { "pagenumber", pagenumber }, + { "pagesize", pagesize }, + { "seed", seed }, + { "updatefrom", updatefrom } + } + ); } #endregion @@ -1043,55 +1639,125 @@ public Task GetReducedAsync( string? webaddress = null, string? sortorder = "ASC", string? lastchange = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return GetEventShortReduced(fields: fields ?? Array.Empty(), language, searchfilter, - startdate, enddate, datetimeformat, source, eventlocation, webaddress, - onlyactive.Value, websiteactive.Value, communityactive.Value, sortorder, null, rawfilter, rawsort, cancellationToken); + return GetEventShortReduced( + fields: fields ?? Array.Empty(), + language, + searchfilter, + startdate, + enddate, + datetimeformat, + source, + eventlocation, + webaddress, + onlyactive.Value, + websiteactive.Value, + communityactive.Value, + sortorder, + null, + rawfilter, + rawsort, + cancellationToken + ); } - private Task GetEventShortReduced( - string[] fields, string language, string? searchfilter, string? startdate, string? enddate, string? datetimeformat, - string? sourcefilter, string? eventlocationfilter, string? webaddressfilter, bool? active, bool? websiteactive, bool? communityactive, string? sortorder, - string? lastchange, string? rawfilter, string? rawsort, CancellationToken cancellationToken) + string[] fields, + string language, + string? searchfilter, + string? startdate, + string? enddate, + string? datetimeformat, + string? sourcefilter, + string? eventlocationfilter, + string? webaddressfilter, + bool? active, + bool? websiteactive, + bool? communityactive, + string? sortorder, + string? lastchange, + string? rawfilter, + string? rawsort, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - string select = $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{EventDescription{language.ToUpper()}\\}}' as \"Name\""; + string select = + $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{EventDescription{language.ToUpper()}\\}}' as \"Name\""; - string orderby = $"data#>>'\\{{EventDescription{language.ToUpper()}\\}}' {sortorder}"; + string orderby = + $"data#>>'\\{{EventDescription{language.ToUpper()}\\}}' {sortorder}"; //Custom Fields filter if (fields.Length > 0) - select += string.Join("", fields.Where(x => x != "Id").Select(field => $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"")); - - EventShortHelper myeventshorthelper = EventShortHelper.Create(startdate, enddate, datetimeformat, - sourcefilter, eventlocationfilter, active, websiteactive, communityactive, null, webaddressfilter, lastchange, sortorder, null); - - var query = - (XQuery)QueryFactory.Query() - .SelectRaw(select) - .From("eventeuracnoi") - .EventShortWhereExpression( - idlist: myeventshorthelper.idlist, sourcelist: myeventshorthelper.sourcelist, - eventlocationlist: myeventshorthelper.eventlocationlist, webaddresslist: myeventshorthelper.webaddresslist, - start: myeventshorthelper.start, end: myeventshorthelper.end, activefilter: myeventshorthelper.activefilter, - websiteactivefilter: myeventshorthelper.websiteactivefilter, communityactivefilter: myeventshorthelper.communityactivefilter, - publishedonlist: myeventshorthelper.publishedonlist, - searchfilter: searchfilter, language: language, lastchange: myeventshorthelper.lastchange, - filterClosedData: FilterClosedData, getbyrooms: false) - .ApplyRawFilter(rawfilter) - .ApplyOrdering(new PGGeoSearchResult() { geosearch = false }, rawsort, orderby); + select += string.Join( + "", + fields + .Where(x => x != "Id") + .Select( + field => + $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"" + ) + ); + + EventShortHelper myeventshorthelper = EventShortHelper.Create( + startdate, + enddate, + datetimeformat, + sourcefilter, + eventlocationfilter, + active, + websiteactive, + communityactive, + null, + webaddressfilter, + lastchange, + sortorder, + null + ); + + var query = (XQuery) + QueryFactory + .Query() + .SelectRaw(select) + .From("eventeuracnoi") + .EventShortWhereExpression( + idlist: myeventshorthelper.idlist, + sourcelist: myeventshorthelper.sourcelist, + eventlocationlist: myeventshorthelper.eventlocationlist, + webaddresslist: myeventshorthelper.webaddresslist, + start: myeventshorthelper.start, + end: myeventshorthelper.end, + activefilter: myeventshorthelper.activefilter, + websiteactivefilter: myeventshorthelper.websiteactivefilter, + communityactivefilter: myeventshorthelper.communityactivefilter, + publishedonlist: myeventshorthelper.publishedonlist, + searchfilter: searchfilter, + language: language, + lastchange: myeventshorthelper.lastchange, + filterClosedData: FilterClosedData, + getbyrooms: false + ) + .ApplyRawFilter(rawfilter) + .ApplyOrdering( + new PGGeoSearchResult() { geosearch = false }, + rawsort, + orderby + ); var compiled = query.Compiler.Compile(query); - var reader = await query.Connection.ExecuteReaderAsync(compiled.Sql, compiled.NamedBindings); + var reader = await query.Connection.ExecuteReaderAsync( + compiled.Sql, + compiled.NamedBindings + ); return reader.ReadAndParseTOJson(); }); @@ -1111,7 +1777,7 @@ private Task GetEventShortReduced( /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// Collection of CommonReduced Objects + /// Collection of CommonReduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -1124,14 +1790,40 @@ public async Task GetMetaRegionsReduced( string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, - CancellationToken cancellationToken = default) + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, null, language, null, null, null, null, null, null, null, cancellationToken); - - return await GetCommonReduced("metaregions", searchfilter, language, commonhelper, fields: fields ?? Array.Empty(), rawfilter, rawsort, geosearchresult, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + null, + language, + null, + null, + null, + null, + null, + null, + null, + cancellationToken + ); + + return await GetCommonReduced( + "metaregions", + searchfilter, + language, + commonhelper, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + geosearchresult, + cancellationToken + ); } /// @@ -1143,7 +1835,7 @@ public async Task GetMetaRegionsReduced( /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// Collection of ExperienceAreaName Objects + /// Collection of ExperienceAreaName Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -1157,14 +1849,40 @@ public async Task GetExperienceAreasReduced( string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, - CancellationToken cancellationToken = default) + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, null, language, visibleinsearch, null, null, null, null, null, null, cancellationToken); - - return await GetCommonReduced("experienceareas", searchfilter, language, commonhelper, fields: fields ?? Array.Empty(), rawfilter, rawsort, geosearchresult, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + null, + language, + visibleinsearch, + null, + null, + null, + null, + null, + null, + cancellationToken + ); + + return await GetCommonReduced( + "experienceareas", + searchfilter, + language, + commonhelper, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + geosearchresult, + cancellationToken + ); } /// @@ -1175,7 +1893,7 @@ public async Task GetExperienceAreasReduced( /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// Collection of CommonReduced Objects + /// Collection of CommonReduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -1189,14 +1907,40 @@ public async Task GetRegionsReduced( string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, - CancellationToken cancellationToken = default) + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, null, language, null, null, null, null,null, null, null, cancellationToken); - - return await GetCommonReduced("regions", searchfilter, language, commonhelper, fields: fields ?? Array.Empty(), rawfilter, rawsort, geosearchresult, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + null, + language, + null, + null, + null, + null, + null, + null, + null, + cancellationToken + ); + + return await GetCommonReduced( + "regions", + searchfilter, + language, + commonhelper, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + geosearchresult, + cancellationToken + ); } /// @@ -1207,7 +1951,7 @@ public async Task GetRegionsReduced( /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// Collection of CommonReduced Objects + /// Collection of CommonReduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -1221,14 +1965,40 @@ public async Task GetTourismvereinReduced( string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, - CancellationToken cancellationToken = default) + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, null, language, null, null, null, null, null, null, null, cancellationToken); - - return await GetCommonReduced("tvs", searchfilter, language, commonhelper, fields: fields ?? Array.Empty(), rawfilter, rawsort, geosearchresult, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + null, + language, + null, + null, + null, + null, + null, + null, + null, + cancellationToken + ); + + return await GetCommonReduced( + "tvs", + searchfilter, + language, + commonhelper, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + geosearchresult, + cancellationToken + ); } /// @@ -1240,7 +2010,7 @@ public async Task GetTourismvereinReduced( /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// Collection of CommonReduced Objects + /// Collection of CommonReduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -1254,14 +2024,40 @@ public async Task GetMunicipalityReduced( string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, - CancellationToken cancellationToken = default) + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, null, language, visibleinsearch, null, null, null, null, null, null, cancellationToken); - - return await GetCommonReduced("municipalities", searchfilter, language, commonhelper, fields: fields ?? Array.Empty(), rawfilter, rawsort, geosearchresult, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + null, + language, + visibleinsearch, + null, + null, + null, + null, + null, + null, + cancellationToken + ); + + return await GetCommonReduced( + "municipalities", + searchfilter, + language, + commonhelper, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + geosearchresult, + cancellationToken + ); } /// @@ -1273,7 +2069,7 @@ public async Task GetMunicipalityReduced( /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// Collection of CommonReduced Objects + /// Collection of CommonReduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -1287,14 +2083,40 @@ public async Task GetDistrictReduced( string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, - CancellationToken cancellationToken = default) + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, null, language, visibleinsearch, null, null, null, null, null, null, cancellationToken); - - return await GetCommonReduced("districts", searchfilter, language, commonhelper, fields: fields ?? Array.Empty(), rawfilter, rawsort, geosearchresult, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + null, + language, + visibleinsearch, + null, + null, + null, + null, + null, + null, + cancellationToken + ); + + return await GetCommonReduced( + "districts", + searchfilter, + language, + commonhelper, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + geosearchresult, + cancellationToken + ); } /// @@ -1305,7 +2127,7 @@ public async Task GetDistrictReduced( /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// Collection of CommonReduced Objects + /// Collection of CommonReduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -1319,14 +2141,40 @@ public async Task GetSkiRegionReduced( string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, - CancellationToken cancellationToken = default) + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, null, language, null, null, null, null, null, null, null, cancellationToken); - - return await GetCommonReduced("skiregions", searchfilter, language, commonhelper, fields: fields ?? Array.Empty(), rawfilter, rawsort, geosearchresult, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + null, + language, + null, + null, + null, + null, + null, + null, + null, + cancellationToken + ); + + return await GetCommonReduced( + "skiregions", + searchfilter, + language, + commonhelper, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + geosearchresult, + cancellationToken + ); } /// @@ -1337,7 +2185,7 @@ public async Task GetSkiRegionReduced( /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in Meters. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') - /// Collection of CommonReduced Objects + /// Collection of CommonReduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -1351,33 +2199,91 @@ public async Task GetSkiAreaReduced( string? searchfilter = null, string? rawfilter = null, string? rawsort = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, - CancellationToken cancellationToken = default) + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, + CancellationToken cancellationToken = default + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - CommonHelper commonhelper = await CommonHelper.CreateAsync(QueryFactory, null, language, null, null, null, null, null, null, null, cancellationToken); - - return await GetCommonReduced("skiareas", searchfilter, language, commonhelper, fields: fields ?? Array.Empty(), rawfilter, rawsort, geosearchresult, cancellationToken); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + CommonHelper commonhelper = await CommonHelper.CreateAsync( + QueryFactory, + null, + language, + null, + null, + null, + null, + null, + null, + null, + cancellationToken + ); + + return await GetCommonReduced( + "skiareas", + searchfilter, + language, + commonhelper, + fields: fields ?? Array.Empty(), + rawfilter, + rawsort, + geosearchresult, + cancellationToken + ); } - private Task GetCommonReduced(string tablename, string? searchfilter, string? language, CommonHelper commonhelper, string[] fields, string? rawfilter, string? rawsort, PGGeoSearchResult geosearchresult, CancellationToken cancellationToken) + private Task GetCommonReduced( + string tablename, + string? searchfilter, + string? language, + CommonHelper commonhelper, + string[] fields, + string? rawfilter, + string? rawsort, + PGGeoSearchResult geosearchresult, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { - string select = $"data#>>'\\{{Id\\}}' as Id, data#>>'\\{{Detail,{language},Title\\}}' as Name"; + string select = + $"data#>>'\\{{Id\\}}' as Id, data#>>'\\{{Detail,{language},Title\\}}' as Name"; string orderby = "data#>>'\\{Shortname\\}' ASC"; //Custom Fields filter if (fields.Length > 0) - select += string.Join("", fields.Where(x => x != "Id").Select(field => $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"")); + select += string.Join( + "", + fields + .Where(x => x != "Id") + .Select( + field => + $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"" + ) + ); - var query = - (XQuery)QueryFactory.Query() + var query = (XQuery) + QueryFactory + .Query() .SelectRaw(select) .From(tablename) - .CommonWhereExpression(idlist: commonhelper.idlist, languagelist: commonhelper.languagelist, visibleinsearch: commonhelper.visibleinsearch, smgtaglist: commonhelper.smgtaglist, activefilter: commonhelper.active, odhactivefilter: commonhelper.smgactive, - publishedonlist: commonhelper.publishedonlist, sourcelist: commonhelper.sourcelist, searchfilter: searchfilter, language: language, lastchange: commonhelper.lastchange, filterClosedData: FilterClosedData) + .CommonWhereExpression( + idlist: commonhelper.idlist, + languagelist: commonhelper.languagelist, + visibleinsearch: commonhelper.visibleinsearch, + smgtaglist: commonhelper.smgtaglist, + activefilter: commonhelper.active, + odhactivefilter: commonhelper.smgactive, + publishedonlist: commonhelper.publishedonlist, + sourcelist: commonhelper.sourcelist, + searchfilter: searchfilter, + language: language, + lastchange: commonhelper.lastchange, + filterClosedData: FilterClosedData + ) .ApplyRawFilter(rawfilter) .ApplyOrdering_GeneratedColumns(geosearchresult, rawsort, orderby); //.OrderByRaw(orderby) @@ -1385,7 +2291,10 @@ private Task GetCommonReduced(string tablename, string? searchfil var compiled = query.Compiler.Compile(query); - var reader = await query.Connection.ExecuteReaderAsync(compiled.Sql, compiled.NamedBindings); + var reader = await query.Connection.ExecuteReaderAsync( + compiled.Sql, + compiled.NamedBindings + ); return reader.ReadAndParseTOJson(); }); @@ -1399,15 +2308,15 @@ private Task GetCommonReduced(string tablename, string? searchfil /// GET Webcam Reduced List /// /// Localization Language, (default:'en') - /// Source Filter(String, ), (default:'null') + /// Source Filter(String, ), (default:'null') /// Active Webcam Filter (possible Values: 'true' only Active Gastronomies, 'false' only Disabled Gastronomies - /// ODH Active (refers to field SmgActive) (Published) Webcam Filter (possible Values: 'true' only published Webcam, 'false' only not published Webcam, (default:'null') + /// ODH Active (refers to field SmgActive) (Published) Webcam Filter (possible Values: 'true' only published Webcam, 'false' only not published Webcam, (default:'null') /// GeoFilter Latitude Format: '46.624975', 'null' = disabled, (default:'null') /// GeoFilter Longitude Format: '11.369909', 'null' = disabled, (default:'null') /// Radius to Search in KM. Only Object withhin the given point and radius are returned and sorted by distance. Random Sorting is disabled if the GeoFilter Informations are provided, (default:'null') /// Select fields to display, by Default Title and Id are selected if fields filter is null More fields are indicated by separator ',' example fields=Id,Active,Shortname. Select also Dictionary fields, example Detail.de.Title, or Elements of Arrays example ImageGallery[0].ImageUrl. (default:'null' all fields are displayed) /// Date from Format (yyyy-MM-dd) (all GBActivityPoi with LastChange >= datefrom are passed), (default: DateTime.Now - 1 Day) - /// Collection of WebcamInfoReduced Objects + /// Collection of WebcamInfoReduced Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -1421,62 +2330,109 @@ public async Task GetReducedWebcamInfoAsync( string? latitude = null, string? longitude = null, string? radius = null, - [ModelBinder(typeof(CommaSeparatedArrayBinder))] - string[]? fields = null, + [ModelBinder(typeof(CommaSeparatedArrayBinder))] string[]? fields = null, string? searchfilter = null, string? rawfilter = null, string? rawsort = null, bool suedtirolmobil = false, CancellationToken cancellationToken = default - ) + ) { - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - - return await GetWebcamInfoReduced(fields: fields ?? Array.Empty(), language, source, searchfilter, active?.Value, odhactive?.Value, - updatefrom, geosearchresult, rawfilter, rawsort, cancellationToken); - + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + + return await GetWebcamInfoReduced( + fields: fields ?? Array.Empty(), + language, + source, + searchfilter, + active?.Value, + odhactive?.Value, + updatefrom, + geosearchresult, + rawfilter, + rawsort, + cancellationToken + ); } private Task GetWebcamInfoReduced( - string[] fields, string? language, string? source, - string? searchfilter, bool? active, bool? smgactive, - string? lastchange, PGGeoSearchResult geosearchresult, - string? rawfilter, string? rawsort, CancellationToken cancellationToken) + string[] fields, + string? language, + string? source, + string? searchfilter, + bool? active, + bool? smgactive, + string? lastchange, + PGGeoSearchResult geosearchresult, + string? rawfilter, + string? rawsort, + CancellationToken cancellationToken + ) { return DoAsyncReturn(async () => { WebcamInfoHelper mywebcaminfohelper = WebcamInfoHelper.Create( - source, null, active, smgactive, lastchange, null); - - string select = $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Webcamname,{language}\\}}' as \"Name\""; + source, + null, + active, + smgactive, + lastchange, + null + ); + + string select = + $"data#>>'\\{{Id\\}}' as \"Id\", data#>>'\\{{Webcamname,{language}\\}}' as \"Name\""; //string orderby = "data#>>'\\{Shortname\\}' ASC"; //Custom Fields filter if (fields.Length > 0) - select += string.Join("", fields.Where(x => x != "Id").Select(field => $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"")); + select += string.Join( + "", + fields + .Where(x => x != "Id") + .Select( + field => + $", data#>'\\{{{field.Replace(".", ",")}\\}}' as \"{field}\"" + ) + ); - var query = - (XQuery)QueryFactory.Query() + var query = (XQuery) + QueryFactory + .Query() .SelectRaw(select) .From("webcams") - .WebCamInfoWhereExpression( - idlist: mywebcaminfohelper.idlist, sourcelist: mywebcaminfohelper.sourcelist, - activefilter: mywebcaminfohelper.active, smgactivefilter: mywebcaminfohelper.smgactive, publishedonlist: mywebcaminfohelper.publishedonlist, - searchfilter: searchfilter, language: language, lastchange: mywebcaminfohelper.lastchange, - languagelist: new List(), filterClosedData: FilterClosedData, reducedData: ReducedData) + .WebCamInfoWhereExpression( + idlist: mywebcaminfohelper.idlist, + sourcelist: mywebcaminfohelper.sourcelist, + activefilter: mywebcaminfohelper.active, + smgactivefilter: mywebcaminfohelper.smgactive, + publishedonlist: mywebcaminfohelper.publishedonlist, + searchfilter: searchfilter, + language: language, + lastchange: mywebcaminfohelper.lastchange, + languagelist: new List(), + filterClosedData: FilterClosedData, + reducedData: ReducedData + ) .ApplyRawFilter(rawfilter) .ApplyOrdering_GeneratedColumns(geosearchresult, rawsort); var compiled = query.Compiler.Compile(query); - var reader = await query.Connection.ExecuteReaderAsync(compiled.Sql, compiled.NamedBindings); + var reader = await query.Connection.ExecuteReaderAsync( + compiled.Sql, + compiled.NamedBindings + ); return reader.ReadAndParseTOJson(); }); } #endregion - } class ResultReduced @@ -1485,7 +2441,6 @@ class ResultReduced public string? Name { get; set; } } - public static class CompatibilityHelpers { public static bool ObjectIsNullOrEmpty(this object obj) @@ -1497,10 +2452,9 @@ public static bool ObjectIsNullOrEmpty(this object obj) { var data = new List>(); - var names = - Enumerable.Range(0, reader.FieldCount) - .Select(i => - (i, reader.GetName(i), reader.GetDataTypeName(i))); + var names = Enumerable + .Range(0, reader.FieldCount) + .Select(i => (i, reader.GetName(i), reader.GetDataTypeName(i))); static bool IsJson(string typeName) => typeName switch @@ -1517,13 +2471,19 @@ static bool IsJson(string typeName) => { var value = reader.GetValue(i); //var value = reader.GetString(i); - dict.Add(name, IsJson(typeName) ? value.ObjectIsNullOrEmpty() ? null : new JRaw(value) : value); + dict.Add( + name, + IsJson(typeName) + ? value.ObjectIsNullOrEmpty() + ? null + : new JRaw(value) + : value + ); } data.Add(dict); } return data; } - } } diff --git a/OdhApiCore/Controllers/other/DeprecatedController.cs b/OdhApiCore/Controllers/other/DeprecatedController.cs index 9449c5162..896248d9f 100644 --- a/OdhApiCore/Controllers/other/DeprecatedController.cs +++ b/OdhApiCore/Controllers/other/DeprecatedController.cs @@ -21,19 +21,25 @@ public class DeprecatedController : ControllerBase [HttpGet, Route("v1/Deprecated")] public async Task Deprecated() { - var requesturl = string.Format("{0}://{1}{2}{3}", HttpContext.Request.Scheme, HttpContext.Request.Host, HttpContext.Request.Path, "swagger/v1/swagger.json"); + var requesturl = string.Format( + "{0}://{1}{2}{3}", + HttpContext.Request.Scheme, + HttpContext.Request.Host, + HttpContext.Request.Path, + "swagger/v1/swagger.json" + ); using (var client = new HttpClient()) { var response = await client.GetAsync(requesturl); - var responsecontent = await response.Content.ReadAsStringAsync(); + var responsecontent = await response.Content.ReadAsStringAsync(); JObject? obj = JsonConvert.DeserializeObject(responsecontent); //obj["dialog"]["prompt"] return Ok(obj); - } + } } } diff --git a/OdhApiCore/Controllers/other/FileUploadController.cs b/OdhApiCore/Controllers/other/FileUploadController.cs index 5c887f3fb..188a37a49 100644 --- a/OdhApiCore/Controllers/other/FileUploadController.cs +++ b/OdhApiCore/Controllers/other/FileUploadController.cs @@ -26,7 +26,11 @@ public class FileUploadController : ControllerBase private readonly ISettings settings; protected ILogger Logger { get; } - public FileUploadController(IWebHostEnvironment env, ISettings settings, ILogger logger) + public FileUploadController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger + ) { this.env = env; this.settings = settings; @@ -34,7 +38,9 @@ public FileUploadController(IWebHostEnvironment env, ISettings settings, ILogger } //[ApiExplorerSettings(IgnoreApi = true)] - [Authorize(Roles = "DataWriter,DataModify,DataCreate,ODHPoiCreate,ODHPoiModify,ODHPoiManager,CommonCreate,CommonModify,CommonManager,ArticleCreate,ArticleModify,ArticleManager,EventShortManager,EventShortCreate")] + [Authorize( + Roles = "DataWriter,DataModify,DataCreate,ODHPoiCreate,ODHPoiModify,ODHPoiManager,CommonCreate,CommonModify,CommonManager,ArticleCreate,ArticleModify,ArticleManager,EventShortManager,EventShortCreate" + )] //[HttpPost, Route("v1/FileUpload/{type}/{directory}")] [HttpPost, Route("v1/FileUpload")] [HttpPost, Route("v1/FileUpload/Image")] @@ -64,10 +70,14 @@ public async Task PostFormData(IFormCollection form) }; var response = await client.PutObjectAsync(request); //UploadPartAsync(request); - if(IsFileImage(file.ContentType)) - filenames.Add(String.Format("{0}{1}", settings.S3ImageresizerConfig.Url, filename)); + if (IsFileImage(file.ContentType)) + filenames.Add( + String.Format("{0}{1}", settings.S3ImageresizerConfig.Url, filename) + ); else - filenames.Add(String.Format("{0}{1}", settings.S3ImageresizerConfig.DocUrl, filename)); + filenames.Add( + String.Format("{0}{1}", settings.S3ImageresizerConfig.DocUrl, filename) + ); } if (filenames.Count == 1) return Ok(filenames.FirstOrDefault()); @@ -76,7 +86,9 @@ public async Task PostFormData(IFormCollection form) } [ApiExplorerSettings(IgnoreApi = true)] - [Authorize(Roles = "DataWriter,DataModify,DataCreate,ODHPoiCreate,ODHPoiModify,ODHPoiManager,CommonCreate,CommonModify,CommonManager,ArticleCreate,ArticleModify,ArticleManager,EventShortManager,EventShortCreate")] + [Authorize( + Roles = "DataWriter,DataModify,DataCreate,ODHPoiCreate,ODHPoiModify,ODHPoiManager,CommonCreate,CommonModify,CommonManager,ArticleCreate,ArticleModify,ArticleManager,EventShortManager,EventShortCreate" + )] [HttpPost, Route("v1/FileUpload/Doc")] public async Task PostFormDataPDF(IFormCollection form) { @@ -104,7 +116,9 @@ public async Task PostFormDataPDF(IFormCollection form) }; var response = await client.PutObjectAsync(request); - filenames.Add(String.Format("{0}{1}", settings.S3ImageresizerConfig.DocUrl, filename)); + filenames.Add( + String.Format("{0}{1}", settings.S3ImageresizerConfig.DocUrl, filename) + ); } if (filenames.Count == 1) return Ok(filenames.FirstOrDefault()); @@ -113,7 +127,9 @@ public async Task PostFormDataPDF(IFormCollection form) } //[ApiExplorerSettings(IgnoreApi = true)] - [Authorize(Roles = "DataWriter,DataMofify,DataCreate,DataDelete,ODHPoiCreate,ODHPoiModify,ODHPoiManager,ODHPoiUpdate,CommonCreate,CommonModify,CommonManager,CommonDelete,ArticleCreate,ArticleModify,ArticleManager,ArticleDelete")] + [Authorize( + Roles = "DataWriter,DataMofify,DataCreate,DataDelete,ODHPoiCreate,ODHPoiModify,ODHPoiManager,ODHPoiUpdate,CommonCreate,CommonModify,CommonManager,CommonDelete,ArticleCreate,ArticleModify,ArticleManager,ArticleDelete" + )] [HttpDelete, Route("v1/FileDelete/{filepath}")] public async Task Delete(string filepath) { @@ -164,11 +180,21 @@ public async Task Delete(string filepath) } catch (AmazonS3Exception e) { - return BadRequest(String.Format("Error encountered on server.Message:'{0}' when deleting an object", e.Message)); + return BadRequest( + String.Format( + "Error encountered on server.Message:'{0}' when deleting an object", + e.Message + ) + ); } catch (Exception e) { - return BadRequest(String.Format("Unknown encountered on server. Message:'{0}' when deleting an object", e.Message)); + return BadRequest( + String.Format( + "Unknown encountered on server. Message:'{0}' when deleting an object", + e.Message + ) + ); } } @@ -178,6 +204,4 @@ private static bool IsFileImage(string contenttype) return contenttype.ToLower().StartsWith("image"); } } - - } diff --git a/OdhApiCore/Controllers/other/GpxController.cs b/OdhApiCore/Controllers/other/GpxController.cs index 2a89b7c62..eac692b6c 100644 --- a/OdhApiCore/Controllers/other/GpxController.cs +++ b/OdhApiCore/Controllers/other/GpxController.cs @@ -27,7 +27,7 @@ public Task GetActivityGpx(string tvid, string gpxid) //[Authorize(Roles = "DataReader,ActivityReader,ODHPoiReader")] [HttpGet, Route("v1/Activity/GpxByUrl/{gpxurl}")] public Task GetActivityGpxURL(string gpxurl) - { + { return this.HttpProxyAsync(gpxurl); } @@ -50,12 +50,18 @@ public IActionResult GetSmgPoiGpx(string gpxid) return BadRequest(); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); - response.Content = new StreamContent(new FileStream(AppDomain.CurrentDomain.BaseDirectory + "/Gpx/" + gpxid + ".gpx", FileMode.Open, FileAccess.Read)); - response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); + response.Content = new StreamContent( + new FileStream( + AppDomain.CurrentDomain.BaseDirectory + "/Gpx/" + gpxid + ".gpx", + FileMode.Open, + FileAccess.Read + ) + ); + response.Content.Headers.ContentDisposition = + new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = gpxid + ".gpx"; return Ok(response); } - } } diff --git a/OdhApiCore/Controllers/other/JsonGeneratorController.cs b/OdhApiCore/Controllers/other/JsonGeneratorController.cs index 15c28e7d2..bc73e96d2 100644 --- a/OdhApiCore/Controllers/other/JsonGeneratorController.cs +++ b/OdhApiCore/Controllers/other/JsonGeneratorController.cs @@ -19,14 +19,18 @@ namespace OdhApiCore.Controllers.other { - [ApiExplorerSettings(IgnoreApi = true)] + [ApiExplorerSettings(IgnoreApi = true)] [ApiController] public class JsonGeneratorController : OdhController - { + { private readonly ISettings settings; - public JsonGeneratorController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) + public JsonGeneratorController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { this.settings = settings; } @@ -34,56 +38,78 @@ public JsonGeneratorController(IWebHostEnvironment env, ISettings settings, ILog #region Accommodation [HttpGet, Route("ODH/AccommodationBooklist")] - public async Task ProduceAccoBooklistJson(CancellationToken cancellationToken) + public async Task ProduceAccoBooklistJson( + CancellationToken cancellationToken + ) { try { - await JsonGeneratorHelper.GenerateJSONAccommodationsForBooklist(QueryFactory, settings.JsonConfig.Jsondir, true, "AccosBookable"); - - return Ok(new - { - operation = "Json Generation", - type = "AccommodationBooklist", - message = "Generate Json AccommodationBooklist succeeded", - success = true - }); + await JsonGeneratorHelper.GenerateJSONAccommodationsForBooklist( + QueryFactory, + settings.JsonConfig.Jsondir, + true, + "AccosBookable" + ); + + return Ok( + new + { + operation = "Json Generation", + type = "AccommodationBooklist", + message = "Generate Json AccommodationBooklist succeeded", + success = true + } + ); } - catch(Exception ex) + catch (Exception ex) { - return BadRequest(new - { - operation = "Json Generation", - type = "AccommodationBooklist", - message = "Generate Json AccommodationBooklist failed error:" + ex.Message, - success = false - }); + return BadRequest( + new + { + operation = "Json Generation", + type = "AccommodationBooklist", + message = "Generate Json AccommodationBooklist failed error:" + ex.Message, + success = false + } + ); } } [HttpGet, Route("ODH/AccommodationFulllist")] - public async Task ProduceAccoFulllistJson(CancellationToken cancellationToken) + public async Task ProduceAccoFulllistJson( + CancellationToken cancellationToken + ) { try { - await JsonGeneratorHelper.GenerateJSONAccommodationsForBooklist(QueryFactory, settings.JsonConfig.Jsondir, true, "AccosAll"); - - return Ok(new - { - operation = "Json Generation", - type = "AccommodationFullist", - message = "Generate Json AccommodationFullist succeeded", - success = true - }); + await JsonGeneratorHelper.GenerateJSONAccommodationsForBooklist( + QueryFactory, + settings.JsonConfig.Jsondir, + true, + "AccosAll" + ); + + return Ok( + new + { + operation = "Json Generation", + type = "AccommodationFullist", + message = "Generate Json AccommodationFullist succeeded", + success = true + } + ); } catch (Exception ex) { - return BadRequest(new - { - operation = "Json Generation", - type = "AccommodationFullist", - message = "Generate Json AccommodationBooklist failed error: " + ex.Message, - success = false - }); + return BadRequest( + new + { + operation = "Json Generation", + type = "AccommodationFullist", + message = "Generate Json AccommodationBooklist failed error: " + ex.Message, + success = false + } + ); } } @@ -96,25 +122,33 @@ public async Task ProduceTagJson(CancellationToken cancellationTo { try { - await JsonGeneratorHelper.GenerateJSONTaglist(QueryFactory, settings.JsonConfig.Jsondir, "GenericTags"); - - return Ok(new - { - operation = "Json Generation", - type = "Taglist", - message = "Generate Json Taglist succeeded", - success = true - }); + await JsonGeneratorHelper.GenerateJSONTaglist( + QueryFactory, + settings.JsonConfig.Jsondir, + "GenericTags" + ); + + return Ok( + new + { + operation = "Json Generation", + type = "Taglist", + message = "Generate Json Taglist succeeded", + success = true + } + ); } catch (Exception ex) { - return BadRequest(new - { - operation = "Json Generation", - type = "Taglist", - message = "Generate Json Taglist failed error: " + ex.Message, - success = false - }); + return BadRequest( + new + { + operation = "Json Generation", + type = "Taglist", + message = "Generate Json Taglist failed error: " + ex.Message, + success = false + } + ); } } @@ -122,68 +156,86 @@ public async Task ProduceTagJson(CancellationToken cancellationTo #region STA - [InvalidateCacheOutput(typeof(OdhApiCore.Controllers.sta.STAController), nameof(OdhApiCore.Controllers.sta.STAController.GetODHActivityPoiListSTA))] // this will invalidate Get in a different controller + [InvalidateCacheOutput( + typeof(OdhApiCore.Controllers.sta.STAController), + nameof(OdhApiCore.Controllers.sta.STAController.GetODHActivityPoiListSTA) + )] // this will invalidate Get in a different controller [HttpGet, Route("STA/JsonPoi")] public async Task ProducePoiSTAJson(CancellationToken cancellationToken) { try { - await STARequestHelper.GenerateJSONODHActivityPoiForSTA(QueryFactory, settings.JsonConfig.Jsondir, settings.XmlConfig.Xmldir); - - return Ok(new - { - operation = "Json Generation", - type = "ODHActivityPoi", - message = "Generate Json ODHActivityPoi for STA succeeded", - success = true - }); + await STARequestHelper.GenerateJSONODHActivityPoiForSTA( + QueryFactory, + settings.JsonConfig.Jsondir, + settings.XmlConfig.Xmldir + ); + + return Ok( + new + { + operation = "Json Generation", + type = "ODHActivityPoi", + message = "Generate Json ODHActivityPoi for STA succeeded", + success = true + } + ); } catch (Exception ex) { - return BadRequest(new - { - operation = "Json Generation", - type = "ODHActivityPoi", - message = "Generate Json ODHActivityPoi for STA failed error:" + ex.Message, - success = false - }); + return BadRequest( + new + { + operation = "Json Generation", + type = "ODHActivityPoi", + message = "Generate Json ODHActivityPoi for STA failed error:" + ex.Message, + success = false + } + ); } } - [InvalidateCacheOutput(typeof(OdhApiCore.Controllers.sta.STAController), nameof(OdhApiCore.Controllers.sta.STAController.GetAccommodationsSTA))] // this will invalidate Get in a different controller + [InvalidateCacheOutput( + typeof(OdhApiCore.Controllers.sta.STAController), + nameof(OdhApiCore.Controllers.sta.STAController.GetAccommodationsSTA) + )] // this will invalidate Get in a different controller [HttpGet, Route("STA/JsonAccommodation")] public async Task ProduceAccoSTAJson(CancellationToken cancellationToken) { try { - await STARequestHelper.GenerateJSONAccommodationsForSTA(QueryFactory, settings.JsonConfig.Jsondir); - - return Ok(new - { - operation = "Json Generation", - type = "Accommodation", - message = "Generate Json Accommodation for STA succeeded", - success = true - }); + await STARequestHelper.GenerateJSONAccommodationsForSTA( + QueryFactory, + settings.JsonConfig.Jsondir + ); + + return Ok( + new + { + operation = "Json Generation", + type = "Accommodation", + message = "Generate Json Accommodation for STA succeeded", + success = true + } + ); } catch (Exception ex) { - return BadRequest(new - { - operation = "Json Generation", - type = "Accommodation", - message = "Generate Json Accommodation for STA failed error:" + ex.Message, - success = false - }); + return BadRequest( + new + { + operation = "Json Generation", + type = "Accommodation", + message = "Generate Json Accommodation for STA failed error:" + ex.Message, + success = false + } + ); } } #endregion - //TODO ADD the Json Generation for + //TODO ADD the Json Generation for //Locationlists - - - } -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/other/JsonLDController.cs b/OdhApiCore/Controllers/other/JsonLDController.cs index bdb8e4c8c..5d96f1e9d 100644 --- a/OdhApiCore/Controllers/other/JsonLDController.cs +++ b/OdhApiCore/Controllers/other/JsonLDController.cs @@ -15,12 +15,14 @@ namespace OdhApiCore.Controllers.api { public class JsonLDController : OdhController - { - public JsonLDController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory, IHttpClientFactory httpClientFactory) - : base(env, settings, logger, queryFactory) - { - - } + { + public JsonLDController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory, + IHttpClientFactory httpClientFactory + ) : base(env, settings, logger, queryFactory) { } /// /// GET Detail Data in JSON LD Format (Schema.org Datatypes as output) @@ -35,7 +37,15 @@ public JsonLDController(IWebHostEnvironment env, ISettings settings, ILogger [Authorize(Roles = "DataReader")] [HttpGet, Route("api/JsonLD/DetailInLD")] - public async Task GetDetailInLD(string type, string Id, string language = "en", string idtoshow = "", string urltoshow = "", string imageurltoshow = "", bool showid = true) + public async Task GetDetailInLD( + string type, + string Id, + string language = "en", + string idtoshow = "", + string urltoshow = "", + string imageurltoshow = "", + bool showid = true + ) { try { @@ -44,34 +54,114 @@ public async Task GetDetailInLD(string type, string Id, string la switch (type.ToLower()) { case "accommodation": - myobject = await LoadFromRavenDBSchemaNet(Id, language, idtoshow, urltoshow, imageurltoshow, type.ToLower(), showid); + myobject = await LoadFromRavenDBSchemaNet( + Id, + language, + idtoshow, + urltoshow, + imageurltoshow, + type.ToLower(), + showid + ); break; case "gastronomy": - myobject = await LoadFromRavenDBSchemaNet(Id, language, idtoshow, urltoshow, imageurltoshow, type.ToLower(), showid); + myobject = await LoadFromRavenDBSchemaNet( + Id, + language, + idtoshow, + urltoshow, + imageurltoshow, + type.ToLower(), + showid + ); break; case "event": - myobject = await LoadFromRavenDBSchemaNet(Id, language, idtoshow, urltoshow, imageurltoshow, type.ToLower(), showid); + myobject = await LoadFromRavenDBSchemaNet( + Id, + language, + idtoshow, + urltoshow, + imageurltoshow, + type.ToLower(), + showid + ); break; case "recipe": - myobject = await LoadFromRavenDBSchemaNet
(Id, language, idtoshow, urltoshow, imageurltoshow, type.ToLower(), showid); + myobject = await LoadFromRavenDBSchemaNet
( + Id, + language, + idtoshow, + urltoshow, + imageurltoshow, + type.ToLower(), + showid + ); break; case "poi": - myobject = await LoadFromRavenDBSchemaNet(Id, language, idtoshow, urltoshow, imageurltoshow, type.ToLower(), showid); + myobject = await LoadFromRavenDBSchemaNet( + Id, + language, + idtoshow, + urltoshow, + imageurltoshow, + type.ToLower(), + showid + ); break; case "region": - myobject = await LoadFromRavenDBSchemaNet(Id, language, idtoshow, urltoshow, imageurltoshow, type.ToLower(), showid); + myobject = await LoadFromRavenDBSchemaNet( + Id, + language, + idtoshow, + urltoshow, + imageurltoshow, + type.ToLower(), + showid + ); break; case "tv": - myobject = await LoadFromRavenDBSchemaNet(Id, language, idtoshow, urltoshow, imageurltoshow, type.ToLower(), showid); + myobject = await LoadFromRavenDBSchemaNet( + Id, + language, + idtoshow, + urltoshow, + imageurltoshow, + type.ToLower(), + showid + ); break; case "municipality": - myobject = await LoadFromRavenDBSchemaNet(Id, language, idtoshow, urltoshow, imageurltoshow, type.ToLower(), showid); + myobject = await LoadFromRavenDBSchemaNet( + Id, + language, + idtoshow, + urltoshow, + imageurltoshow, + type.ToLower(), + showid + ); break; case "district": - myobject = await LoadFromRavenDBSchemaNet(Id, language, idtoshow, urltoshow, imageurltoshow, type.ToLower(), showid); + myobject = await LoadFromRavenDBSchemaNet( + Id, + language, + idtoshow, + urltoshow, + imageurltoshow, + type.ToLower(), + showid + ); break; case "skiarea": - myobject = await LoadFromRavenDBSchemaNet(Id, language, idtoshow, urltoshow, imageurltoshow, type.ToLower(), showid); + myobject = await LoadFromRavenDBSchemaNet( + Id, + language, + idtoshow, + urltoshow, + imageurltoshow, + type.ToLower(), + showid + ); break; default: myobject = new List(); @@ -84,18 +174,23 @@ public async Task GetDetailInLD(string type, string Id, string la if (myobject != null) { if (type.ToLower() == "event") - myjson = JsonConvert.SerializeObject(myobject, Newtonsoft.Json.Formatting.None, - new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore - }); + myjson = JsonConvert.SerializeObject( + myobject, + Newtonsoft.Json.Formatting.None, + new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + } + ); else - myjson = JsonConvert.SerializeObject(myobject.FirstOrDefault(), Newtonsoft.Json.Formatting.None, - new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore - }); - + myjson = JsonConvert.SerializeObject( + myobject.FirstOrDefault(), + Newtonsoft.Json.Formatting.None, + new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + } + ); //switch(myobject.Item1) //{ @@ -116,11 +211,11 @@ public async Task GetDetailInLD(string type, string Id, string la } else return NotFound(); - //return new HttpResponseMessage() - //{ - // StatusCode = HttpStatusCode.NotFound, - // Content = new StringContent("object not found", Encoding.UTF8, "application/ld+json") - //}; + //return new HttpResponseMessage() + //{ + // StatusCode = HttpStatusCode.NotFound, + // Content = new StringContent("object not found", Encoding.UTF8, "application/ld+json") + //}; } catch (Exception ex) { @@ -128,13 +223,21 @@ public async Task GetDetailInLD(string type, string Id, string la } } - private async Task> LoadFromRavenDBSchemaNet(string Id, string language, string idtoshow, string urltoshow, string imagetoshow, string type, bool showid) + private async Task> LoadFromRavenDBSchemaNet( + string Id, + string language, + string idtoshow, + string urltoshow, + string imagetoshow, + string type, + bool showid + ) { - var query = - QueryFactory.Query(type) - .Select("data") - .Where("id", Id.ToUpper()) - .When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query(type) + .Select("data") + .Where("id", Id.ToUpper()) + .When(FilterClosedData, q => q.FilterClosedData()); var myobject = await query.FirstOrDefaultAsync(); @@ -142,11 +245,19 @@ private async Task> LoadFromRavenDBSchemaNet(string Id, string l { var myparsedobject = JsonConvert.DeserializeObject(myobject.Value); if (myparsedobject is { }) - return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet(myparsedobject, type, language, null, idtoshow, urltoshow, imagetoshow, showid); + return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet( + myparsedobject, + type, + language, + null, + idtoshow, + urltoshow, + imagetoshow, + showid + ); } return new(); } - } } diff --git a/OdhApiCore/Controllers/other/LicenseCountController.cs b/OdhApiCore/Controllers/other/LicenseCountController.cs index 248685b40..aca0e4b57 100644 --- a/OdhApiCore/Controllers/other/LicenseCountController.cs +++ b/OdhApiCore/Controllers/other/LicenseCountController.cs @@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; -using OdhApiCore.Filters; +using OdhApiCore.Filters; using SqlKata.Execution; using System; using System.Collections.Generic; @@ -19,15 +19,17 @@ namespace OdhApiCore.Controllers.other [NullStringParameterActionFilter] public class LicenseCountController : OdhController { - public LicenseCountController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) - { - } + public LicenseCountController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { } /// /// GET LicenseCount /// - /// LicenseCountResult Object + /// LicenseCountResult Object /// List created /// Request Error /// Internal Server Error @@ -37,7 +39,8 @@ public LicenseCountController(IWebHostEnvironment env, ISettings settings, ILogg [OdhCacheOutput(ClientTimeSpan = 0, ServerTimeSpan = 36000)] [HttpGet, Route("LicenseCount")] public async Task GetLicenseCount( - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { return await GetAllLicenseCount(cancellationToken); } @@ -46,55 +49,222 @@ private async Task GetAllLicenseCount(CancellationToken cancellat { LicenseCountResult result = new LicenseCountResult(); - result.AccoTotaldataopen = await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata(QueryFactory, "accommodations"); - result.GastroTotaldataopen = await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata(QueryFactory, "gastronomies"); - result.EventTotaldataopen = await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata(QueryFactory, "events"); - result.PoiTotaldataopen = await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata(QueryFactory, "pois"); - result.ActivityTotaldataopen = await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata(QueryFactory, "activities"); - result.RegionTotaldataopen = await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata(QueryFactory, "regions"); - result.TVTotaldataopen = await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata(QueryFactory, "tvs"); - result.SkiAreaTotaldataopen = await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata(QueryFactory, "skiareas"); - result.ODHActivityPoiTotaldataopen = await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata(QueryFactory, "smgpois"); + result.AccoTotaldataopen = + await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata( + QueryFactory, + "accommodations" + ); + result.GastroTotaldataopen = + await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata( + QueryFactory, + "gastronomies" + ); + result.EventTotaldataopen = + await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata( + QueryFactory, + "events" + ); + result.PoiTotaldataopen = await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata( + QueryFactory, + "pois" + ); + result.ActivityTotaldataopen = + await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata( + QueryFactory, + "activities" + ); + result.RegionTotaldataopen = + await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata( + QueryFactory, + "regions" + ); + result.TVTotaldataopen = await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata( + QueryFactory, + "tvs" + ); + result.SkiAreaTotaldataopen = + await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata( + QueryFactory, + "skiareas" + ); + result.ODHActivityPoiTotaldataopen = + await Helper.PostgresLicenseCountHelper.GetTotalCountOpendata( + QueryFactory, + "smgpois" + ); - result.AccoTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount(QueryFactory, "accommodations"); - result.GastroTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount(QueryFactory, "gastronomies"); - result.EventTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount(QueryFactory, "events"); - result.PoiTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount(QueryFactory, "pois"); - result.ActivityTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount(QueryFactory, "activities"); - result.RegionTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount(QueryFactory, "regions"); - result.TVTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount(QueryFactory, "tvs"); - result.SkiAreaTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount(QueryFactory, "skiareas"); - result.ODHActivityPoiTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount(QueryFactory, "smgpois"); + result.AccoTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount( + QueryFactory, + "accommodations" + ); + result.GastroTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount( + QueryFactory, + "gastronomies" + ); + result.EventTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount( + QueryFactory, + "events" + ); + result.PoiTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount( + QueryFactory, + "pois" + ); + result.ActivityTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount( + QueryFactory, + "activities" + ); + result.RegionTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount( + QueryFactory, + "regions" + ); + result.TVTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount( + QueryFactory, + "tvs" + ); + result.SkiAreaTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount( + QueryFactory, + "skiareas" + ); + result.ODHActivityPoiTotaldata = await Helper.PostgresLicenseCountHelper.GetTotalCount( + QueryFactory, + "smgpois" + ); - result.AccoWithCC0Image = await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image(QueryFactory, "accommodations"); - result.GastroWithCC0Image = await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image(QueryFactory, "gastronomies"); - result.EventWithCC0Image = await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image(QueryFactory, "events"); - result.PoiWithCC0Image = await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image(QueryFactory, "pois"); - result.ActivityWithCC0Image = await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image(QueryFactory, "activities"); - result.RegionWithCC0Image = await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image(QueryFactory, "regions"); - result.TVWithCC0Image = await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image(QueryFactory, "tvs"); - result.SkiAreaWithCC0Image = await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image(QueryFactory, "skiareas"); - result.ODHActivityPoiWithCC0Image = await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image(QueryFactory, "smgpois"); + result.AccoWithCC0Image = + await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image( + QueryFactory, + "accommodations" + ); + result.GastroWithCC0Image = + await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image( + QueryFactory, + "gastronomies" + ); + result.EventWithCC0Image = + await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image( + QueryFactory, + "events" + ); + result.PoiWithCC0Image = await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image( + QueryFactory, + "pois" + ); + result.ActivityWithCC0Image = + await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image( + QueryFactory, + "activities" + ); + result.RegionWithCC0Image = + await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image( + QueryFactory, + "regions" + ); + result.TVWithCC0Image = await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image( + QueryFactory, + "tvs" + ); + result.SkiAreaWithCC0Image = + await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image( + QueryFactory, + "skiareas" + ); + result.ODHActivityPoiWithCC0Image = + await Helper.PostgresLicenseCountHelper.GetAllDataWithCC0Image( + QueryFactory, + "smgpois" + ); - result.AccoCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License(QueryFactory, "accommodations"); - result.GastroCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License(QueryFactory, "gastronomies"); - result.EventCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License(QueryFactory, "events"); - result.PoiCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License(QueryFactory, "pois"); - result.ActivityCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License(QueryFactory, "activities"); - result.RegionCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License(QueryFactory, "regions"); - result.TVCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License(QueryFactory, "tvs"); - result.SkiAreaCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License(QueryFactory, "skiareas"); - result.ODHActivityPoiCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License(QueryFactory, "smgpois"); + result.AccoCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License( + QueryFactory, + "accommodations" + ); + result.GastroCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License( + QueryFactory, + "gastronomies" + ); + result.EventCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License( + QueryFactory, + "events" + ); + result.PoiCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License( + QueryFactory, + "pois" + ); + result.ActivityCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License( + QueryFactory, + "activities" + ); + result.RegionCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License( + QueryFactory, + "regions" + ); + result.TVCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License( + QueryFactory, + "tvs" + ); + result.SkiAreaCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License( + QueryFactory, + "skiareas" + ); + result.ODHActivityPoiCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithCC0License( + QueryFactory, + "smgpois" + ); - result.AccoNONCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License(QueryFactory, "accommodations"); - result.GastroNONCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License(QueryFactory, "gastronomies"); - result.EventNONCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License(QueryFactory, "events"); - result.PoiNONCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License(QueryFactory, "pois"); - result.ActivityNONCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License(QueryFactory, "activities"); - result.RegionNONCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License(QueryFactory, "regions"); - result.TVNONCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License(QueryFactory, "tvs"); - result.SkiAreaNONCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License(QueryFactory, "skiareas"); - result.ODHActivityPoiNONCC0ImagesCount = await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License(QueryFactory, "smgpois"); + result.AccoNONCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License( + QueryFactory, + "accommodations" + ); + result.GastroNONCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License( + QueryFactory, + "gastronomies" + ); + result.EventNONCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License( + QueryFactory, + "events" + ); + result.PoiNONCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License( + QueryFactory, + "pois" + ); + result.ActivityNONCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License( + QueryFactory, + "activities" + ); + result.RegionNONCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License( + QueryFactory, + "regions" + ); + result.TVNONCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License( + QueryFactory, + "tvs" + ); + result.SkiAreaNONCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License( + QueryFactory, + "skiareas" + ); + result.ODHActivityPoiNONCC0ImagesCount = + await Helper.PostgresLicenseCountHelper.GetAllImagesWithNONCC0License( + QueryFactory, + "smgpois" + ); return Ok(result); } @@ -102,7 +272,6 @@ private async Task GetAllLicenseCount(CancellationToken cancellat public class LicenseCountResult { - public long AccoTotaldata { get; set; } public long GastroTotaldata { get; set; } public long EventTotaldata { get; set; } diff --git a/OdhApiCore/Controllers/other/LocationController.cs b/OdhApiCore/Controllers/other/LocationController.cs index f36b5edef..7485c1089 100644 --- a/OdhApiCore/Controllers/other/LocationController.cs +++ b/OdhApiCore/Controllers/other/LocationController.cs @@ -23,8 +23,13 @@ public class LocationController : OdhController { private readonly IHttpClientFactory httpClientFactory; - public LocationController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory, IHttpClientFactory httpClientFactory) - : base(env, settings, logger, queryFactory) + public LocationController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory, + IHttpClientFactory httpClientFactory + ) : base(env, settings, logger, queryFactory) { this.httpClientFactory = httpClientFactory; } @@ -35,14 +40,14 @@ public LocationController(IWebHostEnvironment env, ISettings settings, ILogger /// Language field selector, displays data and fields available in the selected language (default 'en'), if 'null' is passed all languages are returned as Dictionary - /// Type ('mta','reg','tvs','mun','fra') Separator ',' : 'null' returns all Location Objects (default) + /// Type ('mta','reg','tvs','mun','fra') Separator ',' : 'null' returns all Location Objects (default) /// Show all Data (true = all, false = show only data marked as visible) /// Locfilter (Separator ',') possible values: mta + MetaREGIONID = (Filter by MetaRegion), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), mun + MUNICIPALITYID = (Filter by Municipality), fra + FRACTIONID = (Filter by Fraction), (default:'null') /// Select fields to display, More fields are indicated by separator ',' example fields=Id,Active,Shortname (default:'null' all fields are displayed). Wiki fields /// Wiki rawfilter /// Wiki rawsort - /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki - /// Reduced List of Locations Objects + /// Remove all Null values from json output. Useful for reducing json size. By default set to false. Documentation on Opendatahub Wiki + /// Reduced List of Locations Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -52,9 +57,16 @@ public async Task GetTheLocationList( string? type = "null", bool showall = true, string? locfilter = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { - return await GetLocationInfoFiltered(language ?? "en", locfilter, showall, type, cancellationToken); + return await GetLocationInfoFiltered( + language ?? "en", + locfilter, + showall, + type, + cancellationToken + ); } /// @@ -62,7 +74,7 @@ public async Task GetTheLocationList( /// /// Language field selector, displays data and fields available in the selected language (default 'en'), if 'null' is passed all languages are returned as Dictionary /// Locfilter (Separator ',') possible values: mta + MetaREGIONID = (Filter by MetaRegion), reg + REGIONID = (Filter by Region), tvs + TOURISMVEREINID = (Filter by Tourismverein), (default:'null') - /// Reduced List of Locations Objects + /// Reduced List of Locations Objects [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] @@ -71,7 +83,8 @@ public async Task GetTheLocationList( public async Task GetTheSkiareaList( string? language = "en", string? locfilter = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default + ) { return await GetSkiAreaInfoFiltered(language ?? "en", locfilter, cancellationToken); } @@ -86,7 +99,13 @@ public async Task GetTheSkiareaList( /// Language /// Location Filter /// Collection of Reduced Location Objects - private async Task GetLocationInfoFiltered(string lang, string? locfilter, bool allactivedata, string? type, CancellationToken cancellationToken) + private async Task GetLocationInfoFiltered( + string lang, + string? locfilter, + bool allactivedata, + string? type, + CancellationToken cancellationToken + ) { List mylocationlist = new List(); List> loclist = new List>(); @@ -133,77 +152,203 @@ private async Task GetLocationInfoFiltered(string lang, string? l if (loctype == "mta") { - var mymetaregionlist = await GetLocationFromDB("metaregions", Tuple.Create("id", locid)); + var mymetaregionlist = await GetLocationFromDB( + "metaregions", + Tuple.Create("id", locid) + ); if (mymetaregionlist != null && mymetaregionlist.Count() > 0) { - var regionlist = mymetaregionlist.FirstOrDefault()?.RegionIds ?? Enumerable.Empty(); - - string regionlistwhere = "data->>'Id' IN (" + Helper.StringHelpers.JoinStringListForPG(",", regionlist, "'") + ") AND " + defaultmunfrafilter; - var myregionlist = await GetLocationFromDB("regions", regionlistwhere); - - string tvlistwhere = "data->>'RegionId' IN (" + Helper.StringHelpers.JoinStringListForPG(",", regionlist, "'") + ") AND " + defaultmunfrafilter; - var mytvlist = await GetLocationFromDB("tvs", tvlistwhere); - - string localitylistwhere = "data->>'RegionId' IN (" + Helper.StringHelpers.JoinStringListForPG(",", regionlist, "'") + ") AND " + defaultmunfrafilter; - var mylocalitylist = await GetLocationFromDB("municipalities", localitylistwhere); - - string fractionlistwhere = "data->>'RegionId' IN (" + Helper.StringHelpers.JoinStringListForPG(",", regionlist, "'") + ") AND " + defaultmunfrafilter; - var myfractionlist = await GetLocationFromDB("districts", fractionlistwhere); - - mymetaregionlistreduced = CreateLocHelperClassDynamic("mta", mymetaregionlist, lang); - myregionlistreduced = CreateLocHelperClassDynamic("reg", myregionlist, lang); - mylocalitylistreduced = CreateLocHelperClassDynamic("mun", mylocalitylist, lang); - mytvlistreduced = CreateLocHelperClassDynamic("tvs", mytvlist, lang); - myfractionlistreduced = CreateLocHelperClassDynamic("fra", myfractionlist, lang); + var regionlist = + mymetaregionlist.FirstOrDefault()?.RegionIds + ?? Enumerable.Empty(); + + string regionlistwhere = + "data->>'Id' IN (" + + Helper.StringHelpers.JoinStringListForPG(",", regionlist, "'") + + ") AND " + + defaultmunfrafilter; + var myregionlist = await GetLocationFromDB( + "regions", + regionlistwhere + ); + + string tvlistwhere = + "data->>'RegionId' IN (" + + Helper.StringHelpers.JoinStringListForPG(",", regionlist, "'") + + ") AND " + + defaultmunfrafilter; + var mytvlist = await GetLocationFromDB( + "tvs", + tvlistwhere + ); + + string localitylistwhere = + "data->>'RegionId' IN (" + + Helper.StringHelpers.JoinStringListForPG(",", regionlist, "'") + + ") AND " + + defaultmunfrafilter; + var mylocalitylist = await GetLocationFromDB( + "municipalities", + localitylistwhere + ); + + string fractionlistwhere = + "data->>'RegionId' IN (" + + Helper.StringHelpers.JoinStringListForPG(",", regionlist, "'") + + ") AND " + + defaultmunfrafilter; + var myfractionlist = await GetLocationFromDB( + "districts", + fractionlistwhere + ); + + mymetaregionlistreduced = CreateLocHelperClassDynamic( + "mta", + mymetaregionlist, + lang + ); + myregionlistreduced = CreateLocHelperClassDynamic( + "reg", + myregionlist, + lang + ); + mylocalitylistreduced = CreateLocHelperClassDynamic( + "mun", + mylocalitylist, + lang + ); + mytvlistreduced = CreateLocHelperClassDynamic( + "tvs", + mytvlist, + lang + ); + myfractionlistreduced = CreateLocHelperClassDynamic( + "fra", + myfractionlist, + lang + ); } } else if (loctype == "reg") { - var myregionlist = await GetLocationFromDB("regions", Tuple.Create("id", locid)); + var myregionlist = await GetLocationFromDB( + "regions", + Tuple.Create("id", locid) + ); - string tvlistwhere = "data->>'RegionId' = '" + locid + "' AND " + defaultmunfrafilter; + string tvlistwhere = + "data->>'RegionId' = '" + locid + "' AND " + defaultmunfrafilter; var mytvlist = await GetLocationFromDB("tvs", tvlistwhere); - string localitylistwhere = "data->>'RegionId' = '" + locid + "' AND " + defaultmunfrafilter; - var mylocalitylist = await GetLocationFromDB("municipalities", localitylistwhere); - - string fractionlistwhere = "data->>'RegionId' = '" + locid + "' AND " + defaultmunfrafilter; - var myfractionlist = await GetLocationFromDB("districts", fractionlistwhere); - - myregionlistreduced = CreateLocHelperClassDynamic("reg", myregionlist, lang); - mylocalitylistreduced = CreateLocHelperClassDynamic("mun", mylocalitylist, lang); - mytvlistreduced = CreateLocHelperClassDynamic("tvs", mytvlist, lang); - myfractionlistreduced = CreateLocHelperClassDynamic("fra", myfractionlist, lang); + string localitylistwhere = + "data->>'RegionId' = '" + locid + "' AND " + defaultmunfrafilter; + var mylocalitylist = await GetLocationFromDB( + "municipalities", + localitylistwhere + ); + + string fractionlistwhere = + "data->>'RegionId' = '" + locid + "' AND " + defaultmunfrafilter; + var myfractionlist = await GetLocationFromDB( + "districts", + fractionlistwhere + ); + + myregionlistreduced = CreateLocHelperClassDynamic( + "reg", + myregionlist, + lang + ); + mylocalitylistreduced = CreateLocHelperClassDynamic( + "mun", + mylocalitylist, + lang + ); + mytvlistreduced = CreateLocHelperClassDynamic( + "tvs", + mytvlist, + lang + ); + myfractionlistreduced = CreateLocHelperClassDynamic( + "fra", + myfractionlist, + lang + ); } else if (loctype == "tvs") { - var mytvlist = await GetLocationFromDB("tvs", Tuple.Create("id", locid)); - - string localitylistwhere = "data->>'TourismvereinId' = '" + locid + "' AND " + defaultmunfrafilter; - var mylocalitylist = await GetLocationFromDB("municipalities", localitylistwhere); - - string fractionlistwhere = "data->>'TourismvereinId' = '" + locid + "' AND " + defaultmunfrafilter; - var myfractionlist = await GetLocationFromDB("districts", fractionlistwhere); - - mytvlistreduced = CreateLocHelperClassDynamic("tvs", mytvlist, lang); - mylocalitylistreduced = CreateLocHelperClassDynamic("mun", mylocalitylist, lang); - myfractionlistreduced = CreateLocHelperClassDynamic("fra", myfractionlist, lang); + var mytvlist = await GetLocationFromDB( + "tvs", + Tuple.Create("id", locid) + ); + + string localitylistwhere = + "data->>'TourismvereinId' = '" + locid + "' AND " + defaultmunfrafilter; + var mylocalitylist = await GetLocationFromDB( + "municipalities", + localitylistwhere + ); + + string fractionlistwhere = + "data->>'TourismvereinId' = '" + locid + "' AND " + defaultmunfrafilter; + var myfractionlist = await GetLocationFromDB( + "districts", + fractionlistwhere + ); + + mytvlistreduced = CreateLocHelperClassDynamic( + "tvs", + mytvlist, + lang + ); + mylocalitylistreduced = CreateLocHelperClassDynamic( + "mun", + mylocalitylist, + lang + ); + myfractionlistreduced = CreateLocHelperClassDynamic( + "fra", + myfractionlist, + lang + ); } else if (loctype == "mun") { - var mylocalitylist = await GetLocationFromDB("municipalities", Tuple.Create("id", locid)); - - string fractionlistwhere = "data->>'MunicipalityId' = '" + locid + "' AND " + defaultmunfrafilter; - var myfractionlist = await GetLocationFromDB("districts", fractionlistwhere); - - mylocalitylistreduced = CreateLocHelperClassDynamic("mun", mylocalitylist, lang); - myfractionlistreduced = CreateLocHelperClassDynamic("fra", myfractionlist, lang); + var mylocalitylist = await GetLocationFromDB( + "municipalities", + Tuple.Create("id", locid) + ); + + string fractionlistwhere = + "data->>'MunicipalityId' = '" + locid + "' AND " + defaultmunfrafilter; + var myfractionlist = await GetLocationFromDB( + "districts", + fractionlistwhere + ); + + mylocalitylistreduced = CreateLocHelperClassDynamic( + "mun", + mylocalitylist, + lang + ); + myfractionlistreduced = CreateLocHelperClassDynamic( + "fra", + myfractionlist, + lang + ); } else if (loctype == "fra") { - var myfractionlist = await GetLocationFromDB("districts", Tuple.Create("id", locid)); - myfractionlistreduced = CreateLocHelperClassDynamic("fra", myfractionlist, lang); + var myfractionlist = await GetLocationFromDB( + "districts", + Tuple.Create("id", locid) + ); + myfractionlistreduced = CreateLocHelperClassDynamic( + "fra", + myfractionlist, + lang + ); } if (locationtypes.Contains("mta") && mymetaregionlistreduced != null) @@ -222,28 +367,63 @@ private async Task GetLocationInfoFiltered(string lang, string? l { if (locationtypes.Contains("mta")) { - var mymetaregionlist = await GetLocationFromDB("metaregions", "data->'Active'='true'"); - mymetaregionlistreduced = CreateLocHelperClassDynamic("mta", mymetaregionlist, lang); + var mymetaregionlist = await GetLocationFromDB( + "metaregions", + "data->'Active'='true'" + ); + mymetaregionlistreduced = CreateLocHelperClassDynamic( + "mta", + mymetaregionlist, + lang + ); } if (locationtypes.Contains("reg")) { - var myregionlist = await GetLocationFromDB("regions", "data->'Active'='true'"); - myregionlistreduced = CreateLocHelperClassDynamic("reg", myregionlist, lang); + var myregionlist = await GetLocationFromDB( + "regions", + "data->'Active'='true'" + ); + myregionlistreduced = CreateLocHelperClassDynamic( + "reg", + myregionlist, + lang + ); } if (locationtypes.Contains("tvs")) { - var mytvlist = await GetLocationFromDB("tvs", "data->'Active'='true'"); - mytvlistreduced = CreateLocHelperClassDynamic("tvs", mytvlist, lang); + var mytvlist = await GetLocationFromDB( + "tvs", + "data->'Active'='true'" + ); + mytvlistreduced = CreateLocHelperClassDynamic( + "tvs", + mytvlist, + lang + ); } if (locationtypes.Contains("mun")) { - var mylocalitylist = await GetLocationFromDB("municipalities", defaultmunfrafilter); - mylocalitylistreduced = CreateLocHelperClassDynamic("mun", mylocalitylist, lang); + var mylocalitylist = await GetLocationFromDB( + "municipalities", + defaultmunfrafilter + ); + mylocalitylistreduced = CreateLocHelperClassDynamic( + "mun", + mylocalitylist, + lang + ); } if (locationtypes.Contains("fra")) { - var myfractionlist = await GetLocationFromDB("districts", defaultmunfrafilter); - myfractionlistreduced = CreateLocHelperClassDynamic("fra", myfractionlist, lang); + var myfractionlist = await GetLocationFromDB( + "districts", + defaultmunfrafilter + ); + myfractionlistreduced = CreateLocHelperClassDynamic( + "fra", + myfractionlist, + lang + ); } if (locationtypes.Contains("mta") && mymetaregionlistreduced != null) @@ -270,7 +450,11 @@ private async Task GetLocationInfoFiltered(string lang, string? l /// /// Collection of Reduced Location Objects [ApiExplorerSettings(IgnoreApi = true)] - private async Task GetSkiAreaInfoFiltered(string lang, string? locfilter, CancellationToken cancellationToken) + private async Task GetSkiAreaInfoFiltered( + string lang, + string? locfilter, + CancellationToken cancellationToken + ) { List mylocationlist = new List(); @@ -307,74 +491,90 @@ private async Task GetSkiAreaInfoFiltered(string lang, string? lo //string skiarealistwhere = "data @> '{ \"TourismvereinIds\": [\"" + locid + "\"]}'"; //var myskiarealist = PostgresSQLHelper.SelectFromTableDataAsObject(conn, "skiareas", "*", skiarealistwhere, "", 0, null); - var myskiarealistquery = - QueryFactory.Query() - .Select("data") - .From("skiareas") - .WhereInJsonb( + var myskiarealistquery = QueryFactory + .Query() + .Select("data") + .From("skiareas") + .WhereInJsonb( new List() { locid }, tvid => new { TourismvereinIds = new[] { tvid.ToUpper() } } - ); + ); var myskiarealist = await myskiarealistquery.GetObjectListAsync(); - myskiarealistreduced = CreateLocHelperClassDynamic("ska", myskiarealist, lang); + myskiarealistreduced = CreateLocHelperClassDynamic( + "ska", + myskiarealist, + lang + ); } else if (loctype == "reg") { //string skiarealistwhere = "data @> '{ \"RegionIds\": [\"" + locid + "\"]}'"; - var myskiarealistquery = - QueryFactory.Query() - .Select("data") - .From("skiareas") - .WhereInJsonb( + var myskiarealistquery = QueryFactory + .Query() + .Select("data") + .From("skiareas") + .WhereInJsonb( new List() { locid }, regid => new { RegionIds = new[] { regid.ToUpper() } } - ); + ); var myskiarealist = await myskiarealistquery.GetObjectListAsync(); - myskiarealistreduced = CreateLocHelperClassDynamic("ska", myskiarealist, lang); + myskiarealistreduced = CreateLocHelperClassDynamic( + "ska", + myskiarealist, + lang + ); } else if (loctype == "mta") { - var mymetaregion = await QueryFactory.Query() - .Select("data") - .From("metaregions") - .Where("id", locid) - .GetObjectSingleAsync(); - - var myskiarealistquery = - QueryFactory.Query() - .Select("data") - .From("skiareas") - .WhereInJsonb( - mymetaregion.RegionIds?.ToList() ?? new List(), + var mymetaregion = await QueryFactory + .Query() + .Select("data") + .From("metaregions") + .Where("id", locid) + .GetObjectSingleAsync(); + + var myskiarealistquery = QueryFactory + .Query() + .Select("data") + .From("skiareas") + .WhereInJsonb( + mymetaregion.RegionIds?.ToList() ?? new List(), regid => new { RegionIds = new[] { regid.ToUpper() } } - ); + ); var myskiarealist = await myskiarealistquery.GetObjectListAsync(); - myskiarealistreduced = CreateLocHelperClassDynamic("ska", myskiarealist, lang); + myskiarealistreduced = CreateLocHelperClassDynamic( + "ska", + myskiarealist, + lang + ); } - if(myskiarealistreduced != null && myskiarealistreduced.Count() > 0) + if (myskiarealistreduced != null && myskiarealistreduced.Count() > 0) mylocationlist.AddRange(myskiarealistreduced); } } else { - var myskiarealistquery = - QueryFactory.Query() - .Select("data") - .From("skiareas"); + var myskiarealistquery = QueryFactory.Query().Select("data").From("skiareas"); var myskiarealist = await myskiarealistquery.GetObjectListAsync(); - myskiarealistreduced = CreateLocHelperClassDynamic("ska", myskiarealist, lang); + myskiarealistreduced = CreateLocHelperClassDynamic( + "ska", + myskiarealist, + lang + ); mylocationlist.AddRange(myskiarealistreduced); } //TO TEST - List mylocationlistraw = mylocationlist.Select(x => new JsonRaw(JsonConvert.SerializeObject(x))).ToList(); + List mylocationlistraw = mylocationlist + .Select(x => new JsonRaw(JsonConvert.SerializeObject(x))) + .ToList(); //return mylocationlist; @@ -386,34 +586,61 @@ private async Task GetSkiAreaInfoFiltered(string lang, string? lo #region HelperMethods - private async Task> GetLocationFromDB(string table, string whereraw) where T : notnull + private async Task> GetLocationFromDB(string table, string whereraw) + where T : notnull { - return await QueryFactory.Query() - .Select("data") - .From(table) - .WhereRaw(whereraw) - .GetObjectListAsync(); + return await QueryFactory + .Query() + .Select("data") + .From(table) + .WhereRaw(whereraw) + .GetObjectListAsync(); } - private async Task> GetLocationFromDB(string table, Tuple where) where T : notnull + + private async Task> GetLocationFromDB( + string table, + Tuple where + ) where T : notnull { - return await QueryFactory.Query() - .Select("data") - .From(table) - .Where(where.Item1, where.Item2) - .GetObjectListAsync(); + return await QueryFactory + .Query() + .Select("data") + .From(table) + .Where(where.Item1, where.Item2) + .GetObjectListAsync(); } - private IEnumerable CreateLocHelperClassDynamic(string typ, IEnumerable locationlist, string? lang) where T : IIdentifiable, IDetailInfosAware + private IEnumerable CreateLocHelperClassDynamic( + string typ, + IEnumerable locationlist, + string? lang + ) where T : IIdentifiable, IDetailInfosAware { var locationlistreduced = default(IEnumerable); if (lang != null) - locationlistreduced = locationlist.Select(x => new LocHelperclassDynamic { typ = typ, name = x.Detail[lang].Title, id = x.Id }); + locationlistreduced = locationlist.Select( + x => + new LocHelperclassDynamic + { + typ = typ, + name = x.Detail[lang].Title, + id = x.Id + } + ); else - locationlistreduced = locationlist.Select(x => new LocHelperclassDynamic { typ = typ, name = x.Detail.ToDictionary(y => y.Key, y => y.Value.Title), id = x.Id }); + locationlistreduced = locationlist.Select( + x => + new LocHelperclassDynamic + { + typ = typ, + name = x.Detail.ToDictionary(y => y.Key, y => y.Value.Title), + id = x.Id + } + ); return locationlistreduced; - } + } #endregion } diff --git a/OdhApiCore/Controllers/other/ODHProxyController.cs b/OdhApiCore/Controllers/other/ODHProxyController.cs index a2d6f96f0..4c3780c86 100644 --- a/OdhApiCore/Controllers/other/ODHProxyController.cs +++ b/OdhApiCore/Controllers/other/ODHProxyController.cs @@ -8,9 +8,8 @@ namespace OdhApiCore.Controllers.other [ApiExplorerSettings(IgnoreApi = true)] public class ODHProxyController : ControllerBase { - - [ApiExplorerSettings(IgnoreApi = true)] - [HttpGet, Route("v1/ODHProxy/{*url}")] + [ApiExplorerSettings(IgnoreApi = true)] + [HttpGet, Route("v1/ODHProxy/{*url}")] public Task GetODHProxy(string url) { try @@ -20,7 +19,7 @@ public Task GetODHProxy(string url) foreach (var paramdict in HttpContext.Request.Query) { parameter = parameter + paramdict.Key + "=" + paramdict.Value; - } + } var fullurl = url + parameter; @@ -31,8 +30,8 @@ public Task GetODHProxy(string url) return this.HttpProxyAsync(fullurl); } - catch(Exception ex) - { + catch (Exception ex) + { return Task.FromException(ex); } } diff --git a/OdhApiCore/Controllers/other/OdhAuthorize.cs b/OdhApiCore/Controllers/other/OdhAuthorize.cs index db987778d..f58bfd6fc 100644 --- a/OdhApiCore/Controllers/other/OdhAuthorize.cs +++ b/OdhApiCore/Controllers/other/OdhAuthorize.cs @@ -11,7 +11,7 @@ public class OdhAuthorizeAttribute : TypeFilterAttribute { public OdhAuthorizeAttribute(string roles) : base(typeof(OdhAuthorizeFilter)) { - Arguments = new object[] { roles } ; + Arguments = new object[] { roles }; } } @@ -28,7 +28,10 @@ public void OnAuthorization(AuthorizationFilterContext context) { bool allowed = false; - if (context.HttpContext.User.Identity != null && context.HttpContext.User.Identity.IsAuthenticated) + if ( + context.HttpContext.User.Identity != null + && context.HttpContext.User.Identity.IsAuthenticated + ) { foreach (var role in _roles) { @@ -43,7 +46,7 @@ public void OnAuthorization(AuthorizationFilterContext context) } else context.Result = new UnauthorizedResult(); - + //TODO, if Token is invalid POST not workign anymore? } } diff --git a/OdhApiCore/Controllers/other/PushNotificationController.cs b/OdhApiCore/Controllers/other/PushNotificationController.cs index 012ba032c..4ce98ce7a 100644 --- a/OdhApiCore/Controllers/other/PushNotificationController.cs +++ b/OdhApiCore/Controllers/other/PushNotificationController.cs @@ -17,8 +17,12 @@ public class PushNotificationController : OdhController { private readonly ISettings settings; - public PushNotificationController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) + public PushNotificationController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { this.settings = settings; } @@ -38,11 +42,11 @@ public async Task Get(string type, string id) var mytable = ODHTypeHelper.TranslateTypeString2Table(type); var mytype = ODHTypeHelper.TranslateTypeString2Type(type); - var query = - QueryFactory.Query(mytable) - .Select("data") - .Where("id", ODHTypeHelper.ConvertIdbyTypeString(type, id)) - .When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query(mytable) + .Select("data") + .Where("id", ODHTypeHelper.ConvertIdbyTypeString(type, id)) + .When(FilterClosedData, q => q.FilterClosedData()); // TODO: Create a logic that constructs a message out of the object @@ -52,7 +56,13 @@ public async Task Get(string type, string id) var message = new PushServerMessage(); - var result = await SendToPushServer.SendMessageToPushServer(pushserverconfig.ServiceUrl, message, pushserverconfig.User, pushserverconfig.Password, message.destination.language); + var result = await SendToPushServer.SendMessageToPushServer( + pushserverconfig.ServiceUrl, + message, + pushserverconfig.User, + pushserverconfig.Password, + message.destination.language + ); return Ok(result); } @@ -69,7 +79,13 @@ public async Task Post([FromBody] PushServerMessage message) { var pushserverconfig = settings.PushServerConfig; - var result = await SendToPushServer.SendMessageToPushServer(pushserverconfig.ServiceUrl, message, pushserverconfig.User, pushserverconfig.Password, message.destination.language); + var result = await SendToPushServer.SendMessageToPushServer( + pushserverconfig.ServiceUrl, + message, + pushserverconfig.User, + pushserverconfig.Password, + message.destination.language + ); return Ok(result); } @@ -85,7 +101,12 @@ public async Task Post([FromBody] PushServerMessage message) [ApiExplorerSettings(IgnoreApi = true)] [Authorize(Roles = "DataWriter,DataCreate,PushMessageWriter")] [HttpGet, Route("FCMMessage/{type}/{id}/{identifier}/{language}")] - public async Task GetFCM(string type, string id, string identifier, string language) + public async Task GetFCM( + string type, + string id, + string identifier, + string language + ) { try { @@ -93,11 +114,11 @@ public async Task GetFCM(string type, string id, string identifie var mytable = ODHTypeHelper.TranslateTypeString2Table(type); var mytype = ODHTypeHelper.TranslateTypeString2Type(type); - var query = - QueryFactory.Query(mytable) - .Select("data") - .Where("id", ODHTypeHelper.ConvertIdbyTypeString(type, id)) - .When(FilterClosedData, q => q.FilterClosedData()); + var query = QueryFactory + .Query(mytable) + .Select("data") + .Where("id", ODHTypeHelper.ConvertIdbyTypeString(type, id)) + .When(FilterClosedData, q => q.FilterClosedData()); var fieldsTohide = FieldsToHide; @@ -116,7 +137,11 @@ public async Task GetFCM(string type, string id, string identifie foreach (var lang in langarr) { //Construct the message - var message = FCMMessageConstructor.ConstructMyMessage(identifier, lang.ToLower(), myobject); + var message = FCMMessageConstructor.ConstructMyMessage( + identifier, + lang.ToLower(), + myobject + ); if (message != null) messages.Add(message); @@ -124,7 +149,9 @@ public async Task GetFCM(string type, string id, string identifie throw new Exception("Message could not be constructed"); } - var pushserverconfig = settings.FCMConfig.Where(x => x.Identifier == identifier).FirstOrDefault(); + var pushserverconfig = settings.FCMConfig + .Where(x => x.Identifier == identifier) + .FirstOrDefault(); if (pushserverconfig == null) throw new Exception("PushserverConfig could not be found"); @@ -133,7 +160,12 @@ public async Task GetFCM(string type, string id, string identifie foreach (var message in messages) { - var result = await FCMPushNotification.SendNotification(message, " https://fcm.googleapis.com/fcm/send", pushserverconfig.SenderId, pushserverconfig.ServerKey); + var result = await FCMPushNotification.SendNotification( + message, + " https://fcm.googleapis.com/fcm/send", + pushserverconfig.SenderId, + pushserverconfig.ServerKey + ); resultlist.Add(message.to, result); } @@ -144,7 +176,6 @@ public async Task GetFCM(string type, string id, string identifie { return BadRequest("Error: " + ex.Message); } - } /// @@ -155,14 +186,24 @@ public async Task GetFCM(string type, string id, string identifie [ApiExplorerSettings(IgnoreApi = true)] [Authorize(Roles = "DataWriter,DataCreate,PushMessageWriter")] [HttpPost, Route("FCMMessage/{identifier}")] - public async Task PostFCMMessage(string identifier, [FromBody] FCMModels message) + public async Task PostFCMMessage( + string identifier, + [FromBody] FCMModels message + ) { //TODO add configurable FCM setting where config can be accessed by identifier - var pushserverconfig = settings.FCMConfig.Where(x => x.Identifier == identifier).FirstOrDefault(); + var pushserverconfig = settings.FCMConfig + .Where(x => x.Identifier == identifier) + .FirstOrDefault(); if (pushserverconfig != null) { - var result = await FCMPushNotification.SendNotification(message, " https://fcm.googleapis.com/fcm/send", pushserverconfig.SenderId, pushserverconfig.ServerKey); + var result = await FCMPushNotification.SendNotification( + message, + " https://fcm.googleapis.com/fcm/send", + pushserverconfig.SenderId, + pushserverconfig.ServerKey + ); return Ok(result); } diff --git a/OdhApiCore/Controllers/other/TestController.cs b/OdhApiCore/Controllers/other/TestController.cs index a763ea6a0..5c762b950 100644 --- a/OdhApiCore/Controllers/other/TestController.cs +++ b/OdhApiCore/Controllers/other/TestController.cs @@ -19,8 +19,8 @@ using System.Globalization; using System.Net.Http; using Swashbuckle.AspNetCore.Annotations; -using DataModel.Annotations; - +using DataModel.Annotations; + namespace OdhApiCore.Controllers.api { [ApiExplorerSettings(IgnoreApi = true)] @@ -32,8 +32,13 @@ public class TestController : OdhController private readonly ISettings settings; private readonly IHttpClientFactory httpClientFactory; - public TestController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory, IHttpClientFactory httpClientFactory) - : base(env, settings, logger, queryFactory) + public TestController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory, + IHttpClientFactory httpClientFactory + ) : base(env, settings, logger, queryFactory) { this.httpClientFactory = httpClientFactory; this.settings = settings; @@ -43,44 +48,48 @@ public TestController(IWebHostEnvironment env, ISettings settings, ILogger("X-Forwarded-For", this.HttpContext); - var xforwardedprotoheader = RemoteIpHelper.GetHeaderValueAs("X-Forwarded-Proto", this.HttpContext); - var xforwardedhostheader = RemoteIpHelper.GetHeaderValueAs("X-Forwarded-Host", this.HttpContext); + var xforwardedforheader = RemoteIpHelper.GetHeaderValueAs( + "X-Forwarded-For", + this.HttpContext + ); + var xforwardedprotoheader = RemoteIpHelper.GetHeaderValueAs( + "X-Forwarded-Proto", + this.HttpContext + ); + var xforwardedhostheader = RemoteIpHelper.GetHeaderValueAs( + "X-Forwarded-Host", + this.HttpContext + ); var xforwardedproto = this.HttpContext.Request.Scheme; - var xforwardedhost = this.HttpContext.Request.Host; + var xforwardedhost = this.HttpContext.Request.Host; return new { @@ -88,18 +97,21 @@ public object GetUrl(CancellationToken cancellationToken) RemoteURL = remoteurl, ForwardedForHeader = xforwardedforheader, ForwardedProtoHeader = xforwardedprotoheader, - ForwardedHostHeader = xforwardedhostheader, + ForwardedHostHeader = xforwardedhostheader, ForwardedProtoContext = xforwardedproto, ForwardedHostContext = xforwardedhost - }; + }; } - //Not working [HttpGet, Route("TestDateTimeConversion1")] public IActionResult GetDatetimeConversion1() { - var date = DateTime.ParseExact("31/12/2020 18:00", "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture); + var date = DateTime.ParseExact( + "31/12/2020 18:00", + "dd/MM/yyyy HH:mm", + CultureInfo.InvariantCulture + ); return Ok(date); } @@ -149,8 +161,18 @@ public IActionResult GetDatetimeConversiont5() [HttpGet, Route("TestDeprecated")] public IActionResult GetDeprecated() { - ObjectwithDeprecated test1 = new ObjectwithDeprecated() { name = "test", name2 = "test", namecol = new List() { "test1", "test2" } }; - ObjectwithDeprecated test2 = new ObjectwithDeprecated() { name = "test2", name2 = "test2", namecol = new List() { "test21", "test22" } }; + ObjectwithDeprecated test1 = new ObjectwithDeprecated() + { + name = "test", + name2 = "test", + namecol = new List() { "test1", "test2" } + }; + ObjectwithDeprecated test2 = new ObjectwithDeprecated() + { + name = "test2", + name2 = "test2", + namecol = new List() { "test21", "test22" } + }; var toreturn = new List(); toreturn.Add(test1); @@ -162,7 +184,7 @@ public IActionResult GetDeprecated() ////Not working //[HttpGet, Route("TestDateTimeConversion6")] //public IActionResult GetDatetimeConversiont6() - //{ + //{ // var date = Convert.ToDateTime("31/12/2020T18:00:00"); // return Ok(date); @@ -203,7 +225,11 @@ public IActionResult GetDeprecated() [HttpGet, Route("WithRole2")] public IActionResult GetWithRole2(CancellationToken cancellationToken) { - return this.Content(User.Identity?.Name + " WithRole2 working", "application/json", Encoding.UTF8); + return this.Content( + User.Identity?.Name + " WithRole2 working", + "application/json", + Encoding.UTF8 + ); } //[HttpGet, Route("Environment")] @@ -257,12 +283,13 @@ public IActionResult GetWithRole2(CancellationToken cancellationToken) #endregion } - + public class ObjectwithDeprecated - { + { public string? name { get; set; } + [SwaggerDeprecated("Will be removed on 12-05-22, please use name instead.")] public string? name2 { get; set; } public ICollection? namecol { get; set; } } -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/other/UpdateApiController.cs b/OdhApiCore/Controllers/other/UpdateApiController.cs index db6835774..64766a96e 100644 --- a/OdhApiCore/Controllers/other/UpdateApiController.cs +++ b/OdhApiCore/Controllers/other/UpdateApiController.cs @@ -24,15 +24,19 @@ namespace OdhApiCore.Controllers.api { - [ApiExplorerSettings(IgnoreApi = true)] + [ApiExplorerSettings(IgnoreApi = true)] [ApiController] public class UpdateApiController : OdhController { private readonly ISettings settings; private readonly IWebHostEnvironment env; - public UpdateApiController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) + public UpdateApiController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { this.env = env; this.settings = settings; @@ -42,11 +46,19 @@ public UpdateApiController(IWebHostEnvironment env, ISettings settings, ILogger< [HttpGet, Route("Raven/{datatype}/Update/{id}")] //[Authorize(Roles = "DataWriter,DataCreate,DataUpdate")] - public async Task UpdateFromRaven(string id, string datatype, CancellationToken cancellationToken) + public async Task UpdateFromRaven( + string id, + string datatype, + CancellationToken cancellationToken + ) { try { - var resulttuple = await GetFromRavenAndTransformToPGObject(id, datatype, cancellationToken); + var resulttuple = await GetFromRavenAndTransformToPGObject( + id, + datatype, + cancellationToken + ); var result = resulttuple.Item2; var updateresult = new UpdateResult @@ -108,7 +120,11 @@ public async Task UpdateFromRaven(string id, string datatype, Can #region ODHRAVEN Helpers - private async Task> GetFromRavenAndTransformToPGObject(string id, string datatype, CancellationToken cancellationToken) + private async Task> GetFromRavenAndTransformToPGObject( + string id, + string datatype, + CancellationToken cancellationToken + ) { var mydata = default(IIdentifiable); var mypgdata = default(IIdentifiable); @@ -119,326 +135,718 @@ private async Task> GetFromRavenAndTransformToPGObje switch (datatype.ToLower()) { case "accommodation": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((AccommodationLinked)mydata, TransformToPGObject.GetAccommodationPGObject); + mypgdata = TransformToPGObject.GetPGObject< + AccommodationLinked, + AccommodationLinked + >( + (AccommodationLinked)mydata, + TransformToPGObject.GetAccommodationPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((AccommodationLinked)mypgdata, "accommodations"); - + myupdateresult = await SaveRavenObjectToPG( + (AccommodationLinked)mypgdata, + "accommodations" + ); + //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((AccommodationLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck( + (AccommodationLinked)mypgdata + ) == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((AccommodationLinked)mypgdata, ReduceDataTransformer.CopyLTSAccommodationToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((AccommodationLinkedReduced)reducedobject, "accommodations"); - } + var reducedobject = ReduceDataTransformer.GetReducedObject( + (AccommodationLinked)mypgdata, + ReduceDataTransformer.CopyLTSAccommodationToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (AccommodationLinkedReduced)reducedobject, + "accommodations" + ); + } //UPDATE ACCOMMODATIONROOMS - var myroomdatalist = await GetDataFromRaven.GetRavenData>("accommodationroom", id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken, "AccommodationRoom?accoid="); + var myroomdatalist = await GetDataFromRaven.GetRavenData< + IEnumerable + >( + "accommodationroom", + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken, + "AccommodationRoom?accoid=" + ); if (myroomdatalist != null) { foreach (var myroomdata in myroomdatalist) { - var mypgroomdata = TransformToPGObject.GetPGObject((AccommodationRoomLinked)myroomdata, TransformToPGObject.GetAccommodationRoomPGObject); - - var accoroomresult = await SaveRavenObjectToPG((AccommodationRoomLinked)mypgroomdata, "accommodationrooms"); + var mypgroomdata = TransformToPGObject.GetPGObject< + AccommodationRoomLinked, + AccommodationRoomLinked + >( + (AccommodationRoomLinked)myroomdata, + TransformToPGObject.GetAccommodationRoomPGObject + ); + + var accoroomresult = await SaveRavenObjectToPG( + (AccommodationRoomLinked)mypgroomdata, + "accommodationrooms" + ); //Merge with updateresult - myupdateresult = GenericResultsHelper.MergeUpdateDetail(new List { myupdateresult, accoroomresult }); + myupdateresult = GenericResultsHelper.MergeUpdateDetail( + new List { myupdateresult, accoroomresult } + ); } } else throw new Exception("No data found!"); - + break; case "gastronomy": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((GastronomyLinked)mydata, TransformToPGObject.GetGastronomyPGObject); + mypgdata = TransformToPGObject.GetPGObject< + GastronomyLinked, + GastronomyLinked + >((GastronomyLinked)mydata, TransformToPGObject.GetGastronomyPGObject); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((GastronomyLinked)mypgdata, "gastronomies"); + myupdateresult = await SaveRavenObjectToPG( + (GastronomyLinked)mypgdata, + "gastronomies" + ); //Check if data has to be reduced and save it - if(ReduceDataTransformer.ReduceDataCheck((GastronomyLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck( + (GastronomyLinked)mypgdata + ) == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((GastronomyLinked)mypgdata, ReduceDataTransformer.CopyLTSGastronomyToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((GastronomyLinkedReduced)reducedobject, "gastronomies"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (GastronomyLinked)mypgdata, + ReduceDataTransformer.CopyLTSGastronomyToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (GastronomyLinkedReduced)reducedobject, + "gastronomies" + ); } break; case "activity": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((LTSActivityLinked)mydata, TransformToPGObject.GetActivityPGObject); + mypgdata = TransformToPGObject.GetPGObject< + LTSActivityLinked, + LTSActivityLinked + >((LTSActivityLinked)mydata, TransformToPGObject.GetActivityPGObject); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((LTSActivityLinked)mypgdata, "activities"); + myupdateresult = await SaveRavenObjectToPG( + (LTSActivityLinked)mypgdata, + "activities" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((LTSActivityLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck( + (LTSActivityLinked)mypgdata + ) == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((LTSActivityLinked)mypgdata, ReduceDataTransformer.CopyLTSActivityToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((LTSActivityLinkedReduced)reducedobject, "activities"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (LTSActivityLinked)mypgdata, + ReduceDataTransformer.CopyLTSActivityToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (LTSActivityLinkedReduced)reducedobject, + "activities" + ); } break; case "poi": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((LTSPoiLinked)mydata, TransformToPGObject.GetPoiPGObject); + mypgdata = TransformToPGObject.GetPGObject( + (LTSPoiLinked)mydata, + TransformToPGObject.GetPoiPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((LTSPoiLinked)mypgdata, "pois"); + myupdateresult = await SaveRavenObjectToPG( + (LTSPoiLinked)mypgdata, + "pois" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((LTSPoiLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck((LTSPoiLinked)mypgdata) + == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((LTSPoiLinked)mypgdata, ReduceDataTransformer.CopyLTSPoiToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((LTSPoiLinkedReduced)reducedobject, "pois"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (LTSPoiLinked)mypgdata, + ReduceDataTransformer.CopyLTSPoiToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (LTSPoiLinkedReduced)reducedobject, + "pois" + ); } break; - case "odhactivitypoi": + case "odhactivitypoi": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((ODHActivityPoiLinked)mydata, TransformToPGObject.GetODHActivityPoiPGObject); + mypgdata = TransformToPGObject.GetPGObject< + ODHActivityPoiLinked, + ODHActivityPoiLinked + >( + (ODHActivityPoiLinked)mydata, + TransformToPGObject.GetODHActivityPoiPGObject + ); else throw new Exception("No data found!"); //Special get all Taglist and traduce it on import - await GenericTaggingHelper.AddMappingToODHActivityPoi(mypgdata, settings.JsonConfig.Jsondir); + await GenericTaggingHelper.AddMappingToODHActivityPoi( + mypgdata, + settings.JsonConfig.Jsondir + ); - myupdateresult = await SaveRavenObjectToPG((ODHActivityPoiLinked)mypgdata, "smgpois"); + myupdateresult = await SaveRavenObjectToPG( + (ODHActivityPoiLinked)mypgdata, + "smgpois" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((ODHActivityPoiLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck( + (ODHActivityPoiLinked)mypgdata + ) == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((ODHActivityPoiLinked)mypgdata, ReduceDataTransformer.CopyLTSODHActivtyPoiToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((LTSODHActivityPoiReduced)reducedobject, "smgpois"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (ODHActivityPoiLinked)mypgdata, + ReduceDataTransformer.CopyLTSODHActivtyPoiToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (LTSODHActivityPoiReduced)reducedobject, + "smgpois" + ); } break; case "event": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((EventLinked)mydata, TransformToPGObject.GetEventPGObject); + mypgdata = TransformToPGObject.GetPGObject( + (EventLinked)mydata, + TransformToPGObject.GetEventPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((EventLinked)mypgdata, "events"); + myupdateresult = await SaveRavenObjectToPG( + (EventLinked)mypgdata, + "events" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((EventLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck((EventLinked)mypgdata) + == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((EventLinked)mypgdata, ReduceDataTransformer.CopyLTSEventToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((EventLinkedReduced)reducedobject, "events"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (EventLinked)mypgdata, + ReduceDataTransformer.CopyLTSEventToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (EventLinkedReduced)reducedobject, + "events" + ); } break; case "webcam": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken, "WebcamInfo/"); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken, + "WebcamInfo/" + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((WebcamInfoLinked)mydata, TransformToPGObject.GetWebcamInfoPGObject); + mypgdata = TransformToPGObject.GetPGObject< + WebcamInfoLinked, + WebcamInfoLinked + >((WebcamInfoLinked)mydata, TransformToPGObject.GetWebcamInfoPGObject); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((WebcamInfoLinked)mypgdata, "webcams"); + myupdateresult = await SaveRavenObjectToPG( + (WebcamInfoLinked)mypgdata, + "webcams" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((WebcamInfoLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck( + (WebcamInfoLinked)mypgdata + ) == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((WebcamInfoLinked)mypgdata, ReduceDataTransformer.CopyLTSWebcamInfoToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((WebcamInfoLinkedReduced)reducedobject, "webcams"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (WebcamInfoLinked)mypgdata, + ReduceDataTransformer.CopyLTSWebcamInfoToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (WebcamInfoLinkedReduced)reducedobject, + "webcams" + ); } break; case "metaregion": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((MetaRegionLinked)mydata, TransformToPGObject.GetMetaRegionPGObject); + mypgdata = TransformToPGObject.GetPGObject< + MetaRegionLinked, + MetaRegionLinked + >((MetaRegionLinked)mydata, TransformToPGObject.GetMetaRegionPGObject); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((MetaRegionLinked)mypgdata, "metaregions"); + myupdateresult = await SaveRavenObjectToPG( + (MetaRegionLinked)mypgdata, + "metaregions" + ); break; case "region": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((RegionLinked)mydata, TransformToPGObject.GetRegionPGObject); + mypgdata = TransformToPGObject.GetPGObject( + (RegionLinked)mydata, + TransformToPGObject.GetRegionPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((RegionLinked)mypgdata, "regions"); + myupdateresult = await SaveRavenObjectToPG( + (RegionLinked)mypgdata, + "regions" + ); break; case "tv": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken, "TourismAssociation/"); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken, + "TourismAssociation/" + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((TourismvereinLinked)mydata, TransformToPGObject.GetTourismAssociationPGObject); + mypgdata = TransformToPGObject.GetPGObject< + TourismvereinLinked, + TourismvereinLinked + >( + (TourismvereinLinked)mydata, + TransformToPGObject.GetTourismAssociationPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((TourismvereinLinked)mypgdata, "tvs"); + myupdateresult = await SaveRavenObjectToPG( + (TourismvereinLinked)mypgdata, + "tvs" + ); break; case "municipality": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((MunicipalityLinked)mydata, TransformToPGObject.GetMunicipalityPGObject); + mypgdata = TransformToPGObject.GetPGObject< + MunicipalityLinked, + MunicipalityLinked + >((MunicipalityLinked)mydata, TransformToPGObject.GetMunicipalityPGObject); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((MunicipalityLinked)mypgdata, "municipalities"); + myupdateresult = await SaveRavenObjectToPG( + (MunicipalityLinked)mypgdata, + "municipalities" + ); break; case "district": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((DistrictLinked)mydata, TransformToPGObject.GetDistrictPGObject); + mypgdata = TransformToPGObject.GetPGObject( + (DistrictLinked)mydata, + TransformToPGObject.GetDistrictPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((DistrictLinked)mypgdata, "districts"); + myupdateresult = await SaveRavenObjectToPG( + (DistrictLinked)mypgdata, + "districts" + ); break; case "experiencearea": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((ExperienceAreaLinked)mydata, TransformToPGObject.GetExperienceAreaPGObject); + mypgdata = TransformToPGObject.GetPGObject< + ExperienceAreaLinked, + ExperienceAreaLinked + >( + (ExperienceAreaLinked)mydata, + TransformToPGObject.GetExperienceAreaPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((ExperienceAreaLinked)mypgdata, "experienceareas"); + myupdateresult = await SaveRavenObjectToPG( + (ExperienceAreaLinked)mypgdata, + "experienceareas" + ); break; case "skiarea": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((SkiAreaLinked)mydata, TransformToPGObject.GetSkiAreaPGObject); + mypgdata = TransformToPGObject.GetPGObject( + (SkiAreaLinked)mydata, + TransformToPGObject.GetSkiAreaPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((SkiAreaLinked)mypgdata, "skiareas"); + myupdateresult = await SaveRavenObjectToPG( + (SkiAreaLinked)mypgdata, + "skiareas" + ); break; case "skiregion": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((SkiRegionLinked)mydata, TransformToPGObject.GetSkiRegionPGObject); + mypgdata = TransformToPGObject.GetPGObject< + SkiRegionLinked, + SkiRegionLinked + >((SkiRegionLinked)mydata, TransformToPGObject.GetSkiRegionPGObject); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((SkiRegionLinked)mypgdata, "skiregions"); + myupdateresult = await SaveRavenObjectToPG( + (SkiRegionLinked)mypgdata, + "skiregions" + ); break; case "article": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((ArticlesLinked)mydata, TransformToPGObject.GetArticlePGObject); + mypgdata = TransformToPGObject.GetPGObject( + (ArticlesLinked)mydata, + TransformToPGObject.GetArticlePGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((ArticlesLinked)mypgdata, "articles"); + myupdateresult = await SaveRavenObjectToPG( + (ArticlesLinked)mypgdata, + "articles" + ); break; case "odhtag": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((ODHTagLinked)mydata, TransformToPGObject.GetODHTagPGObject); + mypgdata = TransformToPGObject.GetPGObject( + (ODHTagLinked)mydata, + TransformToPGObject.GetODHTagPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((ODHTagLinked)mypgdata, "smgtags"); + myupdateresult = await SaveRavenObjectToPG( + (ODHTagLinked)mypgdata, + "smgtags" + ); break; case "measuringpoint": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken, "Weather/Measuringpoint/"); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken, + "Weather/Measuringpoint/" + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((MeasuringpointLinked)mydata, TransformToPGObject.GetMeasuringpointPGObject); + mypgdata = TransformToPGObject.GetPGObject< + MeasuringpointLinked, + MeasuringpointLinked + >( + (MeasuringpointLinked)mydata, + TransformToPGObject.GetMeasuringpointPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((MeasuringpointLinked)mypgdata, "measuringpoints"); + myupdateresult = await SaveRavenObjectToPG( + (MeasuringpointLinked)mypgdata, + "measuringpoints" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((MeasuringpointLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck( + (MeasuringpointLinked)mypgdata + ) == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((MeasuringpointLinked)mypgdata, ReduceDataTransformer.CopyLTSMeasuringpointToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((MeasuringpointLinkedReduced)reducedobject, "measuringpoints"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (MeasuringpointLinked)mypgdata, + ReduceDataTransformer.CopyLTSMeasuringpointToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (MeasuringpointLinkedReduced)reducedobject, + "measuringpoints" + ); } break; case "venue": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((DDVenue)mydata, TransformToPGObject.GetVenuePGObject); + mypgdata = TransformToPGObject.GetPGObject( + (DDVenue)mydata, + TransformToPGObject.GetVenuePGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((DDVenue)mypgdata, "venues"); - + myupdateresult = await SaveRavenObjectToPG( + (DDVenue)mypgdata, + "venues" + ); + //Check if data has to be reduced and save it if (ReduceDataTransformer.ReduceDataCheck((DDVenue)mypgdata) == true) { - var reducedobject = ReduceDataTransformer.GetReducedObject((DDVenue)mypgdata, ReduceDataTransformer.CopyLTSVenueToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((DDVenueReduced)reducedobject, "venues"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (DDVenue)mypgdata, + ReduceDataTransformer.CopyLTSVenueToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (DDVenueReduced)reducedobject, + "venues" + ); } break; case "wine": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((WineLinked)mydata, TransformToPGObject.GetWinePGObject); + mypgdata = TransformToPGObject.GetPGObject( + (WineLinked)mydata, + TransformToPGObject.GetWinePGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((WineLinked)mypgdata, "wines"); + myupdateresult = await SaveRavenObjectToPG( + (WineLinked)mypgdata, + "wines" + ); break; default: throw new Exception("no match found"); } - - return Tuple.Create(mypgdata.Id, GenericResultsHelper.MergeUpdateDetail(new List { myupdateresult, updateresultreduced })); + + return Tuple.Create( + mypgdata.Id, + GenericResultsHelper.MergeUpdateDetail( + new List { myupdateresult, updateresultreduced } + ) + ); } - private async Task SaveRavenObjectToPG(T datatosave, string table) where T : IIdentifiable, IImportDateassigneable, IMetaData, ILicenseInfo + private async Task SaveRavenObjectToPG(T datatosave, string table) + where T : IIdentifiable, IImportDateassigneable, IMetaData, ILicenseInfo { datatosave._Meta.LastUpdate = datatosave.LastChange; @@ -446,9 +854,14 @@ private async Task SaveRavenObjectToPG(T datatosave, string tab var result = await QueryFactory.UpsertData(datatosave, table); - return new UpdateDetail() { created = result.created, updated = result.updated, deleted = result.deleted }; - } + return new UpdateDetail() + { + created = result.created, + updated = result.updated, + deleted = result.deleted + }; + } #endregion } -} \ No newline at end of file +} diff --git a/OdhApiCore/Controllers/sta/STAController.cs b/OdhApiCore/Controllers/sta/STAController.cs index 54b91b612..84fbf9466 100644 --- a/OdhApiCore/Controllers/sta/STAController.cs +++ b/OdhApiCore/Controllers/sta/STAController.cs @@ -17,8 +17,8 @@ using AspNetCore.CacheOutput; using System.IO; using OdhApiCore.GenericHelpers; -using OdhApiCore.Controllers.helper; - +using OdhApiCore.Controllers.helper; + namespace OdhApiCore.Controllers.sta { [ApiExplorerSettings(IgnoreApi = true)] @@ -28,8 +28,12 @@ public class STAController : OdhController private readonly IWebHostEnvironment env; private readonly ISettings settings; - public STAController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) - : base(env, settings, logger, queryFactory) + public STAController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) : base(env, settings, logger, queryFactory) { this.env = env; this.settings = settings; @@ -41,13 +45,17 @@ public STAController(IWebHostEnvironment env, ISettings settings, ILogger GetODHActivityPoiListSTA( string language, - CancellationToken cancellationToken) + CancellationToken cancellationToken + ) { try { var checkedlanguage = CheckLanguages(language); - string fileName = Path.Combine(settings.JsonConfig.Jsondir, $"STAOdhActivitiesPois_{checkedlanguage}.json"); + string fileName = Path.Combine( + settings.JsonConfig.Jsondir, + $"STAOdhActivitiesPois_{checkedlanguage}.json" + ); using (StreamReader r = new StreamReader(fileName)) { @@ -65,15 +73,19 @@ public async Task GetODHActivityPoiListSTA( [OdhCacheOutput(ClientTimeSpan = 14400, ServerTimeSpan = 14400)] [HttpGet, Route("STA/Accommodation")] public async Task GetAccommodationsSTA( - string language, - CancellationToken cancellationToken) + string language, + CancellationToken cancellationToken + ) { try { var checkedlanguage = CheckLanguages(language); //DOCKER ERROR Could not find a part of the path '/app/.\wwwroot\json\/STAAccommodations_de.json'. - string fileName = Path.Combine(settings.JsonConfig.Jsondir, $"STAAccommodations_{checkedlanguage}.json"); + string fileName = Path.Combine( + settings.JsonConfig.Jsondir, + $"STAAccommodations_{checkedlanguage}.json" + ); using (StreamReader r = new StreamReader(fileName)) { @@ -88,7 +100,7 @@ public async Task GetAccommodationsSTA( } } - #endregion + #endregion #region IMPORTER @@ -110,41 +122,47 @@ public async Task GetAccommodationsSTA( [Obsolete("Moved to ODHImporter")] [Authorize(Roles = "DataWriter,STAPoiImport")] [HttpPost, Route("STA/ImportVendingPoints")] - public async Task SendVendingPointsFromSTA(CancellationToken cancellationToken) + public async Task SendVendingPointsFromSTA( + CancellationToken cancellationToken + ) { try { var result = await PostVendingPointsFromSTA(Request); - return Ok(new - { - operation = "Import Vendingpoints", - updatetype = "all", - otherinfo = "STA", - id = "", - message = "Import Vendingpoints succeeded", - recordsmodified = (result.created + result.updated + result.deleted), - created = result.created, - updated = result.updated, - deleted = result.deleted, - success = true - }); + return Ok( + new + { + operation = "Import Vendingpoints", + updatetype = "all", + otherinfo = "STA", + id = "", + message = "Import Vendingpoints succeeded", + recordsmodified = (result.created + result.updated + result.deleted), + created = result.created, + updated = result.updated, + deleted = result.deleted, + success = true + } + ); } catch (Exception ex) { - return BadRequest(new UpdateResult - { - operation = "Import Vendingpoints", - updatetype = "all", - otherinfo = "STA", - id = "", - message = "Import Vendingpoints failed: " + ex.Message, - recordsmodified = 0, - created = 0, - updated = 0, - deleted = 0, - success = false - }); + return BadRequest( + new UpdateResult + { + operation = "Import Vendingpoints", + updatetype = "all", + otherinfo = "STA", + id = "", + message = "Import Vendingpoints failed: " + ex.Message, + recordsmodified = 0, + created = 0, + updated = 0, + deleted = 0, + success = false + } + ); } } @@ -194,23 +212,41 @@ private async Task ImportVendingPointsFromCSV(string csvcontent) foreach (var vendingpoint in vendingpoints.records) { //Parse to ODHActivityPoi - var odhactivitypoi = STA.ParseSTAPois.ParseSTAVendingPointToODHActivityPoi(vendingpoint); + var odhactivitypoi = STA.ParseSTAPois.ParseSTAVendingPointToODHActivityPoi( + vendingpoint + ); //MetaData - odhactivitypoi._Meta = MetadataHelper.GetMetadataobject(odhactivitypoi, MetadataHelper.GetMetadataforOdhActivityPoi); //GetMetadata(data.Id, "odhactivitypoi", sourcemeta, data.LastChange); + odhactivitypoi._Meta = MetadataHelper.GetMetadataobject( + odhactivitypoi, + MetadataHelper.GetMetadataforOdhActivityPoi + ); //GetMetadata(data.Id, "odhactivitypoi", sourcemeta, data.LastChange); //LicenseInfo //License - odhactivitypoi.LicenseInfo = LicenseHelper.GetLicenseforOdhActivityPoi(odhactivitypoi); + odhactivitypoi.LicenseInfo = LicenseHelper.GetLicenseforOdhActivityPoi( + odhactivitypoi + ); - if(odhactivitypoi.GpsPoints.ContainsKey("position")) + if (odhactivitypoi.GpsPoints.ContainsKey("position")) { //Get Nearest District - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(odhactivitypoi.GpsPoints["position"].Latitude, odhactivitypoi.GpsPoints["position"].Longitude, 10000); - var nearestdistrict = await GetLocationInfo.GetNearestDistrict(QueryFactory, geosearchresult, 1); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + odhactivitypoi.GpsPoints["position"].Latitude, + odhactivitypoi.GpsPoints["position"].Longitude, + 10000 + ); + var nearestdistrict = await GetLocationInfo.GetNearestDistrict( + QueryFactory, + geosearchresult, + 1 + ); if (nearestdistrict != null && nearestdistrict.Count() > 0) { //Get LocationInfo Object - var locationinfo = await GetLocationInfo.GetTheLocationInfoDistrict(QueryFactory, nearestdistrict.FirstOrDefault()?.Id); + var locationinfo = await GetLocationInfo.GetTheLocationInfoDistrict( + QueryFactory, + nearestdistrict.FirstOrDefault()?.Id + ); if (locationinfo != null) odhactivitypoi.LocationInfo = locationinfo; @@ -218,14 +254,22 @@ private async Task ImportVendingPointsFromCSV(string csvcontent) } //Adding TypeInfo Additional - odhactivitypoi.AdditionalPoiInfos = await GetAdditionalTypeInfo.GetAdditionalTypeInfoForPoi(QueryFactory, odhactivitypoi?.SubType, new List() { "de","it","en" }); + odhactivitypoi.AdditionalPoiInfos = + await GetAdditionalTypeInfo.GetAdditionalTypeInfoForPoi( + QueryFactory, + odhactivitypoi?.SubType, + new List() { "de", "it", "en" } + ); //Save to PG - //Check if data exists + //Check if data exists - var result = await QueryFactory.UpsertData(odhactivitypoi!, "smgpois"); + var result = await QueryFactory.UpsertData( + odhactivitypoi!, + "smgpois" + ); - if(result.updated != null) + if (result.updated != null) updatecounter = updatecounter + result.updated.Value; if (result.created != null) newcounter = newcounter + result.created.Value; @@ -233,7 +277,12 @@ private async Task ImportVendingPointsFromCSV(string csvcontent) deletecounter = deletecounter + result.deleted.Value; } - return new UpdateDetail() { created = newcounter, updated = updatecounter, deleted = deletecounter }; + return new UpdateDetail() + { + created = newcounter, + updated = updatecounter, + deleted = deletecounter + }; } else if (vendingpoints.Error) throw new Exception(vendingpoints.ErrorMessage); @@ -243,4 +292,4 @@ private async Task ImportVendingPointsFromCSV(string csvcontent) #endregion } -} \ No newline at end of file +} diff --git a/OdhApiCore/Extensions/DistributedCachingExtensions.cs b/OdhApiCore/Extensions/DistributedCachingExtensions.cs index f2e9af39c..834e3354f 100644 --- a/OdhApiCore/Extensions/DistributedCachingExtensions.cs +++ b/OdhApiCore/Extensions/DistributedCachingExtensions.cs @@ -7,19 +7,37 @@ namespace OdhApiCore { public static class DistributedCachingExtensions { - public async static Task SetCacheValueAsync(this IDistributedCache distributedCache, string key, T value, CancellationToken token = default) where T : notnull + public async static Task SetCacheValueAsync( + this IDistributedCache distributedCache, + string key, + T value, + CancellationToken token = default + ) where T : notnull { await distributedCache.SetAsync(key, value.ToByteArray(), token); } - public async static Task SetCacheValueAsync(this IDistributedCache distributedCache, string key, TimeSpan timewindow, T value, CancellationToken token = default) where T : notnull + public async static Task SetCacheValueAsync( + this IDistributedCache distributedCache, + string key, + TimeSpan timewindow, + T value, + CancellationToken token = default + ) where T : notnull { //var options = new DistributedCacheEntryOptions { AbsoluteExpiration = DateTimeOffset.Now.Add(timewindow) }; - var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = timewindow }; + var options = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = timewindow + }; await distributedCache.SetAsync(key, value.ToByteArray(), options, token); } - public async static Task GetCacheValueAsync(this IDistributedCache distributedCache, string key, CancellationToken token = default(CancellationToken)) where T : class + public async static Task GetCacheValueAsync( + this IDistributedCache distributedCache, + string key, + CancellationToken token = default(CancellationToken) + ) where T : class { var result = await distributedCache.GetAsync(key, token); return result.FromByteArray(); diff --git a/OdhApiCore/Extensions/HttpContextExtensions.cs b/OdhApiCore/Extensions/HttpContextExtensions.cs index ad429086c..c83e9c12d 100644 --- a/OdhApiCore/Extensions/HttpContextExtensions.cs +++ b/OdhApiCore/Extensions/HttpContextExtensions.cs @@ -6,14 +6,21 @@ namespace OdhApiCore { public static class HttpContextExtensions { - public static void AddRateLimitHeaders(this HttpContext context, int maxrequests, int requestsdone, int timewindow, string policy, CancellationToken token = default) + public static void AddRateLimitHeaders( + this HttpContext context, + int maxrequests, + int requestsdone, + int timewindow, + string policy, + CancellationToken token = default + ) { var remainingrequests = maxrequests - requestsdone; context.Response.Headers.Add("X-Rate-Limit-Policy", policy); context.Response.Headers.Add("X-Rate-Limit-Limit", maxrequests.ToString()); context.Response.Headers.Add("X-Rate-Limit-Remaining", remainingrequests.ToString()); - context.Response.Headers.Add("X-Rate-Limit-Reset", timewindow.ToString()); + context.Response.Headers.Add("X-Rate-Limit-Reset", timewindow.ToString()); } } } diff --git a/OdhApiCore/Factories/PostgresQueryFactory.cs b/OdhApiCore/Factories/PostgresQueryFactory.cs index b5c17490a..c88728327 100644 --- a/OdhApiCore/Factories/PostgresQueryFactory.cs +++ b/OdhApiCore/Factories/PostgresQueryFactory.cs @@ -7,14 +7,14 @@ namespace OdhApiCore.Factories { - class OdhPostgresCompiler : PostgresCompiler - { - public OdhPostgresCompiler() - { - parameterPlaceholder = "$$"; - } + class OdhPostgresCompiler : PostgresCompiler + { + public OdhPostgresCompiler() + { + parameterPlaceholder = "$$"; + } } - + /// /// For the time of writing QueryFactory doesn't implement IDisposable /// so it is a bit dangerous to use with ASP.NET's DI when used directly. @@ -28,7 +28,8 @@ public PostgresQueryFactory(ISettings settings, ILogger logger) { Connection = new NpgsqlConnection(settings.PostgresConnectionString); Compiler = new OdhPostgresCompiler(); - Logger = info => logger.LogDebug("SQL: {sql} {@parameters}", info.RawSql, info.NamedBindings); + Logger = info => + logger.LogDebug("SQL: {sql} {@parameters}", info.RawSql, info.NamedBindings); } public new void Dispose() diff --git a/OdhApiCore/Filters/AvailabilitySearchInterceptorAttribute.cs b/OdhApiCore/Filters/AvailabilitySearchInterceptorAttribute.cs index 9b0bd6872..f07c224fa 100644 --- a/OdhApiCore/Filters/AvailabilitySearchInterceptorAttribute.cs +++ b/OdhApiCore/Filters/AvailabilitySearchInterceptorAttribute.cs @@ -38,15 +38,22 @@ public bool CheckAvailabilitySearch(System.Security.Claims.ClaimsPrincipal User) return false; } - public AvailabilitySearchInterceptorAttribute(QueryFactory queryFactory, IHttpClientFactory httpClientFactory, ISettings settings) + public AvailabilitySearchInterceptorAttribute( + QueryFactory queryFactory, + IHttpClientFactory httpClientFactory, + ISettings settings + ) { this.httpClientFactory = httpClientFactory; this.settings = settings; this.QueryFactory = queryFactory; } - public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) - { + public override async Task OnActionExecutionAsync( + ActionExecutingContext context, + ActionExecutionDelegate next + ) + { var availabilitysearchavailable = CheckAvailabilitySearch(context.HttpContext.User); // TODO: if Availability Requested and CheckAvailabilitySearch gives false, return a 401 Unauthorized @@ -55,58 +62,135 @@ public override async Task OnActionExecutionAsync(ActionExecutingContext context context.ActionDescriptor.RouteValues.TryGetValue("action", out string? actionid); // Only if Action ID is GetAccommodations perform the Availability Check before - if ((actionid == "GetAccommodations" || actionid == "PostAvailableAccommodations" || actionid == "PostAvailableAccommodationsOnlyMssResult") && availabilitysearchavailable) + if ( + ( + actionid == "GetAccommodations" + || actionid == "PostAvailableAccommodations" + || actionid == "PostAvailableAccommodationsOnlyMssResult" + ) && availabilitysearchavailable + ) { // Getting the Querystrings var actionarguments = context.ActionArguments; bool availabilitycheck = false; - if (actionid == "PostAvailableAccommodations" || actionid == "PostAvailableAccommodationsOnlyMssResult") + if ( + actionid == "PostAvailableAccommodations" + || actionid == "PostAvailableAccommodationsOnlyMssResult" + ) availabilitycheck = true; if (actionid == "GetAccommodations") - availabilitycheck = ((LegacyBool?)actionarguments["availabilitycheck"])?.Value ?? availabilitycheck; - - if(availabilitycheck == true) + availabilitycheck = + ((LegacyBool?)actionarguments["availabilitycheck"])?.Value + ?? availabilitycheck; + + if (availabilitycheck == true) { - string? categoryfilter = actionarguments.ContainsKey("categoryfilter") ? (string?)actionarguments["categoryfilter"] : null; - string? typefilter = actionarguments.ContainsKey("typefilter") ? (string?)actionarguments["typefilter"] : null; - string? featurefilter = actionarguments.ContainsKey("featurefilter") ? (string?)actionarguments["featurefilter"] : null; - string? featureidfilter = actionarguments.ContainsKey("featureidfilter") ? (string?)actionarguments["featureidfilter"] : null; - string? themefilter = actionarguments.ContainsKey("themefilter") ? (string?)actionarguments["themefilter"] : null; - string? badgefilter = actionarguments.ContainsKey("badgefilter") ? (string?)actionarguments["badgefilter"] : null; - string? idfilter = actionarguments.ContainsKey("idfilter") ? (string?)actionarguments["idfilter"] : null; - string? locfilter = actionarguments.ContainsKey("locfilter") ? (string?)actionarguments["locfilter"] : null; - string? altitudefilter = actionarguments.ContainsKey("altitudefilter") ? (string?)actionarguments["altitudefilter"] : null; - string? odhtagfilter = actionarguments.ContainsKey("odhtagfilter") ? (string?)actionarguments["odhtagfilter"] : null; - bool? active = actionarguments.ContainsKey("active") ? ((LegacyBool?)actionarguments["active"])?.Value : null; - bool? odhactive = actionarguments.ContainsKey("odhactive") ? ((LegacyBool?)actionarguments["odhactive"])?.Value : null; - bool? bookablefilter = actionarguments.ContainsKey("bookablefilter") ? ((LegacyBool?)actionarguments["bookablefilter"])?.Value : null; - string? updatefrom = actionarguments.ContainsKey("updatefrom") ? (string?)actionarguments["updatefrom"] : null; - string? seed = actionarguments.ContainsKey("seed") ? (string?)actionarguments["seed"] : null; - string? searchfilter = actionarguments.ContainsKey("searchfilter") ? (string?)actionarguments["searchfilter"] : null; - string? latitude = actionarguments.ContainsKey("latitude") ? (string?)actionarguments["latitude"] : null; - string? longitude = actionarguments.ContainsKey("longitude") ? (string?)actionarguments["longitude"] : null; - string? radius = actionarguments.ContainsKey("radius") ? (string?)actionarguments["radius"] : null; - - string? publishedon = actionarguments.ContainsKey("publishedon") ? (string?)actionarguments["publishedon"] : null; - - string language = actionarguments.ContainsKey("language") ? (string)actionarguments["language"]! : "de"; - string? langfilter = actionarguments.ContainsKey("langfilter") ? (string?)actionarguments!["langfilter"] : null; - - string boardfilter = actionarguments.ContainsKey("boardfilter") ? (string)actionarguments["boardfilter"]! : "0"; - string arrival = actionarguments.ContainsKey("arrival") ? (string)actionarguments["arrival"]! : String.Format("{0:yyyy-MM-dd}", DateTime.Now); - string departure = actionarguments.ContainsKey("departure") ? (string)actionarguments["departure"]! : String.Format("{0:yyyy-MM-dd}", DateTime.Now.AddDays(1)); - string roominfo = actionarguments.ContainsKey("roominfo") ? (string)actionarguments["roominfo"]! : "1-18,18"; - string msssource = actionarguments.ContainsKey("msssource") ? (string)actionarguments["msssource"]! : "sinfo"; - string detail = actionarguments.ContainsKey("detail") ? (string)actionarguments["detail"]! : "0"; - string bokfilter = actionarguments.ContainsKey("bokfilter") ? (string)actionarguments["bokfilter"]! : "hgv"; - string idsource = actionarguments.ContainsKey("idsource") ? (string)actionarguments["idsource"]! : "lts"; - string? sourcefilter = actionarguments.ContainsKey("source") ? (string)actionarguments["source"]! : null; + string? categoryfilter = actionarguments.ContainsKey("categoryfilter") + ? (string?)actionarguments["categoryfilter"] + : null; + string? typefilter = actionarguments.ContainsKey("typefilter") + ? (string?)actionarguments["typefilter"] + : null; + string? featurefilter = actionarguments.ContainsKey("featurefilter") + ? (string?)actionarguments["featurefilter"] + : null; + string? featureidfilter = actionarguments.ContainsKey("featureidfilter") + ? (string?)actionarguments["featureidfilter"] + : null; + string? themefilter = actionarguments.ContainsKey("themefilter") + ? (string?)actionarguments["themefilter"] + : null; + string? badgefilter = actionarguments.ContainsKey("badgefilter") + ? (string?)actionarguments["badgefilter"] + : null; + string? idfilter = actionarguments.ContainsKey("idfilter") + ? (string?)actionarguments["idfilter"] + : null; + string? locfilter = actionarguments.ContainsKey("locfilter") + ? (string?)actionarguments["locfilter"] + : null; + string? altitudefilter = actionarguments.ContainsKey("altitudefilter") + ? (string?)actionarguments["altitudefilter"] + : null; + string? odhtagfilter = actionarguments.ContainsKey("odhtagfilter") + ? (string?)actionarguments["odhtagfilter"] + : null; + bool? active = actionarguments.ContainsKey("active") + ? ((LegacyBool?)actionarguments["active"])?.Value + : null; + bool? odhactive = actionarguments.ContainsKey("odhactive") + ? ((LegacyBool?)actionarguments["odhactive"])?.Value + : null; + bool? bookablefilter = actionarguments.ContainsKey("bookablefilter") + ? ((LegacyBool?)actionarguments["bookablefilter"])?.Value + : null; + string? updatefrom = actionarguments.ContainsKey("updatefrom") + ? (string?)actionarguments["updatefrom"] + : null; + string? seed = actionarguments.ContainsKey("seed") + ? (string?)actionarguments["seed"] + : null; + string? searchfilter = actionarguments.ContainsKey("searchfilter") + ? (string?)actionarguments["searchfilter"] + : null; + string? latitude = actionarguments.ContainsKey("latitude") + ? (string?)actionarguments["latitude"] + : null; + string? longitude = actionarguments.ContainsKey("longitude") + ? (string?)actionarguments["longitude"] + : null; + string? radius = actionarguments.ContainsKey("radius") + ? (string?)actionarguments["radius"] + : null; + + string? publishedon = actionarguments.ContainsKey("publishedon") + ? (string?)actionarguments["publishedon"] + : null; + + string language = actionarguments.ContainsKey("language") + ? (string)actionarguments["language"]! + : "de"; + string? langfilter = actionarguments.ContainsKey("langfilter") + ? (string?)actionarguments!["langfilter"] + : null; + + string boardfilter = actionarguments.ContainsKey("boardfilter") + ? (string)actionarguments["boardfilter"]! + : "0"; + string arrival = actionarguments.ContainsKey("arrival") + ? (string)actionarguments["arrival"]! + : String.Format("{0:yyyy-MM-dd}", DateTime.Now); + string departure = actionarguments.ContainsKey("departure") + ? (string)actionarguments["departure"]! + : String.Format("{0:yyyy-MM-dd}", DateTime.Now.AddDays(1)); + string roominfo = actionarguments.ContainsKey("roominfo") + ? (string)actionarguments["roominfo"]! + : "1-18,18"; + string msssource = actionarguments.ContainsKey("msssource") + ? (string)actionarguments["msssource"]! + : "sinfo"; + string detail = actionarguments.ContainsKey("detail") + ? (string)actionarguments["detail"]! + : "0"; + string bokfilter = actionarguments.ContainsKey("bokfilter") + ? (string)actionarguments["bokfilter"]! + : "hgv"; + string idsource = actionarguments.ContainsKey("idsource") + ? (string)actionarguments["idsource"]! + : "lts"; + string? sourcefilter = actionarguments.ContainsKey("source") + ? (string)actionarguments["source"]! + : null; // Only needed for PostAvailableAccommodations - bool? availabilityonly = actionarguments.ContainsKey("availabilityonly") ? (bool)actionarguments["availabilityonly"]! : false; - bool? withoutids = actionarguments.ContainsKey("withoutids") ? (bool)actionarguments["withoutids"]! : false; + bool? availabilityonly = actionarguments.ContainsKey("availabilityonly") + ? (bool)actionarguments["availabilityonly"]! + : false; + bool? withoutids = actionarguments.ContainsKey("withoutids") + ? (bool)actionarguments["withoutids"]! + : false; if (CheckArrivalAndDeparture(arrival, departure)) { @@ -116,23 +200,61 @@ public override async Task OnActionExecutionAsync(ActionExecutingContext context if (actionid == "GetAccommodations") { AccommodationHelper myhelper = await AccommodationHelper.CreateAsync( - QueryFactory, idfilter: idfilter, locfilter: locfilter, boardfilter: boardfilter, categoryfilter: categoryfilter, typefilter: typefilter, - featurefilter: featurefilter, featureidfilter: featureidfilter, badgefilter: badgefilter, themefilter: themefilter, altitudefilter: altitudefilter, smgtags: odhtagfilter, activefilter: active, - smgactivefilter: odhactive, bookablefilter: bookablefilter, sourcefilter: sourcefilter, lastchange: updatefrom, langfilter: langfilter, publishedonfilter: publishedon, (CancellationToken?)context.ActionArguments["cancellationToken"] ?? new()); - - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(latitude, longitude, radius); - - // Get Accommodations IDlist - var idlist = await GetAccommodationBookList(myhelper, language, seed, searchfilter, geosearchresult); - - booklist = idlist.Where(x => x.Id != null).Select(x => x.Id!.ToUpper()).ToList() ?? new List(); + QueryFactory, + idfilter: idfilter, + locfilter: locfilter, + boardfilter: boardfilter, + categoryfilter: categoryfilter, + typefilter: typefilter, + featurefilter: featurefilter, + featureidfilter: featureidfilter, + badgefilter: badgefilter, + themefilter: themefilter, + altitudefilter: altitudefilter, + smgtags: odhtagfilter, + activefilter: active, + smgactivefilter: odhactive, + bookablefilter: bookablefilter, + sourcefilter: sourcefilter, + lastchange: updatefrom, + langfilter: langfilter, + publishedonfilter: publishedon, + (CancellationToken?)context.ActionArguments["cancellationToken"] + ?? new() + ); + + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + latitude, + longitude, + radius + ); + + // Get Accommodations IDlist + var idlist = await GetAccommodationBookList( + myhelper, + language, + seed, + searchfilter, + geosearchresult + ); + + booklist = + idlist + .Where(x => x.Id != null) + .Select(x => x.Id!.ToUpper()) + .ToList() ?? new List(); } - else if(actionid == "PostAvailableAccommodations" || actionid == "PostAvailableAccommodationsOnlyMssResult") + else if ( + actionid == "PostAvailableAccommodations" + || actionid == "PostAvailableAccommodationsOnlyMssResult" + ) { - if(withoutids == false) + if (withoutids == false) { - //add the parsed ids - string passedids = actionarguments.ContainsKey("idfilter") ? (string)actionarguments["idfilter"]! : ""; + //add the parsed ids + string passedids = actionarguments.ContainsKey("idfilter") + ? (string)actionarguments["idfilter"]! + : ""; booklist = passedids.Split(",").ToList(); } } @@ -142,9 +264,18 @@ public override async Task OnActionExecutionAsync(ActionExecutingContext context if (bokfilterlist.Contains("hgv")) { MssResult mssresult = await GetMSSAvailability( - language: language, arrival: arrival, departure: departure, boardfilter: boardfilter, - roominfo: roominfo, bokfilter: bokfilter, detail: Convert.ToInt32(detail), bookableaccoIDs: booklist, - idsofchannel: idsource, requestsource: msssource, withoutids.Value); + language: language, + arrival: arrival, + departure: departure, + boardfilter: boardfilter, + roominfo: roominfo, + bokfilter: bokfilter, + detail: Convert.ToInt32(detail), + bookableaccoIDs: booklist, + idsofchannel: idsource, + requestsource: msssource, + withoutids.Value + ); if (mssresult != null) { @@ -154,15 +285,22 @@ public override async Task OnActionExecutionAsync(ActionExecutingContext context if (bokfilterlist.Contains("lts")) { MssResult lcsresult = await GetLCSAvailability( - language: language, arrival: arrival, departure: departure, boardfilter: boardfilter, - roominfo: roominfo, bookableaccoIDs: booklist, requestsource: msssource, withoutids: withoutids.Value); + language: language, + arrival: arrival, + departure: departure, + boardfilter: boardfilter, + roominfo: roominfo, + bookableaccoIDs: booklist, + requestsource: msssource, + withoutids: withoutids.Value + ); if (lcsresult != null) { context.HttpContext.Items.Add("lcsavailablity", lcsresult); } } - } + } } await base.OnActionExecutionAsync(context, next); @@ -173,7 +311,10 @@ public override async Task OnActionExecutionAsync(ActionExecutingContext context } } - public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) + public override async Task OnResultExecutionAsync( + ResultExecutingContext context, + ResultExecutionDelegate next + ) { bool availabilitysearchavailable = CheckAvailabilitySearch(context.HttpContext.User); @@ -182,7 +323,7 @@ public override async Task OnResultExecutionAsync(ResultExecutingContext context var query = context.HttpContext.Request.Query; - string idsource = (string?)query["idsource"] ?? "lts"; + string idsource = (string?)query["idsource"] ?? "lts"; bool availabilitycheck = false; @@ -204,8 +345,11 @@ public override async Task OnResultExecutionAsync(ResultExecutingContext context { string language = (string?)query["language"] ?? "de"; string boardfilter = (string?)query["boardfilter"] ?? "0"; - string arrival = (string?)query["arrival"] ?? String.Format("{0:yyyy-MM-dd}", DateTime.Now); - string departure = (string?)query["departure"] ?? String.Format("{0:yyyy-MM-dd}", DateTime.Now.AddDays(1)); + string arrival = + (string?)query["arrival"] ?? String.Format("{0:yyyy-MM-dd}", DateTime.Now); + string departure = + (string?)query["departure"] + ?? String.Format("{0:yyyy-MM-dd}", DateTime.Now.AddDays(1)); string roominfo = (string?)query["roominfo"] ?? "1-18,18"; string msssource = (string?)query["msssource"] ?? "sinfo"; string detail = (string?)query["detail"] ?? "0"; @@ -231,15 +375,28 @@ public override async Task OnResultExecutionAsync(ResultExecutingContext context { MssResult? mssresult = default(MssResult); - if (actionid == "GetAccommodations" || actionid == "PostAvailableAccommodations") + if ( + actionid == "GetAccommodations" + || actionid == "PostAvailableAccommodations" + ) { - mssresult = (MssResult?)context.HttpContext.Items["mssavailablity"]; + mssresult = (MssResult?) + context.HttpContext.Items["mssavailablity"]; } else if (actionid == "GetAccommodation") { mssresult = await GetMSSAvailability( - language: language, arrival: arrival, departure: departure, boardfilter: boardfilter, - roominfo: roominfo, bokfilter: bokfilter, detail: Convert.ToInt32(detail), bookableaccoIDs: bookableAccoIds, idsofchannel: idsource, requestsource: msssource); + language: language, + arrival: arrival, + departure: departure, + boardfilter: boardfilter, + roominfo: roominfo, + bokfilter: bokfilter, + detail: Convert.ToInt32(detail), + bookableaccoIDs: bookableAccoIds, + idsofchannel: idsource, + requestsource: msssource + ); } if (mssresult != null) @@ -250,8 +407,14 @@ public override async Task OnResultExecutionAsync(ResultExecutingContext context if (bokfilterlist.Contains("lts")) { MssResult lcsresult = await GetLCSAvailability( - language: language, arrival: arrival, departure: departure, boardfilter: boardfilter, - roominfo: roominfo, bookableaccoIDs: bookableAccoIds, requestsource: msssource); + language: language, + arrival: arrival, + departure: departure, + boardfilter: boardfilter, + roominfo: roominfo, + bookableaccoIDs: bookableAccoIds, + requestsource: msssource + ); if (lcsresult != null) { @@ -261,14 +424,19 @@ public override async Task OnResultExecutionAsync(ResultExecutingContext context if (result.Count > 0) { - var resultJson = JsonConvert.SerializeObject(result.SelectMany(x => x.MssResponseShort)); + var resultJson = JsonConvert.SerializeObject( + result.SelectMany(x => x.MssResponseShort) + ); mssResponseShortProperty.Value = new JRaw(resultJson); } } } okObject.Value = jtoken; } - else if (context.Result is OkObjectResult okObjectlist && okObjectlist.Value is JsonResult jRawList) + else if ( + context.Result is OkObjectResult okObjectlist + && okObjectlist.Value is JsonResult jRawList + ) { List myRawList = new(); @@ -287,16 +455,28 @@ public override async Task OnResultExecutionAsync(ResultExecutingContext context { MssResult? mssresult = null; - if (actionid == "GetAccommodations" || actionid == "PostAvailableAccommodations") + if ( + actionid == "GetAccommodations" + || actionid == "PostAvailableAccommodations" + ) { - mssresult = (MssResult?)context.HttpContext.Items["mssavailablity"]; + mssresult = (MssResult?) + context.HttpContext.Items["mssavailablity"]; } else if (actionid == "GetAccommodation") { mssresult = await GetMSSAvailability( - language: language, arrival: arrival, departure: departure, boardfilter: boardfilter, - roominfo: roominfo, bokfilter: bokfilter, detail: Convert.ToInt32(detail), bookableaccoIDs: bookableAccoIds, idsofchannel: idsource, - requestsource: msssource); + language: language, + arrival: arrival, + departure: departure, + boardfilter: boardfilter, + roominfo: roominfo, + bokfilter: bokfilter, + detail: Convert.ToInt32(detail), + bookableaccoIDs: bookableAccoIds, + idsofchannel: idsource, + requestsource: msssource + ); } if (mssresult != null) @@ -308,15 +488,25 @@ public override async Task OnResultExecutionAsync(ResultExecutingContext context { MssResult? lcsresult = null; - if (actionid == "GetAccommodations" || actionid == "PostAvailableAccommodations") + if ( + actionid == "GetAccommodations" + || actionid == "PostAvailableAccommodations" + ) { - lcsresult = (MssResult?)context.HttpContext.Items["lcsavailablity"]; + lcsresult = (MssResult?) + context.HttpContext.Items["lcsavailablity"]; } else if (actionid == "GetAccommodation") { lcsresult = await GetLCSAvailability( - language: language, arrival: arrival, departure: departure, boardfilter: boardfilter, - roominfo: roominfo, bookableaccoIDs: bookableAccoIds, requestsource: msssource); + language: language, + arrival: arrival, + departure: departure, + boardfilter: boardfilter, + roominfo: roominfo, + bookableaccoIDs: bookableAccoIds, + requestsource: msssource + ); } if (lcsresult != null) @@ -328,8 +518,12 @@ public override async Task OnResultExecutionAsync(ResultExecutingContext context if (result.Count > 0) { string? accid = jObject.Property("Id")?.Value.ToString(); - var data = result.SelectMany(x => x.MssResponseShort).Where(x => x.A0RID == accid); - mssResponseShortProperty.Value = new JRaw(JsonConvert.SerializeObject(data)); + var data = result + .SelectMany(x => x.MssResponseShort) + .Where(x => x.A0RID == accid); + mssResponseShortProperty.Value = new JRaw( + JsonConvert.SerializeObject(data) + ); } } } @@ -345,62 +539,164 @@ public override async Task OnResultExecutionAsync(ResultExecutingContext context await base.OnResultExecutionAsync(context, next); } - private async Task GetMSSAvailability(string language, string arrival, string departure, string boardfilter, string roominfo, string bokfilter, int? detail, List bookableaccoIDs, string idsofchannel, string requestsource, bool withoutmssids = false, string mssversion = "2") - { + private async Task GetMSSAvailability( + string language, + string arrival, + string departure, + string boardfilter, + string roominfo, + string bokfilter, + int? detail, + List bookableaccoIDs, + string idsofchannel, + string requestsource, + bool withoutmssids = false, + string mssversion = "2" + ) + { // Edge Case No Ids Provided, withoutmssids true if ((bookableaccoIDs.Count == 0) && withoutmssids) { - using var r = new StreamReader(Path.Combine(settings.JsonConfig.Jsondir, $"AccosBookable.json")); + using var r = new StreamReader( + Path.Combine(settings.JsonConfig.Jsondir, $"AccosBookable.json") + ); string json = await r.ReadToEndAsync(); bookableaccoIDs = JsonConvert.DeserializeObject>(json) ?? new(); } - MssHelper myhelper = MssHelper.Create(bookableaccoIDs, idsofchannel, bokfilter, language, roominfo, boardfilter, arrival, departure, detail, requestsource, mssversion); + MssHelper myhelper = MssHelper.Create( + bookableaccoIDs, + idsofchannel, + bokfilter, + language, + roominfo, + boardfilter, + arrival, + departure, + detail, + requestsource, + mssversion + ); if (bookableaccoIDs.Count > 0 || withoutmssids) - { + { // 0 MSS Method Olle channels affamol mit IDList var myparsedresponse = await GetMssData.GetMssResponse( httpClientFactory.CreateClient("mss"), - lang: myhelper.mssrequestlanguage, idlist: myhelper.accoidlist, idsofchannel: myhelper.idsofchannel, mybookingchannels: myhelper.mybokchannels, - myroomdata: myhelper.myroomdata, arrival: myhelper.arrival, departure: myhelper.departure, service: myhelper.service, - hgvservicecode: myhelper.hgvservicecode, offerdetails: myhelper.xoffertype, hoteldetails: myhelper.xhoteldetails, - rooms: myhelper.rooms, requestsource: myhelper.requestsource, version: myhelper.mssversion, mssuser: settings.MssConfig.Username, msspswd: settings.MssConfig.Password, withoutmssids: withoutmssids - ); - + lang: myhelper.mssrequestlanguage, + idlist: myhelper.accoidlist, + idsofchannel: myhelper.idsofchannel, + mybookingchannels: myhelper.mybokchannels, + myroomdata: myhelper.myroomdata, + arrival: myhelper.arrival, + departure: myhelper.departure, + service: myhelper.service, + hgvservicecode: myhelper.hgvservicecode, + offerdetails: myhelper.xoffertype, + hoteldetails: myhelper.xhoteldetails, + rooms: myhelper.rooms, + requestsource: myhelper.requestsource, + version: myhelper.mssversion, + mssuser: settings.MssConfig.Username, + msspswd: settings.MssConfig.Password, + withoutmssids: withoutmssids + ); + if (myparsedresponse != null) return myparsedresponse; } - return new MssResult() { bookableHotels = 0, CheapestChannel = "", Cheapestprice = 0, ResultId = "", MssResponseShort = new List() }; + return new MssResult() + { + bookableHotels = 0, + CheapestChannel = "", + Cheapestprice = 0, + ResultId = "", + MssResponseShort = new List() + }; } - private async Task GetLCSAvailability(string language, string arrival, string departure, string boardfilter, string roominfo, List bookableaccoIDs, string requestsource, bool withoutids = false) + private async Task GetLCSAvailability( + string language, + string arrival, + string departure, + string boardfilter, + string roominfo, + List bookableaccoIDs, + string requestsource, + bool withoutids = false + ) { - LcsHelper myhelper = LcsHelper.Create(bookableaccoIDs, language, roominfo, boardfilter, arrival, departure, requestsource); + LcsHelper myhelper = LcsHelper.Create( + bookableaccoIDs, + language, + roominfo, + boardfilter, + arrival, + departure, + requestsource + ); // Edge Case No Ids Provided, withoutids true if ((bookableaccoIDs.Count == 0) && withoutids) { - using var r = new StreamReader(Path.Combine(settings.JsonConfig.Jsondir, $"AccosAll.json")); + using var r = new StreamReader( + Path.Combine(settings.JsonConfig.Jsondir, $"AccosAll.json") + ); string json = await r.ReadToEndAsync(); bookableaccoIDs = JsonConvert.DeserializeObject>(json) ?? new(); } if (bookableaccoIDs.Count > 0) { - var accosearchrequest = LCS.GetAccommodationDataLCS.GetAccommodationDataSearchRequest(resultRID: "", pageNr: "1", pageSize: "10000", language: myhelper.lcsrequestlanguage, - sortingcriterion: "1", sortingorder: "", sortingpromotebookable: "", request: "0", filters: "0", timespanstart: myhelper.arrival, timespanend: myhelper.departure, - checkavailabilitystatus: "1", onlybookableresults: "0", mealplans: myhelper.service, accommodationrids: myhelper.accoidlist, tourismorg: new List(), - districts: new List(), marketinggroups: new List(), lcsroomstay: myhelper.myroomdata, requestor: requestsource, messagepswd: settings.LcsConfig.MessagePassword); + var accosearchrequest = + LCS.GetAccommodationDataLCS.GetAccommodationDataSearchRequest( + resultRID: "", + pageNr: "1", + pageSize: "10000", + language: myhelper.lcsrequestlanguage, + sortingcriterion: "1", + sortingorder: "", + sortingpromotebookable: "", + request: "0", + filters: "0", + timespanstart: myhelper.arrival, + timespanend: myhelper.departure, + checkavailabilitystatus: "1", + onlybookableresults: "0", + mealplans: myhelper.service, + accommodationrids: myhelper.accoidlist, + tourismorg: new List(), + districts: new List(), + marketinggroups: new List(), + lcsroomstay: myhelper.myroomdata, + requestor: requestsource, + messagepswd: settings.LcsConfig.MessagePassword + ); - var myaccosearchlcs = new LCS.GetAccommodationDataLCS(settings.LcsConfig.Username, settings.LcsConfig.Password); - var response = await myaccosearchlcs.GetAccommodationDataSearchAsync(accosearchrequest); - var myparsedresponse = LCS.ParseAccoSearchResult.ParsemyLCSResponse(language, response, myhelper.rooms); + var myaccosearchlcs = new LCS.GetAccommodationDataLCS( + settings.LcsConfig.Username, + settings.LcsConfig.Password + ); + var response = await myaccosearchlcs.GetAccommodationDataSearchAsync( + accosearchrequest + ); + var myparsedresponse = LCS.ParseAccoSearchResult.ParsemyLCSResponse( + language, + response, + myhelper.rooms + ); if (myparsedresponse != null) return myparsedresponse; } - return new MssResult() { bookableHotels = 0, CheapestChannel = "", Cheapestprice = 0, ResultId = "", MssResponseShort = new List() }; + return new MssResult() + { + bookableHotels = 0, + CheapestChannel = "", + Cheapestprice = 0, + ResultId = "", + MssResponseShort = new List() + }; } private bool CheckArrivalAndDeparture(string arrival, string departure) @@ -421,32 +717,55 @@ private bool CheckArrivalAndDeparture(string arrival, string departure) return true; } - private async Task> GetAccommodationBookList(AccommodationHelper myhelper, string language, string? seed, string? searchfilter, PGGeoSearchResult geosearchresult) + private async Task> GetAccommodationBookList( + AccommodationHelper myhelper, + string language, + string? seed, + string? searchfilter, + PGGeoSearchResult geosearchresult + ) { - string select = $"data#>>'\\{{Id\\}}' as Id, data#>>'\\{{IsBookable\\}}' as IsBookable, data#>>'\\{{AccoBookingChannel\\}}' as AccoBookingChannel"; - - var query = - QueryFactory.Query() - .SelectRaw(select) - .From("accommodations") - .AccommodationWhereExpression( - idlist: myhelper.idlist, accotypelist: myhelper.accotypelist, - categorylist: myhelper.categorylist, featurelist: myhelper.featurelist, featureidlist: myhelper.featureidlist, - badgelist: myhelper.badgelist, themelist: myhelper.themelist, - boardlist: myhelper.boardlist, smgtaglist: myhelper.smgtaglist, - districtlist: myhelper.districtlist, municipalitylist: myhelper.municipalitylist, - tourismvereinlist: myhelper.tourismvereinlist, regionlist: myhelper.regionlist, - apartmentfilter: myhelper.apartment, bookable: myhelper.bookable, altitude: myhelper.altitude, - altitudemin: myhelper.altitudemin, altitudemax: myhelper.altitudemax, - activefilter: myhelper.active, smgactivefilter: myhelper.smgactive, publishedonlist: myhelper.publishedonlist, - sourcelist: myhelper.sourcelist, - searchfilter: searchfilter, language: language, lastchange: myhelper.lastchange, languagelist: new List(), - filterClosedData: false, reducedData: false) //Availability Search only for IDM Users therefore no filte Closed Data, no reduced data - .OrderBySeed(ref seed, "data #>>'\\{Shortname\\}' ASC") - .GeoSearchFilterAndOrderby(geosearchresult); + string select = + $"data#>>'\\{{Id\\}}' as Id, data#>>'\\{{IsBookable\\}}' as IsBookable, data#>>'\\{{AccoBookingChannel\\}}' as AccoBookingChannel"; + + var query = QueryFactory + .Query() + .SelectRaw(select) + .From("accommodations") + .AccommodationWhereExpression( + idlist: myhelper.idlist, + accotypelist: myhelper.accotypelist, + categorylist: myhelper.categorylist, + featurelist: myhelper.featurelist, + featureidlist: myhelper.featureidlist, + badgelist: myhelper.badgelist, + themelist: myhelper.themelist, + boardlist: myhelper.boardlist, + smgtaglist: myhelper.smgtaglist, + districtlist: myhelper.districtlist, + municipalitylist: myhelper.municipalitylist, + tourismvereinlist: myhelper.tourismvereinlist, + regionlist: myhelper.regionlist, + apartmentfilter: myhelper.apartment, + bookable: myhelper.bookable, + altitude: myhelper.altitude, + altitudemin: myhelper.altitudemin, + altitudemax: myhelper.altitudemax, + activefilter: myhelper.active, + smgactivefilter: myhelper.smgactive, + publishedonlist: myhelper.publishedonlist, + sourcelist: myhelper.sourcelist, + searchfilter: searchfilter, + language: language, + lastchange: myhelper.lastchange, + languagelist: new List(), + filterClosedData: false, + reducedData: false + ) //Availability Search only for IDM Users therefore no filte Closed Data, no reduced data + .OrderBySeed(ref seed, "data #>>'\\{Shortname\\}' ASC") + .GeoSearchFilterAndOrderby(geosearchresult); return await query.GetAsync(); } - } } diff --git a/OdhApiCore/Filters/NullStringParameterActionFilterAttribute.cs b/OdhApiCore/Filters/NullStringParameterActionFilterAttribute.cs index 0718b1e76..c90d03f80 100644 --- a/OdhApiCore/Filters/NullStringParameterActionFilterAttribute.cs +++ b/OdhApiCore/Filters/NullStringParameterActionFilterAttribute.cs @@ -5,9 +5,7 @@ namespace OdhApiCore.Controllers { public class NullStringParameterActionFilterAttribute : ActionFilterAttribute { - public NullStringParameterActionFilterAttribute() - { - } + public NullStringParameterActionFilterAttribute() { } public override void OnActionExecuting(ActionExecutingContext context) { @@ -22,4 +20,4 @@ public override void OnActionExecuting(ActionExecutingContext context) base.OnActionExecuting(context); } } -} \ No newline at end of file +} diff --git a/OdhApiCore/Filters/OdhCacheOutputAttribute.cs b/OdhApiCore/Filters/OdhCacheOutputAttribute.cs index bc023a82d..dc22e4810 100644 --- a/OdhApiCore/Filters/OdhCacheOutputAttribute.cs +++ b/OdhApiCore/Filters/OdhCacheOutputAttribute.cs @@ -10,7 +10,8 @@ public class OdhCacheOutputAttribute : CacheOutputAttribute { protected override bool IsCachingAllowed(FilterContext actionContext, bool anonymousOnly) { - var environment = actionContext.HttpContext.RequestServices.GetService(); + var environment = + actionContext.HttpContext.RequestServices.GetService(); if (environment?.IsDevelopment() ?? false) { return false; diff --git a/OdhApiCore/Filters/RequestInterceptorAttribute.cs b/OdhApiCore/Filters/RequestInterceptorAttribute.cs index c835b5066..9844a4121 100644 --- a/OdhApiCore/Filters/RequestInterceptorAttribute.cs +++ b/OdhApiCore/Filters/RequestInterceptorAttribute.cs @@ -19,56 +19,88 @@ public class RequestInterceptorAttribute : ActionFilterAttribute public RequestInterceptorAttribute(ISettings settings) { - this.settings = settings; + this.settings = settings; } - public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) - { + public override async Task OnActionExecutionAsync( + ActionExecutingContext context, + ActionExecutionDelegate next + ) + { context.ActionDescriptor.RouteValues.TryGetValue("action", out string? actionid); - context.ActionDescriptor.RouteValues.TryGetValue("controller", out string? controllerid); + context.ActionDescriptor.RouteValues.TryGetValue( + "controller", + out string? controllerid + ); - var matchedactiontointercept = GetActionsToIntercept(actionid, controllerid, context.ActionArguments); + var matchedactiontointercept = GetActionsToIntercept( + actionid, + controllerid, + context.ActionArguments + ); if (matchedactiontointercept != null) { RouteValueDictionary redirectTargetDictionary = new(); redirectTargetDictionary.Add("action", matchedactiontointercept.RedirectAction); - redirectTargetDictionary.Add("controller", matchedactiontointercept.RedirectController); + redirectTargetDictionary.Add( + "controller", + matchedactiontointercept.RedirectController + ); if (matchedactiontointercept.RedirectQueryStrings != null) { foreach (var redirectqs in matchedactiontointercept.RedirectQueryStrings) { if (context.ActionArguments.ContainsKey(redirectqs)) - redirectTargetDictionary.Add(redirectqs, context.ActionArguments[redirectqs]); + redirectTargetDictionary.Add( + redirectqs, + context.ActionArguments[redirectqs] + ); } } context.Result = new RedirectToRouteResult(redirectTargetDictionary); await context.Result.ExecuteResultAsync(context); } - - await base.OnActionExecutionAsync(context, next); + + await base.OnActionExecutionAsync(context, next); } - public RequestInterceptorConfig? GetActionsToIntercept(string? actionid, string? controller, IDictionary actionarguments) + public RequestInterceptorConfig? GetActionsToIntercept( + string? actionid, + string? controller, + IDictionary actionarguments + ) { - if (settings.RequestInterceptorConfig != null && settings.RequestInterceptorConfig.Where(x => x.Action == actionid && x.Controller == controller).Count() > 0) + if ( + settings.RequestInterceptorConfig != null + && settings.RequestInterceptorConfig + .Where(x => x.Action == actionid && x.Controller == controller) + .Count() > 0 + ) { - foreach(var validconfig in settings.RequestInterceptorConfig.Where(x => x.Action == actionid && x.Controller == controller)) + foreach ( + var validconfig in settings.RequestInterceptorConfig.Where( + x => x.Action == actionid && x.Controller == controller + ) + ) { var match = GetQueryStringsToInterceptAndMatch(validconfig, actionarguments); if (match) return validconfig; - } - } - + } + } + return null; } - public bool GetQueryStringsToInterceptAndMatch(RequestInterceptorConfig config, IDictionary querystrings) + public bool GetQueryStringsToInterceptAndMatch( + RequestInterceptorConfig config, + IDictionary querystrings + ) { // Forget about cancellationtoken and other generated Dictionary configdict = new(); @@ -90,7 +122,7 @@ public bool GetQueryStringsToInterceptAndMatch(RequestInterceptorConfig config, List toexclude = new() { "cancellationToken" }; - foreach(var item in querystrings) + foreach (var item in querystrings) { if (!toexclude.Contains(item.Key)) { @@ -98,7 +130,9 @@ public bool GetQueryStringsToInterceptAndMatch(RequestInterceptorConfig config, { actualdict.TryAdd(item.Key, ((PageSize?)item.Value)?.Value.ToString()); } - else if (item.Key == "highlight" || item.Key == "active" || item.Key == "odhactive") + else if ( + item.Key == "highlight" || item.Key == "active" || item.Key == "odhactive" + ) { if (((LegacyBool?)item.Value)?.Value != null) actualdict.TryAdd(item.Key, ((LegacyBool)item.Value).Value.ToString()); @@ -119,26 +153,28 @@ public bool GetQueryStringsToInterceptAndMatch(RequestInterceptorConfig config, else { actualdict.TryAdd(item.Key, ((string?)item.Value)); - } + } } } // Matching the two Dictionaries - return MatchDictionaries(configdict, actualdict); + return MatchDictionaries(configdict, actualdict); } - private static bool MatchDictionaries(IDictionary dict1, IDictionary dict2) + private static bool MatchDictionaries( + IDictionary dict1, + IDictionary dict2 + ) { - List validlanguages = new() { "de", "it", "en", "nl", "cs", "pl", "fr", "ru" }; + List validlanguages = new() { "de", "it", "en", "nl", "cs", "pl", "fr", "ru" }; // Return only if there is a 1:1 match - foreach(var item in dict1) + foreach (var item in dict1) { // If the Request does not contain the configured QS Key exit immediately if (!dict2.ContainsKey(item.Key)) return false; - // If the config does not contains a * go on if (!item.Value.Contains("*")) { @@ -152,12 +188,12 @@ private static bool MatchDictionaries(IDictionary dict1, IDictio // check if one of the validlanguages matches int matchcount = 0; - foreach(var lang in validlanguages) + foreach (var lang in validlanguages) { var newconfigvalue = item.Value.ToLower().Replace("*", lang); - if(dict2?[item.Key]?.ToLower() == newconfigvalue.ToLower()) - matchcount++; + if (dict2?[item.Key]?.ToLower() == newconfigvalue.ToLower()) + matchcount++; } // If no matches exit immediately diff --git a/OdhApiCore/Formatters/CsvOutputFormatter.cs b/OdhApiCore/Formatters/CsvOutputFormatter.cs index 123be0e0d..ad810b0ef 100644 --- a/OdhApiCore/Formatters/CsvOutputFormatter.cs +++ b/OdhApiCore/Formatters/CsvOutputFormatter.cs @@ -23,7 +23,7 @@ public CsvOutputFormatter() { SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/csv")); - SupportedEncodings.Add(Encoding.UTF8); + SupportedEncodings.Add(Encoding.UTF8); SupportedEncodings.Add(Encoding.Unicode); } @@ -45,30 +45,36 @@ private static dynamic ConvertToExpandoObject(Dictionary dict) //var stringlist = kvp.Value as Newtonsoft.Json.Linq.JArray; var stringlist = kvp.Value as IEnumerable; if (stringlist != null) - eoColl.Add(new KeyValuePair(kvp.Key, String.Join("|", stringlist))); + eoColl.Add( + new KeyValuePair(kvp.Key, String.Join("|", stringlist)) + ); else continue; } else { eoColl.Add(kvp); - } + } } return eo; } - public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) + public override async Task WriteResponseBodyAsync( + OutputFormatterWriteContext context, + Encoding selectedEncoding + ) { //Works only with List Method add an understandable Exception if it is used on single methods //Add support if an object list is returned instead of JsonRAW issue 4762 - + var result = context.Object as IResponse; if (result != null) { - var data = - (from item in result.Items - let dict = JsonConvert.DeserializeObject>(item.Value) - select ConvertToExpandoObject(dict)).ToList(); + var data = ( + from item in result.Items + let dict = JsonConvert.DeserializeObject>(item.Value) + select ConvertToExpandoObject(dict) + ).ToList(); await WriteCSVStream(context, data); } @@ -78,10 +84,13 @@ public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext co if (listresult != null) { - var data = - (from item in listresult - let dict = JsonConvert.DeserializeObject>(item.Value) - select ConvertToExpandoObject(dict)).ToList(); + var data = ( + from item in listresult + let dict = JsonConvert.DeserializeObject>( + item.Value + ) + select ConvertToExpandoObject(dict) + ).ToList(); await WriteCSVStream(context, data); } @@ -100,7 +109,11 @@ private async Task WriteCSVStream(OutputFormatterWriteContext context, List(jsonRaw.Value); - return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet(acco, "accommodation", "de"); + return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet( + acco, + "accommodation", + "de" + ); } else if (path.StartsWithSegments("/v1/Gastronomy")) { var gastro = JsonConvert.DeserializeObject(jsonRaw.Value); - return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet(gastro, "gastronomy", "de"); + return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet( + gastro, + "gastronomy", + "de" + ); } else if (path.StartsWithSegments("/v1/Event")) { var @event = JsonConvert.DeserializeObject(jsonRaw.Value); - return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet(@event, "event", "de"); + return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet( + @event, + "event", + "de" + ); } else if (path.StartsWithSegments("/v1/ODHActivityPoi")) { var poi = JsonConvert.DeserializeObject(jsonRaw.Value); //return JsonLDTransformer.TransformToLD.TransformEventToLD(@event, "de"); - return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet(poi, "poi", "de"); + return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet( + poi, + "poi", + "de" + ); } else if (path.StartsWithSegments("/v1/Region")) { var region = JsonConvert.DeserializeObject(jsonRaw.Value); //return JsonLDTransformer.TransformToLD.TransformEventToLD(@event, "de"); - return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet(region, "region", "de"); + return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet( + region, + "region", + "de" + ); } else if (path.StartsWithSegments("/v1/TourismAssociation")) { var tv = JsonConvert.DeserializeObject(jsonRaw.Value); //return JsonLDTransformer.TransformToLD.TransformEventToLD(@event, "de"); - return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet(tv, "tv", "de"); + return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet( + tv, + "tv", + "de" + ); } else if (path.StartsWithSegments("/v1/Municipality")) { var municipality = JsonConvert.DeserializeObject(jsonRaw.Value); //return JsonLDTransformer.TransformToLD.TransformEventToLD(@event, "de"); - return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet(municipality, "municipality", "de"); + return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet( + municipality, + "municipality", + "de" + ); } else if (path.StartsWithSegments("/v1/District")) { var district = JsonConvert.DeserializeObject(jsonRaw.Value); //return JsonLDTransformer.TransformToLD.TransformEventToLD(@event, "de"); - return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet(district, "district", "de"); + return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet( + district, + "district", + "de" + ); } else if (path.StartsWithSegments("/v1/SkiArea")) { var skiarea = JsonConvert.DeserializeObject(jsonRaw.Value); //return JsonLDTransformer.TransformToLD.TransformEventToLD(@event, "de"); - return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet(skiarea, "skiarea", "de"); + return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet( + skiarea, + "skiarea", + "de" + ); } else if (path.StartsWithSegments("/v1/Article")) { @@ -84,7 +120,11 @@ public JsonLdOutputFormatter() var recipe = JsonConvert.DeserializeObject
(jsonRaw.Value); //return JsonLDTransformer.TransformToLD.TransformEventToLD(@event, "de"); - return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet(recipe, "recipe", "de"); + return JsonLDTransformer.TransformToSchemaNet.TransformDataToSchemaNet( + recipe, + "recipe", + "de" + ); } else { @@ -92,19 +132,25 @@ public JsonLdOutputFormatter() } } - public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) + public override async Task WriteResponseBodyAsync( + OutputFormatterWriteContext context, + Encoding selectedEncoding + ) { if (context.Object is JsonRaw jsonRaw) { var transformed = Transform(context.HttpContext.Request.Path, jsonRaw); if (transformed != null) { - var jsonLD = JsonConvert.SerializeObject(transformed, Newtonsoft.Json.Formatting.None, - new JsonSerializerSettings - { - DefaultValueHandling = DefaultValueHandling.Ignore, - NullValueHandling = NullValueHandling.Ignore - }); + var jsonLD = JsonConvert.SerializeObject( + transformed, + Newtonsoft.Json.Formatting.None, + new JsonSerializerSettings + { + DefaultValueHandling = DefaultValueHandling.Ignore, + NullValueHandling = NullValueHandling.Ignore + } + ); await context.HttpContext.Response.WriteAsync(jsonLD); } else diff --git a/OdhApiCore/Formatters/RawdataOutputFormatter.cs b/OdhApiCore/Formatters/RawdataOutputFormatter.cs index 673ac875d..9de56d5db 100644 --- a/OdhApiCore/Formatters/RawdataOutputFormatter.cs +++ b/OdhApiCore/Formatters/RawdataOutputFormatter.cs @@ -42,14 +42,16 @@ public RawdataOutputFormatter() string table = ODHTypeHelper.TranslateTypeString2Table(odhtype); //Load rawid - var rawid = QueryFactory.Query() - .Select("rawdataid") - .From(table) - .Where("id", id) - .Get() - .FirstOrDefault(); + var rawid = QueryFactory + .Query() + .Select("rawdataid") + .From(table) + .Where("id", id) + .Get() + .FirstOrDefault(); - var rawdata = QueryFactory.Query() + var rawdata = QueryFactory + .Query() .Select("raw") .From("rawdata") .Where("id", rawid) @@ -60,17 +62,20 @@ public RawdataOutputFormatter() } else return null; - } - catch(Exception) + catch (Exception) { return null; - } + } } - public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) + public override async Task WriteResponseBodyAsync( + OutputFormatterWriteContext context, + Encoding selectedEncoding + ) { - var queryFactory = (QueryFactory?)context.HttpContext.RequestServices.GetService(typeof(QueryFactory)); + var queryFactory = (QueryFactory?) + context.HttpContext.RequestServices.GetService(typeof(QueryFactory)); if (context.Object is JsonRaw jsonRaw && queryFactory is { }) { diff --git a/OdhApiCore/GenericHelpers/CustomCacheKeyGenerator.cs b/OdhApiCore/GenericHelpers/CustomCacheKeyGenerator.cs index 7aba70c43..b14d53f4b 100644 --- a/OdhApiCore/GenericHelpers/CustomCacheKeyGenerator.cs +++ b/OdhApiCore/GenericHelpers/CustomCacheKeyGenerator.cs @@ -20,7 +20,11 @@ public class CustomCacheKeyGenerator : DefaultCacheKeyGenerator //ICacheKeyGener // throw new NotImplementedException(); //} - public override string MakeCacheKey(ActionExecutingContext context, string mediaType, bool excludeQueryString = false) + public override string MakeCacheKey( + ActionExecutingContext context, + string mediaType, + bool excludeQueryString = false + ) { var key = base.MakeCacheKey(context, mediaType, excludeQueryString); @@ -43,13 +47,12 @@ protected virtual string FormatUserIdentity(ActionExecutingContext context) { if (context.HttpContext.User.Identity.IsAuthenticated) { - if(!String.IsNullOrEmpty(context.HttpContext.User.Identity.Name)) + if (!String.IsNullOrEmpty(context.HttpContext.User.Identity.Name)) username = context.HttpContext.User.Identity.Name.ToLower(); } } return username; } - } } diff --git a/OdhApiCore/GenericHelpers/RemoteIpHelper.cs b/OdhApiCore/GenericHelpers/RemoteIpHelper.cs index 331f9b1c7..416881188 100644 --- a/OdhApiCore/GenericHelpers/RemoteIpHelper.cs +++ b/OdhApiCore/GenericHelpers/RemoteIpHelper.cs @@ -19,7 +19,9 @@ public static class RemoteIpHelper // http://stackoverflow.com/a/43554000/538763 // if (tryUseXForwardHeader) - ip = GetHeaderValueAs("X-Forwarded-For", context)?.SplitCsv()?.FirstOrDefault(); + ip = GetHeaderValueAs("X-Forwarded-For", context) + ?.SplitCsv() + ?.FirstOrDefault(); // RemoteIpAddress is always null in DNX RC1 Update1 (bug). if (ip.IsNullOrWhitespace() && context?.Connection?.RemoteIpAddress != null) @@ -46,7 +48,7 @@ public static class RemoteIpHelper if (context?.Request?.Headers?.TryGetValue(headerName, out values) ?? false) { - string rawValues = values.ToString(); // writes out as Csv when there are multiple. + string rawValues = values.ToString(); // writes out as Csv when there are multiple. if (!rawValues.IsNullOrWhitespace()) return (T)Convert.ChangeType(values.ToString(), typeof(T)); @@ -54,7 +56,10 @@ public static class RemoteIpHelper return default(T); } - private static List? SplitCsv(this string csvList, bool nullOrWhitespaceInputReturnsNull = false) + private static List? SplitCsv( + this string csvList, + bool nullOrWhitespaceInputReturnsNull = false + ) { if (string.IsNullOrWhiteSpace(csvList)) return nullOrWhitespaceInputReturnsNull ? null : new List(); diff --git a/OdhApiCore/GenericHelpers/STARequestHelper.cs b/OdhApiCore/GenericHelpers/STARequestHelper.cs index 3d9378fbe..7f46b4d67 100644 --- a/OdhApiCore/GenericHelpers/STARequestHelper.cs +++ b/OdhApiCore/GenericHelpers/STARequestHelper.cs @@ -17,60 +17,136 @@ namespace OdhApiCore.GenericHelpers { public class STARequestHelper - { + { public static List GetUrlstoCheck(string domain) { List urltorequest = new List(); - urltorequest.Add(domain + "/v1/Poi?language=de&poitype=447&active=true&fields=Id,Detail.de.Title,ContactInfos.de.City&pagesize=20000"); - urltorequest.Add(domain + "/v1/Accommodation?language=de&poitype=447&active=true&fields=Id,AccoDetail.de.Name,AccoDetail.de.City&pagesize=10000"); - urltorequest.Add(domain + "/v1/ODHActivityPoi?language=de&poitype=447&active=true&fields=Id,Detail.de.Title,ContactInfos.de.City&pagesize=20000"); - urltorequest.Add(domain + "/v1/Poi?language=it&poitype=447&active=true&fields=Id,Detail.it.Title,ContactInfos.it.City&pagesize=20000"); - urltorequest.Add(domain + "/v1/Accommodation?language=it&poitype=447&active=true&fields=Id,AccoDetail.it.Name,AccoDetail.it.City&pagesize=10000"); - urltorequest.Add(domain + "/v1/ODHActivityPoi?language=it&poitype=447&active=true&fields=Id,Detail.it.Title,ContactInfos.it.City&pagesize=20000"); - urltorequest.Add(domain + "/v1/Poi?language=en&poitype=447&active=true&fields=Id,Detail.en.Title,ContactInfos.en.City&pagesize=20000"); - urltorequest.Add(domain + "/v1/Accommodation?language=en&poitype=447&active=true&fields=Id,AccoDetail.en.Name,AccoDetail.en.City&pagesize=10000"); - urltorequest.Add(domain + "/v1/ODHActivityPoi?language=en&poitype=447&active=true&fields=Id,Detail.en.Title,ContactInfos.en.City&pagesize=20000"); - urltorequest.Add(domain + "/v1/Poi?language=de&poitype=447&active=true&fields=Id,Detail.de.Title,ContactInfos.de.City&pagesize=20000"); - urltorequest.Add(domain + "/v1/Accommodation?language=de&poitype=447&active=true&fields=Id,AccoDetail.de.Name,AccoDetail.de.City&pagesize=10000&key="); - urltorequest.Add(domain + "/v1/ODHActivityPoi?language=de&poitype=447&active=true&fields=Id,Detail.de.Title,ContactInfos.de.City&pagesize=20000&key="); - urltorequest.Add(domain + "/v1/Poi?language=it&poitype=447&active=true&fields=Id,Detail.it.Title,ContactInfos.it.City&pagesize=20000&key="); - urltorequest.Add(domain + "/v1/Accommodation?language=it&poitype=447&active=true&fields=Id,AccoDetail.it.Name,AccoDetail.it.City&pagesize=10000&key="); - urltorequest.Add(domain + "/v1/ODHActivityPoi?language=it&poitype=447&active=true&fields=Id,Detail.it.Title,ContactInfos.it.City&pagesize=20000&key="); - urltorequest.Add(domain + "/v1/Poi?language=en&poitype=447&active=true&fields=Id,Detail.en.Title,ContactInfos.en.City&pagesize=20000&key="); - urltorequest.Add(domain + "/v1/Accommodation?language=en&poitype=447&active=true&fields=Id,AccoDetail.en.Name,AccoDetail.en.City&pagesize=10000&key="); - urltorequest.Add(domain + "/v1/ODHActivityPoi?language=en&poitype=447&active=true&fields=Id,Detail.en.Title,ContactInfos.en.City&pagesize=20000&key="); + urltorequest.Add( + domain + + "/v1/Poi?language=de&poitype=447&active=true&fields=Id,Detail.de.Title,ContactInfos.de.City&pagesize=20000" + ); + urltorequest.Add( + domain + + "/v1/Accommodation?language=de&poitype=447&active=true&fields=Id,AccoDetail.de.Name,AccoDetail.de.City&pagesize=10000" + ); + urltorequest.Add( + domain + + "/v1/ODHActivityPoi?language=de&poitype=447&active=true&fields=Id,Detail.de.Title,ContactInfos.de.City&pagesize=20000" + ); + urltorequest.Add( + domain + + "/v1/Poi?language=it&poitype=447&active=true&fields=Id,Detail.it.Title,ContactInfos.it.City&pagesize=20000" + ); + urltorequest.Add( + domain + + "/v1/Accommodation?language=it&poitype=447&active=true&fields=Id,AccoDetail.it.Name,AccoDetail.it.City&pagesize=10000" + ); + urltorequest.Add( + domain + + "/v1/ODHActivityPoi?language=it&poitype=447&active=true&fields=Id,Detail.it.Title,ContactInfos.it.City&pagesize=20000" + ); + urltorequest.Add( + domain + + "/v1/Poi?language=en&poitype=447&active=true&fields=Id,Detail.en.Title,ContactInfos.en.City&pagesize=20000" + ); + urltorequest.Add( + domain + + "/v1/Accommodation?language=en&poitype=447&active=true&fields=Id,AccoDetail.en.Name,AccoDetail.en.City&pagesize=10000" + ); + urltorequest.Add( + domain + + "/v1/ODHActivityPoi?language=en&poitype=447&active=true&fields=Id,Detail.en.Title,ContactInfos.en.City&pagesize=20000" + ); + urltorequest.Add( + domain + + "/v1/Poi?language=de&poitype=447&active=true&fields=Id,Detail.de.Title,ContactInfos.de.City&pagesize=20000" + ); + urltorequest.Add( + domain + + "/v1/Accommodation?language=de&poitype=447&active=true&fields=Id,AccoDetail.de.Name,AccoDetail.de.City&pagesize=10000&key=" + ); + urltorequest.Add( + domain + + "/v1/ODHActivityPoi?language=de&poitype=447&active=true&fields=Id,Detail.de.Title,ContactInfos.de.City&pagesize=20000&key=" + ); + urltorequest.Add( + domain + + "/v1/Poi?language=it&poitype=447&active=true&fields=Id,Detail.it.Title,ContactInfos.it.City&pagesize=20000&key=" + ); + urltorequest.Add( + domain + + "/v1/Accommodation?language=it&poitype=447&active=true&fields=Id,AccoDetail.it.Name,AccoDetail.it.City&pagesize=10000&key=" + ); + urltorequest.Add( + domain + + "/v1/ODHActivityPoi?language=it&poitype=447&active=true&fields=Id,Detail.it.Title,ContactInfos.it.City&pagesize=20000&key=" + ); + urltorequest.Add( + domain + + "/v1/Poi?language=en&poitype=447&active=true&fields=Id,Detail.en.Title,ContactInfos.en.City&pagesize=20000&key=" + ); + urltorequest.Add( + domain + + "/v1/Accommodation?language=en&poitype=447&active=true&fields=Id,AccoDetail.en.Name,AccoDetail.en.City&pagesize=10000&key=" + ); + urltorequest.Add( + domain + + "/v1/ODHActivityPoi?language=en&poitype=447&active=true&fields=Id,Detail.en.Title,ContactInfos.en.City&pagesize=20000&key=" + ); return urltorequest; } - public static async Task GenerateJSONAccommodationsForSTA(QueryFactory queryFactory, string jsondir) + public static async Task GenerateJSONAccommodationsForSTA( + QueryFactory queryFactory, + string jsondir + ) { List languagelist = new List() { "de", "it", "en" }; var serializer = new JsonSerializer(); foreach (var language in languagelist) { - string select = $"data->>'Id' as \"Id\", data->'AccoDetail'->'{language}'->>'Name' AS \"AccoDetail.{language}.Name\", data->'AccoDetail'->'{language}'->>'City' AS \"AccoDetail.{language}.City\""; + string select = + $"data->>'Id' as \"Id\", data->'AccoDetail'->'{language}'->>'Name' AS \"AccoDetail.{language}.Name\", data->'AccoDetail'->'{language}'->>'City' AS \"AccoDetail.{language}.City\""; string orderby = "data ->>'Shortname' ASC"; //List fieldselectorlist = new List() { "Id", "AccoDetail." + language + ".Name", "AccoDetail." + language + ".City" }; - var query = - queryFactory.Query() - .SelectRaw(select) - .From("accommodations") - .AccommodationWhereExpression( - idlist: new List(), accotypelist: new List(), - categorylist: new List(), featurelist: new Dictionary(), featureidlist: new List(), - badgelist: new List(), themelist: new Dictionary(), - boardlist: new List(), smgtaglist: new List(), - districtlist: new List(), municipalitylist: new List(), - tourismvereinlist: new List(), regionlist: new List(), - apartmentfilter: null, bookable: null, altitude: false, - altitudemin: 0, altitudemax: 0, - activefilter: true, smgactivefilter: null, publishedonlist: new List(), sourcelist: new List(), - searchfilter: null, language: language, lastchange: null, languagelist: new List() { language }, - filterClosedData: true, reducedData: true) - .OrderByRaw(orderby); + var query = queryFactory + .Query() + .SelectRaw(select) + .From("accommodations") + .AccommodationWhereExpression( + idlist: new List(), + accotypelist: new List(), + categorylist: new List(), + featurelist: new Dictionary(), + featureidlist: new List(), + badgelist: new List(), + themelist: new Dictionary(), + boardlist: new List(), + smgtaglist: new List(), + districtlist: new List(), + municipalitylist: new List(), + tourismvereinlist: new List(), + regionlist: new List(), + apartmentfilter: null, + bookable: null, + altitude: false, + altitudemin: 0, + altitudemax: 0, + activefilter: true, + smgactivefilter: null, + publishedonlist: new List(), + sourcelist: new List(), + searchfilter: null, + language: language, + lastchange: null, + languagelist: new List() { language }, + filterClosedData: true, + reducedData: true + ) + .OrderByRaw(orderby); var data = (await query.GetAsync()).ToList(); var result = ResponseHelpers.GetResult(1, 1, (uint)data.Count, null, data, null); @@ -80,11 +156,15 @@ public static async Task GenerateJSONAccommodationsForSTA(QueryFactory queryFact using (var writer = File.CreateText(fileName)) { serializer.Serialize(writer, result); - } + } } } - public static async Task GenerateJSONODHActivityPoiForSTA(QueryFactory queryFactory, string jsondir, string xmlconfig) + public static async Task GenerateJSONODHActivityPoiForSTA( + QueryFactory queryFactory, + string jsondir, + string xmlconfig + ) { List languagelist = new List() { "de", "it", "en" }; var serializer = new JsonSerializer(); @@ -92,32 +172,60 @@ public static async Task GenerateJSONODHActivityPoiForSTA(QueryFactory queryFact foreach (var language in languagelist) { //string select = $"data->>'Id' as \"Id\", data->'Detail'->'{language}'->>'Title' AS \"Detail.{language}.Title\", data->'ContactInfos'->'{language}'->>'City' AS \"ContactInfos.{language}.City\""; - string select = $"data->>'Id' as \"Id\", data->'Detail'->'{language}'->>'Title' AS \"Detail.{language}.Title\", data->'LocationInfo'->'MunicipalityInfo'->'Name'->>'{language}' AS \"ContactInfos.{language}.City\""; + string select = + $"data->>'Id' as \"Id\", data->'Detail'->'{language}'->>'Title' AS \"Detail.{language}.Title\", data->'LocationInfo'->'MunicipalityInfo'->'Name'->>'{language}' AS \"ContactInfos.{language}.City\""; string orderby = "data ->>'Shortname' ASC"; //List fieldselectorlist = new List() { "Id", "Detail." + language + ".Title", "ContactInfos." + language + ".City" }; var categoriestoretrieve = GetSTACategoriesToFilter(xmlconfig); - var query = - queryFactory.Query() + var query = queryFactory + .Query() .SelectRaw(select) .From("smgpois") - .ODHActivityPoiWhereExpression( - idlist: new List(), typelist: new List(), - subtypelist: new List(), level3typelist: new List(), - smgtaglist: categoriestoretrieve, smgtaglistand: new List(), districtlist: new List(), - municipalitylist: new List(), tourismvereinlist: new List(), - regionlist: new List(), arealist: new List(), - sourcelist: new List(), languagelist: new List() { language }, - highlight: null, activefilter: true, smgactivefilter: null, - categorycodeslist: new List(), dishcodeslist: new List(), ceremonycodeslist: new List(), facilitycodeslist: new List(), - activitytypelist: new List(), poitypelist: new List(), difficultylist: new List(), distance: false, - distancemin: 0, distancemax: 0, duration: false, durationmin: 0, - durationmax: 0, altitude: false, altitudemin: 0, altitudemax: 0, - tagbehaviour: "", tagdict: null, publishedonlist: new List(), - searchfilter: null, language: language, lastchange: null, - filterClosedData: true, reducedData: true) + .ODHActivityPoiWhereExpression( + idlist: new List(), + typelist: new List(), + subtypelist: new List(), + level3typelist: new List(), + smgtaglist: categoriestoretrieve, + smgtaglistand: new List(), + districtlist: new List(), + municipalitylist: new List(), + tourismvereinlist: new List(), + regionlist: new List(), + arealist: new List(), + sourcelist: new List(), + languagelist: new List() { language }, + highlight: null, + activefilter: true, + smgactivefilter: null, + categorycodeslist: new List(), + dishcodeslist: new List(), + ceremonycodeslist: new List(), + facilitycodeslist: new List(), + activitytypelist: new List(), + poitypelist: new List(), + difficultylist: new List(), + distance: false, + distancemin: 0, + distancemax: 0, + duration: false, + durationmin: 0, + durationmax: 0, + altitude: false, + altitudemin: 0, + altitudemax: 0, + tagbehaviour: "", + tagdict: null, + publishedonlist: new List(), + searchfilter: null, + language: language, + lastchange: null, + filterClosedData: true, + reducedData: true + ) .OrderByRaw(orderby); var data = (await query.GetAsync()).ToList(); @@ -131,8 +239,8 @@ public static async Task GenerateJSONODHActivityPoiForSTA(QueryFactory queryFact { serializer.Serialize(writer, result); } - - //// Create a new file + + //// Create a new file //using (FileStream fs = System.IO.File.Create(fileName)) //{ // //var sz = JsonConvert.SerializeObject(data); @@ -149,7 +257,7 @@ public static async Task GenerateJSONODHActivityPoiForSTA(QueryFactory queryFact // Byte[] mybyte = new UTF8Encoding(true).GetBytes(sz); // fs.Write(mybyte, 0, mybyte.Length); - + //} } } @@ -160,9 +268,30 @@ public static List GetSTACategoriesToFilter(string xmldir) var staconfig = XDocument.Load(xmldir + "STACategories.xml"); - categories.AddRange(staconfig.Root?.Element("ODHActivityPois")?.Element("Categories")?.Elements("Item")?.Select(x => x.Value)?.ToList() ?? new List()); - categories.AddRange(staconfig.Root?.Element("ODHActivityPois")?.Element("SubCategories")?.Elements("Item")?.Select(x => x.Value)?.ToList() ?? new List()); - categories.AddRange(staconfig.Root?.Element("ODHActivityPois")?.Element("PoiCategories")?.Elements("Item")?.Select(x => x.Value)?.ToList() ?? new List()); + categories.AddRange( + staconfig.Root + ?.Element("ODHActivityPois") + ?.Element("Categories") + ?.Elements("Item") + ?.Select(x => x.Value) + ?.ToList() ?? new List() + ); + categories.AddRange( + staconfig.Root + ?.Element("ODHActivityPois") + ?.Element("SubCategories") + ?.Elements("Item") + ?.Select(x => x.Value) + ?.ToList() ?? new List() + ); + categories.AddRange( + staconfig.Root + ?.Element("ODHActivityPois") + ?.Element("PoiCategories") + ?.Elements("Item") + ?.Select(x => x.Value) + ?.ToList() ?? new List() + ); return categories; } diff --git a/OdhApiCore/Middleware/HttpRequestMiddleware.cs b/OdhApiCore/Middleware/HttpRequestMiddleware.cs index 5585e1536..4527aadeb 100644 --- a/OdhApiCore/Middleware/HttpRequestMiddleware.cs +++ b/OdhApiCore/Middleware/HttpRequestMiddleware.cs @@ -9,106 +9,145 @@ namespace OdhApiCore { public static class HttpRequestExtensions { - public static IApplicationBuilder UseODHCustomHttpRequestConfig(this IApplicationBuilder builder, IConfiguration configuration) + public static IApplicationBuilder UseODHCustomHttpRequestConfig( + this IApplicationBuilder builder, + IConfiguration configuration + ) { - return builder.Use(async (context, next) => - { - //If Root is requested forward to Databrowser (Compatibility reason) - if (String.IsNullOrEmpty(context.Request.Path.Value) || context.Request.Path.Value == "/") + return builder.Use( + async (context, next) => { - if (context.Request.Host.ToString().Equals("tourism.opendatahub.bz.it")) + //If Root is requested forward to Databrowser (Compatibility reason) + if ( + String.IsNullOrEmpty(context.Request.Path.Value) + || context.Request.Path.Value == "/" + ) + { + if (context.Request.Host.ToString().Equals("tourism.opendatahub.bz.it")) + { + context.Response.Redirect( + configuration + .GetSection("DataBrowserConfig") + .GetValue("Url") + ); + return; + } + else + { + context.Response.Redirect("/swagger"); + return; + } + } + else if (context.Request.Path.Value == "/api") { - context.Response.Redirect(configuration.GetSection("DataBrowserConfig").GetValue("Url")); + context.Response.Redirect("/v1"); return; } - else + else if (context.Request.Path.Value.StartsWith("/swagger/ui/index")) { context.Response.Redirect("/swagger"); return; } - } - - else if (context.Request.Path.Value == "/api") - { - context.Response.Redirect("/v1"); - return; - } - - else if (context.Request.Path.Value.StartsWith("/swagger/ui/index")) - { - context.Response.Redirect("/swagger"); - return; - } - Stopwatch requesttime = new Stopwatch(); - requesttime.Start(); - - await next(); - - //Log only if api is requested! including HTTP Statuscode therefore after await next(); - //if(context.Request.Path.StartsWithSegments("/v1/", StringComparison.OrdinalIgnoreCase)) - if (!String.IsNullOrEmpty(context.Request.Path.Value) && context.Request.Path.Value.StartsWith("/v1", StringComparison.OrdinalIgnoreCase)) - { - //TODO Make a Referer Class/Method for the logic - var referer = "not provided"; - - if (context.Request.Headers.ContainsKey("Referer")) - referer = context.Request.Headers["Referer"].ToString(); - else + Stopwatch requesttime = new Stopwatch(); + requesttime.Start(); + + await next(); + + //Log only if api is requested! including HTTP Statuscode therefore after await next(); + //if(context.Request.Path.StartsWithSegments("/v1/", StringComparison.OrdinalIgnoreCase)) + if ( + !String.IsNullOrEmpty(context.Request.Path.Value) + && context.Request.Path.Value.StartsWith( + "/v1", + StringComparison.OrdinalIgnoreCase + ) + ) { - //Search the QS for Referer - if (context.Request.Query.ContainsKey("Referer")) + //TODO Make a Referer Class/Method for the logic + var referer = "not provided"; + + if (context.Request.Headers.ContainsKey("Referer")) + referer = context.Request.Headers["Referer"].ToString(); + else + { + //Search the QS for Referer + if (context.Request.Query.ContainsKey("Referer")) + referer = context.Request.Query["Referer"].ToString(); + } + + //Quick Fix, Android is passing http://localhost/ as referer + if ( + referer == "http://localhost/" + && context.Request.Query.ContainsKey("Referer") + ) referer = context.Request.Query["Referer"].ToString(); - } - - //Quick Fix, Android is passing http://localhost/ as referer - if (referer == "http://localhost/" && context.Request.Query.ContainsKey("Referer")) - referer = context.Request.Query["Referer"].ToString(); - - //Origin - var origin = "not provided"; - if (context.Request.Query.ContainsKey("Origin")) - origin = context.Request.Query["Origin"].ToString(); - - //User Agent - var useragent = "not provided"; - if (context.Request.Headers.ContainsKey("User-Agent")) - useragent = context.Request.Headers["User-Agent"].ToString(); - - var urlparameters = context.Request.QueryString.Value != null ? context.Request.QueryString.HasValue ? context.Request.QueryString.Value.Replace("?", "") : "" : ""; - - //To check - var remoteip = RemoteIpHelper.GetRequestIP(context, true); - - //Request Length - requesttime.Stop(); - - //TODO Add Response Size? - - HttpRequestLog httplog = new HttpRequestLog() - { - host = context.Request.Host.ToString(), - path = context.Request.Path.ToString(), - urlparams = urlparameters, //.Replace("&", "-"), //Helper.StringHelpers.GenerateDictionaryFromQuerystring(context.Request.QueryString.ToString()), - referer = referer, - schema = context.Request.Scheme, - useragent = useragent, - username = context.User.Identity != null ? context.User.Identity.Name != null ? context.User.Identity.Name.ToString() : "anonymous" : "anonymous", - ipaddress = remoteip, - statuscode = context.Response.StatusCode, - origin = origin, - elapsedtime = requesttime.ElapsedMilliseconds, - appliedquota = "", - ratelimitkey = "" - }; - LogOutput logoutput = new LogOutput() { id = "", type = "HttpRequest", log = "apiaccess", output = httplog }; - - Console.WriteLine(JsonConvert.SerializeObject(logoutput)); + //Origin + var origin = "not provided"; + if (context.Request.Query.ContainsKey("Origin")) + origin = context.Request.Query["Origin"].ToString(); + + //User Agent + var useragent = "not provided"; + if (context.Request.Headers.ContainsKey("User-Agent")) + useragent = context.Request.Headers["User-Agent"].ToString(); + + var urlparameters = + context.Request.QueryString.Value != null + ? context.Request.QueryString.HasValue + ? context.Request.QueryString.Value.Replace("?", "") + : "" + : ""; + + //To check + var remoteip = RemoteIpHelper.GetRequestIP(context, true); + + //Request Length + requesttime.Stop(); + + //TODO Add Response Size? + + HttpRequestLog httplog = new HttpRequestLog() + { + host = context.Request.Host.ToString(), + path = context.Request.Path.ToString(), + urlparams = urlparameters, //.Replace("&", "-"), //Helper.StringHelpers.GenerateDictionaryFromQuerystring(context.Request.QueryString.ToString()), + referer = referer, + schema = context.Request.Scheme, + useragent = useragent, + username = + context.User.Identity != null + ? context.User.Identity.Name != null + ? context.User.Identity.Name.ToString() + : "anonymous" + : "anonymous", + ipaddress = remoteip, + statuscode = context.Response.StatusCode, + origin = origin, + elapsedtime = requesttime.ElapsedMilliseconds, + appliedquota = "", + ratelimitkey = "" + }; + LogOutput logoutput = new LogOutput() + { + id = "", + type = "HttpRequest", + log = "apiaccess", + output = httplog + }; + + Console.WriteLine(JsonConvert.SerializeObject(logoutput)); + } } - }); + ); } - public static void GenerateLogResponse(Microsoft.AspNetCore.Http.HttpContext context, int? elapsedtime = 0, string? quotaapplied = "", string? cachekey = "") + public static void GenerateLogResponse( + Microsoft.AspNetCore.Http.HttpContext context, + int? elapsedtime = 0, + string? quotaapplied = "", + string? cachekey = "" + ) { //TODO Make a Referer Class/Method for the logic var referer = "not provided"; @@ -136,7 +175,12 @@ public static void GenerateLogResponse(Microsoft.AspNetCore.Http.HttpContext con if (context.Request.Headers.ContainsKey("User-Agent")) useragent = context.Request.Headers["User-Agent"].ToString(); - var urlparameters = context.Request.QueryString.Value != null ? context.Request.QueryString.HasValue ? context.Request.QueryString.Value.Replace("?", "") : "" : ""; + var urlparameters = + context.Request.QueryString.Value != null + ? context.Request.QueryString.HasValue + ? context.Request.QueryString.Value.Replace("?", "") + : "" + : ""; //To check var remoteip = RemoteIpHelper.GetRequestIP(context, true); @@ -151,7 +195,12 @@ public static void GenerateLogResponse(Microsoft.AspNetCore.Http.HttpContext con referer = referer, schema = context.Request.Scheme, useragent = useragent, - username = context.User.Identity != null ? context.User.Identity.Name != null ? context.User.Identity.Name.ToString() : "anonymous" : "anonymous", + username = + context.User.Identity != null + ? context.User.Identity.Name != null + ? context.User.Identity.Name.ToString() + : "anonymous" + : "anonymous", ipaddress = remoteip, statuscode = context.Response.StatusCode, origin = origin, @@ -159,13 +208,15 @@ public static void GenerateLogResponse(Microsoft.AspNetCore.Http.HttpContext con appliedquota = quotaapplied, ratelimitkey = cachekey }; - LogOutput logoutput = new LogOutput() { id = "", type = "HttpRequest", log = "apiaccess", output = httplog }; + LogOutput logoutput = new LogOutput() + { + id = "", + type = "HttpRequest", + log = "apiaccess", + output = httplog + }; Console.WriteLine(JsonConvert.SerializeObject(logoutput)); } - } - - - } diff --git a/OdhApiCore/Middleware/RateLimitMiddleware.cs b/OdhApiCore/Middleware/RateLimitMiddleware.cs index 243e8ec74..effc3db9d 100644 --- a/OdhApiCore/Middleware/RateLimitMiddleware.cs +++ b/OdhApiCore/Middleware/RateLimitMiddleware.cs @@ -56,29 +56,60 @@ public async Task InvokeAsync(HttpContext context, ISettings settings) { var clientStatistics = await GetClientStatisticsByKey(key); - context.AddRateLimitHeaders(rlConfig.MaxRequests, clientStatistics == null ? 0 : clientStatistics.LastSuccessfulResponseTimeList.Count, rlConfig.TimeWindow, rlConfig.Type); - - if (clientStatistics != null && clientStatistics.LastSuccessfulResponseTimeList.Count >= rlConfig.MaxRequests) + context.AddRateLimitHeaders( + rlConfig.MaxRequests, + clientStatistics == null + ? 0 + : clientStatistics.LastSuccessfulResponseTimeList.Count, + rlConfig.TimeWindow, + rlConfig.Type + ); + + if ( + clientStatistics != null + && clientStatistics.LastSuccessfulResponseTimeList.Count >= rlConfig.MaxRequests + ) { // Done by WriteasJson context.Response.StatusCode = (int)HttpStatusCode.TooManyRequests; - await context.Response.WriteAsJsonAsync(new QuotaExceededMessage { Message = "You have exhausted your API Request Quota", Policy = rlConfig.Type, RetryAfter = rlConfig.TimeWindow, RequestsDone = clientStatistics.LastSuccessfulResponseTimeList.Count }); - - HttpRequestExtensions.GenerateLogResponse(context, clientStatistics.LastSuccessfulResponseTimeList.Count, rlConfig.Type, key); + await context.Response.WriteAsJsonAsync( + new QuotaExceededMessage + { + Message = "You have exhausted your API Request Quota", + Policy = rlConfig.Type, + RetryAfter = rlConfig.TimeWindow, + RequestsDone = clientStatistics.LastSuccessfulResponseTimeList.Count + } + ); + + HttpRequestExtensions.GenerateLogResponse( + context, + clientStatistics.LastSuccessfulResponseTimeList.Count, + rlConfig.Type, + key + ); return; } - await UpdateClientStatisticsStorage(key, rlConfig.MaxRequests, TimeSpan.FromSeconds(rlConfig.TimeWindow)); + await UpdateClientStatisticsStorage( + key, + rlConfig.MaxRequests, + TimeSpan.FromSeconds(rlConfig.TimeWindow) + ); } await _next(context); } - private static string GenerateClientKey(HttpContext context) => $"{context.Request.Path}_{context.Connection.RemoteIpAddress}"; + private static string GenerateClientKey(HttpContext context) => + $"{context.Request.Path}_{context.Connection.RemoteIpAddress}"; - private static (RateLimitConfig? rlConfig, string key) GenerateClientKeyExtended(HttpContext context, List rlsettings) + private static (RateLimitConfig? rlConfig, string key) GenerateClientKeyExtended( + HttpContext context, + List rlsettings + ) { RateLimitConfig? ratelimitconfig = default; string ratelimitcachekey = ""; @@ -110,7 +141,6 @@ private static (RateLimitConfig? rlConfig, string key) GenerateClientKeyExtended var jwttoken = ReadMyJWTSecurityToken(token, handler); - if (jwttoken != null) { // Gets name from claims. Generally it's an email address. @@ -143,29 +173,34 @@ private static (RateLimitConfig? rlConfig, string key) GenerateClientKeyExtended // Case 2 Referer passed generate key with Referer else if (!String.IsNullOrEmpty(referer) && String.IsNullOrEmpty(loggeduser)) { - ratelimitcachekey = $"{context.Request.Path}_{context.Connection.RemoteIpAddress}_{referer}"; + ratelimitcachekey = + $"{context.Request.Path}_{context.Connection.RemoteIpAddress}_{referer}"; ratelimitconfig = rlsettings.Where(x => x.Type == "Referer").FirstOrDefault(); } - // Case 3 Logged user, decode token and use username as key else if (!String.IsNullOrEmpty(loggeduser)) { - ratelimitcachekey = $"{context.Request.Path}_{context.Connection.RemoteIpAddress}_{loggeduser}"; + ratelimitcachekey = + $"{context.Request.Path}_{context.Connection.RemoteIpAddress}_{loggeduser}"; ratelimitconfig = rlsettings.Where(x => x.Type == "Basic").FirstOrDefault(); - // If user is in Role - if(!string.IsNullOrEmpty(userrole)) + // If user is in Role + if (!string.IsNullOrEmpty(userrole)) { - if(userrole == "ODH_ROLE_ADVANCED") - ratelimitconfig = rlsettings.Where(x => x.Type == "Advanced").FirstOrDefault(); + if (userrole == "ODH_ROLE_ADVANCED") + ratelimitconfig = rlsettings + .Where(x => x.Type == "Advanced") + .FirstOrDefault(); if (userrole == "ODH_ROLE_PREMIUM") - ratelimitconfig = rlsettings.Where(x => x.Type == "Premium").FirstOrDefault(); + ratelimitconfig = rlsettings + .Where(x => x.Type == "Premium") + .FirstOrDefault(); if (userrole == "ODH_ROLE_ADMIN") ratelimitconfig = rlsettings.Where(x => x.Type == "Admin").FirstOrDefault(); } // Fallback if ratelimitconfig by Role is null - if(ratelimitconfig == null) + if (ratelimitconfig == null) ratelimitconfig = rlsettings.Where(x => x.Type == "Basic").FirstOrDefault(); } // No rate limit @@ -177,7 +212,10 @@ private static (RateLimitConfig? rlConfig, string key) GenerateClientKeyExtended return (ratelimitconfig, ratelimitcachekey); } - private static JwtSecurityToken? ReadMyJWTSecurityToken(string token, JwtSecurityTokenHandler handler) + private static JwtSecurityToken? ReadMyJWTSecurityToken( + string token, + JwtSecurityTokenHandler handler + ) { try { @@ -191,9 +229,14 @@ private static (RateLimitConfig? rlConfig, string key) GenerateClientKeyExtended } } - private async Task GetClientStatisticsByKey(string key) => await _cache.GetCacheValueAsync(key); + private async Task GetClientStatisticsByKey(string key) => + await _cache.GetCacheValueAsync(key); - private async Task UpdateClientStatisticsStorage(string key, int maxRequests, TimeSpan timeWindow) + private async Task UpdateClientStatisticsStorage( + string key, + int maxRequests, + TimeSpan timeWindow + ) { var clientStat = await _cache.GetCacheValueAsync(key); @@ -202,7 +245,11 @@ private async Task UpdateClientStatisticsStorage(string key, int maxRequests, Ti var now = DateTime.UtcNow; clientStat.LastSuccessfulResponseTimeList.Add(now); - clientStat.LastSuccessfulResponseTimeList = RemoveAllExpiredResponseDateTimes(clientStat.LastSuccessfulResponseTimeList, timeWindow, now); + clientStat.LastSuccessfulResponseTimeList = RemoveAllExpiredResponseDateTimes( + clientStat.LastSuccessfulResponseTimeList, + timeWindow, + now + ); await _cache.SetCacheValueAsync(key, timeWindow, clientStat); } @@ -215,14 +262,17 @@ private async Task UpdateClientStatisticsStorage(string key, int maxRequests, Ti await _cache.SetCacheValueAsync(key, timeWindow, clientStatistics); } - } - private static List RemoveAllExpiredResponseDateTimes(List list, TimeSpan timeWindow, DateTime dateto) + private static List RemoveAllExpiredResponseDateTimes( + List list, + TimeSpan timeWindow, + DateTime dateto + ) { var validfrom = dateto.Subtract(timeWindow); - // Remove all no more valid Requests + // Remove all no more valid Requests return list.Where(x => x >= validfrom).ToList(); } @@ -234,10 +284,13 @@ public static MemoryStream GenerateStreamFromString(string value) private static bool CheckNoRestrictionRoutes(PathString currentpath, ISettings settings) { bool toreturn = false; - - if (settings.NoRateLimitConfig.NoRateLimitRoutes != null && currentpath.Value != null && settings.NoRateLimitConfig.NoRateLimitRoutes.Contains(currentpath.Value)) - return true; + if ( + settings.NoRateLimitConfig.NoRateLimitRoutes != null + && currentpath.Value != null + && settings.NoRateLimitConfig.NoRateLimitRoutes.Contains(currentpath.Value) + ) + return true; return toreturn; } @@ -257,10 +310,12 @@ private static bool CheckNoRestricionReferer(HttpContext context, ISettings sett currentreferer = context.Request.Query["Referer"].ToString(); } - if (settings.NoRateLimitConfig.NoRateLimitReferer != null && settings.NoRateLimitConfig.NoRateLimitReferer.Contains(currentreferer)) + if ( + settings.NoRateLimitConfig.NoRateLimitReferer != null + && settings.NoRateLimitConfig.NoRateLimitReferer.Contains(currentreferer) + ) return true; - return toreturn; } } @@ -280,10 +335,7 @@ public class QuotaExceededMessage public string? Message { get; set; } public string? Hint { - get - { - return "https://github.com/noi-techpark/odh-docs/wiki/Api-Quota"; - } + get { return "https://github.com/noi-techpark/odh-docs/wiki/Api-Quota"; } } public string? Policy { get; set; } diff --git a/OdhApiCore/Pages/Index.cshtml.cs b/OdhApiCore/Pages/Index.cshtml.cs index f41d735dc..28f2f76c7 100644 --- a/OdhApiCore/Pages/Index.cshtml.cs +++ b/OdhApiCore/Pages/Index.cshtml.cs @@ -4,9 +4,6 @@ namespace OdhApiCore.Pages { public class IndexModel : PageModel { - public void OnGet() - { - - } + public void OnGet() { } } -} \ No newline at end of file +} diff --git a/OdhApiCore/Program.cs b/OdhApiCore/Program.cs index e7da008ff..9a718164a 100644 --- a/OdhApiCore/Program.cs +++ b/OdhApiCore/Program.cs @@ -9,7 +9,7 @@ public class Program { public static async Task Main(string[] args) { - var host = CreateHostBuilder(args).Build(); + var host = CreateHostBuilder(args).Build(); await host.RunAsync(); } @@ -21,8 +21,7 @@ public static IHostBuilder CreateHostBuilder(string[] args) //{ // config.AddEnvironmentVariables(); //}) - .ConfigureWebHostDefaults(webBuilder => - webBuilder.UseStartup()); + .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()); } } -} \ No newline at end of file +} diff --git a/OdhApiCore/Responses/ResponseHelpers.cs b/OdhApiCore/Responses/ResponseHelpers.cs index 589d3b3d8..3efb6d71b 100644 --- a/OdhApiCore/Responses/ResponseHelpers.cs +++ b/OdhApiCore/Responses/ResponseHelpers.cs @@ -10,13 +10,18 @@ using System.Runtime.InteropServices.ComTypes; using System.Text.Json.Serialization; using System.Threading.Tasks; -using DataModel; - +using DataModel; + namespace OdhApiCore.Responses -{ +{ public static class ResponseHelpers { - private static (string? previouspage, string? nextpage) GetPreviousAndNextPage(uint pagenumber, uint totalpages, IUrlHelper? url, string? seed) + private static (string? previouspage, string? nextpage) GetPreviousAndNextPage( + uint pagenumber, + uint totalpages, + IUrlHelper? url, + string? seed + ) { string? previouspage = null; string? nextpage = null; @@ -38,14 +43,25 @@ private static (string? previouspage, string? nextpage) GetPreviousAndNextPage(u queryDict["pagenumber"] = (pagenumber + 1).ToString(); nextpage = url.Link(null, queryDict); } - } + } return (previouspage, nextpage); } public static JsonResult GetResult( - uint pagenumber, uint totalpages, uint totalcount, string? seed, IEnumerable data, IUrlHelper? url) + uint pagenumber, + uint totalpages, + uint totalcount, + string? seed, + IEnumerable data, + IUrlHelper? url + ) { - var (previouspage, nextpage) = GetPreviousAndNextPage(pagenumber, totalpages, url, seed); + var (previouspage, nextpage) = GetPreviousAndNextPage( + pagenumber, + totalpages, + url, + seed + ); return new JsonResult { TotalResults = totalcount, @@ -59,11 +75,21 @@ public static JsonResult GetResult( } public static JsonResultWithOnlineResults GetResult( - uint pagenumber, uint totalpages, uint totalcount, int onlineresults, string? seed, - IEnumerable data, IUrlHelper url) - where T : notnull + uint pagenumber, + uint totalpages, + uint totalcount, + int onlineresults, + string? seed, + IEnumerable data, + IUrlHelper url + ) where T : notnull { - var (previouspage, nextpage) = GetPreviousAndNextPage(pagenumber, totalpages, url, seed); + var (previouspage, nextpage) = GetPreviousAndNextPage( + pagenumber, + totalpages, + url, + seed + ); return new JsonResultWithOnlineResults { TotalResults = totalcount, @@ -78,11 +104,22 @@ public static JsonResultWithOnlineResults GetResult( } public static JsonResultWithOnlineResultsAndResultId GetResult( - uint pagenumber, uint totalpages, uint totalcount, int onlineresults, - string resultid, string? seed, IEnumerable data, IUrlHelper url) - where T : notnull + uint pagenumber, + uint totalpages, + uint totalcount, + int onlineresults, + string resultid, + string? seed, + IEnumerable data, + IUrlHelper url + ) where T : notnull { - var (previouspage, nextpage) = GetPreviousAndNextPage(pagenumber, totalpages, url, seed); + var (previouspage, nextpage) = GetPreviousAndNextPage( + pagenumber, + totalpages, + url, + seed + ); return new JsonResultWithOnlineResultsAndResultId { TotalResults = totalcount, @@ -98,11 +135,22 @@ public static JsonResultWithOnlineResultsAndResultId GetResult( } public static JsonResultWithOnlineResultsAndResultIdLowercase GetResultLowercase( - uint pagenumber, uint totalpages, uint totalcount, int onlineresults, - string resultid, string seed, IEnumerable data, IUrlHelper url) - where T : notnull + uint pagenumber, + uint totalpages, + uint totalcount, + int onlineresults, + string resultid, + string seed, + IEnumerable data, + IUrlHelper url + ) where T : notnull { - var (previouspage, nextpage) = GetPreviousAndNextPage(pagenumber, totalpages, url, seed); + var (previouspage, nextpage) = GetPreviousAndNextPage( + pagenumber, + totalpages, + url, + seed + ); return new JsonResultWithOnlineResultsAndResultIdLowercase { totalResults = totalcount, @@ -118,10 +166,24 @@ public static JsonResultWithOnlineResultsAndResultIdLowercase GetResultLowerc } public static JsonResultWithBookingInfo GetResult( - uint pagenumber, uint totalpages, uint totalcount, int accosrequested, int availableonline, int availableonrequest, - string resultid, string? seed, IEnumerable data, IUrlHelper url) + uint pagenumber, + uint totalpages, + uint totalcount, + int accosrequested, + int availableonline, + int availableonrequest, + string resultid, + string? seed, + IEnumerable data, + IUrlHelper url + ) { - var (previouspage, nextpage) = GetPreviousAndNextPage(pagenumber, totalpages, url, seed); + var (previouspage, nextpage) = GetPreviousAndNextPage( + pagenumber, + totalpages, + url, + seed + ); return new JsonResultWithBookingInfo { TotalResults = totalcount, diff --git a/OdhApiCore/Settings.cs b/OdhApiCore/Settings.cs index ac7f1cbda..e326d4382 100644 --- a/OdhApiCore/Settings.cs +++ b/OdhApiCore/Settings.cs @@ -14,7 +14,7 @@ public MssConfig(string username, string password) } public string Username { get; private set; } - public string Password { get; private set; } + public string Password { get; private set; } } public class LcsConfig @@ -52,11 +52,11 @@ public class SiagConfig public SiagConfig(string username, string password) { this.Username = username; - this.Password = password; + this.Password = password; } public string Username { get; private set; } - public string Password { get; private set; } + public string Password { get; private set; } } public class XmlConfig @@ -68,14 +68,14 @@ public XmlConfig(string xmldir, string xmldirweather) } public string Xmldir { get; private set; } - public string XmldirWeather { get; private set; } + public string XmldirWeather { get; private set; } } public class JsonConfig { public JsonConfig(string jsondir) { - this.Jsondir = jsondir; + this.Jsondir = jsondir; } public string Jsondir { get; private set; } @@ -83,7 +83,13 @@ public JsonConfig(string jsondir) public class S3ImageresizerConfig { - public S3ImageresizerConfig(string url, string docurl, string bucketaccesspoint, string accesskey, string secretkey) + public S3ImageresizerConfig( + string url, + string docurl, + string bucketaccesspoint, + string accesskey, + string secretkey + ) { this.Url = url; this.DocUrl = docurl; @@ -141,14 +147,22 @@ public Field2HideConfig(string entity, string fields, string validforroles) public class RequestInterceptorConfig { - public RequestInterceptorConfig(string action, string controller, string querystrings, string redirectaction, string redirectcontroller, string redirectquerystrings) + public RequestInterceptorConfig( + string action, + string controller, + string querystrings, + string redirectaction, + string redirectcontroller, + string redirectquerystrings + ) { this.Action = action; this.Controller = controller; this.QueryStrings = querystrings != null ? querystrings.Split('&').ToList() : null; this.RedirectAction = redirectaction; this.RedirectController = redirectcontroller; - this.RedirectQueryStrings = redirectquerystrings != null ? redirectquerystrings.Split('&').ToList() : null; + this.RedirectQueryStrings = + redirectquerystrings != null ? redirectquerystrings.Split('&').ToList() : null; } public string Action { get; private set; } @@ -179,12 +193,12 @@ public FCMConfig(string identifier, string serverkey, string senderid) { this.Identifier = identifier; this.ServerKey = serverkey; - this.SenderId = senderid; + this.SenderId = senderid; } public string Identifier { get; private set; } public string ServerKey { get; private set; } - public string SenderId { get; private set; } + public string SenderId { get; private set; } } public class RateLimitConfig @@ -199,7 +213,7 @@ public RateLimitConfig(string type, int timewindow, int maxrequests) public string Type { get; private set; } public int TimeWindow { get; private set; } public int MaxRequests { get; private set; } - } + } public class NoRateLimitConfig { @@ -208,6 +222,7 @@ public NoRateLimitConfig(List noratelimitroutes, List noratelimi NoRateLimitRoutes = noratelimitroutes; NoRateLimitReferer = noratelimitrefers; } + public List NoRateLimitRoutes { get; private set; } public List NoRateLimitReferer { get; private set; } } @@ -225,6 +240,7 @@ public interface ISettings EBMSConfig EbmsConfig { get; } RavenConfig RavenConfig { get; } PushServerConfig PushServerConfig { get; } + //FCMConfig FCMConfig { get; } List Field2HideConfig { get; } List RequestInterceptorConfig { get; } @@ -240,7 +256,7 @@ public class Settings : ISettings private readonly Lazy connectionString; private readonly MssConfig mssConfig; private readonly LcsConfig lcsConfig; - private readonly CDBConfig cdbConfig; + private readonly CDBConfig cdbConfig; private readonly SiagConfig siagConfig; private readonly XmlConfig xmlConfig; private readonly JsonConfig jsonConfig; @@ -248,6 +264,7 @@ public class Settings : ISettings private readonly EBMSConfig ebmsConfig; private readonly RavenConfig ravenConfig; private readonly PushServerConfig pushserverConfig; + //private readonly FCMConfig fcmConfig; private readonly List field2hideConfig; private readonly List requestInterceptorConfig; @@ -258,74 +275,145 @@ public class Settings : ISettings public Settings(IConfiguration configuration) { this.configuration = configuration; - this.connectionString = new Lazy(() => - this.configuration.GetConnectionString("PGConnection")); + this.connectionString = new Lazy( + () => this.configuration.GetConnectionString("PGConnection") + ); var mss = this.configuration.GetSection("MssConfig"); - this.mssConfig = new MssConfig(mss.GetValue("Username", ""), mss.GetValue("Password", "")); + this.mssConfig = new MssConfig( + mss.GetValue("Username", ""), + mss.GetValue("Password", "") + ); var lcs = this.configuration.GetSection("LcsConfig"); - this.lcsConfig = new LcsConfig(lcs.GetValue("Username", ""), lcs.GetValue("Password", ""), lcs.GetValue("MessagePassword", "")); + this.lcsConfig = new LcsConfig( + lcs.GetValue("Username", ""), + lcs.GetValue("Password", ""), + lcs.GetValue("MessagePassword", "") + ); var cdb = this.configuration.GetSection("CDBConfig"); - this.cdbConfig = new CDBConfig(cdb.GetValue("Username", ""), cdb.GetValue("Password", ""), cdb.GetValue("Url", "")); + this.cdbConfig = new CDBConfig( + cdb.GetValue("Username", ""), + cdb.GetValue("Password", ""), + cdb.GetValue("Url", "") + ); var siag = this.configuration.GetSection("SiagConfig"); - this.siagConfig = new SiagConfig(siag.GetValue("Username", ""), siag.GetValue("Password", "")); + this.siagConfig = new SiagConfig( + siag.GetValue("Username", ""), + siag.GetValue("Password", "") + ); var xml = this.configuration.GetSection("XmlConfig"); - this.xmlConfig = new XmlConfig(xml.GetValue("Xmldir", ""), xml.GetValue("XmldirWeather", "")); + this.xmlConfig = new XmlConfig( + xml.GetValue("Xmldir", ""), + xml.GetValue("XmldirWeather", "") + ); var json = this.configuration.GetSection("JsonConfig"); this.jsonConfig = new JsonConfig(json.GetValue("Jsondir", "")); var s3img = this.configuration.GetSection("S3ImageresizerConfig"); - this.s3imageresizerConfig = new S3ImageresizerConfig(s3img.GetValue("Url", ""), s3img.GetValue("DocUrl", ""), s3img.GetValue("BucketAccessPoint", ""), s3img.GetValue("AccessKey", ""), s3img.GetValue("SecretKey", "")); + this.s3imageresizerConfig = new S3ImageresizerConfig( + s3img.GetValue("Url", ""), + s3img.GetValue("DocUrl", ""), + s3img.GetValue("BucketAccessPoint", ""), + s3img.GetValue("AccessKey", ""), + s3img.GetValue("SecretKey", "") + ); var ebms = this.configuration.GetSection("EBMSConfig"); - this.ebmsConfig = new EBMSConfig(ebms.GetValue("EBMSUser", ""), ebms.GetValue("EBMSPassword", "")); + this.ebmsConfig = new EBMSConfig( + ebms.GetValue("EBMSUser", ""), + ebms.GetValue("EBMSPassword", "") + ); var raven = this.configuration.GetSection("RavenConfig"); - this.ravenConfig = new RavenConfig(raven.GetValue("Username", ""), raven.GetValue("Password", ""), raven.GetValue("ServiceUrl", "")); + this.ravenConfig = new RavenConfig( + raven.GetValue("Username", ""), + raven.GetValue("Password", ""), + raven.GetValue("ServiceUrl", "") + ); var pushserver = this.configuration.GetSection("PushServerConfig"); - this.pushserverConfig = new PushServerConfig(pushserver.GetValue("Username", ""), pushserver.GetValue("Password", ""), pushserver.GetValue("ServiceUrl", "")); - var field2hidelist = this.configuration.GetSection("Field2HideConfig").GetChildren(); + this.pushserverConfig = new PushServerConfig( + pushserver.GetValue("Username", ""), + pushserver.GetValue("Password", ""), + pushserver.GetValue("ServiceUrl", "") + ); + var field2hidelist = this.configuration.GetSection("Field2HideConfig").GetChildren(); this.field2hideConfig = new List(); foreach (var field2hide in field2hidelist) { - this.field2hideConfig.Add(new Field2HideConfig(field2hide.GetValue("Entity", ""), field2hide.GetValue("Fields", ""), field2hide.GetValue("DisplayOnRoles", ""))); + this.field2hideConfig.Add( + new Field2HideConfig( + field2hide.GetValue("Entity", ""), + field2hide.GetValue("Fields", ""), + field2hide.GetValue("DisplayOnRoles", "") + ) + ); } - var requestinterceptorlist = this.configuration.GetSection("RequestInterceptorConfig").GetChildren(); + var requestinterceptorlist = this.configuration + .GetSection("RequestInterceptorConfig") + .GetChildren(); this.requestInterceptorConfig = new List(); foreach (var requestinterceptor in requestinterceptorlist) { - this.requestInterceptorConfig.Add(new RequestInterceptorConfig(requestinterceptor.GetValue("Action", ""), requestinterceptor.GetValue("Controller", ""), requestinterceptor.GetValue("QueryStrings", ""), - requestinterceptor.GetValue("RedirectAction", ""), requestinterceptor.GetValue("RedirectController", ""), requestinterceptor.GetValue("RedirectQueryStrings", ""))); + this.requestInterceptorConfig.Add( + new RequestInterceptorConfig( + requestinterceptor.GetValue("Action", ""), + requestinterceptor.GetValue("Controller", ""), + requestinterceptor.GetValue("QueryStrings", ""), + requestinterceptor.GetValue("RedirectAction", ""), + requestinterceptor.GetValue("RedirectController", ""), + requestinterceptor.GetValue("RedirectQueryStrings", "") + ) + ); } var ratelimitlist = this.configuration.GetSection("RateLimitConfig").GetChildren(); this.rateLimitConfig = new List(); foreach (var ratelimitconfig in ratelimitlist) { - this.rateLimitConfig.Add(new RateLimitConfig(ratelimitconfig.GetValue("Type", ""), ratelimitconfig.GetValue("TimeWindow", 0), ratelimitconfig.GetValue("MaxRequests", 0))); + this.rateLimitConfig.Add( + new RateLimitConfig( + ratelimitconfig.GetValue("Type", ""), + ratelimitconfig.GetValue("TimeWindow", 0), + ratelimitconfig.GetValue("MaxRequests", 0) + ) + ); } - var noratelimitroutes = this.configuration.GetSection("NoRateLimitConfig").GetSection("NoRateLimitRoutesConfig").GetChildren(); - var noratelimitreferers = this.configuration.GetSection("NoRateLimitConfig").GetSection("NoRateLimitRefererConfig").GetChildren(); - this.noRateLimitConfig = new NoRateLimitConfig(new List(), new List()); + var noratelimitroutes = this.configuration + .GetSection("NoRateLimitConfig") + .GetSection("NoRateLimitRoutesConfig") + .GetChildren(); + var noratelimitreferers = this.configuration + .GetSection("NoRateLimitConfig") + .GetSection("NoRateLimitRefererConfig") + .GetChildren(); + this.noRateLimitConfig = new NoRateLimitConfig(new List(), new List()); foreach (var routepath in noratelimitroutes) { - this.noRateLimitConfig.NoRateLimitRoutes.Add(routepath.GetValue("Path","")); + this.noRateLimitConfig.NoRateLimitRoutes.Add( + routepath.GetValue("Path", "") + ); } foreach (var referer in noratelimitreferers) { - this.noRateLimitConfig.NoRateLimitReferer.Add(referer.GetValue("Referer", "")); + this.noRateLimitConfig.NoRateLimitReferer.Add( + referer.GetValue("Referer", "") + ); } this.fcmConfig = new List(); var fcmdict = this.configuration.GetSection("FCMConfig").GetChildren(); - if(fcmdict != null) + if (fcmdict != null) { foreach (var fcmkey in fcmdict) { - var fcmconfigobj = new FCMConfig(fcmkey.Key, fcmkey.GetValue("ServerKey", ""), fcmkey.GetValue("SenderId", "")); + var fcmconfigobj = new FCMConfig( + fcmkey.Key, + fcmkey.GetValue("ServerKey", ""), + fcmkey.GetValue("SenderId", "") + ); this.fcmConfig.Add(fcmconfigobj); } - } + } } public string PostgresConnectionString => this.connectionString.Value; @@ -342,7 +430,8 @@ public Settings(IConfiguration configuration) public PushServerConfig PushServerConfig => this.pushserverConfig; public List FCMConfig => this.fcmConfig; public List Field2HideConfig => this.field2hideConfig; - public List RequestInterceptorConfig => this.requestInterceptorConfig; + public List RequestInterceptorConfig => + this.requestInterceptorConfig; public List RateLimitConfig => this.rateLimitConfig; public NoRateLimitConfig NoRateLimitConfig => this.noRateLimitConfig; } diff --git a/OdhApiCore/Startup.cs b/OdhApiCore/Startup.cs index 0f34625ed..98303ca1b 100644 --- a/OdhApiCore/Startup.cs +++ b/OdhApiCore/Startup.cs @@ -74,14 +74,23 @@ public void ConfigureServices(IServiceCollection services) //services.AddDefaultIdentity() // .AddEntityFrameworkStores(); - services.AddHttpClient("mss", client => - { - //client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate"); - }).ConfigureHttpMessageHandlerBuilder(config => new HttpClientHandler() - { - AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate - }); - services.AddHttpClient("lcs"); // TODO: put LCS config here + services + .AddHttpClient( + "mss", + client => + { + //client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate"); + } + ) + .ConfigureHttpMessageHandlerBuilder( + config => + new HttpClientHandler() + { + AutomaticDecompression = + DecompressionMethods.GZip | DecompressionMethods.Deflate + } + ); + services.AddHttpClient("lcs"); // TODO: put LCS config here //Adding Cache Service in Memory services.AddInMemoryCacheOutput(); @@ -155,7 +164,7 @@ public void ConfigureServices(IServiceCollection services) // options.HttpStatusCode = 429; // options.ClientIdHeader = "Referer"; // options.ClientWhitelist = new List { "Anonymous", "Authenticated" }; - // //General Rule from + // //General Rule from // options.GeneralRules = new List // { // new RateLimitRule() @@ -209,8 +218,8 @@ public void ConfigureServices(IServiceCollection services) //services.AddInMemoryRateLimiting(); - //services.AddSingleton(); - //services.AddSingleton(); + //services.AddSingleton(); + //services.AddSingleton(); services.AddLogging(options => { @@ -218,13 +227,12 @@ public void ConfigureServices(IServiceCollection services) var levelSwitch = new LoggingLevelSwitch { - MinimumLevel = - CurrentEnvironment.IsDevelopment() ? - LogEventLevel.Debug : - LogEventLevel.Warning + MinimumLevel = CurrentEnvironment.IsDevelopment() + ? LogEventLevel.Debug + : LogEventLevel.Warning }; - var loggerConfiguration = new LoggerConfiguration() - .MinimumLevel.ControlledBy(levelSwitch) + var loggerConfiguration = new LoggerConfiguration().MinimumLevel + .ControlledBy(levelSwitch) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console(outputTemplate: "{Message}{NewLine}") @@ -251,8 +259,10 @@ public void ConfigureServices(IServiceCollection services) Log.Logger = loggerConfiguration; }); - services.Configure(options => options.Level = System.IO.Compression.CompressionLevel.Optimal); - services.AddResponseCompression( options => + services.Configure( + options => options.Level = System.IO.Compression.CompressionLevel.Optimal + ); + services.AddResponseCompression(options => { options.EnableForHttps = true; options.Providers.Add(); @@ -260,49 +270,60 @@ public void ConfigureServices(IServiceCollection services) services.AddCors(o => { - o.AddPolicy("CorsPolicy", builder => - { - builder.AllowAnyMethod() + o.AddPolicy( + "CorsPolicy", + builder => + { + builder + .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() .SetIsOriginAllowed(hostName => true); - }); - }); - - services.AddControllers().AddNewtonsoftJson(options => - { - options.SerializerSettings.ContractResolver = new DefaultContractResolver(); - options.SerializerSettings.Converters.Add(new StringEnumConverter()); - //{ - // CamelCaseText = true - //}); + } + ); }); + services + .AddControllers() + .AddNewtonsoftJson(options => + { + options.SerializerSettings.ContractResolver = new DefaultContractResolver(); + options.SerializerSettings.Converters.Add(new StringEnumConverter()); + //{ + // CamelCaseText = true + //}); + }); + services.AddRazorPages(); services.AddSingleton(); services.AddScoped(); - + //Initialize JWT Authentication - services.AddAuthentication(options => + services + .AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) - .AddJwtBearer(jwtBearerOptions => + .AddJwtBearer(jwtBearerOptions => { - jwtBearerOptions.Authority = Configuration.GetSection("OauthServerConfig").GetValue("Authority"); - //jwtBearerOptions.Audience = "account"; + jwtBearerOptions.Authority = Configuration + .GetSection("OauthServerConfig") + .GetValue("Authority"); + //jwtBearerOptions.Audience = "account"; jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "preferred_username", ValidateAudience = false, - ValidateLifetime = true, - ValidIssuer = Configuration.GetSection("OauthServerConfig").GetValue("Authority"), + ValidateLifetime = true, + ValidIssuer = Configuration + .GetSection("OauthServerConfig") + .GetValue("Authority"), ValidateIssuer = true }; jwtBearerOptions.Events = new JwtBearerEvents() - { + { OnAuthenticationFailed = c => { c.NoResult(); @@ -310,75 +331,94 @@ public void ConfigureServices(IServiceCollection services) c.Response.StatusCode = 401; c.Response.ContentType = "text/plain"; return c.Response.WriteAsync(""); - }, + }, }; }); services.AddMvc(options => - { - options.OutputFormatters.Add(new Formatters.CsvOutputFormatter()); - options.FormatterMappings.SetMediaTypeMappingForFormat("csv", "text/csv"); + { + options.OutputFormatters.Add(new Formatters.CsvOutputFormatter()); + options.FormatterMappings.SetMediaTypeMappingForFormat("csv", "text/csv"); - options.OutputFormatters.Add(new Formatters.JsonLdOutputFormatter()); - options.FormatterMappings.SetMediaTypeMappingForFormat("json-ld", "application/ldjson"); + options.OutputFormatters.Add(new Formatters.JsonLdOutputFormatter()); + options.FormatterMappings.SetMediaTypeMappingForFormat( + "json-ld", + "application/ldjson" + ); + + options.OutputFormatters.Add(new Formatters.RawdataOutputFormatter()); + options.FormatterMappings.SetMediaTypeMappingForFormat( + "rawdata", + "application/rawdata" + ); + }); + //.AddJsonOptions(options => + //{ + // options.JsonSerializerOptions.PropertyNameCaseInsensitive = new DefaultContractResolver(); + //}); - options.OutputFormatters.Add(new Formatters.RawdataOutputFormatter()); - options.FormatterMappings.SetMediaTypeMappingForFormat("rawdata", "application/rawdata"); - }); - //.AddJsonOptions(options => - //{ - // options.JsonSerializerOptions.PropertyNameCaseInsensitive = new DefaultContractResolver(); - //}); - services.AddSwaggerGen(c => { - c.SwaggerDoc("v1", new OpenApiInfo { - Title = "OdhApi Tourism .Net Core", - Version = "v1", - Description = "ODH Tourism Api based on .Net Core with PostgreSQL", - TermsOfService = new System.Uri("https://opendatahub.readthedocs.io/en/latest/"), - Contact = new OpenApiContact + c.SwaggerDoc( + "v1", + new OpenApiInfo { - Name = "Open Data Hub Team", - Email = "help@opendatahub.bz.it", - Url = new System.Uri("https://opendatahub.bz.it/"), - }, - }); - c.MapType(() => new OpenApiSchema - { - Type = "boolean" - }); - c.MapType(() => new OpenApiSchema - { - Type = "integer" - }); + Title = "OdhApi Tourism .Net Core", + Version = "v1", + Description = "ODH Tourism Api based on .Net Core with PostgreSQL", + TermsOfService = new System.Uri( + "https://opendatahub.readthedocs.io/en/latest/" + ), + Contact = new OpenApiContact + { + Name = "Open Data Hub Team", + Email = "help@opendatahub.bz.it", + Url = new System.Uri("https://opendatahub.bz.it/"), + }, + } + ); + c.MapType(() => new OpenApiSchema { Type = "boolean" }); + c.MapType(() => new OpenApiSchema { Type = "integer" }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); //var xmlPathdatamodel = Path.Combine(AppContext.BaseDirectory, $"DataModel.xml"); c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true); //c.IncludeXmlComments(xmlPathdatamodel, includeControllerXmlComments: true); - c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - In = ParameterLocation.Header, - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + c.AddSecurityDefinition( + "oauth2", + new OpenApiSecurityScheme { - Password = new OpenApiOAuthFlow + In = ParameterLocation.Header, + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows { - TokenUrl = new Uri(Configuration.GetSection("OauthServerConfig").GetValue("Authority") + "protocol/openid-connect/token") + Password = new OpenApiOAuthFlow + { + TokenUrl = new Uri( + Configuration + .GetSection("OauthServerConfig") + .GetValue("Authority") + + "protocol/openid-connect/token" + ) + }, + ClientCredentials = new OpenApiOAuthFlow + { + TokenUrl = new Uri( + Configuration + .GetSection("OauthServerConfig") + .GetValue("Authority") + + "protocol/openid-connect/token" + ) + } }, - ClientCredentials = new OpenApiOAuthFlow - { - TokenUrl = new Uri(Configuration.GetSection("OauthServerConfig").GetValue("Authority") + "protocol/openid-connect/token") - } - }, - BearerFormat = "JWT", - Scheme = "Bearer" - }); + BearerFormat = "JWT", + Scheme = "Bearer" + } + ); c.SchemaFilter(); c.SchemaFilter(); - c.EnableAnnotations(); + c.EnableAnnotations(); //c.AddSecurityRequirement(new OpenApiSecurityRequirement //{ // { @@ -397,7 +437,7 @@ public void ConfigureServices(IServiceCollection services) services.Configure(options => { - options.ForwardedHeaders = ForwardedHeaders.XForwardedProto; + options.ForwardedHeaders = ForwardedHeaders.XForwardedProto; }); //services.AddHttpContextAccessor(); @@ -410,7 +450,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) //// TODO: Move to Production //app.UseClientRateLimiting(); //app.UseIpRateLimiting(); - + if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); @@ -423,14 +463,19 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) app.UseResponseCompression(); //app.UseHttpsRedirection(); - app.UseStaticFiles(new StaticFileOptions() - { - OnPrepareResponse = ctx => + app.UseStaticFiles( + new StaticFileOptions() { - ctx.Context.Response.Headers.Append("Access-Control-Allow-Origin", "*"); - ctx.Context.Response.Headers.Append("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - }, - }); + OnPrepareResponse = ctx => + { + ctx.Context.Response.Headers.Append("Access-Control-Allow-Origin", "*"); + ctx.Context.Response.Headers.Append( + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept" + ); + }, + } + ); app.UseRouting(); @@ -444,10 +489,15 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(c => { - c.PreSerializeFilters.Add((swagger, httpReq) => - { - swagger.Servers = new List { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}" } }; - }); + c.PreSerializeFilters.Add( + (swagger, httpReq) => + { + swagger.Servers = new List + { + new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}" } + }; + } + ); }); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint. @@ -470,7 +520,6 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) ////LOG EVERY REQUEST WITH HEADERs app.UseODHCustomHttpRequestConfig(Configuration); - //REWRITE, REDIRECT RULES //var rwoptions = new RewriteOptions() // .AddRedirect("api/(.*)", "v1/$1"); @@ -480,10 +529,9 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) //skipRemainingRules: true) app.UseRewriter( - new RewriteOptions() - .AddRedirect("api/(.*)", "v1/$1") - //.AddRewrite(@"^(?=/api)", "/v1", skipRemainingRules: true) - ); + new RewriteOptions().AddRedirect("api/(.*)", "v1/$1") + //.AddRewrite(@"^(?=/api)", "/v1", skipRemainingRules: true) + ); //Not needed at moment //app.UseHttpContext(); @@ -491,7 +539,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); - endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); + endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); } } diff --git a/OdhApiCore/Swagger/DeprecatedAttributeSchemaFilter.cs b/OdhApiCore/Swagger/DeprecatedAttributeSchemaFilter.cs index 25ebd9d2b..d2e7e4857 100644 --- a/OdhApiCore/Swagger/DeprecatedAttributeSchemaFilter.cs +++ b/OdhApiCore/Swagger/DeprecatedAttributeSchemaFilter.cs @@ -10,11 +10,15 @@ public class DeprecatedAttributeSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { - if ((context.ParameterInfo as ICustomAttributeProvider ?? context.MemberInfo) is { } info) + if ( + (context.ParameterInfo as ICustomAttributeProvider ?? context.MemberInfo) is + { } info + ) { - var deprecatedAttribute = info - .GetCustomAttributes(false) - .FirstOrDefault(attribute => attribute.GetType() == typeof(SwaggerDeprecatedAttribute)); + var deprecatedAttribute = info.GetCustomAttributes(false) + .FirstOrDefault( + attribute => attribute.GetType() == typeof(SwaggerDeprecatedAttribute) + ); if (deprecatedAttribute is SwaggerDeprecatedAttribute deprecated) { schema.Deprecated = true; diff --git a/OdhApiCore/Swagger/EnumAttributeSchemaFilter.cs b/OdhApiCore/Swagger/EnumAttributeSchemaFilter.cs index f434f9eb1..8c6807461 100644 --- a/OdhApiCore/Swagger/EnumAttributeSchemaFilter.cs +++ b/OdhApiCore/Swagger/EnumAttributeSchemaFilter.cs @@ -12,11 +12,15 @@ public class EnumAttributeSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { - if ((context.MemberInfo as ICustomAttributeProvider ?? context.ParameterInfo) is { } info) + if ( + (context.MemberInfo as ICustomAttributeProvider ?? context.ParameterInfo) is + { } info + ) { - var obsoleteMemberAttribute = info - .GetCustomAttributes(false) - .FirstOrDefault(attribute => attribute.GetType() == typeof(SwaggerEnumAttribute)); + var obsoleteMemberAttribute = info.GetCustomAttributes(false) + .FirstOrDefault( + attribute => attribute.GetType() == typeof(SwaggerEnumAttribute) + ); if (obsoleteMemberAttribute is SwaggerEnumAttribute obsoleteMember) { var enumValues = new List(); diff --git a/OdhApiCoreTests/Helper/FlagsHelperTests.cs b/OdhApiCoreTests/Helper/FlagsHelperTests.cs index 775753bbd..046bf971a 100644 --- a/OdhApiCoreTests/Helper/FlagsHelperTests.cs +++ b/OdhApiCoreTests/Helper/FlagsHelperTests.cs @@ -21,20 +21,26 @@ public void GetFlags_ValidEnum() public void GetFlags_InvalidEnumType() { var @enum = 12333; - Assert.Throws("withFlags", () => - { - var flags = @enum.GetFlags().ToList(); - }); + Assert.Throws( + "withFlags", + () => + { + var flags = @enum.GetFlags().ToList(); + } + ); } [Fact] public void GetFlags_InvalidNonFlaggedEnum() { var @enum = DayOfWeek.Monday; - Assert.Throws("withFlags", () => - { - var flags = @enum.GetFlags().ToList(); - }); + Assert.Throws( + "withFlags", + () => + { + var flags = @enum.GetFlags().ToList(); + } + ); } [Fact] @@ -47,13 +53,19 @@ public void SetFlags_Test() Assert.True(newenum.HasFlag(ActivityTypeBerg.Hochtouren)); // Functionally equivalent - Assert.Equal(@enum | ActivityTypeBerg.Hochtouren, @enum.SetFlags(ActivityTypeBerg.Hochtouren)); + Assert.Equal( + @enum | ActivityTypeBerg.Hochtouren, + @enum.SetFlags(ActivityTypeBerg.Hochtouren) + ); } [Fact] public void SetFlags_TestWithOnFalse() { - var @enum = ActivityTypeBerg.Bergtouren | ActivityTypeBerg.Schneeschuhtouren | ActivityTypeBerg.Hochtouren; + var @enum = + ActivityTypeBerg.Bergtouren + | ActivityTypeBerg.Schneeschuhtouren + | ActivityTypeBerg.Hochtouren; // Attention, not functionally equivalent! //Assert.Equal(@enum & ActivityTypeBerg.Bergtouren, @enum.SetFlags(ActivityTypeBerg.Bergtouren, false)); @@ -70,7 +82,10 @@ public void IsFlagSet_Test() { var @enum = ActivityTypeBerg.Bergtouren | ActivityTypeBerg.Schneeschuhtouren; // Functionally equivalent - Assert.Equal(@enum.HasFlag(ActivityTypeBerg.Alpinklettern), @enum.IsFlagSet(ActivityTypeBerg.Alpinklettern)); + Assert.Equal( + @enum.HasFlag(ActivityTypeBerg.Alpinklettern), + @enum.IsFlagSet(ActivityTypeBerg.Alpinklettern) + ); } } } diff --git a/OdhApiCoreTests/Helper/JsonTransformerTests.cs b/OdhApiCoreTests/Helper/JsonTransformerTests.cs index 120138d84..b9180c7e5 100644 --- a/OdhApiCoreTests/Helper/JsonTransformerTests.cs +++ b/OdhApiCoreTests/Helper/JsonTransformerTests.cs @@ -14,14 +14,16 @@ public class JsonTransformerTests [Fact] public void FilterByLanguageTest() { - var actual = @"{ + var actual = + @"{ ""languages"": { ""de"": ""hallo"", ""it"": ""ciao"", ""en"": ""hello"" } }"; - var expected = @"{ + var expected = + @"{ ""languages"": { ""de"": ""hallo"" } @@ -35,7 +37,8 @@ public void FilterByLanguageTest() [Fact] public void FilterImagesByCC0LicenseTest() { - var actual = @"[{ + var actual = + @"[{ ""License"": ""CC0"", ""Name"": ""Image1"" }, @@ -43,7 +46,8 @@ public void FilterImagesByCC0LicenseTest() ""License"": ""LTS"", ""Name"": ""Image2"" }]"; - var expected = @"[{ + var expected = + @"[{ ""License"": ""CC0"", ""Name"": ""Image1"" }]"; diff --git a/OdhApiCoreTests/Helper/PostgresSQLOrderByBuilderTests.cs b/OdhApiCoreTests/Helper/PostgresSQLOrderByBuilderTests.cs index 0440f8c6f..c7afb1733 100644 --- a/OdhApiCoreTests/Helper/PostgresSQLOrderByBuilderTests.cs +++ b/OdhApiCoreTests/Helper/PostgresSQLOrderByBuilderTests.cs @@ -32,7 +32,11 @@ public void BuildSeedOrderBy_WithInvalidSeed() string orderby = ""; string? invalidseed = "invalidnumber"; - PostgresSQLOrderByBuilder.BuildSeedOrderBy(ref orderby, ref invalidseed, "orderbyclause"); + PostgresSQLOrderByBuilder.BuildSeedOrderBy( + ref orderby, + ref invalidseed, + "orderbyclause" + ); // CHECK: Is this the correct behavior? Assert.Equal("md5(id || '')", orderby); } diff --git a/OdhApiCoreTests/Helper/PostgresSQLWhereBuilderTests.cs b/OdhApiCoreTests/Helper/PostgresSQLWhereBuilderTests.cs index daff8f06e..0792070e7 100644 --- a/OdhApiCoreTests/Helper/PostgresSQLWhereBuilderTests.cs +++ b/OdhApiCoreTests/Helper/PostgresSQLWhereBuilderTests.cs @@ -14,127 +14,133 @@ public class PostgresSQLWhereBuilderTests [Fact] public void CreateActivityWhereExpression_LoggedUser() { - var query = - new Query() - .From("activities") - .ActivityWhereExpression( - idlist: System.Array.Empty(), - activitytypelist: System.Array.Empty(), - subtypelist: System.Array.Empty(), - difficultylist: System.Array.Empty(), - smgtaglist: System.Array.Empty(), - districtlist: System.Array.Empty(), - municipalitylist: System.Array.Empty(), - tourismvereinlist: System.Array.Empty(), - regionlist: System.Array.Empty(), - arealist: System.Array.Empty(), - distance: false, - distancemin: 0, - distancemax: 0, - duration: false, - durationmin: 0, - durationmax: 0, - altitude: false, - altitudemin: 0, - altitudemax: 0, - highlight: null, - activefilter: null, - smgactivefilter: null, - searchfilter: null, - language: null, - lastchange: null, - languagelist: System.Array.Empty(), - filterClosedData: false, - reducedData: true - ); + var query = new Query() + .From("activities") + .ActivityWhereExpression( + idlist: System.Array.Empty(), + activitytypelist: System.Array.Empty(), + subtypelist: System.Array.Empty(), + difficultylist: System.Array.Empty(), + smgtaglist: System.Array.Empty(), + districtlist: System.Array.Empty(), + municipalitylist: System.Array.Empty(), + tourismvereinlist: System.Array.Empty(), + regionlist: System.Array.Empty(), + arealist: System.Array.Empty(), + distance: false, + distancemin: 0, + distancemax: 0, + duration: false, + durationmin: 0, + durationmax: 0, + altitude: false, + altitudemin: 0, + altitudemax: 0, + highlight: null, + activefilter: null, + smgactivefilter: null, + searchfilter: null, + language: null, + lastchange: null, + languagelist: System.Array.Empty(), + filterClosedData: false, + reducedData: true + ); var result = compiler.Compile(query); - Assert.Equal("SELECT * FROM \"activities\" WHERE ((gen_source <> 'lts') OR (gen_source = 'lts' AND gen_reduced = $$))", result.RawSql); + Assert.Equal( + "SELECT * FROM \"activities\" WHERE ((gen_source <> 'lts') OR (gen_source = 'lts' AND gen_reduced = $$))", + result.RawSql + ); } [Fact] public void CreateActivityWhereExpression_Anonymous() { - var query = - new Query() - .From("activities") - .ActivityWhereExpression( - idlist: System.Array.Empty(), - activitytypelist: System.Array.Empty(), - subtypelist: System.Array.Empty(), - difficultylist: System.Array.Empty(), - smgtaglist: System.Array.Empty(), - districtlist: System.Array.Empty(), - municipalitylist: System.Array.Empty(), - tourismvereinlist: System.Array.Empty(), - regionlist: System.Array.Empty(), - arealist: System.Array.Empty(), - distance: false, - distancemin: 0, - distancemax: 0, - duration: false, - durationmin: 0, - durationmax: 0, - altitude: false, - altitudemin: 0, - altitudemax: 0, - highlight: null, - activefilter: null, - smgactivefilter: null, - searchfilter: null, - language: null, - lastchange: null, - languagelist: System.Array.Empty(), - filterClosedData: true, - reducedData: true - ); + var query = new Query() + .From("activities") + .ActivityWhereExpression( + idlist: System.Array.Empty(), + activitytypelist: System.Array.Empty(), + subtypelist: System.Array.Empty(), + difficultylist: System.Array.Empty(), + smgtaglist: System.Array.Empty(), + districtlist: System.Array.Empty(), + municipalitylist: System.Array.Empty(), + tourismvereinlist: System.Array.Empty(), + regionlist: System.Array.Empty(), + arealist: System.Array.Empty(), + distance: false, + distancemin: 0, + distancemax: 0, + duration: false, + durationmin: 0, + durationmax: 0, + altitude: false, + altitudemin: 0, + altitudemax: 0, + highlight: null, + activefilter: null, + smgactivefilter: null, + searchfilter: null, + language: null, + lastchange: null, + languagelist: System.Array.Empty(), + filterClosedData: true, + reducedData: true + ); var result = compiler.Compile(query); - Assert.Equal("SELECT * FROM \"activities\" WHERE ((gen_source <> 'lts' AND (gen_licenseinfo_closeddata IS NULL OR gen_licenseinfo_closeddata = $$)) OR (gen_source = 'lts' AND gen_reduced = true AND ((gen_licenseinfo_closeddata IS NULL OR gen_licenseinfo_closeddata = $$))))", result.RawSql); + Assert.Equal( + "SELECT * FROM \"activities\" WHERE ((gen_source <> 'lts' AND (gen_licenseinfo_closeddata IS NULL OR gen_licenseinfo_closeddata = $$)) OR (gen_source = 'lts' AND gen_reduced = true AND ((gen_licenseinfo_closeddata IS NULL OR gen_licenseinfo_closeddata = $$))))", + result.RawSql + ); } [Fact] public void CreateActivityWhereExpression_IDMUser() { - var query = - new Query() - .From("activities") - .ActivityWhereExpression( - idlist: System.Array.Empty(), - activitytypelist: System.Array.Empty(), - subtypelist: System.Array.Empty(), - difficultylist: System.Array.Empty(), - smgtaglist: System.Array.Empty(), - districtlist: System.Array.Empty(), - municipalitylist: System.Array.Empty(), - tourismvereinlist: System.Array.Empty(), - regionlist: System.Array.Empty(), - arealist: System.Array.Empty(), - distance: false, - distancemin: 0, - distancemax: 0, - duration: false, - durationmin: 0, - durationmax: 0, - altitude: false, - altitudemin: 0, - altitudemax: 0, - highlight: null, - activefilter: null, - smgactivefilter: null, - searchfilter: null, - language: null, - lastchange: null, - languagelist: System.Array.Empty(), - filterClosedData: false, - reducedData: false - ); + var query = new Query() + .From("activities") + .ActivityWhereExpression( + idlist: System.Array.Empty(), + activitytypelist: System.Array.Empty(), + subtypelist: System.Array.Empty(), + difficultylist: System.Array.Empty(), + smgtaglist: System.Array.Empty(), + districtlist: System.Array.Empty(), + municipalitylist: System.Array.Empty(), + tourismvereinlist: System.Array.Empty(), + regionlist: System.Array.Empty(), + arealist: System.Array.Empty(), + distance: false, + distancemin: 0, + distancemax: 0, + duration: false, + durationmin: 0, + durationmax: 0, + altitude: false, + altitudemin: 0, + altitudemax: 0, + highlight: null, + activefilter: null, + smgactivefilter: null, + searchfilter: null, + language: null, + lastchange: null, + languagelist: System.Array.Empty(), + filterClosedData: false, + reducedData: false + ); var result = compiler.Compile(query); - Assert.Equal("SELECT * FROM \"activities\" WHERE ((gen_source <> 'lts') OR (gen_source = 'lts' AND gen_reduced = $$))", result.RawSql); + Assert.Equal( + "SELECT * FROM \"activities\" WHERE ((gen_source <> 'lts') OR (gen_source = 'lts' AND gen_reduced = $$))", + result.RawSql + ); } } } diff --git a/OdhApiCoreTests/Helper/SmgTagTransformerTests.cs b/OdhApiCoreTests/Helper/SmgTagTransformerTests.cs index 6ef95d74e..b6061d5ad 100644 --- a/OdhApiCoreTests/Helper/SmgTagTransformerTests.cs +++ b/OdhApiCoreTests/Helper/SmgTagTransformerTests.cs @@ -11,10 +11,7 @@ public class SmgTagTransformerTests { public static TheoryData GetLanguages() { - return new TheoryData - { - "de", "it", "en", "ru" - }; + return new TheoryData { "de", "it", "en", "ru" }; } [Theory] @@ -23,7 +20,9 @@ public void TransformToLocalizedSmgTag_EmptySmgTags(string language) { var smgtagslist = Enumerable.Empty(); IEnumerable result = SmgTagTransformer.TransformToLocalizedSmgTag( - smgtagslist, language); + smgtagslist, + language + ); Assert.NotNull(result); Assert.Empty(result); } @@ -43,12 +42,11 @@ public void TransformToLocalizedSmgTag_SingleSmgTag(string language) }, ValidForEntity = Array.Empty() }; - var smgtagslist = new SmgTags[] - { - expectedSmgTag - }; + var smgtagslist = new SmgTags[] { expectedSmgTag }; IEnumerable result = SmgTagTransformer.TransformToLocalizedSmgTag( - smgtagslist, language); + smgtagslist, + language + ); Assert.NotNull(result); var smgtag = Assert.Single(result); Assert.Equal(expectedSmgTag.Id, smgtag.Id); diff --git a/OdhApiCoreTests/IntegrationTests/ActivityApiControllerTests.cs b/OdhApiCoreTests/IntegrationTests/ActivityApiControllerTests.cs index 21b18700a..a98b6cc04 100644 --- a/OdhApiCoreTests/IntegrationTests/ActivityApiControllerTests.cs +++ b/OdhApiCoreTests/IntegrationTests/ActivityApiControllerTests.cs @@ -12,7 +12,8 @@ namespace OdhApiCoreTests.IntegrationTets { [Trait("Category", "Integration")] - public class ActivityApiControllerTests : IClassFixture> + public class ActivityApiControllerTests + : IClassFixture> { private readonly HttpClient _client; private readonly CustomWebApplicationFactory _factory; @@ -20,10 +21,9 @@ public class ActivityApiControllerTests : IClassFixture factory) { _factory = factory; - _client = factory.CreateClient(new WebApplicationFactoryClientOptions - { - AllowAutoRedirect = false - }); + _client = factory.CreateClient( + new WebApplicationFactoryClientOptions { AllowAutoRedirect = false } + ); } [Theory] @@ -34,15 +34,21 @@ public ActivityApiControllerTests(CustomWebApplicationFactory(json); Assert.NotEmpty(data); diff --git a/OdhApiCoreTests/IntegrationTests/CustomWebApplicationFactory.cs b/OdhApiCoreTests/IntegrationTests/CustomWebApplicationFactory.cs index d844ba0f0..ab0779f99 100644 --- a/OdhApiCoreTests/IntegrationTests/CustomWebApplicationFactory.cs +++ b/OdhApiCoreTests/IntegrationTests/CustomWebApplicationFactory.cs @@ -17,15 +17,14 @@ JValue value when (value.Value == null) => default!, }; } - public class CustomWebApplicationFactory : WebApplicationFactory where TStartup : class + public class CustomWebApplicationFactory : WebApplicationFactory + where TStartup : class { protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { - var sp = services - .AddRouting() - .BuildServiceProvider(); + var sp = services.AddRouting().BuildServiceProvider(); //using (var scope = sp.CreateScope()) //{ diff --git a/OdhApiCoreTests/IntegrationTests/FilterTests.cs b/OdhApiCoreTests/IntegrationTests/FilterTests.cs index 317ae5133..ccd33fa75 100644 --- a/OdhApiCoreTests/IntegrationTests/FilterTests.cs +++ b/OdhApiCoreTests/IntegrationTests/FilterTests.cs @@ -13,7 +13,6 @@ namespace OdhApiCoreTests.IntegrationTests { [Trait("Category", "Integration")] public class FilterTests : IClassFixture> - { private readonly HttpClient _client; private readonly CustomWebApplicationFactory _factory; @@ -21,20 +20,22 @@ public class FilterTests : IClassFixture factory) { _factory = factory; - _client = factory.CreateClient(new WebApplicationFactoryClientOptions - { - AllowAutoRedirect = false - }); + _client = factory.CreateClient( + new WebApplicationFactoryClientOptions { AllowAutoRedirect = false } + ); } [Fact] public async Task TestFields() { - var url = "/v1/Accommodation?pagesize=20&pagenumber=1&fields=AccoDetail.de.Name,Features[*].Name,HgvId,Test"; + var url = + "/v1/Accommodation?pagesize=20&pagenumber=1&fields=AccoDetail.de.Name,Features[*].Name,HgvId,Test"; var response = await _client.GetAsync(url); response.EnsureSuccessStatusCode(); - Assert.Equal("application/json; charset=utf-8", - response.Content.Headers.ContentType?.ToString()); + Assert.Equal( + "application/json; charset=utf-8", + response.Content.Headers.ContentType?.ToString() + ); string json = await response.Content.ReadAsStringAsync(); dynamic? data = JsonConvert.DeserializeObject(json); Assert.NotNull(data); diff --git a/OdhApiCoreTests/IntegrationTests/PoiApiControllerTests.cs b/OdhApiCoreTests/IntegrationTests/PoiApiControllerTests.cs index cc4713361..1a62ecec2 100644 --- a/OdhApiCoreTests/IntegrationTests/PoiApiControllerTests.cs +++ b/OdhApiCoreTests/IntegrationTests/PoiApiControllerTests.cs @@ -12,7 +12,8 @@ namespace OdhApiCoreTests.IntegrationTets { [Trait("Category", "Integration")] - public class PoiApiControllerTests : IClassFixture> + public class PoiApiControllerTests + : IClassFixture> { private readonly HttpClient _client; private readonly CustomWebApplicationFactory _factory; @@ -20,10 +21,9 @@ public class PoiApiControllerTests : IClassFixture factory) { _factory = factory; - _client = factory.CreateClient(new WebApplicationFactoryClientOptions - { - AllowAutoRedirect = false - }); + _client = factory.CreateClient( + new WebApplicationFactoryClientOptions { AllowAutoRedirect = false } + ); } [Theory] @@ -32,17 +32,23 @@ public PoiApiControllerTests(CustomWebApplicationFactory fac [InlineData("/v1/Poi?poitype=12")] [InlineData("/v1/Poi?language=de")] [InlineData("/v1/Poi?language=en")] - [InlineData("/v1/Poi?pagenumber=1&pagesize=100&poitype=511&locfilter=tvs522822F751CA11D18F1400A02427D15E&active=true&seed=null")] + [InlineData( + "/v1/Poi?pagenumber=1&pagesize=100&poitype=511&locfilter=tvs522822F751CA11D18F1400A02427D15E&active=true&seed=null" + )] //[InlineData("/v1/Poi?pagenumber=1&pagesize=100&poitype=511&areafilter=tvs522822F751CA11D18F1400A02427D15E&active=true&seed=null")] //[InlineData("/v1/Poi?pagenumber=1&pagesize=10&poitype=11&locfilter=tvs5228229651CA11D18F1400A02427D15E&odhactive=true&active=true&seed=null")] [InlineData("/v1/Poi?pagenumber=1&pagesize=10&poitype=511&seed=null")] - [InlineData("/v1/Poi?pagenumber=1&pagesize=20&poitype=Sport%20und%20Freizeit&subtype=null&idlist=null&locfilter=null&areafilter=null&highlight=null&active=null&odhactive=null&odhtagfilter=null&seed=null")] + [InlineData( + "/v1/Poi?pagenumber=1&pagesize=20&poitype=Sport%20und%20Freizeit&subtype=null&idlist=null&locfilter=null&areafilter=null&highlight=null&active=null&odhactive=null&odhtagfilter=null&seed=null" + )] public async Task Get_Pois(string url) { var response = await _client.GetAsync(url); response.EnsureSuccessStatusCode(); - Assert.Equal("application/json; charset=utf-8", - response.Content.Headers.ContentType?.ToString()); + Assert.Equal( + "application/json; charset=utf-8", + response.Content.Headers.ContentType?.ToString() + ); string json = await response.Content.ReadAsStringAsync(); dynamic? data = JsonConvert.DeserializeObject(json); Assert.NotNull(data); @@ -69,8 +75,10 @@ public async Task Get_SinglePoi(string url) { var response = await _client.GetAsync(url); response.EnsureSuccessStatusCode(); - Assert.Equal("application/json; charset=utf-8", - response.Content.Headers.ContentType?.ToString()); + Assert.Equal( + "application/json; charset=utf-8", + response.Content.Headers.ContentType?.ToString() + ); string json = await response.Content.ReadAsStringAsync(); dynamic? data = JsonConvert.DeserializeObject(json); Assert.NotNull(data); @@ -110,8 +118,10 @@ public async Task Get_PoiTypes() { var response = await _client.GetAsync("/v1/PoiTypes"); response.EnsureSuccessStatusCode(); - Assert.Equal("application/json; charset=utf-8", - response.Content.Headers.ContentType?.ToString()); + Assert.Equal( + "application/json; charset=utf-8", + response.Content.Headers.ContentType?.ToString() + ); string json = await response.Content.ReadAsStringAsync(); dynamic? data = JsonConvert.DeserializeObject(json); Assert.NotEmpty(data); diff --git a/OdhApiImporter/Controllers/DataModifyApiController.cs b/OdhApiImporter/Controllers/DataModifyApiController.cs index 0a93440fa..116527df8 100644 --- a/OdhApiImporter/Controllers/DataModifyApiController.cs +++ b/OdhApiImporter/Controllers/DataModifyApiController.cs @@ -31,7 +31,12 @@ public class DataModifyApiController : Controller private readonly ILogger logger; private readonly IWebHostEnvironment env; - public DataModifyApiController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) + public DataModifyApiController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) { this.env = env; this.settings = settings; @@ -44,43 +49,53 @@ public DataModifyApiController(IWebHostEnvironment env, ISettings settings, ILog [HttpGet, Route("ModifyEventShort")] public async Task ModifyEventShort(CancellationToken cancellationToken) { - CustomDataOperation customdataoperation = new CustomDataOperation(settings, QueryFactory); + CustomDataOperation customdataoperation = new CustomDataOperation( + settings, + QueryFactory + ); var objectscount = await customdataoperation.UpdateAllEventShortstonewDataModel(); - return Ok(new UpdateResult - { - operation = "Modify EventShort", - updatetype = "custom", - otherinfo = "", - message = "Done", - recordsmodified = objectscount, - created = 0, - deleted = 0, - id = "", - updated = objectscount, - success = true - }); + return Ok( + new UpdateResult + { + operation = "Modify EventShort", + updatetype = "custom", + otherinfo = "", + message = "Done", + recordsmodified = objectscount, + created = 0, + deleted = 0, + id = "", + updated = objectscount, + success = true + } + ); } [HttpGet, Route("ModifySTAVendingpoint")] public async Task ModifySTAVendingpoint(CancellationToken cancellationToken) { - CustomDataOperation customdataoperation = new CustomDataOperation(settings, QueryFactory); + CustomDataOperation customdataoperation = new CustomDataOperation( + settings, + QueryFactory + ); var objectscount = await customdataoperation.UpdateAllSTAVendingpoints(); - return Ok(new UpdateResult - { - operation = "Modify STA Vendingpoint", - updatetype = "custom", - otherinfo = "", - message = "Done", - recordsmodified = objectscount, - created = 0, - deleted = 0, - id = "", - updated = objectscount, - success = true - }); + return Ok( + new UpdateResult + { + operation = "Modify STA Vendingpoint", + updatetype = "custom", + otherinfo = "", + message = "Done", + recordsmodified = objectscount, + created = 0, + deleted = 0, + id = "", + updated = objectscount, + success = true + } + ); } #endregion @@ -90,26 +105,29 @@ public async Task ModifySTAVendingpoint(CancellationToken cancell [HttpGet, Route("FillDummyNews")] public async Task FillDBWithDummynews(CancellationToken cancellationToken) { - CustomDataOperation customdataoperation = new CustomDataOperation(settings, QueryFactory); + CustomDataOperation customdataoperation = new CustomDataOperation( + settings, + QueryFactory + ); var objectscount = await customdataoperation.FillDBWithDummyNews(); - return Ok(new UpdateResult - { - operation = "Modify Articles", - updatetype = "custom", - otherinfo = "", - message = "Done", - recordsmodified = objectscount, - created = 0, - deleted = 0, - id = "", - updated = objectscount, - success = true - }); + return Ok( + new UpdateResult + { + operation = "Modify Articles", + updatetype = "custom", + otherinfo = "", + message = "Done", + recordsmodified = objectscount, + created = 0, + deleted = 0, + id = "", + updated = objectscount, + success = true + } + ); } #endregion - - } } diff --git a/OdhApiImporter/Controllers/JsonGeneratorController.cs b/OdhApiImporter/Controllers/JsonGeneratorController.cs index 69159cebe..44968bf19 100644 --- a/OdhApiImporter/Controllers/JsonGeneratorController.cs +++ b/OdhApiImporter/Controllers/JsonGeneratorController.cs @@ -18,7 +18,12 @@ public class JsonGeneratorController : Controller private readonly ILogger logger; private readonly IWebHostEnvironment env; - public JsonGeneratorController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) + public JsonGeneratorController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) { this.env = env; this.settings = settings; @@ -33,25 +38,33 @@ public async Task ProduceTagJson(CancellationToken cancellationTo { try { - await JsonGeneratorHelper.GenerateJSONTaglist(QueryFactory, settings.JsonConfig.Jsondir, "GenericTags"); + await JsonGeneratorHelper.GenerateJSONTaglist( + QueryFactory, + settings.JsonConfig.Jsondir, + "GenericTags" + ); - return Ok(new - { - operation = "Json Generation", - type = "Taglist", - message = "Generate Json Taglist succeeded", - success = true - }); + return Ok( + new + { + operation = "Json Generation", + type = "Taglist", + message = "Generate Json Taglist succeeded", + success = true + } + ); } catch (Exception ex) { - return BadRequest(new - { - operation = "Json Generation", - type = "Taglist", - message = "Generate Json Taglist failed error: " + ex.Message, - success = false - }); + return BadRequest( + new + { + operation = "Json Generation", + type = "Taglist", + message = "Generate Json Taglist failed error: " + ex.Message, + success = false + } + ); } } diff --git a/OdhApiImporter/Controllers/TestController.cs b/OdhApiImporter/Controllers/TestController.cs index 4aab78aaf..15c3caa14 100644 --- a/OdhApiImporter/Controllers/TestController.cs +++ b/OdhApiImporter/Controllers/TestController.cs @@ -9,7 +9,6 @@ public class TestController : Controller [HttpGet, Route("Test")] public IActionResult Get() { - return Ok("importer alive"); } } diff --git a/OdhApiImporter/Controllers/UpdateApiController.cs b/OdhApiImporter/Controllers/UpdateApiController.cs index 20d66fec3..9a3e1ba02 100644 --- a/OdhApiImporter/Controllers/UpdateApiController.cs +++ b/OdhApiImporter/Controllers/UpdateApiController.cs @@ -26,7 +26,7 @@ namespace OdhApiImporter.Controllers { - [ApiExplorerSettings(IgnoreApi = true)] + [ApiExplorerSettings(IgnoreApi = true)] [ApiController] public class UpdateApiController : Controller { @@ -35,19 +35,28 @@ public class UpdateApiController : Controller private readonly ILogger logger; private readonly IWebHostEnvironment env; - public UpdateApiController(IWebHostEnvironment env, ISettings settings, ILogger logger, QueryFactory queryFactory) + public UpdateApiController( + IWebHostEnvironment env, + ISettings settings, + ILogger logger, + QueryFactory queryFactory + ) { this.env = env; this.settings = settings; this.logger = logger; this.QueryFactory = queryFactory; - } + } #region UPDATE FROM RAVEN INSTANCE [HttpGet, Route("Raven/{datatype}/Update/{id}")] //[Authorize(Roles = "DataWriter,DataCreate,DataUpdate")] - public async Task UpdateFromRaven(string id, string datatype, CancellationToken cancellationToken = default) + public async Task UpdateFromRaven( + string id, + string datatype, + CancellationToken cancellationToken = default + ) { UpdateDetail updatedetail = default(UpdateDetail); string operation = "Update Raven"; @@ -58,16 +67,39 @@ public async Task UpdateFromRaven(string id, string datatype, Can try { RAVENImportHelper ravenimporthelper = new RAVENImportHelper(settings, QueryFactory); - var resulttuple = await ravenimporthelper.GetFromRavenAndTransformToPGObject(id, datatype, cancellationToken); + var resulttuple = await ravenimporthelper.GetFromRavenAndTransformToPGObject( + id, + datatype, + cancellationToken + ); updatedetail = resulttuple.Item2; - var updateResult = GenericResultsHelper.GetSuccessUpdateResult(resulttuple.Item1, source, operation, updatetype, "Update Raven succeeded", otherinfo, updatedetail, true); + var updateResult = GenericResultsHelper.GetSuccessUpdateResult( + resulttuple.Item1, + source, + operation, + updatetype, + "Update Raven succeeded", + otherinfo, + updatedetail, + true + ); return Ok(updateResult); } catch (Exception ex) { - var errorResult = GenericResultsHelper.GetErrorUpdateResult(id, source, operation, updatetype, "Update Raven failed", otherinfo, updatedetail, ex, true); + var errorResult = GenericResultsHelper.GetErrorUpdateResult( + id, + source, + operation, + updatetype, + "Update Raven failed", + otherinfo, + updatedetail, + ex, + true + ); return BadRequest(errorResult); } @@ -78,7 +110,9 @@ public async Task UpdateFromRaven(string id, string datatype, Can #region EBMS DATA SYNC (EventShort) [HttpGet, Route("EBMS/EventShort/UpdateAll")] - public async Task UpdateAllEBMS(CancellationToken cancellationToken = default) + public async Task UpdateAllEBMS( + CancellationToken cancellationToken = default + ) { UpdateDetail updatedetail = default(UpdateDetail); string operation = "Update EBMS"; @@ -87,27 +121,56 @@ public async Task UpdateAllEBMS(CancellationToken cancellationTok try { - EBMSImportHelper ebmsimporthelper = new EBMSImportHelper(settings, QueryFactory, "eventeuracnoi"); + EBMSImportHelper ebmsimporthelper = new EBMSImportHelper( + settings, + QueryFactory, + "eventeuracnoi" + ); updatedetail = await ebmsimporthelper.SaveDataToODH(null, cancellationToken); - var updateResult = GenericResultsHelper.GetSuccessUpdateResult(null, source, operation, updatetype, "EBMS Eventshorts update succeeded", "", updatedetail, true); + var updateResult = GenericResultsHelper.GetSuccessUpdateResult( + null, + source, + operation, + updatetype, + "EBMS Eventshorts update succeeded", + "", + updatedetail, + true + ); return Ok(updateResult); } - catch(Exception ex) + catch (Exception ex) { - var updateResult = GenericResultsHelper.GetErrorUpdateResult(null, source, operation, updatetype, "EBMS Eventshorts update failed", "", updatedetail, ex, true); + var updateResult = GenericResultsHelper.GetErrorUpdateResult( + null, + source, + operation, + updatetype, + "EBMS Eventshorts update failed", + "", + updatedetail, + ex, + true + ); return BadRequest(updateResult); } } [HttpGet, Route("EBMS/EventShort/UpdateSingle/{id}")] - public IActionResult UpdateSingleEBMS(string id, CancellationToken cancellationToken = default) + public IActionResult UpdateSingleEBMS( + string id, + CancellationToken cancellationToken = default + ) { - return StatusCode(StatusCodes.Status501NotImplemented, new { error = "Not Implemented" }); + return StatusCode( + StatusCodes.Status501NotImplemented, + new { error = "Not Implemented" } + ); //try - //{ + //{ // return Ok(new UpdateResult // { // operation = "Update EBMS", @@ -144,7 +207,9 @@ public IActionResult UpdateSingleEBMS(string id, CancellationToken cancellationT #region NINJA DATA SYNC (Events Centro Trevi and DRIN) [HttpGet, Route("NINJA/Events/UpdateAll")] - public async Task UpdateAllNinjaEvents(CancellationToken cancellationToken = default) + public async Task UpdateAllNinjaEvents( + CancellationToken cancellationToken = default + ) { UpdateDetail updatedetail = default(UpdateDetail); string operation = "Update Ninja Events"; @@ -152,32 +217,59 @@ public async Task UpdateAllNinjaEvents(CancellationToken cancella string source = "mobilityapi"; try - { + { NINJAImportHelper ninjaimporthelper = new NINJAImportHelper(settings, QueryFactory); updatedetail = await ninjaimporthelper.SaveDataToODH(null, cancellationToken); - var updateResult = GenericResultsHelper.GetSuccessUpdateResult(null, source, operation, updatetype, "Ninja Events update succeeded", "", updatedetail, true); + var updateResult = GenericResultsHelper.GetSuccessUpdateResult( + null, + source, + operation, + updatetype, + "Ninja Events update succeeded", + "", + updatedetail, + true + ); return Ok(updateResult); } catch (Exception ex) { - var errorResult = GenericResultsHelper.GetErrorUpdateResult(null, source, operation, updatetype, "Ninja Events update failed", "", updatedetail, ex, true); + var errorResult = GenericResultsHelper.GetErrorUpdateResult( + null, + source, + operation, + updatetype, + "Ninja Events update failed", + "", + updatedetail, + ex, + true + ); return BadRequest(errorResult); } } [HttpGet, Route("NINJA/Events/UpdateSingle/{id}")] - public IActionResult UpdateSingleNinjaEvents(string id, CancellationToken cancellationToken = default) - { - return StatusCode(StatusCodes.Status501NotImplemented, new { error = "Not Implemented" }); + public IActionResult UpdateSingleNinjaEvents( + string id, + CancellationToken cancellationToken = default + ) + { + return StatusCode( + StatusCodes.Status501NotImplemented, + new { error = "Not Implemented" } + ); } - #endregion + #endregion - #region SIAG DATA SYNC WEATHER + #region SIAG DATA SYNC WEATHER [HttpGet, Route("Siag/Weather/Import")] - public async Task ImportWeather(CancellationToken cancellationToken = default) + public async Task ImportWeather( + CancellationToken cancellationToken = default + ) { UpdateDetail updatedetail = default(UpdateDetail); string operation = "Import Weather data"; @@ -186,21 +278,47 @@ public async Task ImportWeather(CancellationToken cancellationTok try { - SIAGImportHelper siagimporthelper = new SIAGImportHelper(settings, QueryFactory, "weatherdatahistory"); + SIAGImportHelper siagimporthelper = new SIAGImportHelper( + settings, + QueryFactory, + "weatherdatahistory" + ); updatedetail = await siagimporthelper.SaveWeatherToHistoryTable(cancellationToken); - var updateResult = GenericResultsHelper.GetSuccessUpdateResult(null, source, operation, updatetype, "Import Weather data succeeded", "actual", updatedetail, true); + var updateResult = GenericResultsHelper.GetSuccessUpdateResult( + null, + source, + operation, + updatetype, + "Import Weather data succeeded", + "actual", + updatedetail, + true + ); - return Ok(updateResult); + return Ok(updateResult); } catch (Exception ex) { - var errorResult = GenericResultsHelper.GetErrorUpdateResult(null, source, operation, updatetype, "Import Weather data failed", "actual", updatedetail, ex, true); - return BadRequest(errorResult); + var errorResult = GenericResultsHelper.GetErrorUpdateResult( + null, + source, + operation, + updatetype, + "Import Weather data failed", + "actual", + updatedetail, + ex, + true + ); + return BadRequest(errorResult); } } [HttpGet, Route("Siag/Weather/Import/{id}")] - public async Task ImportWeatherByID(string id, CancellationToken cancellationToken = default) + public async Task ImportWeatherByID( + string id, + CancellationToken cancellationToken = default + ) { UpdateDetail updatedetail = default(UpdateDetail); string operation = "Import Weather data"; @@ -209,15 +327,41 @@ public async Task ImportWeatherByID(string id, CancellationToken try { - SIAGImportHelper siagimporthelper = new SIAGImportHelper(settings, QueryFactory, "weatherdatahistory"); - updatedetail = await siagimporthelper.SaveWeatherToHistoryTable(cancellationToken, id); - var updateResult = GenericResultsHelper.GetSuccessUpdateResult(id, source, operation, updatetype, "Import Weather data succeeded id:" + id.ToString(), "byid", updatedetail, true); + SIAGImportHelper siagimporthelper = new SIAGImportHelper( + settings, + QueryFactory, + "weatherdatahistory" + ); + updatedetail = await siagimporthelper.SaveWeatherToHistoryTable( + cancellationToken, + id + ); + var updateResult = GenericResultsHelper.GetSuccessUpdateResult( + id, + source, + operation, + updatetype, + "Import Weather data succeeded id:" + id.ToString(), + "byid", + updatedetail, + true + ); - return Ok(updateResult); + return Ok(updateResult); } catch (Exception ex) { - var updateResult = GenericResultsHelper.GetErrorUpdateResult(null, source, operation, updatetype, "Import Weather data failed id:" + id.ToString(), "byid", updatedetail, ex, true); + var updateResult = GenericResultsHelper.GetErrorUpdateResult( + null, + source, + operation, + updatetype, + "Import Weather data failed id:" + id.ToString(), + "byid", + updatedetail, + ex, + true + ); return BadRequest(updateResult); } } @@ -236,17 +380,40 @@ public async Task ImportMuseum(CancellationToken cancellationToke try { - SIAGImportHelper siagimporthelper = new SIAGImportHelper(settings, QueryFactory, "smgpois"); + SIAGImportHelper siagimporthelper = new SIAGImportHelper( + settings, + QueryFactory, + "smgpois" + ); updatedetail = await siagimporthelper.SaveDataToODH(null, cancellationToken); - var updateResult = GenericResultsHelper.GetSuccessUpdateResult(null, source, operation, updatetype, "Import SIAG Museum data succeeded", "actual", updatedetail, true); + var updateResult = GenericResultsHelper.GetSuccessUpdateResult( + null, + source, + operation, + updatetype, + "Import SIAG Museum data succeeded", + "actual", + updatedetail, + true + ); return Ok(updateResult); } catch (Exception ex) { - var updateResult = GenericResultsHelper.GetErrorUpdateResult(null, source, operation, updatetype, "Import SIAG Museum data failed", "actual", updatedetail, ex, true); - return BadRequest(updateResult); + var updateResult = GenericResultsHelper.GetErrorUpdateResult( + null, + source, + operation, + updatetype, + "Import SIAG Museum data failed", + "actual", + updatedetail, + ex, + true + ); + return BadRequest(updateResult); } } @@ -292,7 +459,9 @@ public async Task ImportMuseum(CancellationToken cancellationToke //[Authorize(Roles = "DataWriter,STAPoiImport")] [HttpPost, Route("STA/VendingPoints/UpdateAll")] - public async Task SendVendingPointsFromSTA(CancellationToken cancellationToken) + public async Task SendVendingPointsFromSTA( + CancellationToken cancellationToken + ) { UpdateDetail updatedetail = default(UpdateDetail); string operation = "Import Vendingpoints"; @@ -304,15 +473,37 @@ public async Task SendVendingPointsFromSTA(CancellationToken canc { STAImportHelper staimporthelper = new STAImportHelper(settings, QueryFactory); - updatedetail = await staimporthelper.PostVendingPointsFromSTA(Request, cancellationToken); - - var updateResult = GenericResultsHelper.GetSuccessUpdateResult("", source, operation, updatetype, "Import Vendingpoints succeeded", otherinfo, updatedetail, true); + updatedetail = await staimporthelper.PostVendingPointsFromSTA( + Request, + cancellationToken + ); + + var updateResult = GenericResultsHelper.GetSuccessUpdateResult( + "", + source, + operation, + updatetype, + "Import Vendingpoints succeeded", + otherinfo, + updatedetail, + true + ); return Ok(updateResult); } catch (Exception ex) { - var errorResult = GenericResultsHelper.GetErrorUpdateResult("", source, operation, updatetype, "Import Vendingpoints failed", otherinfo, updatedetail, ex, true); + var errorResult = GenericResultsHelper.GetErrorUpdateResult( + "", + source, + operation, + updatetype, + "Import Vendingpoints failed", + otherinfo, + updatedetail, + ex, + true + ); return BadRequest(errorResult); } @@ -323,39 +514,72 @@ public async Task SendVendingPointsFromSTA(CancellationToken canc #region DSS DATA SYNC [HttpGet, Route("DSS/{dssentity}/UpdateAll")] - public async Task UpdateAllDSSLifts(string dssentity, CancellationToken cancellationToken = default) + public async Task UpdateAllDSSLifts( + string dssentity, + CancellationToken cancellationToken = default + ) { UpdateDetail updatedetail = default(UpdateDetail); string operation = "Update DSS " + dssentity; string updatetype = "all"; - string source = "dss"; + string source = "dss"; try { - DSSImportHelper dssimporthelper = new DSSImportHelper(settings, QueryFactory, "smgpois"); + DSSImportHelper dssimporthelper = new DSSImportHelper( + settings, + QueryFactory, + "smgpois" + ); dssimporthelper.entitytype = dssentity; - + updatedetail = await dssimporthelper.SaveDataToODH(null, cancellationToken); - var updateResult = GenericResultsHelper.GetSuccessUpdateResult(null, source, operation, updatetype, "DSS " + dssentity + " update succeeded", "", updatedetail, true); + var updateResult = GenericResultsHelper.GetSuccessUpdateResult( + null, + source, + operation, + updatetype, + "DSS " + dssentity + " update succeeded", + "", + updatedetail, + true + ); return Ok(updateResult); } catch (Exception ex) { - var errorResult = GenericResultsHelper.GetErrorUpdateResult(null, source, operation, updatetype, "DSS " + dssentity + " update failed", "", updatedetail, ex, true); + var errorResult = GenericResultsHelper.GetErrorUpdateResult( + null, + source, + operation, + updatetype, + "DSS " + dssentity + " update failed", + "", + updatedetail, + ex, + true + ); return BadRequest(errorResult); } } [HttpGet, Route("DSS/{dssentity}/UpdateSingle/{id}")] - public IActionResult UpdateSingleDSS(string dssentity, string id, CancellationToken cancellationToken = default) + public IActionResult UpdateSingleDSS( + string dssentity, + string id, + CancellationToken cancellationToken = default + ) { - return StatusCode(StatusCodes.Status501NotImplemented, new { error = "Not Implemented" }); + return StatusCode( + StatusCodes.Status501NotImplemented, + new { error = "Not Implemented" } + ); //try - //{ + //{ // return Ok(new UpdateResult // { // operation = "Update EBMS", @@ -388,6 +612,5 @@ public IActionResult UpdateSingleDSS(string dssentity, string id, CancellationTo } #endregion - } } diff --git a/OdhApiImporter/DefaultBackgroundTaskQueue.cs b/OdhApiImporter/DefaultBackgroundTaskQueue.cs index 7266705cf..619f861a7 100644 --- a/OdhApiImporter/DefaultBackgroundTaskQueue.cs +++ b/OdhApiImporter/DefaultBackgroundTaskQueue.cs @@ -11,14 +11,14 @@ public class DefaultBackgroundTaskQueue : IBackgroundTaskQueue public DefaultBackgroundTaskQueue(int capacity) { - BoundedChannelOptions options = new(capacity) - { - FullMode = BoundedChannelFullMode.Wait - }; + BoundedChannelOptions options = + new(capacity) { FullMode = BoundedChannelFullMode.Wait }; _queue = Channel.CreateBounded>(options); } - public async ValueTask QueueBackgroundWorkItemAsync(Func workItem) + public async ValueTask QueueBackgroundWorkItemAsync( + Func workItem + ) { if (workItem is null) { @@ -27,9 +27,13 @@ public async ValueTask QueueBackgroundWorkItemAsync(Func> DequeueAsync(CancellationToken cancellationToken) + public async ValueTask> DequeueAsync( + CancellationToken cancellationToken + ) { - Func? workItem = await _queue.Reader.ReadAsync(cancellationToken); + Func? workItem = await _queue.Reader.ReadAsync( + cancellationToken + ); return workItem; } } diff --git a/OdhApiImporter/Factories/PostgresQueryFactory.cs b/OdhApiImporter/Factories/PostgresQueryFactory.cs index 06d850a3f..ba4cd612f 100644 --- a/OdhApiImporter/Factories/PostgresQueryFactory.cs +++ b/OdhApiImporter/Factories/PostgresQueryFactory.cs @@ -20,7 +20,8 @@ public PostgresQueryFactory(ISettings settings, ILogger logger) { Connection = new NpgsqlConnection(settings.PostgresConnectionString); Compiler = new PostgresCompiler(); - Logger = info => logger.LogDebug("SQL: {sql} {@parameters}", info.RawSql, info.NamedBindings); + Logger = info => + logger.LogDebug("SQL: {sql} {@parameters}", info.RawSql, info.NamedBindings); } public new void Dispose() diff --git a/OdhApiImporter/Helpers/CUSTOM/CustomDataOperation.cs b/OdhApiImporter/Helpers/CUSTOM/CustomDataOperation.cs index fcfa816f6..6cbef5494 100644 --- a/OdhApiImporter/Helpers/CUSTOM/CustomDataOperation.cs +++ b/OdhApiImporter/Helpers/CUSTOM/CustomDataOperation.cs @@ -25,9 +25,7 @@ public CustomDataOperation(ISettings settings, QueryFactory queryfactory) public async Task UpdateAllEventShortstonewDataModel() { //Load all data from PG and resave - var query = QueryFactory.Query() - .SelectRaw("data") - .From("eventeuracnoi"); + var query = QueryFactory.Query().SelectRaw("data").From("eventeuracnoi"); var data = await query.GetObjectListAsync(); int i = 0; @@ -38,14 +36,25 @@ public async Task UpdateAllEventShortstonewDataModel() eventshort.LastChange = eventshort.ChangedOn; //Setting MetaInfo - eventshort._Meta = MetadataHelper.GetMetadataobject(eventshort, MetadataHelper.GetMetadataforEventShort); + eventshort._Meta = MetadataHelper.GetMetadataobject( + eventshort, + MetadataHelper.GetMetadataforEventShort + ); eventshort._Meta.LastUpdate = eventshort.LastChange; //Save tp DB - //TODO CHECK IF THIS WORKS - var queryresult = await QueryFactory.Query("eventeuracnoi").Where("id", eventshort.Id) + //TODO CHECK IF THIS WORKS + var queryresult = await QueryFactory + .Query("eventeuracnoi") + .Where("id", eventshort.Id) //.UpdateAsync(new JsonBData() { id = eventshort.Id.ToLower(), data = new JsonRaw(eventshort) }); - .UpdateAsync(new JsonBData() { id = eventshort.Id?.ToLower() ?? "", data = new JsonRaw(eventshort) }); + .UpdateAsync( + new JsonBData() + { + id = eventshort.Id?.ToLower() ?? "", + data = new JsonRaw(eventshort) + } + ); i++; } @@ -56,10 +65,11 @@ public async Task UpdateAllEventShortstonewDataModel() public async Task UpdateAllSTAVendingpoints() { //Load all data from PG and resave - var query = QueryFactory.Query() - .SelectRaw("data") - .From("smgpois") - .Where("gen_source", "sta"); + var query = QueryFactory + .Query() + .SelectRaw("data") + .From("smgpois") + .Where("gen_source", "sta"); var data = await query.GetObjectListAsync(); int i = 0; @@ -71,10 +81,18 @@ public async Task UpdateAllSTAVendingpoints() stapoi.Source = "sta"; //Save tp DB - //TODO CHECK IF THIS WORKS - var queryresult = await QueryFactory.Query("smgpois").Where("id", stapoi.Id) + //TODO CHECK IF THIS WORKS + var queryresult = await QueryFactory + .Query("smgpois") + .Where("id", stapoi.Id) //.UpdateAsync(new JsonBData() { id = eventshort.Id.ToLower(), data = new JsonRaw(eventshort) }); - .UpdateAsync(new JsonBData() { id = stapoi.Id?.ToLower() ?? "", data = new JsonRaw(stapoi) }); + .UpdateAsync( + new JsonBData() + { + id = stapoi.Id?.ToLower() ?? "", + data = new JsonRaw(stapoi) + } + ); i++; } @@ -88,24 +106,84 @@ public async Task FillDBWithDummyNews() for (int i = 1; i <= 120; i++) { - ArticlesLinked myarticle = new ArticlesLinked(); + ArticlesLinked myarticle = new ArticlesLinked(); myarticle.Id = Guid.NewGuid().ToString().ToUpper(); myarticle.Type = "newsfeednoi"; myarticle.Active = true; - myarticle.Detail.TryAddOrUpdate("de", new Detail() { Title = "TesttitleDE" + i, BaseText = "testtextDE " + i, Language = "de", AdditionalText = "additionaltextde" + i }); - myarticle.Detail.TryAddOrUpdate("it", new Detail() { Title = "TesttitleIT" + i, BaseText = "testtextIT " + i, Language = "it", AdditionalText = "additionaltextit" + i }); - myarticle.Detail.TryAddOrUpdate("en", new Detail() { Title = "TesttitleEN" + i, BaseText = "testtextEN " + i, Language = "en", AdditionalText = "additionaltexten" + i }); + myarticle.Detail.TryAddOrUpdate( + "de", + new Detail() + { + Title = "TesttitleDE" + i, + BaseText = "testtextDE " + i, + Language = "de", + AdditionalText = "additionaltextde" + i + } + ); + myarticle.Detail.TryAddOrUpdate( + "it", + new Detail() + { + Title = "TesttitleIT" + i, + BaseText = "testtextIT " + i, + Language = "it", + AdditionalText = "additionaltextit" + i + } + ); + myarticle.Detail.TryAddOrUpdate( + "en", + new Detail() + { + Title = "TesttitleEN" + i, + BaseText = "testtextEN " + i, + Language = "en", + AdditionalText = "additionaltexten" + i + } + ); myarticle.HasLanguage = new List() { "de", "it", "en" }; - myarticle.LicenseInfo = new LicenseInfo() { Author = "", License = "CC0", ClosedData = false, LicenseHolder= "https://noi.bz.it" }; - - myarticle.ContactInfos.TryAddOrUpdate("de", new ContactInfos() { Email = "community@noi.bz.it", LogoUrl = "https://databrowser.opendatahub.bz.it/icons/NOI.png", Language = "de", CompanyName = "NOI Techpark" }); - myarticle.ContactInfos.TryAddOrUpdate("it", new ContactInfos() { Email = "community@noi.bz.it", LogoUrl = "https://databrowser.opendatahub.bz.it/icons/NOI.png", Language = "it", CompanyName = "NOI Techpark" }); - myarticle.ContactInfos.TryAddOrUpdate("en", new ContactInfos() { Email = "community@noi.bz.it", LogoUrl = "https://databrowser.opendatahub.bz.it/icons/NOI.png", Language = "en", CompanyName = "NOI Techpark" }); + myarticle.LicenseInfo = new LicenseInfo() + { + Author = "", + License = "CC0", + ClosedData = false, + LicenseHolder = "https://noi.bz.it" + }; + + myarticle.ContactInfos.TryAddOrUpdate( + "de", + new ContactInfos() + { + Email = "community@noi.bz.it", + LogoUrl = "https://databrowser.opendatahub.bz.it/icons/NOI.png", + Language = "de", + CompanyName = "NOI Techpark" + } + ); + myarticle.ContactInfos.TryAddOrUpdate( + "it", + new ContactInfos() + { + Email = "community@noi.bz.it", + LogoUrl = "https://databrowser.opendatahub.bz.it/icons/NOI.png", + Language = "it", + CompanyName = "NOI Techpark" + } + ); + myarticle.ContactInfos.TryAddOrUpdate( + "en", + new ContactInfos() + { + Email = "community@noi.bz.it", + LogoUrl = "https://databrowser.opendatahub.bz.it/icons/NOI.png", + Language = "en", + CompanyName = "NOI Techpark" + } + ); myarticle.ArticleDate = DateTime.Now.Date.AddDays(i); - + if (i % 5 == 0) { myarticle.ArticleDateTo = DateTime.Now.Date.AddMonths(i); @@ -116,19 +194,21 @@ public async Task FillDBWithDummyNews() myarticle.SmgActive = true; myarticle.Source = "noi"; - if(i % 3 == 0) + if (i % 3 == 0) { myarticle.SmgTags = new List() { "important" }; } - var pgcrudresult = await QueryFactory.UpsertData(myarticle, "articles"); + var pgcrudresult = await QueryFactory.UpsertData( + myarticle, + "articles" + ); - if(pgcrudresult.created != null) + if (pgcrudresult.created != null) crudcount = crudcount + pgcrudresult.created.Value; - } return crudcount; - } + } } } diff --git a/OdhApiImporter/Helpers/DSS/DSSImportHelper.cs b/OdhApiImporter/Helpers/DSS/DSSImportHelper.cs index acf0a3134..f75f06d0c 100644 --- a/OdhApiImporter/Helpers/DSS/DSSImportHelper.cs +++ b/OdhApiImporter/Helpers/DSS/DSSImportHelper.cs @@ -24,7 +24,8 @@ public class DSSImportHelper : ImportHelper, IImportHelper // this.settings = settings; //} - public DSSImportHelper(ISettings settings, QueryFactory queryfactory, string table) : base(settings, queryfactory, table) + public DSSImportHelper(ISettings settings, QueryFactory queryfactory, string table) + : base(settings, queryfactory, table) { requesttypelist = new(); entitytype = ""; @@ -33,7 +34,10 @@ public DSSImportHelper(ISettings settings, QueryFactory queryfactory, string tab public List requesttypelist { get; set; } public string entitytype { get; set; } - public async Task SaveDataToODH(DateTime? lastchanged = null, CancellationToken cancellationToken = default) + public async Task SaveDataToODH( + DateTime? lastchanged = null, + CancellationToken cancellationToken = default + ) { requesttypelist = new List(); @@ -53,7 +57,14 @@ public async Task SaveDataToODH(DateTime? lastchanged = null, Canc foreach (var requesttype in requesttypelist) { //Get DSS data - dssdata.Add(await GetDSSData.GetDSSDataAsync(requesttype, settings.DSSConfig.User, settings.DSSConfig.Password, settings.DSSConfig.ServiceUrl)); + dssdata.Add( + await GetDSSData.GetDSSDataAsync( + requesttype, + settings.DSSConfig.User, + settings.DSSConfig.Password, + settings.DSSConfig.ServiceUrl + ) + ); } var updateresult = await ImportData(dssdata, cancellationToken); @@ -61,7 +72,10 @@ public async Task SaveDataToODH(DateTime? lastchanged = null, Canc return updateresult; } - public async Task ImportData(List dssinput, CancellationToken cancellationToken) + public async Task ImportData( + List dssinput, + CancellationToken cancellationToken + ) { int updatecounter = 0; int newcounter = 0; @@ -73,16 +87,18 @@ public async Task ImportData(List dssinput, CancellationT { string lastupdatestr = dssinput[0].lastUpdate; //interface lastupdate - DateTime.TryParseExact(lastupdatestr, "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime lastupdate); + DateTime.TryParseExact( + lastupdatestr, + "dd.MM.yyyy HH:mm:ss", + CultureInfo.InvariantCulture, + DateTimeStyles.None, + out DateTime lastupdate + ); - var areaquery = QueryFactory.Query() - .SelectRaw("data") - .From("areas"); + var areaquery = QueryFactory.Query().SelectRaw("data").From("areas"); // Get all Areas - var arealist = - await areaquery - .GetAllAsObject(); + var arealist = await areaquery.GetAllAsObject(); var validforentity = new List(); @@ -99,19 +115,21 @@ await areaquery // Get all valid categories - var subcategories = await QueryFactory.Query() - .SelectRaw("data") - .From("smgtags") - .ODHTagValidForEntityFilter(validforentity) - .ODHTagMainEntityFilter(new List() { "smgpoi" }) - .GetAllAsObject(); + var subcategories = await QueryFactory + .Query() + .SelectRaw("data") + .From("smgtags") + .ODHTagValidForEntityFilter(validforentity) + .ODHTagMainEntityFilter(new List() { "smgpoi" }) + .GetAllAsObject(); //Temporary get winter/anderes tag and add it to validcategories - var maincategories = await QueryFactory.Query() - .SelectRaw("data") - .From("smgtags") - .IdIlikeFilter(new List() { "winter","anderes" }) - .GetAllAsObject(); + var maincategories = await QueryFactory + .Query() + .SelectRaw("data") + .From("smgtags") + .IdIlikeFilter(new List() { "winter", "anderes" }) + .GetAllAsObject(); validcategories.AddRange(maincategories); validcategories.AddRange(subcategories); @@ -133,13 +151,24 @@ await areaquery //TODO if Area can be mapped return locationinfo if (parsedobject.GpsInfo != null && parsedobject.GpsInfo.Count > 0) { - if (parsedobject.GpsInfo.FirstOrDefault()?.Latitude != 0 && parsedobject.GpsInfo.FirstOrDefault()?.Longitude != 0) + if ( + parsedobject.GpsInfo.FirstOrDefault()?.Latitude != 0 + && parsedobject.GpsInfo.FirstOrDefault()?.Longitude != 0 + ) { - var district = await GetLocationInfo.GetNearestDistrictbyGPS(QueryFactory, parsedobject.GpsInfo.FirstOrDefault()!.Latitude, parsedobject.GpsInfo.FirstOrDefault()!.Longitude, 30000); + var district = await GetLocationInfo.GetNearestDistrictbyGPS( + QueryFactory, + parsedobject.GpsInfo.FirstOrDefault()!.Latitude, + parsedobject.GpsInfo.FirstOrDefault()!.Longitude, + 30000 + ); if (district != null) { - var locinfo = await GetLocationInfo.GetTheLocationInfoDistrict(QueryFactory, district.Id); + var locinfo = await GetLocationInfo.GetTheLocationInfoDistrict( + QueryFactory, + district.Id + ); parsedobject.LocationInfo = locinfo; parsedobject.TourismorganizationId = locinfo.TvInfo?.Id; @@ -152,7 +181,14 @@ await areaquery if (dssskiarearid != null) { //TODO Select Area which has the mapping to dss/rid and fill AreaId Array and LocationInfo.Area - var area = arealist.Where(x => x.Mapping.ContainsKey("dss") && x.Mapping["dss"].ContainsKey("pid") && x.Mapping["dss"]["pid"] == dssskiarearid.ToString()).FirstOrDefault(); + var area = arealist + .Where( + x => + x.Mapping.ContainsKey("dss") + && x.Mapping["dss"].ContainsKey("pid") + && x.Mapping["dss"]["pid"] == dssskiarearid.ToString() + ) + .FirstOrDefault(); if (area?.Id != null) { @@ -160,75 +196,130 @@ await areaquery if (parsedobject.LocationInfo == null) parsedobject.LocationInfo = new LocationInfoLinked(); - Dictionary areanames = new Dictionary(); - if (area.Shortname is { }) - { - areanames.Add("de", area.Shortname); - areanames.Add("it", area.Shortname); - areanames.Add("en", area.Shortname); - areanames.Add("nl", area.Shortname); - areanames.Add("cs", area.Shortname); - areanames.Add("pl", area.Shortname); - areanames.Add("fr", area.Shortname); - areanames.Add("ru", area.Shortname); + Dictionary areanames = + new Dictionary(); + if (area.Shortname is { }) + { + areanames.Add("de", area.Shortname); + areanames.Add("it", area.Shortname); + areanames.Add("en", area.Shortname); + areanames.Add("nl", area.Shortname); + areanames.Add("cs", area.Shortname); + areanames.Add("pl", area.Shortname); + areanames.Add("fr", area.Shortname); + areanames.Add("ru", area.Shortname); } - parsedobject.LocationInfo.AreaInfo = new AreaInfoLinked() { Id = area.Id, Name = areanames }; + parsedobject.LocationInfo.AreaInfo = new AreaInfoLinked() + { + Id = area.Id, + Name = areanames + }; //Use RegionId, TVId from Area if (parsedobject.LocationInfo.RegionInfo == null) if (!String.IsNullOrEmpty(area.RegionId)) - parsedobject.LocationInfo.RegionInfo = new RegionInfoLinked() { Id = area.RegionId, Name = null }; - + parsedobject.LocationInfo.RegionInfo = + new RegionInfoLinked() + { + Id = area.RegionId, + Name = null + }; + if (parsedobject.LocationInfo.TvInfo == null) if (!String.IsNullOrEmpty(area.TourismvereinId)) { - parsedobject.LocationInfo.TvInfo = new TvInfoLinked() { Id = area.TourismvereinId, Name = null }; + parsedobject.LocationInfo.TvInfo = new TvInfoLinked() + { + Id = area.TourismvereinId, + Name = null + }; parsedobject.TourismorganizationId = area.TourismvereinId; } - if (parsedobject.LocationInfo.MunicipalityInfo == null) if (!String.IsNullOrEmpty(area.MunicipalityId)) - parsedobject.LocationInfo.MunicipalityInfo = new MunicipalityInfoLinked() { Id = area.MunicipalityId, Name = null }; - + parsedobject.LocationInfo.MunicipalityInfo = + new MunicipalityInfoLinked() + { + Id = area.MunicipalityId, + Name = null + }; } } //Setting Categorization by Valid Tags - var currentcategories = validcategories.Where(x => parsedobject.SmgTags?.Select(y => y.ToLower()).Contains(x.Id.ToLower()) ?? false); - - foreach (var languagecategory in parsedobject.HasLanguage ?? new List()) + var currentcategories = validcategories.Where( + x => + parsedobject.SmgTags + ?.Select(y => y.ToLower()) + .Contains(x.Id.ToLower()) ?? false + ); + + foreach ( + var languagecategory in parsedobject.HasLanguage ?? new List() + ) { if (parsedobject.AdditionalPoiInfos == null) - parsedobject.AdditionalPoiInfos = new Dictionary(); + parsedobject.AdditionalPoiInfos = + new Dictionary(); //Set MainType, SubType, PoiType var additionalpoiinfo = new AdditionalPoiInfos(); additionalpoiinfo.Language = languagecategory; - var maintypeobj = validcategories.Where(x => x.Id == parsedobject.Type?.ToLower()).FirstOrDefault(); - var subtypeobj = validcategories.Where(x => x.Id == parsedobject.SubType?.ToLower()).FirstOrDefault(); - - additionalpoiinfo.MainType = maintypeobj != null && maintypeobj.TagName != null && maintypeobj.TagName.ContainsKey(languagecategory) ? maintypeobj.TagName[languagecategory] : ""; - additionalpoiinfo.SubType = subtypeobj != null && subtypeobj.TagName != null && subtypeobj.TagName.ContainsKey(languagecategory) ? subtypeobj.TagName[languagecategory] : ""; + var maintypeobj = validcategories + .Where(x => x.Id == parsedobject.Type?.ToLower()) + .FirstOrDefault(); + var subtypeobj = validcategories + .Where(x => x.Id == parsedobject.SubType?.ToLower()) + .FirstOrDefault(); + + additionalpoiinfo.MainType = + maintypeobj != null + && maintypeobj.TagName != null + && maintypeobj.TagName.ContainsKey(languagecategory) + ? maintypeobj.TagName[languagecategory] + : ""; + additionalpoiinfo.SubType = + subtypeobj != null + && subtypeobj.TagName != null + && subtypeobj.TagName.ContainsKey(languagecategory) + ? subtypeobj.TagName[languagecategory] + : ""; //Add the AdditionalPoi Info (include Novelty) if (entitytype.ToLower() == "lift") - additionalpoiinfo.Novelty = (string)item["info-text"][languagecategory]; + additionalpoiinfo.Novelty = (string) + item["info-text"][languagecategory]; if (entitytype.ToLower() == "slope") - additionalpoiinfo.Novelty = (string)item["info-text-winter"][languagecategory]; - - foreach (var smgtagtotranslate in currentcategories.Where(x => x.DisplayAsCategory == true)) + additionalpoiinfo.Novelty = (string) + item["info-text-winter"][languagecategory]; + + foreach ( + var smgtagtotranslate in currentcategories.Where( + x => x.DisplayAsCategory == true + ) + ) { if (additionalpoiinfo.Categories == null) additionalpoiinfo.Categories = new List(); - if (smgtagtotranslate.TagName.ContainsKey(languagecategory) && !additionalpoiinfo.Categories.Contains(smgtagtotranslate.TagName[languagecategory].Trim())) - additionalpoiinfo.Categories.Add(smgtagtotranslate.TagName[languagecategory].Trim()); + if ( + smgtagtotranslate.TagName.ContainsKey(languagecategory) + && !additionalpoiinfo.Categories.Contains( + smgtagtotranslate.TagName[languagecategory].Trim() + ) + ) + additionalpoiinfo.Categories.Add( + smgtagtotranslate.TagName[languagecategory].Trim() + ); } - parsedobject.AdditionalPoiInfos.TryAddOrUpdate(languagecategory, additionalpoiinfo); + parsedobject.AdditionalPoiInfos.TryAddOrUpdate( + languagecategory, + additionalpoiinfo + ); } //Set shortname @@ -242,26 +333,56 @@ await areaquery ODHTagHelper.SetMainCategorizationForODHActivityPoi(parsedobject); //Special get all Taglist and traduce it on import - - await GenericTaggingHelper.AddMappingToODHActivityPoi(parsedobject, settings.JsonConfig.Jsondir); + + await GenericTaggingHelper.AddMappingToODHActivityPoi( + parsedobject, + settings.JsonConfig.Jsondir + ); //Save parsedobject to DB + Save Rawdata to DB - var pgcrudresult = await InsertDataToDB(parsedobject, new KeyValuePair((string)item.pid, item)); + var pgcrudresult = await InsertDataToDB( + parsedobject, + new KeyValuePair((string)item.pid, item) + ); newcounter = newcounter + pgcrudresult.created ?? 0; updatecounter = updatecounter + pgcrudresult.updated ?? 0; - WriteLog.LogToConsole(parsedobject.Id, "dataimport", "single.dss" + entitytype, new ImportLog() { sourceid = parsedobject.Id, sourceinterface = "dss." + entitytype + "base", success = true, error = "" }); + WriteLog.LogToConsole( + parsedobject.Id, + "dataimport", + "single.dss" + entitytype, + new ImportLog() + { + sourceid = parsedobject.Id, + sourceinterface = "dss." + entitytype + "base", + success = true, + error = "" + } + ); } else { - WriteLog.LogToConsole(parsedobject?.Id ?? "-1", "dataimport", "single.dss" + entitytype, new ImportLog() { sourceid = parsedobject?.Id ?? "-1", sourceinterface = "dss." + entitytype + "base", success = false, error = entitytype + " could not be parsed" }); + WriteLog.LogToConsole( + parsedobject?.Id ?? "-1", + "dataimport", + "single.dss" + entitytype, + new ImportLog() + { + sourceid = parsedobject?.Id ?? "-1", + sourceinterface = "dss." + entitytype + "base", + success = false, + error = entitytype + " could not be parsed" + } + ); } } } //Begin SetDataNotinListToInactive - var idlistdb = await GetAllDSSDataByInterface(new List() { "dss" + entitytype + "base" }); + var idlistdb = await GetAllDSSDataByInterface( + new List() { "dss" + entitytype + "base" } + ); var idstodelete = idlistdb.Where(p => !idlistdssinterface.Any(p2 => p2 == p)); @@ -270,16 +391,42 @@ await areaquery var deletedisableresult = await DeleteOrDisableData(idtodelete, false); if (deletedisableresult.Item1 > 0) - WriteLog.LogToConsole(idtodelete, "dataimport", "single.dss" + entitytype, new ImportLog() { sourceid = idtodelete, sourceinterface = "mobility.culture", success = true, error = "" }); + WriteLog.LogToConsole( + idtodelete, + "dataimport", + "single.dss" + entitytype, + new ImportLog() + { + sourceid = idtodelete, + sourceinterface = "mobility.culture", + success = true, + error = "" + } + ); else if (deletedisableresult.Item2 > 0) - WriteLog.LogToConsole(idtodelete, "dataimport", "single.dss" + entitytype, new ImportLog() { sourceid = idtodelete, sourceinterface = "mobility.culture", success = true, error = "" }); - + WriteLog.LogToConsole( + idtodelete, + "dataimport", + "single.dss" + entitytype, + new ImportLog() + { + sourceid = idtodelete, + sourceinterface = "mobility.culture", + success = true, + error = "" + } + ); - deletecounter = deletecounter + deletedisableresult.Item1 + deletedisableresult.Item2; + deletecounter = + deletecounter + deletedisableresult.Item1 + deletedisableresult.Item2; } - - return new UpdateDetail() { created = newcounter, updated = updatecounter, deleted = deletecounter }; + return new UpdateDetail() + { + created = newcounter, + updated = updatecounter, + deleted = deletecounter + }; } //Parse the dss interface content @@ -289,20 +436,25 @@ await areaquery string odhdssid = "dss_" + dssinput.pid; //Get the ODH Item - var mydssquery = QueryFactory.Query(table) - .Select("data") - .Where("id", odhdssid); + var mydssquery = QueryFactory.Query(table).Select("data").Where("id", odhdssid); - var odhactivitypoiindb = await mydssquery.GetFirstOrDefaultAsObject(); + var odhactivitypoiindb = + await mydssquery.GetFirstOrDefaultAsObject(); var odhactivitypoi = default(ODHActivityPoiLinked); if (entitytype.ToLower() == "lift") { - odhactivitypoi = ParseDSSToODHActivityPoi.ParseDSSLiftDataToODHActivityPoi(odhactivitypoiindb, dssinput); + odhactivitypoi = ParseDSSToODHActivityPoi.ParseDSSLiftDataToODHActivityPoi( + odhactivitypoiindb, + dssinput + ); } else if (entitytype.ToLower() == "slope") { - odhactivitypoi = ParseDSSToODHActivityPoi.ParseDSSSlopeDataToODHActivityPoi(odhactivitypoiindb, dssinput); + odhactivitypoi = ParseDSSToODHActivityPoi.ParseDSSSlopeDataToODHActivityPoi( + odhactivitypoiindb, + dssinput + ); } //TODOS all of this stuff, Tags, Categories etc.... @@ -310,18 +462,29 @@ await areaquery return odhactivitypoi; } - private async Task InsertDataToDB(ODHActivityPoiLinked odhactivitypoi, KeyValuePair dssdata) + private async Task InsertDataToDB( + ODHActivityPoiLinked odhactivitypoi, + KeyValuePair dssdata + ) { try { odhactivitypoi.Id = odhactivitypoi.Id?.ToLower(); //Set LicenseInfo - odhactivitypoi.LicenseInfo = Helper.LicenseHelper.GetLicenseInfoobject(odhactivitypoi, Helper.LicenseHelper.GetLicenseforOdhActivityPoi); + odhactivitypoi.LicenseInfo = + Helper.LicenseHelper.GetLicenseInfoobject( + odhactivitypoi, + Helper.LicenseHelper.GetLicenseforOdhActivityPoi + ); var rawdataid = await InsertInRawDataDB(dssdata); - - var pgcrudresult = await QueryFactory.UpsertData(odhactivitypoi, table, rawdataid); + + var pgcrudresult = await QueryFactory.UpsertData( + odhactivitypoi, + table, + rawdataid + ); //Hack insert also in Activity table await InsertInLegacyActivityTable(odhactivitypoi); @@ -337,25 +500,27 @@ private async Task InsertDataToDB(ODHActivityPoiLinked odhactivity private async Task InsertInRawDataDB(KeyValuePair dssdata) { return await QueryFactory.InsertInRawtableAndGetIdAsync( - new RawDataStore() - { - datasource = "dss", - importdate = DateTime.Now, - raw = JsonConvert.SerializeObject(dssdata.Value), - sourceinterface = entitytype + "base", - sourceid = dssdata.Key, - sourceurl = settings.DSSConfig.ServiceUrl, - type = "odhactivitypoi-" + entitytype - }); + new RawDataStore() + { + datasource = "dss", + importdate = DateTime.Now, + raw = JsonConvert.SerializeObject(dssdata.Value), + sourceinterface = entitytype + "base", + sourceid = dssdata.Key, + sourceurl = settings.DSSConfig.ServiceUrl, + type = "odhactivitypoi-" + entitytype + } + ); } - private async Task> GetAllDSSDataByInterface(List syncsourceinterfacelist) + private async Task> GetAllDSSDataByInterface( + List syncsourceinterfacelist + ) { - - var query = - QueryFactory.Query(table) - .Select("id") - .SourceFilter_GeneratedColumn(syncsourceinterfacelist); + var query = QueryFactory + .Query(table) + .Select("id") + .SourceFilter_GeneratedColumn(syncsourceinterfacelist); var idlist = await query.GetAsync(); @@ -366,19 +531,25 @@ private async Task> GetAllDSSDataByInterface(List syncsourc //TODO before each import clear activity table data - private async Task InsertInLegacyActivityTable(ODHActivityPoiLinked odhactivitypoi) + private async Task InsertInLegacyActivityTable( + ODHActivityPoiLinked odhactivitypoi + ) { - //Transform to LTSActivityLinked var activity = TransformODHActivityPoiToActivity(odhactivitypoi); - + //Insert in Table - var pgcrudresult = await QueryFactory.UpsertData(activity, "activities"); + var pgcrudresult = await QueryFactory.UpsertData( + activity, + "activities" + ); return pgcrudresult; } - - private LTSActivityLinked TransformODHActivityPoiToActivity(ODHActivityPoiLinked odhactivitypoi) + + private LTSActivityLinked TransformODHActivityPoiToActivity( + ODHActivityPoiLinked odhactivitypoi + ) { //TODO Transform class LTSActivityLinked myactivity = CastODHActivityTOLTSActivity(odhactivitypoi); @@ -388,39 +559,97 @@ private LTSActivityLinked TransformODHActivityPoiToActivity(ODHActivityPoiLinked { myactivity.Type = "Aufstiegsanlagen"; - var types = GetSubTypeAndPoiTypeFromFlagDescription(myactivity.SmgTags?.ToList() ?? new()); + var types = GetSubTypeAndPoiTypeFromFlagDescription( + myactivity.SmgTags?.ToList() ?? new() + ); myactivity.SubType = types.Item1; myactivity.PoiType = types.Item2; - myactivity.AdditionalPoiInfos.TryAddOrUpdate("de", new AdditionalPoiInfos() { Language = "de", MainType = "Aufstiegsanlagen", SubType = "" }); - myactivity.AdditionalPoiInfos.TryAddOrUpdate("it", new AdditionalPoiInfos() { Language = "it", MainType = "lifts", SubType = "" }); - myactivity.AdditionalPoiInfos.TryAddOrUpdate("en", new AdditionalPoiInfos() { Language = "en", MainType = "ascensioni", SubType = "" }); - + myactivity.AdditionalPoiInfos.TryAddOrUpdate( + "de", + new AdditionalPoiInfos() + { + Language = "de", + MainType = "Aufstiegsanlagen", + SubType = "" + } + ); + myactivity.AdditionalPoiInfos.TryAddOrUpdate( + "it", + new AdditionalPoiInfos() + { + Language = "it", + MainType = "lifts", + SubType = "" + } + ); + myactivity.AdditionalPoiInfos.TryAddOrUpdate( + "en", + new AdditionalPoiInfos() + { + Language = "en", + MainType = "ascensioni", + SubType = "" + } + ); } - else if(odhactivitypoi.SyncSourceInterface == "dssslopebase") + else if (odhactivitypoi.SyncSourceInterface == "dssslopebase") { - myactivity.Type = "Piste"; + myactivity.Type = "Piste"; myactivity.SubType = "Ski Alpin"; - if(myactivity.Difficulty == "2") + if (myactivity.Difficulty == "2") myactivity.PoiType = "blau"; if (myactivity.Difficulty == "4") myactivity.PoiType = "rot"; if (myactivity.Difficulty == "6") myactivity.PoiType = "schwarz"; - myactivity.AdditionalPoiInfos.TryAddOrUpdate("de", new AdditionalPoiInfos() { Language = "de", MainType = "Ski alpin", SubType = "Piste" }); - myactivity.AdditionalPoiInfos.TryAddOrUpdate("it", new AdditionalPoiInfos() { Language = "it", MainType = "Sci alpino", SubType = "piste" }); - myactivity.AdditionalPoiInfos.TryAddOrUpdate("en", new AdditionalPoiInfos() { Language = "en", MainType = "Ski alpin", SubType = "slopes" }); + myactivity.AdditionalPoiInfos.TryAddOrUpdate( + "de", + new AdditionalPoiInfos() + { + Language = "de", + MainType = "Ski alpin", + SubType = "Piste" + } + ); + myactivity.AdditionalPoiInfos.TryAddOrUpdate( + "it", + new AdditionalPoiInfos() + { + Language = "it", + MainType = "Sci alpino", + SubType = "piste" + } + ); + myactivity.AdditionalPoiInfos.TryAddOrUpdate( + "en", + new AdditionalPoiInfos() + { + Language = "en", + MainType = "Ski alpin", + SubType = "slopes" + } + ); } //Type to Tag - if (!String.IsNullOrEmpty(myactivity.Type) && (!myactivity.SmgTags?.Contains(myactivity.Type.ToLower()) ?? false)) + if ( + !String.IsNullOrEmpty(myactivity.Type) + && (!myactivity.SmgTags?.Contains(myactivity.Type.ToLower()) ?? false) + ) myactivity.SmgTags?.Add(myactivity.Type.ToLower()); - if (!String.IsNullOrEmpty(myactivity.SubType) && (!myactivity.SmgTags?.Contains(myactivity.SubType.ToLower()) ?? false)) + if ( + !String.IsNullOrEmpty(myactivity.SubType) + && (!myactivity.SmgTags?.Contains(myactivity.SubType.ToLower()) ?? false) + ) myactivity.SmgTags?.Add(myactivity.SubType.ToLower()); - if (!String.IsNullOrEmpty(myactivity.PoiType) && (!myactivity.SmgTags?.Contains(myactivity.PoiType.ToLower()) ?? false)) + if ( + !String.IsNullOrEmpty(myactivity.PoiType) + && (!myactivity.SmgTags?.Contains(myactivity.PoiType.ToLower()) ?? false) + ) myactivity.SmgTags?.Add(myactivity.PoiType.ToLower()); if (myactivity.SmgTags?.Contains("anderes") ?? false) @@ -444,26 +673,55 @@ private LTSActivityLinked TransformODHActivityPoiToActivity(ODHActivityPoiLinked myactivity.GpsInfo?.Add(gpsresult.Item2); myactivity.GpsPoints.TryAddOrUpdate(gpsresult.Item1, gpsresult.Item2); } - } + } return myactivity; } - private Tuple GetSubTypeAndPoiTypeFromFlagDescription(List odhtags) + private Tuple GetSubTypeAndPoiTypeFromFlagDescription( + List odhtags + ) { List validtags = new List(); List dsslifttypes = new List() { - "Seilbahn","Kabinenbahn","Unterirdische Bahn","Sessellift","Sessellift","Skilift","Schrägaufzug","Klein-Skilift","Telemix","Standseilbahn/Zahnradbahn", - "Skibus","Zug","Sessellift","Sessellift","Sessellift","Förderband","4er Sessellift kuppelbar","6er Sessellift kuppelbar","8er Sessellift kuppelbar" + "Seilbahn", + "Kabinenbahn", + "Unterirdische Bahn", + "Sessellift", + "Sessellift", + "Skilift", + "Schrägaufzug", + "Klein-Skilift", + "Telemix", + "Standseilbahn/Zahnradbahn", + "Skibus", + "Zug", + "Sessellift", + "Sessellift", + "Sessellift", + "Förderband", + "4er Sessellift kuppelbar", + "6er Sessellift kuppelbar", + "8er Sessellift kuppelbar" }; - foreach(var odhtag in odhtags) + foreach (var odhtag in odhtags) { - if(odhtag != "activity" && odhtag != "poi" && - odhtag != "anderes" && odhtag != "aufstiegsanlagen" && odhtag != "weitere aufstiegsanlagen" && - odhtag != "winter" && odhtag != "skirundtouren pisten" && odhtag != "pisten" && odhtag != "ski alpin" && odhtag != "piste" && odhtag != "weitere pisten") + if ( + odhtag != "activity" + && odhtag != "poi" + && odhtag != "anderes" + && odhtag != "aufstiegsanlagen" + && odhtag != "weitere aufstiegsanlagen" + && odhtag != "winter" + && odhtag != "skirundtouren pisten" + && odhtag != "pisten" + && odhtag != "ski alpin" + && odhtag != "piste" + && odhtag != "weitere pisten" + ) { validtags.Add(odhtag); } @@ -508,7 +766,7 @@ private LTSActivityLinked CastODHActivityTOLTSActivity(ODHActivityPoiLinked odha myactivity.DistanceLength = odhactivitypoi.DistanceLength; myactivity.Exposition = odhactivitypoi.Exposition; myactivity.FeetClimb = odhactivitypoi.FeetClimb; - myactivity.FirstImport = odhactivitypoi.FirstImport; + myactivity.FirstImport = odhactivitypoi.FirstImport; myactivity.GpsInfo = new List(); //myactivity.GpsPoints = odhactivitypoi.GpsPoints; myactivity.GpsTrack = odhactivitypoi.GpsTrack; @@ -542,26 +800,45 @@ private LTSActivityLinked CastODHActivityTOLTSActivity(ODHActivityPoiLinked odha myactivity.SmgTags = odhactivitypoi.SmgTags; myactivity.Source = odhactivitypoi.Source; myactivity.TourismorganizationId = odhactivitypoi.TourismorganizationId; - myactivity.WayNumber = odhactivitypoi.WayNumber; + myactivity.WayNumber = odhactivitypoi.WayNumber; return myactivity; } private Tuple ReturnGpsInfoActivityKey(GpsInfo gpsinfo) { - string activitygpstypevalue = ""; string gpstypekey = ""; - switch(gpsinfo.Gpstype) + switch (gpsinfo.Gpstype) { - case "valleystationpoint": activitygpstypevalue = "Talstation"; gpstypekey = "position"; break; - case "middlestationpoint" : activitygpstypevalue = "Mittelstation"; gpstypekey = "middleposition"; break; - case "mountainstationpoint" : activitygpstypevalue = "Bergstation"; gpstypekey = "endposition"; break; - case "position": activitygpstypevalue = "Startpunkt"; gpstypekey = "position"; break; - }; + case "valleystationpoint": + activitygpstypevalue = "Talstation"; + gpstypekey = "position"; + break; + case "middlestationpoint": + activitygpstypevalue = "Mittelstation"; + gpstypekey = "middleposition"; + break; + case "mountainstationpoint": + activitygpstypevalue = "Bergstation"; + gpstypekey = "endposition"; + break; + case "position": + activitygpstypevalue = "Startpunkt"; + gpstypekey = "position"; + break; + } + ; - GpsInfo gpstoreturn = new GpsInfo() { Gpstype = activitygpstypevalue, Altitude = gpsinfo.Altitude, AltitudeUnitofMeasure = gpsinfo.AltitudeUnitofMeasure, Latitude = gpsinfo.Latitude, Longitude = gpsinfo.Longitude }; + GpsInfo gpstoreturn = new GpsInfo() + { + Gpstype = activitygpstypevalue, + Altitude = gpsinfo.Altitude, + AltitudeUnitofMeasure = gpsinfo.AltitudeUnitofMeasure, + Latitude = gpsinfo.Latitude, + Longitude = gpsinfo.Longitude + }; return Tuple.Create(gpstypekey, gpstoreturn); } diff --git a/OdhApiImporter/Helpers/EBMS/EBMSImportHelper.cs b/OdhApiImporter/Helpers/EBMS/EBMSImportHelper.cs index 133cc4d35..b08af06ed 100644 --- a/OdhApiImporter/Helpers/EBMS/EBMSImportHelper.cs +++ b/OdhApiImporter/Helpers/EBMS/EBMSImportHelper.cs @@ -22,16 +22,20 @@ public class EBMSImportHelper : ImportHelper, IImportHelper // this.settings = settings; //} - public EBMSImportHelper(ISettings settings, QueryFactory queryfactory, string table) : base(settings, queryfactory, table) - { - - } + public EBMSImportHelper(ISettings settings, QueryFactory queryfactory, string table) + : base(settings, queryfactory, table) { } #region EBMS Helpers - public async Task SaveDataToODH(DateTime? lastchanged, CancellationToken cancellationToken) + public async Task SaveDataToODH( + DateTime? lastchanged, + CancellationToken cancellationToken + ) { - var resulttuple = ImportEBMSData.GetEbmsEvents(settings.EbmsConfig.User, settings.EbmsConfig.Password); + var resulttuple = ImportEBMSData.GetEbmsEvents( + settings.EbmsConfig.User, + settings.EbmsConfig.Password + ); var resulttuplesorted = resulttuple.OrderBy(x => x.Item1.StartDate); var currenteventshort = await GetAllEventsShort(DateTime.Now); @@ -45,10 +49,10 @@ public async Task SaveDataToODH(DateTime? lastchanged, Cancellatio foreach (var (eventshort, eventebms) in resulttuplesorted) { - var query = - QueryFactory.Query("eventeuracnoi") - .Select("data") - .Where("id", eventshort.Id); + var query = QueryFactory + .Query("eventeuracnoi") + .Select("data") + .Where("id", eventshort.Id); var eventindb = await query.GetFirstOrDefaultAsObject(); @@ -90,7 +94,6 @@ public async Task SaveDataToODH(DateTime? lastchanged, Cancellatio soldout = eventindb.SoldOut; } - if (changedonDB != eventshort.ChangedOn) { eventshort.ImageGallery = imagegallery; @@ -110,39 +113,69 @@ public async Task SaveDataToODH(DateTime? lastchanged, Cancellatio eventshort.ExternalOrganizer = externalorganizer; //New If CompanyName is Noi - blablabla assign TechnologyField automatically and Write to Display5 if not empty "NOI" - if (!String.IsNullOrEmpty(eventshort.CompanyName) && eventshort.CompanyName.StartsWith("NOI - ")) + if ( + !String.IsNullOrEmpty(eventshort.CompanyName) + && eventshort.CompanyName.StartsWith("NOI - ") + ) { if (String.IsNullOrEmpty(eventshort.Display5)) eventshort.Display5 = "NOI"; - eventshort.TechnologyFields = AssignTechnologyfieldsautomatically(eventshort.CompanyName, eventshort.TechnologyFields); + eventshort.TechnologyFields = AssignTechnologyfieldsautomatically( + eventshort.CompanyName, + eventshort.TechnologyFields + ); } - var queryresult = await InsertDataToDB(eventshort, new KeyValuePair(eventebms.EventId.ToString(), eventebms)); + var queryresult = await InsertDataToDB( + eventshort, + new KeyValuePair( + eventebms.EventId.ToString(), + eventebms + ) + ); newcounter = newcounter + queryresult.created ?? 0; - updatecounter = updatecounter + queryresult.updated ?? 0; + updatecounter = updatecounter + queryresult.updated ?? 0; } } if (resulttuple.Select(x => x.Item1).Count() > 0) - deletecounter = await DeleteDeletedEvents(resulttuple.Select(x => x.Item1).ToList(), currenteventshort.ToList()); + deletecounter = await DeleteDeletedEvents( + resulttuple.Select(x => x.Item1).ToList(), + currenteventshort.ToList() + ); - return new UpdateDetail() { created = newcounter, updated = updatecounter, deleted = deletecounter }; + return new UpdateDetail() + { + created = newcounter, + updated = updatecounter, + deleted = deletecounter + }; } - private async Task InsertDataToDB(EventShortLinked eventshort, KeyValuePair ebmsevent) + private async Task InsertDataToDB( + EventShortLinked eventshort, + KeyValuePair ebmsevent + ) { try - { + { //Setting LicenseInfo - eventshort.LicenseInfo = Helper.LicenseHelper.GetLicenseInfoobject(eventshort, Helper.LicenseHelper.GetLicenseforEventShort); + eventshort.LicenseInfo = Helper.LicenseHelper.GetLicenseInfoobject( + eventshort, + Helper.LicenseHelper.GetLicenseforEventShort + ); //Check Languages eventshort.CheckMyInsertedLanguages(); var rawdataid = await InsertInRawDataDB(ebmsevent); - return await QueryFactory.UpsertData(eventshort, "eventeuracnoi", rawdataid); + return await QueryFactory.UpsertData( + eventshort, + "eventeuracnoi", + rawdataid + ); } catch (Exception ex) { @@ -153,20 +186,23 @@ private async Task InsertDataToDB(EventShortLinked eventshort, Key private async Task InsertInRawDataDB(KeyValuePair eventebms) { return await QueryFactory.InsertInRawtableAndGetIdAsync( - new RawDataStore() - { - datasource = "eurac", - importdate = DateTime.Now, - raw = JsonConvert.SerializeObject(eventebms.Value), - sourceinterface = "ebms", - sourceid = eventebms.Key, - sourceurl = "https://emea-interface.ungerboeck.com", - type = "event_euracnoi" - }); + new RawDataStore() + { + datasource = "eurac", + importdate = DateTime.Now, + raw = JsonConvert.SerializeObject(eventebms.Value), + sourceinterface = "ebms", + sourceid = eventebms.Key, + sourceurl = "https://emea-interface.ungerboeck.com", + type = "event_euracnoi" + } + ); } - - private static List? AssignTechnologyfieldsautomatically(string companyname, List? technologyfields) + private static List? AssignTechnologyfieldsautomatically( + string companyname, + List? technologyfields + ) { if (technologyfields == null) technologyfields = new List(); @@ -175,7 +211,12 @@ private async Task InsertInRawDataDB(KeyValuePair ev AssignTechnologyFields(companyname, "Digital", "Digital", technologyfields); AssignTechnologyFields(companyname, "Alpine", "Alpine", technologyfields); - AssignTechnologyFields(companyname, "Automotive", "Automotive/Automation", technologyfields); + AssignTechnologyFields( + companyname, + "Automotive", + "Automotive/Automation", + technologyfields + ); AssignTechnologyFields(companyname, "Food", "Food", technologyfields); AssignTechnologyFields(companyname, "Green", "Green", technologyfields); @@ -185,14 +226,22 @@ private async Task InsertInRawDataDB(KeyValuePair ev return technologyfields; } - private static void AssignTechnologyFields(string companyname, string tocheck, string toassign, List automatictechnologyfields) + private static void AssignTechnologyFields( + string companyname, + string tocheck, + string toassign, + List automatictechnologyfields + ) { if (companyname.Contains(tocheck)) if (!automatictechnologyfields.Contains(toassign)) automatictechnologyfields.Add(toassign); } - private async Task DeleteDeletedEvents(List eventshortfromnow, List eventshortinDB) + private async Task DeleteDeletedEvents( + List eventshortfromnow, + List eventshortinDB + ) { //TODO CHECK if Event is in list, if not, DELETE! //TODO CHECK IF THIS IS WORKING CORRECTLY @@ -211,12 +260,17 @@ private async Task DeleteDeletedEvents(List eventshortfro { //Set to inactive or delete? - var eventshorttodeactivate = eventshortinDB.Where(x => x.EventId == idtodelete).FirstOrDefault(); + var eventshorttodeactivate = eventshortinDB + .Where(x => x.EventId == idtodelete) + .FirstOrDefault(); //TODO CHECK IF IT WORKS if (eventshorttodeactivate != null) { - await QueryFactory.Query("eventeuracnoi").Where("id", eventshorttodeactivate.Id?.ToLower()).DeleteAsync(); + await QueryFactory + .Query("eventeuracnoi") + .Where("id", eventshorttodeactivate.Id?.ToLower()) + .DeleteAsync(); deletecounter++; } } @@ -229,17 +283,19 @@ private async Task> GetAllEventsShort(DateTime now { var today = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0); - var query = - QueryFactory.Query("eventeuracnoi") - .Select("data") - .WhereRaw("(((to_date(data->> 'EndDate', 'YYYY-MM-DD') >= '" + String.Format("{0:yyyy-MM-dd}", today) + "'))) AND(data#>>'\\{Source\\}' = ?)", "EBMS"); + var query = QueryFactory + .Query("eventeuracnoi") + .Select("data") + .WhereRaw( + "(((to_date(data->> 'EndDate', 'YYYY-MM-DD') >= '" + + String.Format("{0:yyyy-MM-dd}", today) + + "'))) AND(data#>>'\\{Source\\}' = ?)", + "EBMS" + ); return await query.GetAllAsObject(); } - - #endregion - } } diff --git a/OdhApiImporter/Helpers/IImportHelper.cs b/OdhApiImporter/Helpers/IImportHelper.cs index 5a7448743..8516c4a05 100644 --- a/OdhApiImporter/Helpers/IImportHelper.cs +++ b/OdhApiImporter/Helpers/IImportHelper.cs @@ -10,7 +10,10 @@ namespace OdhApiImporter.Helpers { public interface IImportHelper { - Task SaveDataToODH(DateTime? lastchanged = null, CancellationToken cancellationToken = default); + Task SaveDataToODH( + DateTime? lastchanged = null, + CancellationToken cancellationToken = default + ); Task> DeleteOrDisableData(string id, bool delete); } @@ -19,7 +22,7 @@ public class ImportHelper { protected readonly QueryFactory QueryFactory; protected readonly ISettings settings; - protected readonly string table; + protected readonly string table; public ImportHelper(ISettings settings, QueryFactory queryfactory, string table) { @@ -35,15 +38,11 @@ public async Task> DeleteOrDisableData(string id, bool delete) if (delete) { - deleteresult = await QueryFactory.Query(table).Where("id", id) - .DeleteAsync(); + deleteresult = await QueryFactory.Query(table).Where("id", id).DeleteAsync(); } else { - var query = - QueryFactory.Query(table) - .Select("data") - .Where("id", id); + var query = QueryFactory.Query(table).Select("data").Where("id", id); var data = await query.GetFirstOrDefaultAsObject(); @@ -54,14 +53,15 @@ public async Task> DeleteOrDisableData(string id, bool delete) data.Active = false; data.SmgActive = false; - updateresult = await QueryFactory.Query(table).Where("id", id) - .UpdateAsync(new JsonBData() { id = id, data = new JsonRaw(data) }); + updateresult = await QueryFactory + .Query(table) + .Where("id", id) + .UpdateAsync(new JsonBData() { id = id, data = new JsonRaw(data) }); } } } return Tuple.Create(updateresult, deleteresult); } - } } diff --git a/OdhApiImporter/Helpers/NINJA/NINJAImportHelper.cs b/OdhApiImporter/Helpers/NINJA/NINJAImportHelper.cs index 66c6d8fc2..33457c3be 100644 --- a/OdhApiImporter/Helpers/NINJA/NINJAImportHelper.cs +++ b/OdhApiImporter/Helpers/NINJA/NINJAImportHelper.cs @@ -25,7 +25,10 @@ public NINJAImportHelper(ISettings settings, QueryFactory queryfactory) #region NINJA Helpers - public async Task SaveDataToODH(DateTime? lastchanged = null, CancellationToken cancellationToken = default) + public async Task SaveDataToODH( + DateTime? lastchanged = null, + CancellationToken cancellationToken = default + ) { //Import the data from Mobility Api var culturelist = await ImportList(cancellationToken); @@ -35,19 +38,34 @@ public async Task SaveDataToODH(DateTime? lastchanged = null, Canc return result; } - private async Task,NinjaObject> > ImportList(CancellationToken cancellationToken) + private async Task, NinjaObject>> ImportList( + CancellationToken cancellationToken + ) { var responseevents = await GetNinjaData.GetNinjaEvent(); var responseplaces = await GetNinjaData.GetNinjaPlaces(); - WriteLog.LogToConsole("", "dataimport", "list.mobilityculture", new ImportLog() { sourceid = "", sourceinterface = "mobility.culture", success = true, error = "" }); + WriteLog.LogToConsole( + "", + "dataimport", + "list.mobilityculture", + new ImportLog() + { + sourceid = "", + sourceinterface = "mobility.culture", + success = true, + error = "" + } + ); return Tuple.Create(responseevents, responseplaces); } - private async Task SaveEventsToPG(ICollection> ninjadataarr, ICollection> ninjaplaceroomarr) + private async Task SaveEventsToPG( + ICollection> ninjadataarr, + ICollection> ninjaplaceroomarr + ) { - var newimportcounter = 0; var updateimportcounter = 0; var errorimportcounter = 0; @@ -62,12 +80,21 @@ private async Task SaveEventsToPG(ICollection x.sname == kvp.Value.place).FirstOrDefault(); - var room = ninjaplaceroomarr.Where(x => x.sname == kvp.Value.room).FirstOrDefault(); - - var eventtosave = ParseNinjaData.ParseNinjaEventToODHEvent(kvp.Key, kvp.Value, place, room); - - if(eventtosave != null) + var place = ninjaplaceroomarr + .Where(x => x.sname == kvp.Value.place) + .FirstOrDefault(); + var room = ninjaplaceroomarr + .Where(x => x.sname == kvp.Value.room) + .FirstOrDefault(); + + var eventtosave = ParseNinjaData.ParseNinjaEventToODHEvent( + kvp.Key, + kvp.Value, + place, + room + ); + + if (eventtosave != null) { //Setting Location Info //Location Info (by GPS Point) @@ -94,14 +121,36 @@ private async Task SaveEventsToPG(ICollection SaveEventsToPG(ICollection 0) - WriteLog.LogToConsole(idtodelete, "dataimport", "single.mobilityculture", new ImportLog() { sourceid = idtodelete, sourceinterface = "mobility.culture", success = true, error = "" }); + if (deletedisableresult.Item1 > 0) + WriteLog.LogToConsole( + idtodelete, + "dataimport", + "single.mobilityculture", + new ImportLog() + { + sourceid = idtodelete, + sourceinterface = "mobility.culture", + success = true, + error = "" + } + ); else if (deletedisableresult.Item2 > 0) - WriteLog.LogToConsole(idtodelete, "dataimport", "single.mobilityculture", new ImportLog() { sourceid = idtodelete, sourceinterface = "mobility.culture", success = true, error = "" }); - + WriteLog.LogToConsole( + idtodelete, + "dataimport", + "single.mobilityculture", + new ImportLog() + { + sourceid = idtodelete, + sourceinterface = "mobility.culture", + success = true, + error = "" + } + ); - deleteimportcounter = deleteimportcounter + deletedisableresult.Item1 + deletedisableresult.Item2; + deleteimportcounter = + deleteimportcounter + deletedisableresult.Item1 + deletedisableresult.Item2; } - return new UpdateDetail() { updated = updateimportcounter, created = newimportcounter, deleted = deleteimportcounter }; + return new UpdateDetail() + { + updated = updateimportcounter, + created = newimportcounter, + deleted = deleteimportcounter + }; } //Check if logic can be moved here //private async Task SetDataNotinListToInactive() //{ - + //} - private async Task InsertDataToDB(EventLinked eventtosave, KeyValuePair ninjaevent) + private async Task InsertDataToDB( + EventLinked eventtosave, + KeyValuePair ninjaevent + ) { try { eventtosave.Id = eventtosave.Id?.ToUpper(); //Set LicenseInfo - eventtosave.LicenseInfo = Helper.LicenseHelper.GetLicenseInfoobject(eventtosave, Helper.LicenseHelper.GetLicenseforEvent); + eventtosave.LicenseInfo = Helper.LicenseHelper.GetLicenseInfoobject( + eventtosave, + Helper.LicenseHelper.GetLicenseforEvent + ); var rawdataid = await InsertInRawDataDB(ninjaevent); - return await QueryFactory.UpsertData(eventtosave, "events", rawdataid); + return await QueryFactory.UpsertData(eventtosave, "events", rawdataid); } catch (Exception ex) { @@ -153,46 +235,50 @@ private async Task InsertDataToDB(EventLinked eventtosave, KeyValu private async Task InsertInRawDataDB(KeyValuePair ninjaevent) { return await QueryFactory.InsertInRawtableAndGetIdAsync( - new RawDataStore() - { - datasource = "ninja", - importdate = DateTime.Now, - raw = JsonConvert.SerializeObject(ninjaevent.Value), - sourceinterface = "culture", - sourceid = ninjaevent.Key, - sourceurl = "https://mobility.api.opendatahub.bz.it/v2/flat/Culture/", - type = "event_centrotrevi-drin" - }); - } - - private async Task> DeleteOrDisableData(string eventid, bool delete) + new RawDataStore() + { + datasource = "ninja", + importdate = DateTime.Now, + raw = JsonConvert.SerializeObject(ninjaevent.Value), + sourceinterface = "culture", + sourceid = ninjaevent.Key, + sourceurl = "https://mobility.api.opendatahub.bz.it/v2/flat/Culture/", + type = "event_centrotrevi-drin" + } + ); + } + + private async Task> DeleteOrDisableData(string eventid, bool delete) { var deleteresult = 0; var updateresult = 0; if (delete) { - deleteresult = await QueryFactory.Query("events").Where("id", eventid) + deleteresult = await QueryFactory + .Query("events") + .Where("id", eventid) .DeleteAsync(); } else { - var query = - QueryFactory.Query("events") - .Select("data") - .Where("id", eventid); + var query = QueryFactory.Query("events").Select("data").Where("id", eventid); var data = await query.GetFirstOrDefaultAsObject(); - if (data != null) + if (data != null) { if (data.Active != false || data.SmgActive != false) { data.Active = false; data.SmgActive = false; - updateresult = await QueryFactory.Query("events").Where("id", eventid) - .UpdateAsync(new JsonBData() { id = eventid, data = new JsonRaw(data) }); + updateresult = await QueryFactory + .Query("events") + .Where("id", eventid) + .UpdateAsync( + new JsonBData() { id = eventid, data = new JsonRaw(data) } + ); } } } @@ -206,11 +292,10 @@ private async Task> DeleteOrDisableData(string eventid, bool dele private async Task> GetAllEventsBySource(List sourcelist) { - - var query = - QueryFactory.Query("events") - .Select("id") - .SourceFilter_GeneratedColumn(sourcelist); + var query = QueryFactory + .Query("events") + .Select("id") + .SourceFilter_GeneratedColumn(sourcelist); var eventids = await query.GetAsync(); @@ -219,7 +304,12 @@ private async Task> GetAllEventsBySource(List sourcelist) private async Task SetLocationInfo(EventLinked myevent) { - var district = await GetLocationInfo.GetNearestDistrictbyGPS(QueryFactory, myevent.Latitude, myevent.Longitude, 30000); + var district = await GetLocationInfo.GetNearestDistrictbyGPS( + QueryFactory, + myevent.Latitude, + myevent.Longitude, + 30000 + ); if (district == null) return; @@ -227,7 +317,10 @@ private async Task SetLocationInfo(EventLinked myevent) myevent.DistrictId = district.Id; myevent.DistrictIds = new List() { district.Id }; - var locinfo = await GetLocationInfo.GetTheLocationInfoDistrict(QueryFactory, district.Id); + var locinfo = await GetLocationInfo.GetTheLocationInfoDistrict( + QueryFactory, + district.Id + ); if (locinfo != null) { LocationInfoLinked locinfolinked = new LocationInfoLinked @@ -259,6 +352,5 @@ private async Task SetLocationInfo(EventLinked myevent) } #endregion - } } diff --git a/OdhApiImporter/Helpers/RAVEN/RAVENImportHelper.cs b/OdhApiImporter/Helpers/RAVEN/RAVENImportHelper.cs index a1910ecc5..e38106d66 100644 --- a/OdhApiImporter/Helpers/RAVEN/RAVENImportHelper.cs +++ b/OdhApiImporter/Helpers/RAVEN/RAVENImportHelper.cs @@ -27,7 +27,11 @@ public RAVENImportHelper(ISettings settings, QueryFactory queryfactory) //TODO Check if passed id has to be tranformed to lowercase or uppercase - public async Task> GetFromRavenAndTransformToPGObject(string id, string datatype, CancellationToken cancellationToken) + public async Task> GetFromRavenAndTransformToPGObject( + string id, + string datatype, + CancellationToken cancellationToken + ) { var mydata = default(IIdentifiable); var mypgdata = default(IIdentifiable); @@ -38,35 +42,82 @@ public async Task> GetFromRavenAndTransformToPGObjec switch (datatype.ToLower()) { case "accommodation": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((AccommodationLinked)mydata, TransformToPGObject.GetAccommodationPGObject); + mypgdata = TransformToPGObject.GetPGObject< + AccommodationLinked, + AccommodationLinked + >( + (AccommodationLinked)mydata, + TransformToPGObject.GetAccommodationPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((AccommodationLinked)mypgdata, "accommodations"); + myupdateresult = await SaveRavenObjectToPG( + (AccommodationLinked)mypgdata, + "accommodations" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((AccommodationLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck( + (AccommodationLinked)mypgdata + ) == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((AccommodationLinked)mypgdata, ReduceDataTransformer.CopyLTSAccommodationToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((AccommodationLinkedReduced)reducedobject, "accommodations"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (AccommodationLinked)mypgdata, + ReduceDataTransformer.CopyLTSAccommodationToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (AccommodationLinkedReduced)reducedobject, + "accommodations" + ); } //UPDATE ACCOMMODATIONROOMS - var myroomdatalist = await GetDataFromRaven.GetRavenData>("accommodationroom", id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken, "AccommodationRoom?accoid="); + var myroomdatalist = await GetDataFromRaven.GetRavenData< + IEnumerable + >( + "accommodationroom", + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken, + "AccommodationRoom?accoid=" + ); if (myroomdatalist != null) { foreach (var myroomdata in myroomdatalist) { - var mypgroomdata = TransformToPGObject.GetPGObject((AccommodationRoomLinked)myroomdata, TransformToPGObject.GetAccommodationRoomPGObject); - - var accoroomresult = await SaveRavenObjectToPG((AccommodationRoomLinked)mypgroomdata, "accommodationrooms"); + var mypgroomdata = TransformToPGObject.GetPGObject< + AccommodationRoomLinked, + AccommodationRoomLinked + >( + (AccommodationRoomLinked)myroomdata, + TransformToPGObject.GetAccommodationRoomPGObject + ); + + var accoroomresult = await SaveRavenObjectToPG( + (AccommodationRoomLinked)mypgroomdata, + "accommodationrooms" + ); //Merge with updateresult - myupdateresult = GenericResultsHelper.MergeUpdateDetail(new List { myupdateresult, accoroomresult }); + myupdateresult = GenericResultsHelper.MergeUpdateDetail( + new List { myupdateresult, accoroomresult } + ); } } else @@ -75,280 +126,620 @@ public async Task> GetFromRavenAndTransformToPGObjec break; case "gastronomy": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((GastronomyLinked)mydata, TransformToPGObject.GetGastronomyPGObject); + mypgdata = TransformToPGObject.GetPGObject< + GastronomyLinked, + GastronomyLinked + >((GastronomyLinked)mydata, TransformToPGObject.GetGastronomyPGObject); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((GastronomyLinked)mypgdata, "gastronomies"); + myupdateresult = await SaveRavenObjectToPG( + (GastronomyLinked)mypgdata, + "gastronomies" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((GastronomyLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck( + (GastronomyLinked)mypgdata + ) == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((GastronomyLinked)mypgdata, ReduceDataTransformer.CopyLTSGastronomyToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((GastronomyLinkedReduced)reducedobject, "gastronomies"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (GastronomyLinked)mypgdata, + ReduceDataTransformer.CopyLTSGastronomyToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (GastronomyLinkedReduced)reducedobject, + "gastronomies" + ); } break; case "activity": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((LTSActivityLinked)mydata, TransformToPGObject.GetActivityPGObject); + mypgdata = TransformToPGObject.GetPGObject< + LTSActivityLinked, + LTSActivityLinked + >((LTSActivityLinked)mydata, TransformToPGObject.GetActivityPGObject); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((LTSActivityLinked)mypgdata, "activities"); + myupdateresult = await SaveRavenObjectToPG( + (LTSActivityLinked)mypgdata, + "activities" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((LTSActivityLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck( + (LTSActivityLinked)mypgdata + ) == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((LTSActivityLinked)mypgdata, ReduceDataTransformer.CopyLTSActivityToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((LTSActivityLinkedReduced)reducedobject, "activities"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (LTSActivityLinked)mypgdata, + ReduceDataTransformer.CopyLTSActivityToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (LTSActivityLinkedReduced)reducedobject, + "activities" + ); } break; case "poi": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((LTSPoiLinked)mydata, TransformToPGObject.GetPoiPGObject); + mypgdata = TransformToPGObject.GetPGObject( + (LTSPoiLinked)mydata, + TransformToPGObject.GetPoiPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((LTSPoiLinked)mypgdata, "pois"); + myupdateresult = await SaveRavenObjectToPG( + (LTSPoiLinked)mypgdata, + "pois" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((LTSPoiLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck((LTSPoiLinked)mypgdata) + == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((LTSPoiLinked)mypgdata, ReduceDataTransformer.CopyLTSPoiToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((LTSPoiLinkedReduced)reducedobject, "pois"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (LTSPoiLinked)mypgdata, + ReduceDataTransformer.CopyLTSPoiToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (LTSPoiLinkedReduced)reducedobject, + "pois" + ); } break; case "odhactivitypoi": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((ODHActivityPoiLinked)mydata, TransformToPGObject.GetODHActivityPoiPGObject); + mypgdata = TransformToPGObject.GetPGObject< + ODHActivityPoiLinked, + ODHActivityPoiLinked + >( + (ODHActivityPoiLinked)mydata, + TransformToPGObject.GetODHActivityPoiPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((ODHActivityPoiLinked)mypgdata, "smgpois"); + myupdateresult = await SaveRavenObjectToPG( + (ODHActivityPoiLinked)mypgdata, + "smgpois" + ); //Special get all Taglist and traduce it on import - await GenericTaggingHelper.AddMappingToODHActivityPoi(mypgdata, settings.JsonConfig.Jsondir); + await GenericTaggingHelper.AddMappingToODHActivityPoi( + mypgdata, + settings.JsonConfig.Jsondir + ); - myupdateresult = await SaveRavenObjectToPG((ODHActivityPoiLinked)mypgdata, "smgpois"); + myupdateresult = await SaveRavenObjectToPG( + (ODHActivityPoiLinked)mypgdata, + "smgpois" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((ODHActivityPoiLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck( + (ODHActivityPoiLinked)mypgdata + ) == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((ODHActivityPoiLinked)mypgdata, ReduceDataTransformer.CopyLTSODHActivtyPoiToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((LTSODHActivityPoiReduced)reducedobject, "smgpois"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (ODHActivityPoiLinked)mypgdata, + ReduceDataTransformer.CopyLTSODHActivtyPoiToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (LTSODHActivityPoiReduced)reducedobject, + "smgpois" + ); } break; case "event": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((EventLinked)mydata, TransformToPGObject.GetEventPGObject); + mypgdata = TransformToPGObject.GetPGObject( + (EventLinked)mydata, + TransformToPGObject.GetEventPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((EventLinked)mypgdata, "events"); - + myupdateresult = await SaveRavenObjectToPG( + (EventLinked)mypgdata, + "events" + ); + //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((EventLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck((EventLinked)mypgdata) + == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((EventLinked)mypgdata, ReduceDataTransformer.CopyLTSEventToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((EventLinkedReduced)reducedobject, "events"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (EventLinked)mypgdata, + ReduceDataTransformer.CopyLTSEventToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (EventLinkedReduced)reducedobject, + "events" + ); } break; case "webcam": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((WebcamInfoLinked)mydata, TransformToPGObject.GetWebcamInfoPGObject); + mypgdata = TransformToPGObject.GetPGObject< + WebcamInfoLinked, + WebcamInfoLinked + >((WebcamInfoLinked)mydata, TransformToPGObject.GetWebcamInfoPGObject); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((EventLinked)mypgdata, "events"); + myupdateresult = await SaveRavenObjectToPG( + (EventLinked)mypgdata, + "events" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((WebcamInfoLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck( + (WebcamInfoLinked)mypgdata + ) == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((WebcamInfoLinked)mypgdata, ReduceDataTransformer.CopyLTSWebcamInfoToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((WebcamInfoLinkedReduced)reducedobject, "webcams"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (WebcamInfoLinked)mypgdata, + ReduceDataTransformer.CopyLTSWebcamInfoToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (WebcamInfoLinkedReduced)reducedobject, + "webcams" + ); } break; case "metaregion": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((MetaRegionLinked)mydata, TransformToPGObject.GetMetaRegionPGObject); + mypgdata = TransformToPGObject.GetPGObject< + MetaRegionLinked, + MetaRegionLinked + >((MetaRegionLinked)mydata, TransformToPGObject.GetMetaRegionPGObject); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((MetaRegionLinked)mypgdata, "metaregions"); + myupdateresult = await SaveRavenObjectToPG( + (MetaRegionLinked)mypgdata, + "metaregions" + ); break; case "region": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((RegionLinked)mydata, TransformToPGObject.GetRegionPGObject); + mypgdata = TransformToPGObject.GetPGObject( + (RegionLinked)mydata, + TransformToPGObject.GetRegionPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((RegionLinked)mypgdata, "regions"); + myupdateresult = await SaveRavenObjectToPG( + (RegionLinked)mypgdata, + "regions" + ); break; case "tv": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((TourismvereinLinked)mydata, TransformToPGObject.GetTourismAssociationPGObject); + mypgdata = TransformToPGObject.GetPGObject< + TourismvereinLinked, + TourismvereinLinked + >( + (TourismvereinLinked)mydata, + TransformToPGObject.GetTourismAssociationPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((TourismvereinLinked)mypgdata, "tvs"); + myupdateresult = await SaveRavenObjectToPG( + (TourismvereinLinked)mypgdata, + "tvs" + ); break; case "municipality": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((MunicipalityLinked)mydata, TransformToPGObject.GetMunicipalityPGObject); + mypgdata = TransformToPGObject.GetPGObject< + MunicipalityLinked, + MunicipalityLinked + >((MunicipalityLinked)mydata, TransformToPGObject.GetMunicipalityPGObject); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((MunicipalityLinked)mypgdata, "municipalities"); + myupdateresult = await SaveRavenObjectToPG( + (MunicipalityLinked)mypgdata, + "municipalities" + ); break; case "district": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((DistrictLinked)mydata, TransformToPGObject.GetDistrictPGObject); + mypgdata = TransformToPGObject.GetPGObject( + (DistrictLinked)mydata, + TransformToPGObject.GetDistrictPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((DistrictLinked)mypgdata, "districts"); + myupdateresult = await SaveRavenObjectToPG( + (DistrictLinked)mypgdata, + "districts" + ); break; case "experiencearea": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((ExperienceAreaLinked)mydata, TransformToPGObject.GetExperienceAreaPGObject); + mypgdata = TransformToPGObject.GetPGObject< + ExperienceAreaLinked, + ExperienceAreaLinked + >( + (ExperienceAreaLinked)mydata, + TransformToPGObject.GetExperienceAreaPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((ExperienceAreaLinked)mypgdata, "experienceareas"); + myupdateresult = await SaveRavenObjectToPG( + (ExperienceAreaLinked)mypgdata, + "experienceareas" + ); break; case "skiarea": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((SkiAreaLinked)mydata, TransformToPGObject.GetSkiAreaPGObject); + mypgdata = TransformToPGObject.GetPGObject( + (SkiAreaLinked)mydata, + TransformToPGObject.GetSkiAreaPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((SkiAreaLinked)mypgdata, "skiareas"); + myupdateresult = await SaveRavenObjectToPG( + (SkiAreaLinked)mypgdata, + "skiareas" + ); break; case "skiregion": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((SkiRegionLinked)mydata, TransformToPGObject.GetSkiRegionPGObject); + mypgdata = TransformToPGObject.GetPGObject< + SkiRegionLinked, + SkiRegionLinked + >((SkiRegionLinked)mydata, TransformToPGObject.GetSkiRegionPGObject); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((SkiRegionLinked)mypgdata, "skiregions"); + myupdateresult = await SaveRavenObjectToPG( + (SkiRegionLinked)mypgdata, + "skiregions" + ); break; case "article": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((ArticlesLinked)mydata, TransformToPGObject.GetArticlePGObject); + mypgdata = TransformToPGObject.GetPGObject( + (ArticlesLinked)mydata, + TransformToPGObject.GetArticlePGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((ArticlesLinked)mypgdata, "articles"); + myupdateresult = await SaveRavenObjectToPG( + (ArticlesLinked)mypgdata, + "articles" + ); break; case "odhtag": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((ODHTagLinked)mydata, TransformToPGObject.GetODHTagPGObject); + mypgdata = TransformToPGObject.GetPGObject( + (ODHTagLinked)mydata, + TransformToPGObject.GetODHTagPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((ODHTagLinked)mypgdata, "smgtags"); + myupdateresult = await SaveRavenObjectToPG( + (ODHTagLinked)mypgdata, + "smgtags" + ); break; case "measuringpoint": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken, "Weather/Measuringpoint/"); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken, + "Weather/Measuringpoint/" + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((MeasuringpointLinked)mydata, TransformToPGObject.GetMeasuringpointPGObject); + mypgdata = TransformToPGObject.GetPGObject< + MeasuringpointLinked, + MeasuringpointLinked + >( + (MeasuringpointLinked)mydata, + TransformToPGObject.GetMeasuringpointPGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((MeasuringpointLinked)mypgdata, "measuringpoints"); + myupdateresult = await SaveRavenObjectToPG( + (MeasuringpointLinked)mypgdata, + "measuringpoints" + ); //Check if data has to be reduced and save it - if (ReduceDataTransformer.ReduceDataCheck((MeasuringpointLinked)mypgdata) == true) + if ( + ReduceDataTransformer.ReduceDataCheck( + (MeasuringpointLinked)mypgdata + ) == true + ) { - var reducedobject = ReduceDataTransformer.GetReducedObject((MeasuringpointLinked)mypgdata, ReduceDataTransformer.CopyLTSMeasuringpointToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((MeasuringpointLinkedReduced)reducedobject, "measuringpoints"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (MeasuringpointLinked)mypgdata, + ReduceDataTransformer.CopyLTSMeasuringpointToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (MeasuringpointLinkedReduced)reducedobject, + "measuringpoints" + ); } break; case "venue": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((DDVenue)mydata, TransformToPGObject.GetVenuePGObject); + mypgdata = TransformToPGObject.GetPGObject( + (DDVenue)mydata, + TransformToPGObject.GetVenuePGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((DDVenue)mypgdata, "venues"); + myupdateresult = await SaveRavenObjectToPG( + (DDVenue)mypgdata, + "venues" + ); //Check if data has to be reduced and save it if (ReduceDataTransformer.ReduceDataCheck((DDVenue)mypgdata) == true) { - var reducedobject = ReduceDataTransformer.GetReducedObject((DDVenue)mypgdata, ReduceDataTransformer.CopyLTSVenueToReducedObject); - - updateresultreduced = await SaveRavenObjectToPG((DDVenueReduced)reducedobject, "venues"); + var reducedobject = ReduceDataTransformer.GetReducedObject( + (DDVenue)mypgdata, + ReduceDataTransformer.CopyLTSVenueToReducedObject + ); + + updateresultreduced = await SaveRavenObjectToPG( + (DDVenueReduced)reducedobject, + "venues" + ); } break; case "wine": - mydata = await GetDataFromRaven.GetRavenData(datatype, id, settings.RavenConfig.ServiceUrl, settings.RavenConfig.User, settings.RavenConfig.Password, cancellationToken); + mydata = await GetDataFromRaven.GetRavenData( + datatype, + id, + settings.RavenConfig.ServiceUrl, + settings.RavenConfig.User, + settings.RavenConfig.Password, + cancellationToken + ); if (mydata != null) - mypgdata = TransformToPGObject.GetPGObject((WineLinked)mydata, TransformToPGObject.GetWinePGObject); + mypgdata = TransformToPGObject.GetPGObject( + (WineLinked)mydata, + TransformToPGObject.GetWinePGObject + ); else throw new Exception("No data found!"); - myupdateresult = await SaveRavenObjectToPG((WineLinked)mypgdata, "wines"); + myupdateresult = await SaveRavenObjectToPG( + (WineLinked)mypgdata, + "wines" + ); break; @@ -356,16 +747,27 @@ public async Task> GetFromRavenAndTransformToPGObjec throw new Exception("no match found"); } - return Tuple.Create(mypgdata.Id, GenericResultsHelper.MergeUpdateDetail(new List { myupdateresult, updateresultreduced })); + return Tuple.Create( + mypgdata.Id, + GenericResultsHelper.MergeUpdateDetail( + new List { myupdateresult, updateresultreduced } + ) + ); } - private async Task SaveRavenObjectToPG(T datatosave, string table) where T : IIdentifiable, IImportDateassigneable, IMetaData, ILicenseInfo + private async Task SaveRavenObjectToPG(T datatosave, string table) + where T : IIdentifiable, IImportDateassigneable, IMetaData, ILicenseInfo { datatosave._Meta.LastUpdate = datatosave.LastChange; var result = await QueryFactory.UpsertData(datatosave, table); - return new UpdateDetail() { created = result.created, updated = result.updated, deleted = result.deleted }; + return new UpdateDetail() + { + created = result.created, + updated = result.updated, + deleted = result.deleted + }; } #endregion diff --git a/OdhApiImporter/Helpers/SIAG/SIAGImportHelper.cs b/OdhApiImporter/Helpers/SIAG/SIAGImportHelper.cs index 63433084b..77217834b 100644 --- a/OdhApiImporter/Helpers/SIAG/SIAGImportHelper.cs +++ b/OdhApiImporter/Helpers/SIAG/SIAGImportHelper.cs @@ -14,11 +14,8 @@ namespace OdhApiImporter.Helpers { public class SIAGImportHelper : ImportHelper, IImportHelper { - public SIAGImportHelper(ISettings settings, QueryFactory queryfactory, string table) : base(settings, queryfactory, table) - { - - } - + public SIAGImportHelper(ISettings settings, QueryFactory queryfactory, string table) + : base(settings, queryfactory, table) { } #region SIAG Weather @@ -27,7 +24,10 @@ public SIAGImportHelper(ISettings settings, QueryFactory queryfactory, string ta /// /// /// - public async Task SaveWeatherToHistoryTable(CancellationToken cancellationToken, string? id = null) + public async Task SaveWeatherToHistoryTable( + CancellationToken cancellationToken, + string? id = null + ) { string? weatherresponsetaskde = ""; string? weatherresponsetaskit = ""; @@ -35,24 +35,67 @@ public async Task SaveWeatherToHistoryTable(CancellationToken canc if (!String.IsNullOrEmpty(id)) { - weatherresponsetaskde = await SIAG.GetWeatherData.GetSiagWeatherData("de", settings.SiagConfig.Username, settings.SiagConfig.Password, true, id); - weatherresponsetaskit = await SIAG.GetWeatherData.GetSiagWeatherData("it", settings.SiagConfig.Username, settings.SiagConfig.Password, true, id); - weatherresponsetasken = await SIAG.GetWeatherData.GetSiagWeatherData("en", settings.SiagConfig.Username, settings.SiagConfig.Password, true, id); + weatherresponsetaskde = await SIAG.GetWeatherData.GetSiagWeatherData( + "de", + settings.SiagConfig.Username, + settings.SiagConfig.Password, + true, + id + ); + weatherresponsetaskit = await SIAG.GetWeatherData.GetSiagWeatherData( + "it", + settings.SiagConfig.Username, + settings.SiagConfig.Password, + true, + id + ); + weatherresponsetasken = await SIAG.GetWeatherData.GetSiagWeatherData( + "en", + settings.SiagConfig.Username, + settings.SiagConfig.Password, + true, + id + ); } else { - weatherresponsetaskde = await SIAG.GetWeatherData.GetSiagWeatherData("de", settings.SiagConfig.Username, settings.SiagConfig.Password, true); - weatherresponsetaskit = await SIAG.GetWeatherData.GetSiagWeatherData("it", settings.SiagConfig.Username, settings.SiagConfig.Password, true); - weatherresponsetasken = await SIAG.GetWeatherData.GetSiagWeatherData("en", settings.SiagConfig.Username, settings.SiagConfig.Password, true); + weatherresponsetaskde = await SIAG.GetWeatherData.GetSiagWeatherData( + "de", + settings.SiagConfig.Username, + settings.SiagConfig.Password, + true + ); + weatherresponsetaskit = await SIAG.GetWeatherData.GetSiagWeatherData( + "it", + settings.SiagConfig.Username, + settings.SiagConfig.Password, + true + ); + weatherresponsetasken = await SIAG.GetWeatherData.GetSiagWeatherData( + "en", + settings.SiagConfig.Username, + settings.SiagConfig.Password, + true + ); } - if (!String.IsNullOrEmpty(weatherresponsetaskde) && !String.IsNullOrEmpty(weatherresponsetaskit) && !String.IsNullOrEmpty(weatherresponsetasken)) + if ( + !String.IsNullOrEmpty(weatherresponsetaskde) + && !String.IsNullOrEmpty(weatherresponsetaskit) + && !String.IsNullOrEmpty(weatherresponsetasken) + ) { //Save all Responses to rawdata table - var siagweatherde = JsonConvert.DeserializeObject(weatherresponsetaskde); - var siagweatherit = JsonConvert.DeserializeObject(weatherresponsetaskit); - var siagweatheren = JsonConvert.DeserializeObject(weatherresponsetasken); + var siagweatherde = JsonConvert.DeserializeObject( + weatherresponsetaskde + ); + var siagweatherit = JsonConvert.DeserializeObject( + weatherresponsetaskit + ); + var siagweatheren = JsonConvert.DeserializeObject( + weatherresponsetasken + ); RawDataStore rawData = new RawDataStore(); rawData.importdate = DateTime.Now; @@ -61,15 +104,33 @@ public async Task SaveWeatherToHistoryTable(CancellationToken canc rawData.datasource = "siag"; rawData.sourceinterface = "weatherbulletin"; rawData.sourceurl = "http://daten.buergernetz.bz.it/services/weather/bulletin"; - rawData.raw = JsonConvert.SerializeObject(new { de = siagweatherde, it = siagweatherit, en = siagweatheren }); + rawData.raw = JsonConvert.SerializeObject( + new { de = siagweatherde, it = siagweatherit, en = siagweatheren } + ); - var insertresultraw = await QueryFactory.Query("rawdata") - .InsertGetIdAsync(rawData); + var insertresultraw = await QueryFactory + .Query("rawdata") + .InsertGetIdAsync(rawData); //Save parsed Response to measurement history table - var odhweatherresultde = await SIAG.GetWeatherData.ParseSiagWeatherDataToODHWeather("de", settings.XmlConfig.XmldirWeather, weatherresponsetaskde, true); - var odhweatherresultit = await SIAG.GetWeatherData.ParseSiagWeatherDataToODHWeather("it", settings.XmlConfig.XmldirWeather, weatherresponsetaskit, true); - var odhweatherresulten = await SIAG.GetWeatherData.ParseSiagWeatherDataToODHWeather("en", settings.XmlConfig.XmldirWeather, weatherresponsetasken, true); + var odhweatherresultde = await SIAG.GetWeatherData.ParseSiagWeatherDataToODHWeather( + "de", + settings.XmlConfig.XmldirWeather, + weatherresponsetaskde, + true + ); + var odhweatherresultit = await SIAG.GetWeatherData.ParseSiagWeatherDataToODHWeather( + "it", + settings.XmlConfig.XmldirWeather, + weatherresponsetaskit, + true + ); + var odhweatherresulten = await SIAG.GetWeatherData.ParseSiagWeatherDataToODHWeather( + "en", + settings.XmlConfig.XmldirWeather, + weatherresponsetasken, + true + ); //Insert into Measuringhistorytable //var insertresultde = await QueryFactory.Query("weatherdatahistory") @@ -91,17 +152,26 @@ public async Task SaveWeatherToHistoryTable(CancellationToken canc myweatherhistory.LastChange = odhweatherresultde.date; myweatherhistory.Shortname = odhweatherresultde.evolutiontitle; - - var insertresult = await QueryFactory.UpsertData(myweatherhistory, "weatherdatahistory", insertresultraw, true); + var insertresult = await QueryFactory.UpsertData( + myweatherhistory, + "weatherdatahistory", + insertresultraw, + true + ); //var insertresult = await QueryFactory.Query("weatherdatahistory") // .InsertAsync(new JsonBDataRaw { id = odhweatherresultde.Id.ToString(), data = new JsonRaw(myweatherhistory), rawdataid = insertresultraw }); ////Save to PG - ////Check if data exists + ////Check if data exists //var result = await QueryFactory.UpsertData(odhactivitypoi!, "weatherdatahistory", insertresultraw); - return new UpdateDetail() { created = insertresult.created, updated = insertresult.updated, deleted = insertresult.deleted }; + return new UpdateDetail() + { + created = insertresult.created, + updated = insertresult.updated, + deleted = insertresult.deleted + }; } else throw new Exception("No weatherdata received from source!"); @@ -111,7 +181,10 @@ public async Task SaveWeatherToHistoryTable(CancellationToken canc #region SIAG Museumdata - public async Task SaveDataToODH(DateTime? lastchanged = null, CancellationToken cancellationToken = default) + public async Task SaveDataToODH( + DateTime? lastchanged = null, + CancellationToken cancellationToken = default + ) { //Import the actual museums List from SIAG var museumslist = await ImportList(cancellationToken); @@ -120,7 +193,9 @@ public async Task SaveDataToODH(DateTime? lastchanged = null, Canc //If in the DB there are museums no more listed in the siag response set this data to inactive var deleteresult = await SetDataNotinListToInactive(museumslist, cancellationToken); - return GenericResultsHelper.MergeUpdateDetail(new List() { updateresult, deleteresult }); + return GenericResultsHelper.MergeUpdateDetail( + new List() { updateresult, deleteresult } + ); } private async Task ImportList(CancellationToken cancellationToken) @@ -133,12 +208,16 @@ private async Task ImportList(CancellationToken cancellationToken) XNamespace ns = "http://service.kks.siag"; XNamespace ax211 = "http://data.service.kks.siag/xsd"; - var mymuseumlist2 = myxml.Root?.Element(ns + "return")?.Elements(ax211 + "museums") ?? Enumerable.Empty(); + var mymuseumlist2 = + myxml.Root?.Element(ns + "return")?.Elements(ax211 + "museums") + ?? Enumerable.Empty(); foreach (XElement idtoimport in mymuseumlist2) { XElement mymuseum = new XElement("Museum"); - mymuseum.Add(new XAttribute("ID", idtoimport.Element(ax211 + "museId")?.Value ?? "")); + mymuseum.Add( + new XAttribute("ID", idtoimport.Element(ax211 + "museId")?.Value ?? "") + ); mymuseum.Add(new XAttribute("PLZ", idtoimport.Element(ax211 + "plz")?.Value ?? "")); mymuseums.Add(mymuseum); @@ -146,12 +225,26 @@ private async Task ImportList(CancellationToken cancellationToken) mymuseumlist.Add(mymuseums); - WriteLog.LogToConsole("", "dataimport", "list.siagmuseum", new ImportLog() { sourceid = "", sourceinterface = "siag.museum", success = true, error = "" }); + WriteLog.LogToConsole( + "", + "dataimport", + "list.siagmuseum", + new ImportLog() + { + sourceid = "", + sourceinterface = "siag.museum", + success = true, + error = "" + } + ); return mymuseumlist; } - private async Task ImportData(XDocument mymuseumlist, CancellationToken cancellationToken) + private async Task ImportData( + XDocument mymuseumlist, + CancellationToken cancellationToken + ) { string museumid = ""; @@ -166,12 +259,28 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation //Load ValidTagsfor Categories var validtagsforcategories = default(IEnumerable); //For AdditionalInfos - List languagelistcategories = new List() { "de", "it", "en", "nl", "cs", "pl", "fr", "ru" }; + List languagelistcategories = new List() + { + "de", + "it", + "en", + "nl", + "cs", + "pl", + "fr", + "ru" + }; //Getting valid Tags for Museums - validtagsforcategories = await ODHTagHelper.GetODHTagsValidforTranslations(QueryFactory, new List() { "Kultur Sehenswürdigkeiten" }); - - foreach (XElement mymuseumelement in mymuseumroot?.Elements("Museum") ?? Enumerable.Empty()) + validtagsforcategories = await ODHTagHelper.GetODHTagsValidforTranslations( + QueryFactory, + new List() { "Kultur Sehenswürdigkeiten" } + ); + + foreach ( + XElement mymuseumelement in mymuseumroot?.Elements("Museum") + ?? Enumerable.Empty() + ) { museumid = mymuseumelement.Attribute("ID")?.Value ?? ""; string plz = mymuseumelement.Attribute("PLZ")?.Value ?? ""; @@ -180,15 +289,16 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation var mymuseumdata = await SIAG.GetMuseumFromSIAG.GetMuseumDetail(museumid); var mymuseumxml = mymuseumdata?.Root?.Element(ns + "return"); - var mymuseumquery = QueryFactory.Query("smgpois") + var mymuseumquery = QueryFactory + .Query("smgpois") .Select("data") .WhereRaw("data->>'CustomId' = $$", museumid.ToLower()); - var mymuseum = await mymuseumquery.GetFirstOrDefaultAsObject(); + var mymuseum = + await mymuseumquery.GetFirstOrDefaultAsObject(); if (mymuseum == null) { - //Neuen Datensatz mymuseum = new ODHActivityPoiLinked(); mymuseum.FirstImport = DateTime.Now; @@ -215,12 +325,18 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation mymuseum.Shortname = mymuseum.Detail["de"].Title?.Trim(); //Suedtirol Type laden - var mysmgmaintype = await ODHTagHelper.GeODHTagByID(QueryFactory, "Kultur Sehenswürdigkeiten"); + var mysmgmaintype = await ODHTagHelper.GeODHTagByID( + QueryFactory, + "Kultur Sehenswürdigkeiten" + ); var mysmgsubtype = await ODHTagHelper.GeODHTagByID(QueryFactory, "Museen"); var mysmgpoipoitype = new List(); List museumskategorien = new List(); - var mymuseumscategoriesstrings = mymuseum.PoiProperty["de"].Where(x => x.Name == "categories").Select(x => x.Value).ToList(); + var mymuseumscategoriesstrings = mymuseum.PoiProperty["de"] + .Where(x => x.Name == "categories") + .Select(x => x.Value) + .ToList(); foreach (var mymuseumscategoriesstring in mymuseumscategoriesstrings) { var splittedlist = mymuseumscategoriesstring?.Split(',').ToList() ?? new(); @@ -231,7 +347,10 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation { museumskategorien.Add(splitted.Trim()); - var mykategoriequery = await ODHTagHelper.GeODHTagByID(QueryFactory, "Museen " + splitted.Trim()); + var mykategoriequery = await ODHTagHelper.GeODHTagByID( + QueryFactory, + "Museen " + splitted.Trim() + ); if (mykategoriequery is { }) mysmgpoipoitype.Add(mykategoriequery); } @@ -253,10 +372,12 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation { foreach (var mysmgpoipoitypel in mysmgpoipoitype) { - if (mysmgpoipoitypel.Id is { } && !mysmgtags.Contains(mysmgpoipoitypel.Id.ToLower())) + if ( + mysmgpoipoitypel.Id is { } + && !mysmgtags.Contains(mysmgpoipoitypel.Id.ToLower()) + ) mysmgtags.Add(mysmgpoipoitypel.Id.ToLower()); } - } mymuseum.SmgTags = mysmgtags.ToList(); @@ -279,36 +400,63 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation additional.Language = langcat; additional.MainType = mysmgmaintype?.TagName[langcat]; additional.SubType = mysmgsubtype?.TagName[langcat]; - additional.PoiType = mysmgpoipoitype.Count > 0 ? mysmgpoipoitype.FirstOrDefault()?.TagName[langcat] : ""; + additional.PoiType = + mysmgpoipoitype.Count > 0 + ? mysmgpoipoitype.FirstOrDefault()?.TagName[langcat] + : ""; mymuseum.AdditionalPoiInfos.TryAddOrUpdate(langcat, additional); } //Setting Categorization by Valid Tags - var currentcategories = validtagsforcategories.Where(x => mymuseum.SmgTags.Contains(x.Id.ToLower())); + var currentcategories = validtagsforcategories.Where( + x => mymuseum.SmgTags.Contains(x.Id.ToLower()) + ); foreach (var smgtagtotranslate in currentcategories) { foreach (string languagecategory in languagelistcategories) { if (mymuseum.AdditionalPoiInfos![languagecategory].Categories == null) - mymuseum.AdditionalPoiInfos[languagecategory].Categories = new List(); - - if (smgtagtotranslate.TagName.ContainsKey(languagecategory) && (!mymuseum.AdditionalPoiInfos?[languagecategory].Categories?.Contains(smgtagtotranslate.TagName[languagecategory].Trim()) ?? false)) - mymuseum.AdditionalPoiInfos![languagecategory]!.Categories!.Add(smgtagtotranslate.TagName[languagecategory].Trim()); + mymuseum.AdditionalPoiInfos[languagecategory].Categories = + new List(); + + if ( + smgtagtotranslate.TagName.ContainsKey(languagecategory) + && ( + !mymuseum.AdditionalPoiInfos?[ + languagecategory + ].Categories?.Contains( + smgtagtotranslate.TagName[languagecategory].Trim() + ) ?? false + ) + ) + mymuseum.AdditionalPoiInfos![languagecategory]!.Categories!.Add( + smgtagtotranslate.TagName[languagecategory].Trim() + ); } } - //Get Locationinfo by given GPS Points if (mymuseum.GpsInfo != null && mymuseum.GpsInfo.Count > 0) { - if (mymuseum.GpsInfo.FirstOrDefault()?.Latitude != 0 && mymuseum.GpsInfo.FirstOrDefault()?.Longitude != 0) + if ( + mymuseum.GpsInfo.FirstOrDefault()?.Latitude != 0 + && mymuseum.GpsInfo.FirstOrDefault()?.Longitude != 0 + ) { - var district = await GetLocationInfo.GetNearestDistrictbyGPS(QueryFactory, mymuseum.GpsInfo.FirstOrDefault()!.Latitude, mymuseum.GpsInfo.FirstOrDefault()!.Longitude, 30000); + var district = await GetLocationInfo.GetNearestDistrictbyGPS( + QueryFactory, + mymuseum.GpsInfo.FirstOrDefault()!.Latitude, + mymuseum.GpsInfo.FirstOrDefault()!.Longitude, + 30000 + ); if (district != null) { - var locinfo = await GetLocationInfo.GetTheLocationInfoDistrict(QueryFactory, district.Id); + var locinfo = await GetLocationInfo.GetTheLocationInfoDistrict( + QueryFactory, + district.Id + ); mymuseum.LocationInfo = locinfo; mymuseum.TourismorganizationId = locinfo.TvInfo?.Id; @@ -320,9 +468,17 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation if (mymuseum.LocationInfo == null) { if (gemeindeid.StartsWith("3")) - mymuseum.LocationInfo = await GetLocationInfo.GetTheLocationInfoMunicipality_Siag(QueryFactory, gemeindeid); + mymuseum.LocationInfo = + await GetLocationInfo.GetTheLocationInfoMunicipality_Siag( + QueryFactory, + gemeindeid + ); if (gemeindeid.StartsWith("8")) - mymuseum.LocationInfo = await GetLocationInfo.GetTheLocationInfoDistrict_Siag(QueryFactory, gemeindeid); + mymuseum.LocationInfo = + await GetLocationInfo.GetTheLocationInfoDistrict_Siag( + QueryFactory, + gemeindeid + ); mymuseum.TourismorganizationId = mymuseum.LocationInfo?.TvInfo?.Id; } @@ -331,7 +487,7 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation { //mymuseum.CustomId = siagid; mymuseum.Active = true; - //mymuseum.SmgActive = true; + //mymuseum.SmgActive = true; if (mymuseumxml is { }) SIAG.Parser.ParseMuseum.ParseMuseumToPG(mymuseum, mymuseumxml, plz); @@ -343,13 +499,18 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation subtype = "Naturparkhäuser"; //Suedtirol Type laden - var mysmgmaintype = await ODHTagHelper.GeODHTagByID(QueryFactory, "Kultur Sehenswürdigkeiten"); + var mysmgmaintype = await ODHTagHelper.GeODHTagByID( + QueryFactory, + "Kultur Sehenswürdigkeiten" + ); var mysmgsubtype = await ODHTagHelper.GeODHTagByID(QueryFactory, subtype); var mysmgpoipoitype = new List(); - List museumskategorien = new List(); - var mymuseumscategoriesstrings = mymuseum.PoiProperty["de"].Where(x => x.Name == "categories").Select(x => x.Value).ToList(); + var mymuseumscategoriesstrings = mymuseum.PoiProperty["de"] + .Where(x => x.Name == "categories") + .Select(x => x.Value) + .ToList(); foreach (var mymuseumscategoriesstring in mymuseumscategoriesstrings) { var splittedlist = mymuseumscategoriesstring?.Split(',').ToList() ?? new(); @@ -360,7 +521,10 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation { museumskategorien.Add(splitted.Trim()); - var mykategoriequery = await ODHTagHelper.GeODHTagByID(QueryFactory, "Museen " + splitted.Trim()); + var mykategoriequery = await ODHTagHelper.GeODHTagByID( + QueryFactory, + "Museen " + splitted.Trim() + ); if (mykategoriequery is { }) mysmgpoipoitype.Add(mykategoriequery); } @@ -371,15 +535,24 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation mymuseum.SubType = mysmgsubtype?.Shortname; mymuseum.SmgTags ??= new List(); - if (mysmgmaintype?.Id is { } && !mymuseum.SmgTags.Contains(mysmgmaintype.Id.ToLower())) + if ( + mysmgmaintype?.Id is { } + && !mymuseum.SmgTags.Contains(mysmgmaintype.Id.ToLower()) + ) mymuseum.SmgTags.Add(mysmgmaintype.Id.ToLower()); - if (mysmgsubtype?.Id is { } && !mymuseum.SmgTags.Contains(mysmgsubtype.Id.ToLower())) + if ( + mysmgsubtype?.Id is { } + && !mymuseum.SmgTags.Contains(mysmgsubtype.Id.ToLower()) + ) mymuseum.SmgTags.Add(mysmgsubtype.Id.ToLower()); if (mysmgpoipoitype.Count > 0) { foreach (var mysmgpoitypel in mysmgpoipoitype) { - if (mysmgpoitypel.Id is { } && !mymuseum.SmgTags.Contains(mysmgpoitypel.Id.ToLower())) + if ( + mysmgpoitypel.Id is { } + && !mymuseum.SmgTags.Contains(mysmgpoitypel.Id.ToLower()) + ) mymuseum.SmgTags.Add(mysmgpoitypel.Id.ToLower()); } } @@ -389,28 +562,44 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation else mymuseum.PoiType = ""; - foreach (var langcat in languagelistcategories) { AdditionalPoiInfos additional = new AdditionalPoiInfos(); additional.Language = langcat; additional.MainType = mysmgmaintype?.TagName[langcat]; additional.SubType = mysmgsubtype?.TagName[langcat]; - additional.PoiType = mysmgpoipoitype.Count > 0 ? mysmgpoipoitype.FirstOrDefault()?.TagName[langcat] : ""; + additional.PoiType = + mysmgpoipoitype.Count > 0 + ? mysmgpoipoitype.FirstOrDefault()?.TagName[langcat] + : ""; mymuseum.AdditionalPoiInfos.TryAddOrUpdate(langcat, additional); } //Setting Categorization by Valid Tags - var currentcategories = validtagsforcategories.Where(x => mymuseum.SmgTags.Contains(x.Id.ToLower())); + var currentcategories = validtagsforcategories.Where( + x => mymuseum.SmgTags.Contains(x.Id.ToLower()) + ); foreach (var smgtagtotranslate in currentcategories) { foreach (var languagecategory in languagelistcategories) { if (mymuseum.AdditionalPoiInfos[languagecategory].Categories == null) - mymuseum.AdditionalPoiInfos[languagecategory].Categories = new List(); - - if (smgtagtotranslate.TagName.ContainsKey(languagecategory) && (!mymuseum.AdditionalPoiInfos[languagecategory].Categories?.Contains(smgtagtotranslate.TagName[languagecategory].Trim()) ?? false)) - mymuseum.AdditionalPoiInfos[languagecategory].Categories?.Add(smgtagtotranslate.TagName[languagecategory].Trim()); + mymuseum.AdditionalPoiInfos[languagecategory].Categories = + new List(); + + if ( + smgtagtotranslate.TagName.ContainsKey(languagecategory) + && ( + !mymuseum.AdditionalPoiInfos[ + languagecategory + ].Categories?.Contains( + smgtagtotranslate.TagName[languagecategory].Trim() + ) ?? false + ) + ) + mymuseum.AdditionalPoiInfos[languagecategory].Categories?.Add( + smgtagtotranslate.TagName[languagecategory].Trim() + ); } } } @@ -419,37 +608,68 @@ private async Task ImportData(XDocument mymuseumlist, Cancellation mymuseum.Source = "SIAG"; mymuseum.SyncSourceInterface = "museumdata"; mymuseum.SyncUpdateMode = "Full"; - mymuseum.LastChange = DateTime.Now; + mymuseum.LastChange = DateTime.Now; //Setting LicenseInfo - mymuseum.LicenseInfo = Helper.LicenseHelper.GetLicenseInfoobject(mymuseum, Helper.LicenseHelper.GetLicenseforOdhActivityPoi); + mymuseum.LicenseInfo = Helper.LicenseHelper.GetLicenseInfoobject( + mymuseum, + Helper.LicenseHelper.GetLicenseforOdhActivityPoi + ); //Special get all Taglist and traduce it on import - await GenericTaggingHelper.AddMappingToODHActivityPoi(mymuseum, settings.JsonConfig.Jsondir); + await GenericTaggingHelper.AddMappingToODHActivityPoi( + mymuseum, + settings.JsonConfig.Jsondir + ); - if (mymuseumdata?.Root is { }) - { - var result = await InsertDataToDB(mymuseum, new KeyValuePair(museumid, mymuseumdata.Root)); + if (mymuseumdata?.Root is { }) + { + var result = await InsertDataToDB( + mymuseum, + new KeyValuePair(museumid, mymuseumdata.Root) + ); newcounter = newcounter + result.created ?? 0; updatecounter = updatecounter + result.updated ?? 0; if (mymuseum.Id is { }) - WriteLog.LogToConsole(mymuseum.Id, "dataimport", "single.siagmuseum", new ImportLog() { sourceid = mymuseum.Id, sourceinterface = "siag.museum", success = true, error = "" }); + WriteLog.LogToConsole( + mymuseum.Id, + "dataimport", + "single.siagmuseum", + new ImportLog() + { + sourceid = mymuseum.Id, + sourceinterface = "siag.museum", + success = true, + error = "" + } + ); } } - return new UpdateDetail() { created = newcounter, updated = updatecounter, deleted = 0 }; + return new UpdateDetail() + { + created = newcounter, + updated = updatecounter, + deleted = 0 + }; } - - private async Task SetDataNotinListToInactive(XDocument mymuseumlist, CancellationToken cancellationToken) + + private async Task SetDataNotinListToInactive( + XDocument mymuseumlist, + CancellationToken cancellationToken + ) { - List mymuseumroot = mymuseumlist.Root?.Elements("Museum").Select(x => x.Attribute("ID")?.Value).ToList() ?? new(); - - var mymuseumquery = QueryFactory.Query("smgpois") + List mymuseumroot = + mymuseumlist.Root?.Elements("Museum").Select(x => x.Attribute("ID")?.Value).ToList() + ?? new(); + + var mymuseumquery = QueryFactory + .Query("smgpois") .Select("data->>'CustomId'") .Where("gen_syncsourceinterface", "museumdata"); var mymuseumsonraven = await mymuseumquery.GetAsync(); - + var idstodelete = mymuseumsonraven.Where(p => !mymuseumroot.Any(p2 => p2 == p)); int updateresult = 0; @@ -462,22 +682,38 @@ private async Task SetDataNotinListToInactive(XDocument mymuseumli updateresult = updateresult + result.Item1; deleteresult = deleteresult + result.Item2; } - - return new UpdateDetail() { created = 0, updated = updateresult, deleted = deleteresult }; + + return new UpdateDetail() + { + created = 0, + updated = updateresult, + deleted = deleteresult + }; } - private async Task InsertDataToDB(ODHActivityPoiLinked odhactivitypoi, KeyValuePair siagmuseumdata) + private async Task InsertDataToDB( + ODHActivityPoiLinked odhactivitypoi, + KeyValuePair siagmuseumdata + ) { try - { + { odhactivitypoi.Id = odhactivitypoi.Id?.ToLower(); //Set LicenseInfo - odhactivitypoi.LicenseInfo = Helper.LicenseHelper.GetLicenseInfoobject(odhactivitypoi, Helper.LicenseHelper.GetLicenseforOdhActivityPoi); + odhactivitypoi.LicenseInfo = + Helper.LicenseHelper.GetLicenseInfoobject( + odhactivitypoi, + Helper.LicenseHelper.GetLicenseforOdhActivityPoi + ); var rawdataid = await InsertInRawDataDB(siagmuseumdata); - return await QueryFactory.UpsertData(odhactivitypoi, "smgpois", rawdataid); + return await QueryFactory.UpsertData( + odhactivitypoi, + "smgpois", + rawdataid + ); } catch (Exception ex) { @@ -488,16 +724,17 @@ private async Task InsertDataToDB(ODHActivityPoiLinked odhactivity private async Task InsertInRawDataDB(KeyValuePair siagmuseumdata) { return await QueryFactory.InsertInRawtableAndGetIdAsync( - new RawDataStore() - { - datasource = "siag", - importdate = DateTime.Now, - raw = siagmuseumdata.Value.ToString(), - sourceinterface = "museumdata", - sourceid = siagmuseumdata.Key, - sourceurl = "https://musport.prov.bz.it/musport/services/MuseumsService/", - type = "odhactivitypoi-museum" - }); + new RawDataStore() + { + datasource = "siag", + importdate = DateTime.Now, + raw = siagmuseumdata.Value.ToString(), + sourceinterface = "museumdata", + sourceid = siagmuseumdata.Key, + sourceurl = "https://musport.prov.bz.it/musport/services/MuseumsService/", + type = "odhactivitypoi-museum" + } + ); } #endregion } diff --git a/OdhApiImporter/Helpers/STA/STAImportHelper.cs b/OdhApiImporter/Helpers/STA/STAImportHelper.cs index 5e2096f91..24ff17a94 100644 --- a/OdhApiImporter/Helpers/STA/STAImportHelper.cs +++ b/OdhApiImporter/Helpers/STA/STAImportHelper.cs @@ -32,7 +32,10 @@ private static async Task ReadStringDataManual(HttpRequest request) } } - public async Task PostVendingPointsFromSTA(HttpRequest request, CancellationToken cancellationToken) + public async Task PostVendingPointsFromSTA( + HttpRequest request, + CancellationToken cancellationToken + ) { string jsonContent = await ReadStringDataManual(request); @@ -44,7 +47,10 @@ public async Task PostVendingPointsFromSTA(HttpRequest request, Ca throw new Exception("no Content"); } - private async Task ImportVendingPointsFromCSV(string csvcontent, CancellationToken cancellationToken) + private async Task ImportVendingPointsFromCSV( + string csvcontent, + CancellationToken cancellationToken + ) { var vendingpoints = await STA.GetDataFromSTA.ImportCSVFromSTA(csvcontent); @@ -58,25 +64,40 @@ private async Task ImportVendingPointsFromCSV(string csvcontent, C foreach (var vendingpoint in vendingpoints.records) { //Parse to ODHActivityPoi - var odhactivitypoi = STA.ParseSTAPois.ParseSTAVendingPointToODHActivityPoi(vendingpoint); + var odhactivitypoi = STA.ParseSTAPois.ParseSTAVendingPointToODHActivityPoi( + vendingpoint + ); if (odhactivitypoi != null) { //MetaData //odhactivitypoi._Meta = MetadataHelper.GetMetadataobject(odhactivitypoi, MetadataHelper.GetMetadataforOdhActivityPoi); //GetMetadata(data.Id, "odhactivitypoi", sourcemeta, data.LastChange); //LicenseInfo //License - odhactivitypoi.LicenseInfo = LicenseHelper.GetLicenseforOdhActivityPoi(odhactivitypoi); + odhactivitypoi.LicenseInfo = LicenseHelper.GetLicenseforOdhActivityPoi( + odhactivitypoi + ); if (odhactivitypoi.GpsPoints.ContainsKey("position")) { //Get Nearest District - var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult(odhactivitypoi.GpsPoints["position"].Latitude, odhactivitypoi.GpsPoints["position"].Longitude, 10000); - var nearestdistrict = await GetLocationInfo.GetNearestDistrict(QueryFactory, geosearchresult, 1); + var geosearchresult = Helper.GeoSearchHelper.GetPGGeoSearchResult( + odhactivitypoi.GpsPoints["position"].Latitude, + odhactivitypoi.GpsPoints["position"].Longitude, + 10000 + ); + var nearestdistrict = await GetLocationInfo.GetNearestDistrict( + QueryFactory, + geosearchresult, + 1 + ); if (nearestdistrict != null && nearestdistrict.Count() > 0) { //Get LocationInfo Object - var locationinfo = await GetLocationInfo.GetTheLocationInfoDistrict(QueryFactory, nearestdistrict.FirstOrDefault()?.Id); + var locationinfo = await GetLocationInfo.GetTheLocationInfoDistrict( + QueryFactory, + nearestdistrict.FirstOrDefault()?.Id + ); if (locationinfo != null) odhactivitypoi.LocationInfo = locationinfo; @@ -84,33 +105,50 @@ private async Task ImportVendingPointsFromCSV(string csvcontent, C } //Adding TypeInfo Additional - odhactivitypoi.AdditionalPoiInfos = await GetAdditionalTypeInfo.GetAdditionalTypeInfoForPoi(QueryFactory, odhactivitypoi?.SubType, new List() { "de", "it", "en" }); - - if (odhactivitypoi is { }) + odhactivitypoi.AdditionalPoiInfos = + await GetAdditionalTypeInfo.GetAdditionalTypeInfoForPoi( + QueryFactory, + odhactivitypoi?.SubType, + new List() { "de", "it", "en" } + ); + + if (odhactivitypoi is { }) { - ODHTagHelper.SetMainCategorizationForODHActivityPoi(odhactivitypoi); - - //Special get all Taglist and traduce it on import - await GenericTaggingHelper.AddMappingToODHActivityPoi(odhactivitypoi, settings.JsonConfig.Jsondir); - - //Save to Rawdatatable - var rawdataid = await InsertInRawDataDB(vendingpoint); - - //Save to PG - //Check if data exists - var result = await QueryFactory.UpsertData(odhactivitypoi, "smgpois", rawdataid); - - if (result.updated != null) - updatecounter = updatecounter + result.updated.Value; - if (result.created != null) - newcounter = newcounter + result.created.Value; - if (result.deleted != null) + ODHTagHelper.SetMainCategorizationForODHActivityPoi(odhactivitypoi); + + //Special get all Taglist and traduce it on import + await GenericTaggingHelper.AddMappingToODHActivityPoi( + odhactivitypoi, + settings.JsonConfig.Jsondir + ); + + //Save to Rawdatatable + var rawdataid = await InsertInRawDataDB(vendingpoint); + + //Save to PG + //Check if data exists + var result = await QueryFactory.UpsertData( + odhactivitypoi, + "smgpois", + rawdataid + ); + + if (result.updated != null) + updatecounter = updatecounter + result.updated.Value; + if (result.created != null) + newcounter = newcounter + result.created.Value; + if (result.deleted != null) deletecounter = deletecounter + result.deleted.Value; } } } - return new UpdateDetail() { created = newcounter, updated = updatecounter, deleted = deletecounter }; + return new UpdateDetail() + { + created = newcounter, + updated = updatecounter, + deleted = deletecounter + }; } else if (vendingpoints.Error) throw new Exception(vendingpoints.ErrorMessage); @@ -121,16 +159,17 @@ private async Task ImportVendingPointsFromCSV(string csvcontent, C private async Task InsertInRawDataDB(STA.STAVendingPoint stavendingpoint) { return await QueryFactory.InsertInRawtableAndGetIdAsync( - new RawDataStore() - { - datasource = "sta", - importdate = DateTime.Now, - raw = JsonConvert.SerializeObject(stavendingpoint), - sourceinterface = "csv", - sourceid = stavendingpoint?.STA_ID ?? "", - sourceurl = "csvfile", - type = "poi_sta_vendingpoint" - }); + new RawDataStore() + { + datasource = "sta", + importdate = DateTime.Now, + raw = JsonConvert.SerializeObject(stavendingpoint), + sourceinterface = "csv", + sourceid = stavendingpoint?.STA_ID ?? "", + sourceurl = "csvfile", + type = "poi_sta_vendingpoint" + } + ); } } } diff --git a/OdhApiImporter/Helpers/SUEDTIROLWEIN/SUEDTIROLWEINImportHelper.cs b/OdhApiImporter/Helpers/SUEDTIROLWEIN/SUEDTIROLWEINImportHelper.cs index 2cc1fa05b..2e6044368 100644 --- a/OdhApiImporter/Helpers/SUEDTIROLWEIN/SUEDTIROLWEINImportHelper.cs +++ b/OdhApiImporter/Helpers/SUEDTIROLWEIN/SUEDTIROLWEINImportHelper.cs @@ -3,7 +3,7 @@ using SuedtirolWein; using System; using System.Collections.Generic; -using System.Linq; +using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; @@ -21,14 +21,18 @@ public SuedtirolWeinImportHelper(ISettings settings, QueryFactory queryfactory) this.settings = settings; } - public async Task SaveSuedtirolWeinGastronomiesToODH(QueryFactory QueryFactory, DateTime? lastchanged = null, CancellationToken cancellationToken = default) + public async Task SaveSuedtirolWeinGastronomiesToODH( + QueryFactory QueryFactory, + DateTime? lastchanged = null, + CancellationToken cancellationToken = default + ) { var winegastrolist = await GetSuedtirolWeinGastronomiesList(cancellationToken); - foreach (var winedata in winegastrolist["de"].Root?.Elements("item") ?? Enumerable.Empty()) - { - - } + foreach ( + var winedata in winegastrolist["de"].Root?.Elements("item") + ?? Enumerable.Empty() + ) { } //var updateresult = await ImportMuseums(museumslist, cancellationToken); //SetMuseumsnotinListToInactive() //SetSuedtirolWineCompanyToInactive(documentStore, tracesource, log, winedatalistde); @@ -37,7 +41,9 @@ public async Task SaveSuedtirolWeinGastronomiesToODH(QueryFactory return new UpdateDetail(); } - public async Task> GetSuedtirolWeinGastronomiesList(CancellationToken cancellationToken = default) + public async Task> GetSuedtirolWeinGastronomiesList( + CancellationToken cancellationToken = default + ) { var winedatalistde = await GetSuedtirolWeinData.GetSueditrolWineCompaniesAsync("de"); var winedatalistit = await GetSuedtirolWeinData.GetSueditrolWineCompaniesAsync("it"); @@ -62,6 +68,5 @@ public void ImportSuedtirolWeinGastronomy(XElement winedata) { //ImportSuedtirolWineCompanySingle(documentStore, tracesource, log, winedata, mywinedata, i); } - } } diff --git a/OdhApiImporter/IBackgroundTaskQueue.cs b/OdhApiImporter/IBackgroundTaskQueue.cs index 007ccb638..6ebd3fb79 100644 --- a/OdhApiImporter/IBackgroundTaskQueue.cs +++ b/OdhApiImporter/IBackgroundTaskQueue.cs @@ -6,10 +6,10 @@ namespace OdhApiImporter { public interface IBackgroundTaskQueue { - ValueTask QueueBackgroundWorkItemAsync( - Func workItem); + ValueTask QueueBackgroundWorkItemAsync(Func workItem); ValueTask> DequeueAsync( - CancellationToken cancellationToken); + CancellationToken cancellationToken + ); } } diff --git a/OdhApiImporter/MonitorLoop.cs b/OdhApiImporter/MonitorLoop.cs index 51268e2d6..33901a701 100644 --- a/OdhApiImporter/MonitorLoop.cs +++ b/OdhApiImporter/MonitorLoop.cs @@ -14,7 +14,11 @@ public class MonitorLoop private readonly ILogger _logger; private readonly CancellationToken _cancellationToken; - public MonitorLoop(IBackgroundTaskQueue taskQueue, ILogger logger, IHostApplicationLifetime applicationLifetime) + public MonitorLoop( + IBackgroundTaskQueue taskQueue, + ILogger logger, + IHostApplicationLifetime applicationLifetime + ) { _taskQueue = taskQueue; _logger = logger; @@ -60,7 +64,11 @@ private async ValueTask BuildWorkItemAsync(CancellationToken cancellationToken) ++delayLoop; - _logger.LogInformation("Queued work item {Guid} is running. {DelayLoop}/3", guid, delayLoop); + _logger.LogInformation( + "Queued work item {Guid} is running. {DelayLoop}/3", + guid, + delayLoop + ); } string format = delayLoop switch diff --git a/OdhApiImporter/Program.cs b/OdhApiImporter/Program.cs index 5ec505167..18fffeffc 100644 --- a/OdhApiImporter/Program.cs +++ b/OdhApiImporter/Program.cs @@ -20,7 +20,10 @@ public static async Task Main(string[] args) await host.RunAsync(); } - private static void ConfigureServices(HostBuilderContext context, IServiceCollection services) + private static void ConfigureServices( + HostBuilderContext context, + IServiceCollection services + ) { //services.AddHostedService(); //services.AddSingleton(); diff --git a/OdhApiImporter/QueuedHostedService.cs b/OdhApiImporter/QueuedHostedService.cs index ebbf2b462..26e071bf3 100644 --- a/OdhApiImporter/QueuedHostedService.cs +++ b/OdhApiImporter/QueuedHostedService.cs @@ -13,15 +13,18 @@ public class QueuedHostedService : BackgroundService private readonly IBackgroundTaskQueue _taskQueue; private readonly ILogger _logger; - public QueuedHostedService(IBackgroundTaskQueue taskQueue, ILogger logger) => - (_taskQueue, _logger) = (taskQueue, logger); + public QueuedHostedService( + IBackgroundTaskQueue taskQueue, + ILogger logger + ) => (_taskQueue, _logger) = (taskQueue, logger); protected override Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation( - $"{nameof(QueuedHostedService)} is running.{Environment.NewLine}" + - $"{Environment.NewLine}Tap W to add a work item to the " + - $"background queue.{Environment.NewLine}"); + $"{nameof(QueuedHostedService)} is running.{Environment.NewLine}" + + $"{Environment.NewLine}Tap W to add a work item to the " + + $"background queue.{Environment.NewLine}" + ); return ProcessTaskQueueAsync(stoppingToken); } @@ -32,8 +35,9 @@ private async Task ProcessTaskQueueAsync(CancellationToken stoppingToken) { try { - Func? workItem = - await _taskQueue.DequeueAsync(stoppingToken); + Func? workItem = await _taskQueue.DequeueAsync( + stoppingToken + ); await workItem(stoppingToken); } @@ -50,8 +54,7 @@ private async Task ProcessTaskQueueAsync(CancellationToken stoppingToken) public override Task StopAsync(CancellationToken cancellationToken) { - _logger.LogInformation( - $"{nameof(QueuedHostedService)} is stopping."); + _logger.LogInformation($"{nameof(QueuedHostedService)} is stopping."); return base.StopAsync(cancellationToken); } diff --git a/OdhApiImporter/Settings.cs b/OdhApiImporter/Settings.cs index 64dd6e650..6222dcd8f 100644 --- a/OdhApiImporter/Settings.cs +++ b/OdhApiImporter/Settings.cs @@ -12,7 +12,7 @@ public MssConfig(string username, string password) } public string Username { get; private set; } - public string Password { get; private set; } + public string Password { get; private set; } } public class LcsConfig @@ -50,11 +50,11 @@ public class SiagConfig public SiagConfig(string username, string password) { this.Username = username; - this.Password = password; + this.Password = password; } public string Username { get; private set; } - public string Password { get; private set; } + public string Password { get; private set; } } public class XmlConfig @@ -66,14 +66,14 @@ public XmlConfig(string xmldir, string xmldirweather) } public string Xmldir { get; private set; } - public string XmldirWeather { get; private set; } + public string XmldirWeather { get; private set; } } public class JsonConfig { public JsonConfig(string jsondir) { - this.Jsondir = jsondir; + this.Jsondir = jsondir; } public string Jsondir { get; private set; } @@ -81,7 +81,13 @@ public JsonConfig(string jsondir) public class S3ImageresizerConfig { - public S3ImageresizerConfig(string url, string docurl, string bucketaccesspoint, string accesskey, string secretkey) + public S3ImageresizerConfig( + string url, + string docurl, + string bucketaccesspoint, + string accesskey, + string secretkey + ) { this.Url = url; this.DocUrl = docurl; @@ -157,7 +163,7 @@ public class Settings : ISettings private readonly IConfiguration configuration; private readonly Lazy connectionString; private readonly MssConfig mssConfig; - private readonly LcsConfig lcsConfig; + private readonly LcsConfig lcsConfig; private readonly CDBConfig cdbConfig; private readonly SiagConfig siagConfig; private readonly XmlConfig xmlConfig; @@ -170,28 +176,63 @@ public class Settings : ISettings public Settings(IConfiguration configuration) { this.configuration = configuration; - this.connectionString = new Lazy(() => - this.configuration.GetConnectionString("PGConnection")); + this.connectionString = new Lazy( + () => this.configuration.GetConnectionString("PGConnection") + ); var mss = this.configuration.GetSection("MssConfig"); - this.mssConfig = new MssConfig(mss.GetValue("Username", ""), mss.GetValue("Password", "")); + this.mssConfig = new MssConfig( + mss.GetValue("Username", ""), + mss.GetValue("Password", "") + ); var lcs = this.configuration.GetSection("LcsConfig"); - this.lcsConfig = new LcsConfig(lcs.GetValue("Username", ""), lcs.GetValue("Password", ""), lcs.GetValue("MessagePassword", "")); + this.lcsConfig = new LcsConfig( + lcs.GetValue("Username", ""), + lcs.GetValue("Password", ""), + lcs.GetValue("MessagePassword", "") + ); var cdb = this.configuration.GetSection("CDBConfig"); - this.cdbConfig = new CDBConfig(cdb.GetValue("Username", ""), cdb.GetValue("Password", ""), cdb.GetValue("Url", "")); + this.cdbConfig = new CDBConfig( + cdb.GetValue("Username", ""), + cdb.GetValue("Password", ""), + cdb.GetValue("Url", "") + ); var siag = this.configuration.GetSection("SiagConfig"); - this.siagConfig = new SiagConfig(siag.GetValue("Username", ""), siag.GetValue("Password", "")); + this.siagConfig = new SiagConfig( + siag.GetValue("Username", ""), + siag.GetValue("Password", "") + ); var xml = this.configuration.GetSection("XmlConfig"); - this.xmlConfig = new XmlConfig(xml.GetValue("Xmldir", ""), xml.GetValue("XmldirWeather", "")); + this.xmlConfig = new XmlConfig( + xml.GetValue("Xmldir", ""), + xml.GetValue("XmldirWeather", "") + ); var json = this.configuration.GetSection("JsonConfig"); this.jsonConfig = new JsonConfig(json.GetValue("Jsondir", "")); var s3img = this.configuration.GetSection("S3ImageresizerConfig"); - this.s3imageresizerConfig = new S3ImageresizerConfig(s3img.GetValue("Url", ""), s3img.GetValue("DocUrl", ""), s3img.GetValue("BucketAccessPoint", ""), s3img.GetValue("AccessKey", ""), s3img.GetValue("SecretKey", "")); + this.s3imageresizerConfig = new S3ImageresizerConfig( + s3img.GetValue("Url", ""), + s3img.GetValue("DocUrl", ""), + s3img.GetValue("BucketAccessPoint", ""), + s3img.GetValue("AccessKey", ""), + s3img.GetValue("SecretKey", "") + ); var ebms = this.configuration.GetSection("EBMSConfig"); - this.ebmsConfig = new EBMSConfig(ebms.GetValue("EBMSUser", ""), ebms.GetValue("EBMSPassword", "")); + this.ebmsConfig = new EBMSConfig( + ebms.GetValue("EBMSUser", ""), + ebms.GetValue("EBMSPassword", "") + ); var raven = this.configuration.GetSection("RavenConfig"); - this.ravenConfig = new RavenConfig(raven.GetValue("Username", ""), raven.GetValue("Password", ""), raven.GetValue("ServiceUrl", "")); + this.ravenConfig = new RavenConfig( + raven.GetValue("Username", ""), + raven.GetValue("Password", ""), + raven.GetValue("ServiceUrl", "") + ); var dss = this.configuration.GetSection("DSSConfig"); - this.dssConfig = new DSSConfig(dss.GetValue("Username", ""), dss.GetValue("Password", ""), dss.GetValue("ServiceUrl", "")); + this.dssConfig = new DSSConfig( + dss.GetValue("Username", ""), + dss.GetValue("Password", ""), + dss.GetValue("ServiceUrl", "") + ); } public string PostgresConnectionString => this.connectionString.Value; diff --git a/OdhApiImporter/Startup.cs b/OdhApiImporter/Startup.cs index 55f8b19ac..1520a5fec 100644 --- a/OdhApiImporter/Startup.cs +++ b/OdhApiImporter/Startup.cs @@ -23,6 +23,7 @@ public static void ConfigureServices(IServiceCollection services) services.AddMvc(); } + public static void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) diff --git a/PushServer/FCMMessageConstructor.cs b/PushServer/FCMMessageConstructor.cs index 0d28e3e70..4378f1ad0 100644 --- a/PushServer/FCMMessageConstructor.cs +++ b/PushServer/FCMMessageConstructor.cs @@ -9,7 +9,11 @@ namespace PushServer { public class FCMMessageConstructor { - public static FCMModels? ConstructMyMessage(string identifier, string language, IIdentifiable myobject) + public static FCMModels? ConstructMyMessage( + string identifier, + string language, + IIdentifiable myobject + ) { var message = default(FCMModels); @@ -26,8 +30,18 @@ public class FCMMessageConstructor notification.icon = "ic_notification"; notification.link = deeplink; - notification.title = ((ArticlesLinked)myobject).Detail.ContainsKey(language) && !String.IsNullOrEmpty(((ArticlesLinked)myobject).Detail[language].Title) ? ((ArticlesLinked)myobject).Detail[language].Title : "Noi Community App News"; - notification.body = ((ArticlesLinked)myobject).Detail.ContainsKey(language) && !String.IsNullOrEmpty(((ArticlesLinked)myobject).Detail[language].AdditionalText) ? ((ArticlesLinked)myobject).Detail[language].AdditionalText : "Check out the latest News on the NOI Community App"; + notification.title = + ((ArticlesLinked)myobject).Detail.ContainsKey(language) + && !String.IsNullOrEmpty(((ArticlesLinked)myobject).Detail[language].Title) + ? ((ArticlesLinked)myobject).Detail[language].Title + : "Noi Community App News"; + notification.body = + ((ArticlesLinked)myobject).Detail.ContainsKey(language) + && !String.IsNullOrEmpty( + ((ArticlesLinked)myobject).Detail[language].AdditionalText + ) + ? ((ArticlesLinked)myobject).Detail[language].AdditionalText + : "Check out the latest News on the NOI Community App"; notification.sound = "default"; message.notification = notification; @@ -35,6 +49,5 @@ public class FCMMessageConstructor return message; } - } } diff --git a/PushServer/FCMPushNotification.cs b/PushServer/FCMPushNotification.cs index 5729c19ce..84381c077 100644 --- a/PushServer/FCMPushNotification.cs +++ b/PushServer/FCMPushNotification.cs @@ -11,37 +11,65 @@ namespace PushServer { #region Direct Send FCM to Firebase - public class FCMPushNotificationResponse + public class FCMPushNotificationResponse { - public bool Success { get; set; } - public string? Response { get; set; } - public Exception? Error { get; set; } - } - - public class FCMPushNotification - { - public static async Task SendNotification(FCMModels fcmmessage, string fcmurl, string fcmsenderid, string fcmauthkey) - { - FCMPushNotification result = new FCMPushNotification(); - try - { - HttpClient myclient = new HttpClient(); - - myclient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + fcmauthkey); - myclient.DefaultRequestHeaders.TryAddWithoutValidation("Sender", string.Format("id={0}", fcmsenderid)); - - var myresponse = await myclient.PostAsync(fcmurl, new StringContent(JsonConvert.SerializeObject(fcmmessage), Encoding.UTF8, "application/json")); - - var myresponseparsed = await myresponse.Content.ReadAsStringAsync(); - - return new FCMPushNotificationResponse() { Error = null, Response = myresponseparsed, Success = true }; - } - catch (Exception ex) - { - return new FCMPushNotificationResponse() { Error = ex, Response = "Error", Success = false }; - } - } - } + public bool Success { get; set; } + public string? Response { get; set; } + public Exception? Error { get; set; } + } + + public class FCMPushNotification + { + public static async Task SendNotification( + FCMModels fcmmessage, + string fcmurl, + string fcmsenderid, + string fcmauthkey + ) + { + FCMPushNotification result = new FCMPushNotification(); + try + { + HttpClient myclient = new HttpClient(); + + myclient.DefaultRequestHeaders.TryAddWithoutValidation( + "Authorization", + "key=" + fcmauthkey + ); + myclient.DefaultRequestHeaders.TryAddWithoutValidation( + "Sender", + string.Format("id={0}", fcmsenderid) + ); + + var myresponse = await myclient.PostAsync( + fcmurl, + new StringContent( + JsonConvert.SerializeObject(fcmmessage), + Encoding.UTF8, + "application/json" + ) + ); + + var myresponseparsed = await myresponse.Content.ReadAsStringAsync(); + + return new FCMPushNotificationResponse() + { + Error = null, + Response = myresponseparsed, + Success = true + }; + } + catch (Exception ex) + { + return new FCMPushNotificationResponse() + { + Error = ex, + Response = "Error", + Success = false + }; + } + } + } #endregion } diff --git a/PushServer/GetPushServerMessages.cs b/PushServer/GetPushServerMessages.cs index 6b48861e4..ae0c53a49 100644 --- a/PushServer/GetPushServerMessages.cs +++ b/PushServer/GetPushServerMessages.cs @@ -13,134 +13,179 @@ public class GetPushServerMessages { #region Weather - public static PushServerMessage? GetWeatherInfo(string siaguser, string siagpswd, string xmldir, string language, string group, TraceSource tracesource) - { - try - { - var weatherdata = GetWeatherForPushServer(language, "", "", xmldir, siaguser, siagpswd).Result; - //var weatherdatait = GetWeatherForPushServer("it", "", "", xmldir, siaguser, siagpswd).Result; - //var weatherdataen = GetWeatherForPushServer("en", "", "", xmldir, siaguser, siagpswd).Result; - - var weatherdatacondition = weatherdata.Conditions.Where(x => x.date.Date == DateTime.Now.Date).FirstOrDefault(); - //var weatherdataconditionit = weatherdatait.Conditions.Where(x => x.date.Date == DateTime.Now.Date).FirstOrDefault(); - //var weatherdataconditionen = weatherdataen.Conditions.Where(x => x.date.Date == DateTime.Now.Date).FirstOrDefault(); - - if (weatherdatacondition is not { }) - return null; - - tracesource.TraceEvent(TraceEventType.Information, 0, "Weatherinfo GET success, language " + language); - - return ParseWeatherData(weatherdatacondition, language, group); - } - catch (Exception ex) - { - tracesource.TraceEvent(TraceEventType.Error, 0, "PushServer Get Weather Error, language: " + language + " Error: " + ex.Message); - - return null; - } - } - - private static async Task GetWeatherForPushServer(string language, string locfilter, string stationidtype, string xmldir, string siaguser, string siagpswd) - { - var result = await GetWeatherData.GetSiagWeatherData(language, siaguser, siagpswd, true); - - return await GetWeatherData.ParseSiagWeatherDataToODHWeather(language, xmldir, result, true); - } - - private static PushServerMessage ParseWeatherData(Conditions weather, string language, string group) - { - PushServerMessage weathermessage = new PushServerMessage(); - weathermessage.title = weather.Title; - weathermessage.text = weather.Weatherdesc; - weathermessage.image = weather.WeatherImgurl; - weathermessage.video = ""; - - PushServerDestination pushserverdestination = new PushServerDestination(); - pushserverdestination.group = group; - pushserverdestination.language = language; - - weathermessage.destination = pushserverdestination; - - return weathermessage; - } + public static PushServerMessage? GetWeatherInfo( + string siaguser, + string siagpswd, + string xmldir, + string language, + string group, + TraceSource tracesource + ) + { + try + { + var weatherdata = GetWeatherForPushServer( + language, + "", + "", + xmldir, + siaguser, + siagpswd + ).Result; + //var weatherdatait = GetWeatherForPushServer("it", "", "", xmldir, siaguser, siagpswd).Result; + //var weatherdataen = GetWeatherForPushServer("en", "", "", xmldir, siaguser, siagpswd).Result; + + var weatherdatacondition = weatherdata.Conditions + .Where(x => x.date.Date == DateTime.Now.Date) + .FirstOrDefault(); + //var weatherdataconditionit = weatherdatait.Conditions.Where(x => x.date.Date == DateTime.Now.Date).FirstOrDefault(); + //var weatherdataconditionen = weatherdataen.Conditions.Where(x => x.date.Date == DateTime.Now.Date).FirstOrDefault(); + + if (weatherdatacondition is not { }) + return null; + + tracesource.TraceEvent( + TraceEventType.Information, + 0, + "Weatherinfo GET success, language " + language + ); + + return ParseWeatherData(weatherdatacondition, language, group); + } + catch (Exception ex) + { + tracesource.TraceEvent( + TraceEventType.Error, + 0, + "PushServer Get Weather Error, language: " + language + " Error: " + ex.Message + ); + + return null; + } + } + + private static async Task GetWeatherForPushServer( + string language, + string locfilter, + string stationidtype, + string xmldir, + string siaguser, + string siagpswd + ) + { + var result = await GetWeatherData.GetSiagWeatherData( + language, + siaguser, + siagpswd, + true + ); + + return await GetWeatherData.ParseSiagWeatherDataToODHWeather( + language, + xmldir, + result, + true + ); + } + + private static PushServerMessage ParseWeatherData( + Conditions weather, + string language, + string group + ) + { + PushServerMessage weathermessage = new PushServerMessage(); + weathermessage.title = weather.Title; + weathermessage.text = weather.Weatherdesc; + weathermessage.image = weather.WeatherImgurl; + weathermessage.video = ""; + + PushServerDestination pushserverdestination = new PushServerDestination(); + pushserverdestination.group = group; + pushserverdestination.language = language; + + weathermessage.destination = pushserverdestination; + + return weathermessage; + } #endregion - //#region Tip of the day + //#region Tip of the day - //public static PushServerMessage GetTipOfTheDay(IDocumentStore documentStore, string language, string group, TraceSource tracesource) - //{ - // try - // { - // //Get Tip of The Day - // var mytip = GetTipofTheDayforPushServer(documentStore); + //public static PushServerMessage GetTipOfTheDay(IDocumentStore documentStore, string language, string group, TraceSource tracesource) + //{ + // try + // { + // //Get Tip of The Day + // var mytip = GetTipofTheDayforPushServer(documentStore); - // //Parse Tip of the Day to - // var parsedtip = ParseTipofTheDayData(mytip, language, group); + // //Parse Tip of the Day to + // var parsedtip = ParseTipofTheDayData(mytip, language, group); - // tracesource.TraceEvent(TraceEventType.Information, 0, "Tip GET success, language " + language); + // tracesource.TraceEvent(TraceEventType.Information, 0, "Tip GET success, language " + language); - // return parsedtip; - // } - // catch (Exception ex) - // { - // tracesource.TraceEvent(TraceEventType.Error, 0, "PushServer Get Tip Error" + ex.Message); + // return parsedtip; + // } + // catch (Exception ex) + // { + // tracesource.TraceEvent(TraceEventType.Error, 0, "PushServer Get Tip Error" + ex.Message); - // return null; - // } - //} + // return null; + // } + //} - //private static SmgPoi GetTipofTheDayforPushServer(IDocumentStore documentStore) - //{ - // List mylanglist = new List() { "de", "it", "en" }; + //private static SmgPoi GetTipofTheDayforPushServer(IDocumentStore documentStore) + //{ + // List mylanglist = new List() { "de", "it", "en" }; - // //Typen - // List typestoexclude = new List() { "Essen Trinken", "Anderes" }; - // //Subtypen - // List subtypestoexclude = new List() { "Radverleih", "Skischulen Skiverleih" }; - // //PoiTypen - // List poitypestoexclude = new List(); + // //Typen + // List typestoexclude = new List() { "Essen Trinken", "Anderes" }; + // //Subtypen + // List subtypestoexclude = new List() { "Radverleih", "Skischulen Skiverleih" }; + // //PoiTypen + // List poitypestoexclude = new List(); - // Helper.TipOfTheDayHelper.AssignTipsFilters(typestoexclude, subtypestoexclude, poitypestoexclude); + // Helper.TipOfTheDayHelper.AssignTipsFilters(typestoexclude, subtypestoexclude, poitypestoexclude); - // using (var session = documentStore.OpenSession()) - // { - // var mytip = session.Query() - // .Where(x => x.Highlight == true) - // //.Where(x => x.Type != "Essen Trinken" && x.Type != "Winter") - // .Where(x => !x.Type.In(typestoexclude) && !x.SubType.In(subtypestoexclude) && !x.PoiType.In(poitypestoexclude)) //Des war nui schaugn obs geat - // .WhereIf(mylanglist.Count > 0, x => x.HasLanguage.In(mylanglist)) - // .Where(x => x.Active == true) - // .Customize(x => x.RandomOrdering()) - // .ProjectFromIndexFieldsInto() - // .FirstOrDefault(); + // using (var session = documentStore.OpenSession()) + // { + // var mytip = session.Query() + // .Where(x => x.Highlight == true) + // //.Where(x => x.Type != "Essen Trinken" && x.Type != "Winter") + // .Where(x => !x.Type.In(typestoexclude) && !x.SubType.In(subtypestoexclude) && !x.PoiType.In(poitypestoexclude)) //Des war nui schaugn obs geat + // .WhereIf(mylanglist.Count > 0, x => x.HasLanguage.In(mylanglist)) + // .Where(x => x.Active == true) + // .Customize(x => x.RandomOrdering()) + // .ProjectFromIndexFieldsInto() + // .FirstOrDefault(); - // return mytip; - // } - //} + // return mytip; + // } + //} - //private static PushServerMessage ParseTipofTheDayData(SmgPoi mytip, string language, string group) - //{ - // PushServerMessage weathermessage = new PushServerMessage(); - // weathermessage.title = System.Net.WebUtility.HtmlDecode(mytip.Detail[language].Title); + //private static PushServerMessage ParseTipofTheDayData(SmgPoi mytip, string language, string group) + //{ + // PushServerMessage weathermessage = new PushServerMessage(); + // weathermessage.title = System.Net.WebUtility.HtmlDecode(mytip.Detail[language].Title); - // //Achtung hier muss ein sanitizer her - // weathermessage.text = System.Net.WebUtility.HtmlDecode(mytip.Detail[language].BaseText); + // //Achtung hier muss ein sanitizer her + // weathermessage.text = System.Net.WebUtility.HtmlDecode(mytip.Detail[language].BaseText); - // weathermessage.image = mytip.ImageGallery.FirstOrDefault().ImageUrl; - // weathermessage.video = ""; + // weathermessage.image = mytip.ImageGallery.FirstOrDefault().ImageUrl; + // weathermessage.video = ""; - // PushServerDestination pushserverdestination = new PushServerDestination(); - // pushserverdestination.group = group; - // pushserverdestination.language = language; + // PushServerDestination pushserverdestination = new PushServerDestination(); + // pushserverdestination.group = group; + // pushserverdestination.language = language; - // weathermessage.destination = pushserverdestination; + // weathermessage.destination = pushserverdestination; - // return weathermessage; - //} + // return weathermessage; + //} - //#endregion - } + //#endregion + } } diff --git a/PushServer/SendToPushServer.cs b/PushServer/SendToPushServer.cs index e4be2eaab..3b9a7e04f 100644 --- a/PushServer/SendToPushServer.cs +++ b/PushServer/SendToPushServer.cs @@ -10,79 +10,110 @@ namespace PushServer { - public class SendToPushServer - { - public static async Task SendMessageToPushServer(string serviceurl, PushServerMessage data, string pushserveruser, string pushserverpass, string language) - { - try - { - if (data == null) - throw new Exception("data is null"); - - //HttpClient myclient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); - //myclient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate"); - //HttpClient myclient = new HttpClient(new Cred { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); - HttpClient myclient = new HttpClient(); - - var byteArray = Encoding.ASCII.GetBytes(pushserveruser + ":" + pushserverpass); - myclient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); - - //myclient.DefaultRequestHeaders.Add("",""); - - //var json = JsonConvert.SerializeObject(data, Formatting.Indented); - - var myresponse = await myclient.PostAsync(serviceurl, new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")); - - var myresponseparsed = await myresponse.Content.ReadAsStringAsync(); - - //tracesource.TraceEvent(TraceEventType.Information, 0, "Pushed Message:" + json); - //tracesource.TraceEvent(TraceEventType.Information, 0, "PushServer Send Weather success language , info: " + myresponseparsed + " language " + language); - - return myresponseparsed; - } - catch (Exception ex) - { - //tracesource.TraceEvent(TraceEventType.Error, 0, "PushServer Send Weather FAILED, error: " + ex.Message + " language " + language); - - return ex.Message; - } - } - - public static async Task SendCustomMessageToPushServer(string serviceurl, PushServerCustomMessage data, string pushserveruser, string pushserverpass) - { - try - { - if (data == null) - throw new Exception("data is null"); - - //HttpClient myclient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); - //myclient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate"); - //HttpClient myclient = new HttpClient(new Cred { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); - HttpClient myclient = new HttpClient(); - - var byteArray = Encoding.ASCII.GetBytes(pushserveruser + ":" + pushserverpass); - myclient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); - - //myclient.DefaultRequestHeaders.Add("",""); - - var json = JsonConvert.SerializeObject(data, Formatting.Indented); - - var myresponse = await myclient.PostAsync(serviceurl, new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")); - - var myresponseparsed = await myresponse.Content.ReadAsStringAsync(); - - //tracesource.TraceEvent(TraceEventType.Information, 0, "PushServer Send Weather success, info: " + myresponseparsed); - - return myresponseparsed; - } - catch (Exception ex) - { - //tracesource.TraceEvent(TraceEventType.Error, 0, "PushServer Send Weather FAILED, error: " + ex.Message); - - return ex.Message; - } - } - - } - + public class SendToPushServer + { + public static async Task SendMessageToPushServer( + string serviceurl, + PushServerMessage data, + string pushserveruser, + string pushserverpass, + string language + ) + { + try + { + if (data == null) + throw new Exception("data is null"); + + //HttpClient myclient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); + //myclient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate"); + //HttpClient myclient = new HttpClient(new Cred { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); + HttpClient myclient = new HttpClient(); + + var byteArray = Encoding.ASCII.GetBytes(pushserveruser + ":" + pushserverpass); + myclient.DefaultRequestHeaders.Authorization = + new System.Net.Http.Headers.AuthenticationHeaderValue( + "Basic", + Convert.ToBase64String(byteArray) + ); + + //myclient.DefaultRequestHeaders.Add("",""); + + //var json = JsonConvert.SerializeObject(data, Formatting.Indented); + + var myresponse = await myclient.PostAsync( + serviceurl, + new StringContent( + JsonConvert.SerializeObject(data), + Encoding.UTF8, + "application/json" + ) + ); + + var myresponseparsed = await myresponse.Content.ReadAsStringAsync(); + + //tracesource.TraceEvent(TraceEventType.Information, 0, "Pushed Message:" + json); + //tracesource.TraceEvent(TraceEventType.Information, 0, "PushServer Send Weather success language , info: " + myresponseparsed + " language " + language); + + return myresponseparsed; + } + catch (Exception ex) + { + //tracesource.TraceEvent(TraceEventType.Error, 0, "PushServer Send Weather FAILED, error: " + ex.Message + " language " + language); + + return ex.Message; + } + } + + public static async Task SendCustomMessageToPushServer( + string serviceurl, + PushServerCustomMessage data, + string pushserveruser, + string pushserverpass + ) + { + try + { + if (data == null) + throw new Exception("data is null"); + + //HttpClient myclient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); + //myclient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate"); + //HttpClient myclient = new HttpClient(new Cred { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); + HttpClient myclient = new HttpClient(); + + var byteArray = Encoding.ASCII.GetBytes(pushserveruser + ":" + pushserverpass); + myclient.DefaultRequestHeaders.Authorization = + new System.Net.Http.Headers.AuthenticationHeaderValue( + "Basic", + Convert.ToBase64String(byteArray) + ); + + //myclient.DefaultRequestHeaders.Add("",""); + + var json = JsonConvert.SerializeObject(data, Formatting.Indented); + + var myresponse = await myclient.PostAsync( + serviceurl, + new StringContent( + JsonConvert.SerializeObject(data), + Encoding.UTF8, + "application/json" + ) + ); + + var myresponseparsed = await myresponse.Content.ReadAsStringAsync(); + + //tracesource.TraceEvent(TraceEventType.Information, 0, "PushServer Send Weather success, info: " + myresponseparsed); + + return myresponseparsed; + } + catch (Exception ex) + { + //tracesource.TraceEvent(TraceEventType.Error, 0, "PushServer Send Weather FAILED, error: " + ex.Message); + + return ex.Message; + } + } + } } diff --git a/RAVEN/GetDataFromRaven.cs b/RAVEN/GetDataFromRaven.cs index cb4e1e112..9b8a84930 100644 --- a/RAVEN/GetDataFromRaven.cs +++ b/RAVEN/GetDataFromRaven.cs @@ -10,28 +10,51 @@ namespace RAVEN { public class GetDataFromRaven - { - public static async Task GetRavenData(string type, string id, string odhravenserviceurl, string username, string password, CancellationToken cancellationToken, string overwriterequesturl = null) + { + public static async Task GetRavenData( + string type, + string id, + string odhravenserviceurl, + string username, + string password, + CancellationToken cancellationToken, + string overwriterequesturl = null + ) { try { var requesturl = odhravenserviceurl + type + "/" + id; if (!String.IsNullOrEmpty(overwriterequesturl)) - requesturl = odhravenserviceurl + overwriterequesturl + id; + requesturl = odhravenserviceurl + overwriterequesturl + id; CredentialCache wrCache = new CredentialCache(); - wrCache.Add(new Uri(requesturl), "Basic", new NetworkCredential(username, password)); + wrCache.Add( + new Uri(requesturl), + "Basic", + new NetworkCredential(username, password) + ); //If handler is sending the request twice add manually the header client.DefaultRequestHeaders.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Context.UserName + ":" + Context.Password))); - using (var handler = new HttpClientHandler { Credentials = wrCache, PreAuthenticate = true }) + using ( + var handler = new HttpClientHandler + { + Credentials = wrCache, + PreAuthenticate = true + } + ) { using (var client = new HttpClient(handler)) { //client.DefaultRequestHeaders.Referrer = new Uri(); client.Timeout = TimeSpan.FromSeconds(20); - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password))); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( + "Basic", + Convert.ToBase64String( + Encoding.UTF8.GetBytes(username + ":" + password) + ) + ); var myresponse = await client.GetAsync(requesturl); @@ -46,7 +69,7 @@ public static async Task GetRavenData(string type, string id, string odhra catch (Exception) { return default(T); - } + } } } } diff --git a/RAVEN/TransformToPGObject.cs b/RAVEN/TransformToPGObject.cs index 0fdd78e60..26bf9e25b 100644 --- a/RAVEN/TransformToPGObject.cs +++ b/RAVEN/TransformToPGObject.cs @@ -35,8 +35,14 @@ public static AccommodationLinked GetAccommodationPGObject(AccommodationLinked d if (String.IsNullOrEmpty(data.Source)) data.Source = "lts"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforAccommodation); //GetMetadata(data.Id, "accommodation", "lts", data.LastChange); - data.PublishedOn = PublishedOnHelper.GetPublishenOnList("accommodation", data.SmgActive); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforAccommodation + ); //GetMetadata(data.Id, "accommodation", "lts", data.LastChange); + data.PublishedOn = PublishedOnHelper.GetPublishenOnList( + "accommodation", + data.SmgActive + ); return data; } @@ -53,7 +59,7 @@ public static ODHActivityPoiLinked GetODHActivityPoiPGObject(ODHActivityPoiLinke if (data.SmgTags != null && data.SmgTags.Count > 0) data.SmgTags = data.SmgTags.Select(x => x.ToLower()).ToList(); - + if (!String.IsNullOrEmpty(data.CustomId)) data.CustomId = data.CustomId.ToUpper(); @@ -93,9 +99,9 @@ public static ODHActivityPoiLinked GetODHActivityPoiPGObject(ODHActivityPoiLinke { data.GpsPoints.Add("position" + i, gpsinfo); i++; - } + } } - } + } string sourcemeta = data.Source.ToLower(); @@ -108,21 +114,33 @@ public static ODHActivityPoiLinked GetODHActivityPoiPGObject(ODHActivityPoiLinke } //Remove empty dictionary keys - data.PoiProperty = data.PoiProperty == null ? new Dictionary>() : data.PoiProperty.Where(f => f.Value.Count > 0).ToDictionary(x => x.Key, x => x.Value); - + data.PoiProperty = + data.PoiProperty == null + ? new Dictionary>() + : data.PoiProperty + .Where(f => f.Value.Count > 0) + .ToDictionary(x => x.Key, x => x.Value); //if (sourcemeta == "common" || sourcemeta == "magnolia" || sourcemeta == "content") // sourcemeta = "idm"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforOdhActivityPoi); //GetMetadata(data.Id, "odhactivitypoi", sourcemeta, data.LastChange); - data.PublishedOn = PublishedOnHelper.GetPublishenOnList("odhactivitypoi", data.SmgActive); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforOdhActivityPoi + ); //GetMetadata(data.Id, "odhactivitypoi", sourcemeta, data.LastChange); + data.PublishedOn = PublishedOnHelper.GetPublishenOnList( + "odhactivitypoi", + data.SmgActive + ); ODHTagHelper.SetMainCategorizationForODHActivityPoi(data); return data; } - public static AccommodationRoomLinked GetAccommodationRoomPGObject(AccommodationRoomLinked data) + public static AccommodationRoomLinked GetAccommodationRoomPGObject( + AccommodationRoomLinked data + ) { data.Id = data.Id.ToUpper(); data.A0RID = data.A0RID.ToUpper(); @@ -144,7 +162,10 @@ public static AccommodationRoomLinked GetAccommodationRoomPGObject(Accommodation // datasource = datasource.ToLower(); //} - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforAccommodationRoom); //GetMetadata(data.Id, "accommodationroom", datasource, data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforAccommodationRoom + ); //GetMetadata(data.Id, "accommodationroom", datasource, data.LastChange); data.PublishedOn = PublishedOnHelper.GetPublishenOnList("accommodationroom", true); return data; @@ -220,11 +241,14 @@ public static LTSActivityLinked GetActivityPGObject(LTSActivityLinked data) myltstag.Id = myltstag.Id.ToLower(); } } - + if (String.IsNullOrEmpty(data2.Source)) data2.Source = "lts"; - data2._Meta = MetadataHelper.GetMetadataobject(data2, MetadataHelper.GetMetadataforActivity); //GetMetadata(data.Id, "ltsactivity", "lts", data.LastChange); + data2._Meta = MetadataHelper.GetMetadataobject( + data2, + MetadataHelper.GetMetadataforActivity + ); //GetMetadata(data.Id, "ltsactivity", "lts", data.LastChange); data2.PublishedOn = new List(); return data2; @@ -232,7 +256,6 @@ public static LTSActivityLinked GetActivityPGObject(LTSActivityLinked data) public static LTSPoiLinked GetPoiPGObject(LTSPoiLinked data) { - data.Id = data.Id.ToUpper(); if (data.SmgTags != null && data.SmgTags.Count > 0) @@ -251,7 +274,10 @@ public static LTSPoiLinked GetPoiPGObject(LTSPoiLinked data) data.PublishedOn = new List(); - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforPoi); //GetMetadata(data.Id, "ltspoi", "lts", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforPoi + ); //GetMetadata(data.Id, "ltspoi", "lts", data.LastChange); return data; } @@ -266,7 +292,10 @@ public static ArticlesLinked GetArticlePGObject(ArticlesLinked data) if (String.IsNullOrEmpty(data.Source)) data.Source = "idm"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforArticle); //GetMetadata(data.Id, "article", "idm", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforArticle + ); //GetMetadata(data.Id, "article", "idm", data.LastChange); data.PublishedOn = PublishedOnHelper.GetPublishenOnList("article", data.SmgActive); return data; @@ -283,7 +312,10 @@ public static PackageLinked GetPackagePGObject(PackageLinked data) if (String.IsNullOrEmpty(data.Source)) data.Source = "hgv"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforPackage); //GetMetadata(data.Id, "package", "hgv", data.LastUpdate); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforPackage + ); //GetMetadata(data.Id, "package", "hgv", data.LastUpdate); data.PublishedOn = PublishedOnHelper.GetPublishenOnList("package", data.SmgActive); return data; @@ -298,7 +330,10 @@ public static EventLinked GetEventPGObject(EventLinked data) data.Source = "lts"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforEvent); //GetMetadata(data.Id, "event", "lts", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforEvent + ); //GetMetadata(data.Id, "event", "lts", data.LastChange); data.PublishedOn = PublishedOnHelper.GetPublishenOnList("event", data.SmgActive); return data; @@ -318,7 +353,10 @@ public static GastronomyLinked GetGastronomyPGObject(GastronomyLinked data) data.PublishedOn = new List(); - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforGastronomy); //GetMetadata(data.Id, "ltsgastronomy", "lts", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforGastronomy + ); //GetMetadata(data.Id, "ltsgastronomy", "lts", data.LastChange); return data; } @@ -344,8 +382,12 @@ public static WebcamInfoLinked GetWebcamInfoPGObject(WebcamInfoLinked data) else data.Source = data.Source.ToLower(); - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforWebcam); //GetMetadata(data.Id, "webcam", sourcemeta, data.LastChange); - var webcampublished = data.WebcamAssignedOn != null && data.WebcamAssignedOn.Count > 0 ? true : false; + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforWebcam + ); //GetMetadata(data.Id, "webcam", sourcemeta, data.LastChange); + var webcampublished = + data.WebcamAssignedOn != null && data.WebcamAssignedOn.Count > 0 ? true : false; data.PublishedOn = PublishedOnHelper.GetPublishenOnList("webcam", webcampublished); @@ -361,10 +403,15 @@ public static MeasuringpointLinked GetMeasuringpointPGObject(MeasuringpointLinke else data.Source = data.Source.ToLower(); - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforMeasuringpoint); //GetMetadata(data.Id, "measuringpoint", "lts", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforMeasuringpoint + ); //GetMetadata(data.Id, "measuringpoint", "lts", data.LastChange); - - data.PublishedOn = PublishedOnHelper.GetPublishenOnList("mesuringpoint", data.SmgActive); + data.PublishedOn = PublishedOnHelper.GetPublishenOnList( + "mesuringpoint", + data.SmgActive + ); return data; } @@ -374,8 +421,11 @@ public static DDVenue GetVenuePGObject(DDVenue data) data.Id = data.Id.ToUpper(); data.LastChange = data.meta.lastUpdate; - data.Shortname = data.attributes.name != null && data.attributes.name.Keys.Count > 0 ? data.attributes.name.FirstOrDefault().Value : ""; - data.LicenseInfo = data.odhdata.LicenseInfo; + data.Shortname = + data.attributes.name != null && data.attributes.name.Keys.Count > 0 + ? data.attributes.name.FirstOrDefault().Value + : ""; + data.LicenseInfo = data.odhdata.LicenseInfo; if (data.odhdata.GpsInfo != null) { @@ -394,11 +444,21 @@ public static DDVenue GetVenuePGObject(DDVenue data) } } - data.odhdata.ODHActive = !data.attributes.categories.Contains("lts/visi_unpublishedOnODH") && data.attributes.categories.Contains("lts/visi_publishedOnODH") ? true : false; + data.odhdata.ODHActive = + !data.attributes.categories.Contains("lts/visi_unpublishedOnODH") + && data.attributes.categories.Contains("lts/visi_publishedOnODH") + ? true + : false; data.links.self = ODHConstant.ApplicationURL + "Venue/" + data.Id; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforVenue); - data.odhdata.PublishedOn = PublishedOnHelper.GetPublishenOnList("venue", data.odhdata.ODHActive); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforVenue + ); + data.odhdata.PublishedOn = PublishedOnHelper.GetPublishenOnList( + "venue", + data.odhdata.ODHActive + ); //fixes data.odhdata.Source = data.odhdata.Source.ToLower(); @@ -418,7 +478,10 @@ public static MetaRegionLinked GetMetaRegionPGObject(MetaRegionLinked data) if (String.IsNullOrEmpty(data.Source)) data.Source = "idm"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforMetaRegion); //GetMetadata(data.Id, "metaregion", "idm", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforMetaRegion + ); //GetMetadata(data.Id, "metaregion", "idm", data.LastChange); data.PublishedOn = PublishedOnHelper.GetPublishenOnList("metaregion", data.SmgActive); return data; @@ -429,11 +492,14 @@ public static RegionLinked GetRegionPGObject(RegionLinked data) data.Id = data.Id.ToUpper(); if (data.SmgTags != null && data.SmgTags.Count > 0) data.SmgTags = data.SmgTags.Select(x => x.ToLower()).ToList(); - + if (String.IsNullOrEmpty(data.Source)) data.Source = "idm"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforRegion); //GetMetadata(data.Id, "region", "idm", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforRegion + ); //GetMetadata(data.Id, "region", "idm", data.LastChange); data.PublishedOn = PublishedOnHelper.GetPublishenOnList("region", data.SmgActive); return data; @@ -448,8 +514,14 @@ public static TourismvereinLinked GetTourismAssociationPGObject(TourismvereinLin if (String.IsNullOrEmpty(data.Source)) data.Source = "idm"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforTourismverein); //GetMetadata(data.Id, "tourismassociation", "idm", data.LastChange); - data.PublishedOn = PublishedOnHelper.GetPublishenOnList("tourismassociation", data.SmgActive); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforTourismverein + ); //GetMetadata(data.Id, "tourismassociation", "idm", data.LastChange); + data.PublishedOn = PublishedOnHelper.GetPublishenOnList( + "tourismassociation", + data.SmgActive + ); return data; } @@ -463,7 +535,10 @@ public static MunicipalityLinked GetMunicipalityPGObject(MunicipalityLinked data if (String.IsNullOrEmpty(data.Source)) data.Source = "idm"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforMunicipality); //GetMetadata(data.Id, "municipality", "idm", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforMunicipality + ); //GetMetadata(data.Id, "municipality", "idm", data.LastChange); data.PublishedOn = PublishedOnHelper.GetPublishenOnList("municipality", data.SmgActive); return data; @@ -478,7 +553,10 @@ public static DistrictLinked GetDistrictPGObject(DistrictLinked data) if (String.IsNullOrEmpty(data.Source)) data.Source = "idm"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforDistrict); //GetMetadata(data.Id, "district", "idm", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforDistrict + ); //GetMetadata(data.Id, "district", "idm", data.LastChange); data.PublishedOn = PublishedOnHelper.GetPublishenOnList("district", data.SmgActive); return data; @@ -493,16 +571,25 @@ public static ExperienceAreaLinked GetExperienceAreaPGObject(ExperienceAreaLinke if (String.IsNullOrEmpty(data.Source)) data.Source = "idm"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforExperienceArea); //GetMetadata(data.Id, "experiencearea", "idm", data.LastChange); - data.PublishedOn = PublishedOnHelper.GetPublishenOnList("experiencearea", data.SmgActive); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforExperienceArea + ); //GetMetadata(data.Id, "experiencearea", "idm", data.LastChange); + data.PublishedOn = PublishedOnHelper.GetPublishenOnList( + "experiencearea", + data.SmgActive + ); return data; } public static AreaLinked GetAreaPGObject(AreaLinked data) { - data.Id = data.Id.ToUpper(); - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforArea); //GetMetadata(data.Id, "area", "lts", data.LastChange); + data.Id = data.Id.ToUpper(); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforArea + ); //GetMetadata(data.Id, "area", "lts", data.LastChange); return data; } @@ -516,7 +603,10 @@ public static SkiAreaLinked GetSkiAreaPGObject(SkiAreaLinked data) if (String.IsNullOrEmpty(data.Source)) data.Source = "idm"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforSkiArea); //GetMetadata(data.Id, "skiarea", "idm", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforSkiArea + ); //GetMetadata(data.Id, "skiarea", "idm", data.LastChange); data.PublishedOn = PublishedOnHelper.GetPublishenOnList("skiarea", data.SmgActive); return data; @@ -525,14 +615,17 @@ public static SkiAreaLinked GetSkiAreaPGObject(SkiAreaLinked data) public static SkiRegionLinked GetSkiRegionPGObject(SkiRegionLinked data) { data.Id = data.Id.ToUpper(); - + if (data.SmgTags != null && data.SmgTags.Count > 0) data.SmgTags = data.SmgTags.Select(x => x.ToLower()).ToList(); if (String.IsNullOrEmpty(data.Source)) data.Source = "idm"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforSkiRegion); //GetMetadata(data.Id, "skiregion", "idm", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforSkiRegion + ); //GetMetadata(data.Id, "skiregion", "idm", data.LastChange); data.PublishedOn = PublishedOnHelper.GetPublishenOnList("skiregion", data.SmgActive); return data; @@ -545,7 +638,10 @@ public static WineLinked GetWinePGObject(WineLinked data) if (String.IsNullOrEmpty(data.Source)) data.Source = "suedtirolwein"; - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforWineAward); //GetMetadata(data.Id, "wineaward", "suedtirolwein", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforWineAward + ); //GetMetadata(data.Id, "wineaward", "suedtirolwein", data.LastChange); //data.PublishedOn = PublishedOnHelper.GetPublishenOnList("wine", data.SmgActive); return data; @@ -556,7 +652,7 @@ public static ODHTagLinked GetODHTagPGObject(ODHTagLinked data) data.Id = data.Id.ToLower(); data.MainEntity = data.MainEntity.ToLower(); - + List validforentitynew = new List(); foreach (var validforentity in data.ValidForEntity) { @@ -571,7 +667,10 @@ public static ODHTagLinked GetODHTagPGObject(ODHTagLinked data) if (!data.ValidForEntity.Contains(data.MainEntity)) data.ValidForEntity.Add(data.MainEntity); - data._Meta = MetadataHelper.GetMetadataobject(data, MetadataHelper.GetMetadataforOdhTag); //GetMetadata(data.Id, "wineaward", "suedtirolwein", data.LastChange); + data._Meta = MetadataHelper.GetMetadataobject( + data, + MetadataHelper.GetMetadataforOdhTag + ); //GetMetadata(data.Id, "wineaward", "suedtirolwein", data.LastChange); return data; } diff --git a/SIAG/GetMuseumDataFromSiag.cs b/SIAG/GetMuseumDataFromSiag.cs index 20fefe8fc..029e1e275 100644 --- a/SIAG/GetMuseumDataFromSiag.cs +++ b/SIAG/GetMuseumDataFromSiag.cs @@ -10,11 +10,11 @@ namespace SIAG { public class GetMuseumFromSIAG { - public const string serviceurl = @"https://musport.prov.bz.it/musport/services/MuseumsService/"; + public const string serviceurl = + @"https://musport.prov.bz.it/musport/services/MuseumsService/"; public static async Task MuseumList() { - string requesturl = serviceurl + "getMuseums"; using (var client = new HttpClient()) { @@ -22,12 +22,10 @@ public static async Task MuseumList() return myresponse; } - } public static async Task GetMuseumList() { - var myresponse = MuseumList(); var myresponsecontent = await myresponse.Result.Content.ReadAsStringAsync(); @@ -35,7 +33,6 @@ public static async Task GetMuseumList() XDocument xresponse = XDocument.Parse(myresponsecontent); return xresponse; - } public static async Task MuseumDetail(string museumid) @@ -52,7 +49,11 @@ public static async Task MuseumDetail(string museumid) } catch (Exception ex) { - return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(ex.Message) }; + return new HttpResponseMessage + { + StatusCode = HttpStatusCode.BadRequest, + Content = new StringContent(ex.Message) + }; } } diff --git a/SIAG/GetWeatherData.cs b/SIAG/GetWeatherData.cs index 175b06e75..bc2be8514 100644 --- a/SIAG/GetWeatherData.cs +++ b/SIAG/GetWeatherData.cs @@ -18,37 +18,71 @@ public class GetWeatherData public const string source = "opendata"; #region Weather general - + //Gets SIAG Weather Data (RAW DATA) - public static async Task GetSiagWeatherData(string lang, string siaguser, string siagpswd, bool json, string? id = null) + public static async Task GetSiagWeatherData( + string lang, + string siaguser, + string siagpswd, + bool json, + string? id = null + ) { //Request on Siag Service - HttpResponseMessage weatherresponse = await GetWeatherFromSIAG.RequestAsync(lang, siaguser, siagpswd, source, json, id); + HttpResponseMessage weatherresponse = await GetWeatherFromSIAG.RequestAsync( + lang, + siaguser, + siagpswd, + source, + json, + id + ); //Reading Content and returning return await weatherresponse.Content.ReadAsStringAsync(); } //Parses to ODH Format - public static Task ParseSiagWeatherDataToODHWeather(string lang, string xmldir, string weatherresponsetask, bool json) + public static Task ParseSiagWeatherDataToODHWeather( + string lang, + string xmldir, + string weatherresponsetask, + bool json + ) { var weatherinfo = XDocument.Load(xmldir + "Weather.xml"); if (json) { - return Task.FromResult(ParseWeather.ParsemyWeatherJsonResponse(lang, weatherinfo, weatherresponsetask)); + return Task.FromResult( + ParseWeather.ParsemyWeatherJsonResponse(lang, weatherinfo, weatherresponsetask) + ); } XDocument myweatherresponse = XDocument.Parse(weatherresponsetask); - return Task.FromResult(ParseWeather.ParsemyWeatherResponse(lang, weatherinfo, myweatherresponse, source)); + return Task.FromResult( + ParseWeather.ParsemyWeatherResponse(lang, weatherinfo, myweatherresponse, source) + ); } #endregion - public static async Task GetCurrentStationWeatherAsync(string lang, string stationid, string stationidtype, string xmldir, string siaguser, string siagpswd) + public static async Task GetCurrentStationWeatherAsync( + string lang, + string stationid, + string stationidtype, + string xmldir, + string siaguser, + string siagpswd + ) { try { - HttpResponseMessage weatherresponse = await GetWeatherFromSIAG.RequestAsync(lang, siaguser, siagpswd, source); + HttpResponseMessage weatherresponse = await GetWeatherFromSIAG.RequestAsync( + lang, + siaguser, + siagpswd, + source + ); //Content auslesen und XDocument Parsen var weatherresponsetask = await weatherresponse.Content.ReadAsStringAsync(); @@ -58,7 +92,7 @@ public static Task ParseSiagWeatherDataToODHWeather(string lang, string //Testen //string mystationid = (from x in weatherinfo.Root.Elements("Station") - // let y = x.Elements(stationidtype + "s").SelectMany(y => y.Elements(stationidtype).Elements("ID").Select(u => u.Value)) + // let y = x.Elements(stationidtype + "s").SelectMany(y => y.Elements(stationidtype).Elements("ID").Select(u => u.Value)) // where y == stationid // select x.Attribute("Id").Value).FirstOrDefault(); @@ -67,12 +101,28 @@ public static Task ParseSiagWeatherDataToODHWeather(string lang, string if (stationidtype == "Id") mystationid = stationid; else - mystationid = weatherinfo.Root?.Elements("Station").Where(x => x.Elements(stationidtype + "s").Elements(stationidtype).Attributes("ID").Select(y => y.Value).Contains(stationid)).Select(u => u.Attribute("Id")?.Value).FirstOrDefault(); - + mystationid = weatherinfo.Root + ?.Elements("Station") + .Where( + x => + x.Elements(stationidtype + "s") + .Elements(stationidtype) + .Attributes("ID") + .Select(y => y.Value) + .Contains(stationid) + ) + .Select(u => u.Attribute("Id")?.Value) + .FirstOrDefault(); if (mystationid != null) { - var myweather = ParseWeather.ParsemyStationWeatherResponse(lang, weatherinfo, myweatherresponse, mystationid, source); + var myweather = ParseWeather.ParsemyStationWeatherResponse( + lang, + weatherinfo, + myweatherresponse, + mystationid, + source + ); return myweather; } @@ -87,7 +137,15 @@ public static Task ParseSiagWeatherDataToODHWeather(string lang, string } } - public static async Task> GetCurrentBezirkWeatherAsync(string lang, string bezirksid, string tvrid, string regid, string xmldir, string siaguser, string siagpswd) + public static async Task> GetCurrentBezirkWeatherAsync( + string lang, + string bezirksid, + string tvrid, + string regid, + string xmldir, + string siaguser, + string siagpswd + ) { var currentbezirksidlist = new List(); @@ -97,10 +155,12 @@ public static Task ParseSiagWeatherDataToODHWeather(string lang, string { var bezirkweatherinfo = XDocument.Load(xmldir + "BezirkWeather.xml"); - var currentbezirksid = (from x in bezirkweatherinfo.Root?.Elements("Bezirk") - from y in x.Element("TVList")?.Elements("TV") ?? Enumerable.Empty() - where y.Attribute("ID")?.Value == tvrid - select x.Attribute("ID")?.Value).FirstOrDefault(); + var currentbezirksid = ( + from x in bezirkweatherinfo.Root?.Elements("Bezirk") + from y in x.Element("TVList")?.Elements("TV") ?? Enumerable.Empty() + where y.Attribute("ID")?.Value == tvrid + select x.Attribute("ID")?.Value + ).FirstOrDefault(); if (!String.IsNullOrEmpty(currentbezirksid)) currentbezirksidlist.Add(currentbezirksid); @@ -109,10 +169,13 @@ where y.Attribute("ID")?.Value == tvrid { var bezirkweatherinfo = XDocument.Load(xmldir + "BezirkWeather.xml"); - var currentbezirksid = (from x in bezirkweatherinfo.Root?.Elements("Bezirk") - from y in x.Element("RegionList")?.Elements("Region") ?? Enumerable.Empty() - where y.Attribute("ID")?.Value == regid - select x.Attribute("ID")?.Value).FirstOrDefault(); + var currentbezirksid = ( + from x in bezirkweatherinfo.Root?.Elements("Bezirk") + from y in x.Element("RegionList")?.Elements("Region") + ?? Enumerable.Empty() + where y.Attribute("ID")?.Value == regid + select x.Attribute("ID")?.Value + ).FirstOrDefault(); if (!String.IsNullOrEmpty(currentbezirksid)) currentbezirksidlist.Add(currentbezirksid); @@ -121,34 +184,49 @@ where y.Attribute("ID")?.Value == regid { var bezirkweatherinfo = XDocument.Load(xmldir + "BezirkWeather.xml"); - currentbezirksidlist = (from x in bezirkweatherinfo.Root?.Elements("Bezirk") - select x.Attribute("ID")?.Value).ToList(); + currentbezirksidlist = ( + from x in bezirkweatherinfo.Root?.Elements("Bezirk") + select x.Attribute("ID")?.Value + ).ToList(); } - var bezirksweatherlist = new List(); if (currentbezirksidlist.Count > 0) { foreach (var currentbezirksid in currentbezirksidlist) { - HttpResponseMessage weatherresponse = await GetWeatherFromSIAG.RequestBezirksWeatherAsync(lang, currentbezirksid, siaguser, siagpswd, source); + HttpResponseMessage weatherresponse = + await GetWeatherFromSIAG.RequestBezirksWeatherAsync( + lang, + currentbezirksid, + siaguser, + siagpswd, + source + ); //Content auslesen und XDocument Parsen var weatherresponsetask = await weatherresponse.Content.ReadAsStringAsync(); XDocument myweatherresponse = XDocument.Parse(weatherresponsetask); - var myweather = ParseWeather.ParsemyBezirksWeatherResponse(lang, myweatherresponse, source); + var myweather = ParseWeather.ParsemyBezirksWeatherResponse( + lang, + myweatherresponse, + source + ); bezirksweatherlist.Add(myweather); - } + } } return bezirksweatherlist; } - public static async Task> GetCurrentRealTimeWEatherAsync(string lang) + public static async Task> GetCurrentRealTimeWEatherAsync( + string lang + ) { - HttpResponseMessage weatherresponse = await GetWeatherFromSIAG.RequestRealtimeWeatherAsync(lang); + HttpResponseMessage weatherresponse = + await GetWeatherFromSIAG.RequestRealtimeWeatherAsync(lang); //Content auslesen und XDocument Parsen var weatherresponsetask = await weatherresponse.Content.ReadAsStringAsync(); @@ -166,12 +244,20 @@ public static async Task> GetCurrentRealTimeWEather { if (row.t != "--") { - WeatherRealTime myrealtimeweather = new WeatherRealTime(); - myrealtimeweather.altitude = Convert.ToDouble(row.altitude, CultureInfo.InvariantCulture); - myrealtimeweather.latitude = Convert.ToDouble(row.latitude.Value.Replace(',', '.'), CultureInfo.InvariantCulture); - myrealtimeweather.longitude = Convert.ToDouble(row.longitude.Value.Replace(',', '.'), CultureInfo.InvariantCulture); + myrealtimeweather.altitude = Convert.ToDouble( + row.altitude, + CultureInfo.InvariantCulture + ); + myrealtimeweather.latitude = Convert.ToDouble( + row.latitude.Value.Replace(',', '.'), + CultureInfo.InvariantCulture + ); + myrealtimeweather.longitude = Convert.ToDouble( + row.longitude.Value.Replace(',', '.'), + CultureInfo.InvariantCulture + ); myrealtimeweather.categoryId = row.categoryId; myrealtimeweather.code = row.code; myrealtimeweather.dd = row.dd; @@ -194,7 +280,8 @@ public static async Task> GetCurrentRealTimeWEather myrealtimeweather.wMax = row.wMax; myrealtimeweather.zoomLevel = row.zoomlevel; - List myrealtimemeasurments = new List(); + List myrealtimemeasurments = + new List(); foreach (var measurement in row.measurements) { @@ -216,9 +303,13 @@ public static async Task> GetCurrentRealTimeWEather return myrealtimeweatherlist.ToList(); } - public static async Task GetCurrentRealTimeWEatherSingleAsync(string lang, string stationid) + public static async Task GetCurrentRealTimeWEatherSingleAsync( + string lang, + string stationid + ) { - HttpResponseMessage weatherresponse = await GetWeatherFromSIAG.RequestRealtimeWeatherAsync(lang); + HttpResponseMessage weatherresponse = + await GetWeatherFromSIAG.RequestRealtimeWeatherAsync(lang); //Content auslesen und XDocument Parsen var weatherresponsetask = await weatherresponse.Content.ReadAsStringAsync(); @@ -229,17 +320,27 @@ public static async Task> GetCurrentRealTimeWEather CultureInfo myculture = new CultureInfo("de-DE"); - var row = ((IEnumerable?)stuff?.rows)?.Cast() - .Where(p => p.id == stationid).FirstOrDefault(); + var row = ((IEnumerable?)stuff?.rows) + ?.Cast() + .Where(p => p.id == stationid) + .FirstOrDefault(); if (row?.t != "--") { - WeatherRealTime myrealtimeweather = new WeatherRealTime(); - myrealtimeweather.altitude = Convert.ToDouble(row.altitude, CultureInfo.InvariantCulture); - myrealtimeweather.latitude = Convert.ToDouble(row.latitude.Value.Replace(',', '.'), CultureInfo.InvariantCulture); - myrealtimeweather.longitude = Convert.ToDouble(row.longitude.Value.Replace(',', '.'), CultureInfo.InvariantCulture); + myrealtimeweather.altitude = Convert.ToDouble( + row.altitude, + CultureInfo.InvariantCulture + ); + myrealtimeweather.latitude = Convert.ToDouble( + row.latitude.Value.Replace(',', '.'), + CultureInfo.InvariantCulture + ); + myrealtimeweather.longitude = Convert.ToDouble( + row.longitude.Value.Replace(',', '.'), + CultureInfo.InvariantCulture + ); myrealtimeweather.categoryId = row.categoryId; myrealtimeweather.code = row.code; myrealtimeweather.dd = row.dd; @@ -281,7 +382,6 @@ public static async Task> GetCurrentRealTimeWEather } else return null; - } } } diff --git a/SIAG/GetWeatherFromSIAG.cs b/SIAG/GetWeatherFromSIAG.cs index f45201c8b..77fe257cc 100644 --- a/SIAG/GetWeatherFromSIAG.cs +++ b/SIAG/GetWeatherFromSIAG.cs @@ -10,15 +10,26 @@ namespace SIAG { public class GetWeatherFromSIAG { - public const string serviceurlsiag = @"https://wetter.ws.siag.it/Weather_V1.svc/web/getLastProvBulletin"; - public const string serviceurlbezirksiag = @"https://wetter.ws.siag.it/Agriculture_V1.svc/web/getLastBulletin"; + public const string serviceurlsiag = + @"https://wetter.ws.siag.it/Weather_V1.svc/web/getLastProvBulletin"; + public const string serviceurlbezirksiag = + @"https://wetter.ws.siag.it/Agriculture_V1.svc/web/getLastBulletin"; public const string serviceurlrealtime = @"http://weather.services.siag.it/api/v2/station"; - public const string serviceurl = @"http://daten.buergernetz.bz.it/services/weather/bulletin"; - public const string serviceurlbezirk = @" http://daten.buergernetz.bz.it/services/weather/district/"; - - public static async Task RequestAsync(string lang, string siaguser, string siagpswd, string source, bool usejson = false, string? weatherid = null) + public const string serviceurl = + @"http://daten.buergernetz.bz.it/services/weather/bulletin"; + public const string serviceurlbezirk = + @" http://daten.buergernetz.bz.it/services/weather/district/"; + + public static async Task RequestAsync( + string lang, + string siaguser, + string siagpswd, + string source, + bool usejson = false, + string? weatherid = null + ) { try { @@ -26,24 +37,35 @@ public static async Task RequestAsync(string lang, string s if (usejson) { format = "json"; - } + } string requesturl = serviceurl + "?lang=" + lang + "&format=" + format; - if(!String.IsNullOrEmpty(weatherid)) - requesturl = serviceurl + "/" + weatherid + "?lang=" + lang + "&format=" + format; + if (!String.IsNullOrEmpty(weatherid)) + requesturl = + serviceurl + "/" + weatherid + "?lang=" + lang + "&format=" + format; if (source == "siag" && !usejson) { requesturl = serviceurlsiag + "?lang=" + lang + "&format=" + format; if (!String.IsNullOrEmpty(weatherid)) - requesturl = serviceurlsiag + "/" + weatherid + "?lang=" + lang + "&format=" + format; + requesturl = + serviceurlsiag + + "/" + + weatherid + + "?lang=" + + lang + + "&format=" + + format; } - CredentialCache wrCache = new CredentialCache(); - wrCache.Add(new Uri(requesturl), "Basic", new NetworkCredential(siaguser, siagpswd)); + wrCache.Add( + new Uri(requesturl), + "Basic", + new NetworkCredential(siaguser, siagpswd) + ); using (var handler = new HttpClientHandler { Credentials = wrCache }) { @@ -57,22 +79,36 @@ public static async Task RequestAsync(string lang, string s } catch (Exception ex) { - return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(ex.Message) }; + return new HttpResponseMessage + { + StatusCode = HttpStatusCode.BadRequest, + Content = new StringContent(ex.Message) + }; } - } - public static async Task RequestBezirksWeatherAsync(string lang, string distid, string siaguser, string siagpswd, string source) + public static async Task RequestBezirksWeatherAsync( + string lang, + string distid, + string siaguser, + string siagpswd, + string source + ) { try { - string requesturl = serviceurlbezirk + distid + "/bulletin?lang=" + lang + "&format=xml"; + string requesturl = + serviceurlbezirk + distid + "/bulletin?lang=" + lang + "&format=xml"; if (source == "siag") requesturl = serviceurlbezirksiag + "?lang=" + lang + "&dist=" + distid; CredentialCache wrCache = new CredentialCache(); - wrCache.Add(new Uri(requesturl), "Basic", new NetworkCredential(siaguser, siagpswd)); + wrCache.Add( + new Uri(requesturl), + "Basic", + new NetworkCredential(siaguser, siagpswd) + ); using (var handler = new HttpClientHandler { Credentials = wrCache }) { @@ -86,9 +122,12 @@ public static async Task RequestBezirksWeatherAsync(string } catch (Exception ex) { - return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(ex.Message) }; + return new HttpResponseMessage + { + StatusCode = HttpStatusCode.BadRequest, + Content = new StringContent(ex.Message) + }; } - } public static async Task RequestRealtimeWeatherAsync(string lang) @@ -109,9 +148,12 @@ public static async Task RequestRealtimeWeatherAsync(string } catch (Exception ex) { - return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(ex.Message) }; + return new HttpResponseMessage + { + StatusCode = HttpStatusCode.BadRequest, + Content = new StringContent(ex.Message) + }; } } - } } diff --git a/SIAG/Model/SiagWeatherModel.cs b/SIAG/Model/SiagWeatherModel.cs index 457d9e158..de1cd31c4 100644 --- a/SIAG/Model/SiagWeatherModel.cs +++ b/SIAG/Model/SiagWeatherModel.cs @@ -17,7 +17,7 @@ public class SiagWeather public string type { get; set; } public string evolution { get; set; } public string evolutionTitle { get; set; } - public Dayforecast[] dayForecasts { get; set; } + public Dayforecast[] dayForecasts { get; set; } } public class Today diff --git a/SIAG/Parser/ParseMuseum.cs b/SIAG/Parser/ParseMuseum.cs index 1098e4766..7ad4d68a5 100644 --- a/SIAG/Parser/ParseMuseum.cs +++ b/SIAG/Parser/ParseMuseum.cs @@ -11,7 +11,11 @@ namespace SIAG.Parser { public class ParseMuseum { - public static ODHActivityPoiLinked ParseMuseumToPG(ODHActivityPoiLinked mymuseum, XElement mysiagmuseum, string plz) + public static ODHActivityPoiLinked ParseMuseumToPG( + ODHActivityPoiLinked mymuseum, + XElement mysiagmuseum, + string plz + ) { XNamespace ax211 = "http://data.service.kks.siag/xsd"; @@ -50,7 +54,9 @@ public static ODHActivityPoiLinked ParseMuseumToPG(ODHActivityPoiLinked mymuseum string wwwDE = mysiagmuseum.Element(ax211 + "wwwD").Value; string wwwIT = mysiagmuseum.Element(ax211 + "wwwI").Value; - bool freeentrance = Convert.ToBoolean(mysiagmuseum.Element(ax211 + "freierEintritt").Value); + bool freeentrance = Convert.ToBoolean( + mysiagmuseum.Element(ax211 + "freierEintritt").Value + ); //bool besonderesobjekt = String.IsNullOrEmpty(mysiagmuseum.Element(ax211 + "besonderesObjekt").Value) ? false : Convert.ToBoolean(mysiagmuseum.Element(ax211 + "besonderesObjekt").Value); //string besonderesobjektDE = String.IsNullOrEmpty(mysiagmuseum.Element(ax211 + "besonderesObjekt").Value) ? "" : mysiagmuseum.Element(ax211 + "besonderesObjekt").Element(ax211 + "beschreibungD").Value; @@ -93,7 +99,7 @@ public static ODHActivityPoiLinked ParseMuseumToPG(ODHActivityPoiLinked mymuseum List imagegallerylist = new List(); - foreach(var photogallery in mysiagmuseum.Elements(ax211 + "photoGallery")) + foreach (var photogallery in mysiagmuseum.Elements(ax211 + "photoGallery")) { string imagedescDE = photogallery.Element(ax211 + "beschreibungD").Value; string imagedescIT = photogallery.Element(ax211 + "beschreibungI").Value; @@ -105,10 +111,10 @@ public static ODHActivityPoiLinked ParseMuseumToPG(ODHActivityPoiLinked mymuseum string titleEN = photogallery.Element(ax211 + "titelE").Value; string resourceid = photogallery.Element(ax211 + "resoId").Value; - ImageGallery myimage = new ImageGallery(); myimage.ImageSource = "SIAG"; - myimage.ImageUrl = "https://musport.prov.bz.it/musport/servlet/resource?id=" + resourceid; + myimage.ImageUrl = + "https://musport.prov.bz.it/musport/servlet/resource?id=" + resourceid; myimage.ImageTitle["de"] = titleDE; myimage.ImageTitle["it"] = titleIT; myimage.ImageTitle["en"] = titleEN; @@ -140,7 +146,10 @@ public static ODHActivityPoiLinked ParseMuseumToPG(ODHActivityPoiLinked mymuseum museumservicelistIT.Add(museumservice.Element(ax211 + "bezeichnungI").Value); museumservicelistEN.Add(museumservice.Element(ax211 + "bezeichnungE").Value); - if (museumservice.Element(ax211 + "bezeichnungD").Value == "Familienfreundliches Museum") + if ( + museumservice.Element(ax211 + "bezeichnungD").Value + == "Familienfreundliches Museum" + ) addfamilytag = true; if (museumservice.Element(ax211 + "bezeichnungD").Value == "Behindertengerecht") @@ -449,7 +458,7 @@ public static ODHActivityPoiLinked ParseMuseumToPG(ODHActivityPoiLinked mymuseum } mymuseum.SmgTags = smgtaglist.ToList(); - + return mymuseum; } } diff --git a/SIAG/Parser/ParseWeather.cs b/SIAG/Parser/ParseWeather.cs index 733c6dd6e..cb36f4653 100644 --- a/SIAG/Parser/ParseWeather.cs +++ b/SIAG/Parser/ParseWeather.cs @@ -12,16 +12,34 @@ public class ParseWeather { //string urlfrom indicates 'siag' old parsing, 'opendata' new url - public static Weather ParsemyWeatherResponse(string lang, XDocument weatherdataxml, XDocument weatherresponse, string urlfrom) + public static Weather ParsemyWeatherResponse( + string lang, + XDocument weatherdataxml, + XDocument weatherresponse, + string urlfrom + ) { try { Weather myweather = new Weather(); myweather.Id = Convert.ToInt32(weatherresponse.Root.Element("Id").Value); - myweather.date = Convert.ToDateTime(weatherresponse.Root.Element("date").Value.Replace("00:00:00", weatherresponse.Root.Element("hour").Value + ":00")); - myweather.evolution = weatherresponse.Root.Element("evolution") != null ? weatherresponse.Root.Element("evolution").Value : null; - myweather.evolutiontitle = weatherresponse.Root.Element("evolutionTitle") != null ? weatherresponse.Root.Element("evolutionTitle").Value : null; + myweather.date = Convert.ToDateTime( + weatherresponse.Root + .Element("date") + .Value.Replace( + "00:00:00", + weatherresponse.Root.Element("hour").Value + ":00" + ) + ); + myweather.evolution = + weatherresponse.Root.Element("evolution") != null + ? weatherresponse.Root.Element("evolution").Value + : null; + myweather.evolutiontitle = + weatherresponse.Root.Element("evolutionTitle") != null + ? weatherresponse.Root.Element("evolutionTitle").Value + : null; myweather.language = lang; myweather.LicenseInfo = Helper.LicenseHelper.GetLicenseforWeather(); @@ -44,14 +62,28 @@ public static Weather ParsemyWeatherResponse(string lang, XDocument weatherdatax myforecast.Reliability = forecast.Element("reliability").Value; myforecast.Weathercode = forecast.Element("symbol").Element("code").Value; - myforecast.Weatherdesc = forecast.Element("symbol").Element("description").Value; - myforecast.WeatherImgurl = forecast.Element("symbol").Element("imageURL").Value; - - myforecast.TempMaxmax = Convert.ToInt32(forecast.Element("tempMax").Element("max").Value); - myforecast.TempMaxmin = Convert.ToInt32(forecast.Element("tempMax").Element("min").Value); - - myforecast.TempMinmax = Convert.ToInt32(forecast.Element("tempMin").Element("max").Value); - myforecast.TempMinmin = Convert.ToInt32(forecast.Element("tempMin").Element("min").Value); + myforecast.Weatherdesc = forecast + .Element("symbol") + .Element("description") + .Value; + myforecast.WeatherImgurl = forecast + .Element("symbol") + .Element("imageURL") + .Value; + + myforecast.TempMaxmax = Convert.ToInt32( + forecast.Element("tempMax").Element("max").Value + ); + myforecast.TempMaxmin = Convert.ToInt32( + forecast.Element("tempMax").Element("min").Value + ); + + myforecast.TempMinmax = Convert.ToInt32( + forecast.Element("tempMin").Element("max").Value + ); + myforecast.TempMinmin = Convert.ToInt32( + forecast.Element("tempMin").Element("min").Value + ); myweather.Forecast.Add(myforecast); } @@ -63,31 +95,87 @@ public static Weather ParsemyWeatherResponse(string lang, XDocument weatherdatax { Mountain mymountaintoday = new Mountain(); mymountaintoday.date = Convert.ToDateTime(mountaintoday.Element("date").Value); - mymountaintoday.Title = mountaintoday.Element("title") != null ? mountaintoday.Element("title").Value : ""; - mymountaintoday.Zerolimit = mountaintoday.Element("zerolimit") != null ? mountaintoday.Element("zerolimit").Value : ""; - mymountaintoday.Weatherdesc = mountaintoday.Element("weather") != null ? mountaintoday.Element("weather").Value : ""; - - mymountaintoday.Conditions = mountaintoday.Element("conditions") != null ? mountaintoday.Element("conditions").Value : ""; + mymountaintoday.Title = + mountaintoday.Element("title") != null + ? mountaintoday.Element("title").Value + : ""; + mymountaintoday.Zerolimit = + mountaintoday.Element("zerolimit") != null + ? mountaintoday.Element("zerolimit").Value + : ""; + mymountaintoday.Weatherdesc = + mountaintoday.Element("weather") != null + ? mountaintoday.Element("weather").Value + : ""; + + mymountaintoday.Conditions = + mountaintoday.Element("conditions") != null + ? mountaintoday.Element("conditions").Value + : ""; mymountaintoday.MountainImgurl = mountaintoday.Element("imageURL").Value; - mymountaintoday.Moonrise = mountaintoday.Elements("moonRise").Count() > 0 ? mountaintoday.Element("moonRise").Value : ""; - mymountaintoday.Moonset = mountaintoday.Elements("moonSet").Count() > 0 ? mountaintoday.Element("moonSet").Value : ""; - mymountaintoday.Sunrise = mountaintoday.Elements("sunRise").Count() > 0 ? mountaintoday.Element("sunRise").Value : ""; - mymountaintoday.Sunset = mountaintoday.Elements("sunSet").Count() > 0 ? mountaintoday.Element("sunSet").Value : ""; + mymountaintoday.Moonrise = + mountaintoday.Elements("moonRise").Count() > 0 + ? mountaintoday.Element("moonRise").Value + : ""; + mymountaintoday.Moonset = + mountaintoday.Elements("moonSet").Count() > 0 + ? mountaintoday.Element("moonSet").Value + : ""; + mymountaintoday.Sunrise = + mountaintoday.Elements("sunRise").Count() > 0 + ? mountaintoday.Element("sunRise").Value + : ""; + mymountaintoday.Sunset = + mountaintoday.Elements("sunSet").Count() > 0 + ? mountaintoday.Element("sunSet").Value + : ""; mymountaintoday.Reliability = mountaintoday.Element("reliability").Value; - mymountaintoday.Temp1000 = Convert.ToInt32(mountaintoday.Element("temp1000").Value); - mymountaintoday.Temp2000 = Convert.ToInt32(mountaintoday.Element("temp2000").Value); - mymountaintoday.Temp3000 = Convert.ToInt32(mountaintoday.Element("temp3000").Value); - mymountaintoday.Temp4000 = Convert.ToInt32(mountaintoday.Element("temp4000").Value); - - mymountaintoday.Northcode = mountaintoday.Element("north").Element("code").Value; - mymountaintoday.Northdesc = mountaintoday.Element("north").Element("description").Value; - mymountaintoday.Northimgurl = mountaintoday.Element("north").Element("imageURL").Value; - mymountaintoday.Southcode = mountaintoday.Element("south").Element("code").Value; - mymountaintoday.Southdesc = mountaintoday.Element("south").Element("description").Value; - mymountaintoday.Southimgurl = mountaintoday.Element("south").Element("imageURL").Value; + mymountaintoday.Temp1000 = Convert.ToInt32( + mountaintoday.Element("temp1000").Value + ); + mymountaintoday.Temp2000 = Convert.ToInt32( + mountaintoday.Element("temp2000").Value + ); + mymountaintoday.Temp3000 = Convert.ToInt32( + mountaintoday.Element("temp3000").Value + ); + mymountaintoday.Temp4000 = Convert.ToInt32( + mountaintoday.Element("temp4000").Value + ); + + mymountaintoday.Northcode = mountaintoday + .Element("north") + .Element("code") + .Value; + mymountaintoday.Northdesc = mountaintoday + .Element("north") + .Element("description") + .Value; + mymountaintoday.Northimgurl = mountaintoday + .Element("north") + .Element("imageURL") + .Value; + mymountaintoday.Southcode = mountaintoday + .Element("south") + .Element("code") + .Value; + mymountaintoday.Southdesc = mountaintoday + .Element("south") + .Element("description") + .Value; + mymountaintoday.Southimgurl = mountaintoday + .Element("south") + .Element("imageURL") + .Value; mymountaintoday.Windcode = mountaintoday.Element("wind").Element("code").Value; - mymountaintoday.Winddesc = mountaintoday.Element("wind").Element("description").Value; - mymountaintoday.WindImgurl = mountaintoday.Element("wind").Element("imageURL").Value; + mymountaintoday.Winddesc = mountaintoday + .Element("wind") + .Element("description") + .Value; + mymountaintoday.WindImgurl = mountaintoday + .Element("wind") + .Element("imageURL") + .Value; myweather.Mountain.Add(mymountaintoday); } @@ -98,32 +186,103 @@ public static Weather ParsemyWeatherResponse(string lang, XDocument weatherdatax if (mountaintomorrow.HasElements) { Mountain mymountaintomorrow = new Mountain(); - mymountaintomorrow.date = Convert.ToDateTime(mountaintomorrow.Element("date").Value); - mymountaintomorrow.Title = mountaintomorrow.Element("title") != null ? mountaintomorrow.Element("title").Value : ""; - mymountaintomorrow.Zerolimit = mountaintomorrow.Element("zerolimit") != null ? mountaintomorrow.Element("zerolimit").Value : ""; - mymountaintomorrow.Weatherdesc = mountaintomorrow.Element("weather") != null ? mountaintomorrow.Element("weather").Value : ""; - - mymountaintomorrow.Conditions = mountaintomorrow.Element("conditions") != null ? mountaintomorrow.Element("conditions").Value : ""; - mymountaintomorrow.MountainImgurl = mountaintomorrow.Element("imageURL") != null ? mountaintomorrow.Element("imageURL").Value : ""; - mymountaintomorrow.Moonrise = mountaintomorrow.Elements("moonRise").Count() > 0 ? mountaintomorrow.Element("moonRise").Value : ""; - mymountaintomorrow.Moonset = mountaintomorrow.Elements("moonSet").Count() > 0 ? mountaintomorrow.Element("moonSet").Value : ""; - mymountaintomorrow.Sunrise = mountaintomorrow.Elements("sunRise").Count() > 0 ? mountaintomorrow.Element("sunRise").Value : ""; - mymountaintomorrow.Sunset = mountaintomorrow.Elements("sunSet").Count() > 0 ? mountaintomorrow.Element("sunSet").Value : ""; - mymountaintomorrow.Reliability = mountaintomorrow.Element("reliability") != null ? mountaintomorrow.Element("reliability").Value : ""; - mymountaintomorrow.Temp1000 = mountaintomorrow.Element("temp1000") != null ? Convert.ToInt32(mountaintomorrow.Element("temp1000").Value) : 0; - mymountaintomorrow.Temp2000 = mountaintomorrow.Element("temp2000") != null ? Convert.ToInt32(mountaintomorrow.Element("temp2000").Value) : 0; - mymountaintomorrow.Temp3000 = mountaintomorrow.Element("temp3000") != null ? Convert.ToInt32(mountaintomorrow.Element("temp3000").Value) : 0; - mymountaintomorrow.Temp4000 = mountaintomorrow.Element("temp4000") != null ? Convert.ToInt32(mountaintomorrow.Element("temp4000").Value) : 0; - - mymountaintomorrow.Northcode = mountaintomorrow.Element("north").Element("code").Value; - mymountaintomorrow.Northdesc = mountaintomorrow.Element("north").Element("description").Value; - mymountaintomorrow.Northimgurl = mountaintomorrow.Element("north").Element("imageURL").Value; - mymountaintomorrow.Southcode = mountaintomorrow.Element("south").Element("code").Value; - mymountaintomorrow.Southdesc = mountaintomorrow.Element("south").Element("description").Value; - mymountaintomorrow.Southimgurl = mountaintomorrow.Element("south").Element("imageURL").Value; - mymountaintomorrow.Windcode = mountaintomorrow.Element("wind").Element("code").Value; - mymountaintomorrow.Winddesc = mountaintomorrow.Element("wind").Element("description").Value; - mymountaintomorrow.WindImgurl = mountaintomorrow.Element("wind").Element("imageURL").Value; + mymountaintomorrow.date = Convert.ToDateTime( + mountaintomorrow.Element("date").Value + ); + mymountaintomorrow.Title = + mountaintomorrow.Element("title") != null + ? mountaintomorrow.Element("title").Value + : ""; + mymountaintomorrow.Zerolimit = + mountaintomorrow.Element("zerolimit") != null + ? mountaintomorrow.Element("zerolimit").Value + : ""; + mymountaintomorrow.Weatherdesc = + mountaintomorrow.Element("weather") != null + ? mountaintomorrow.Element("weather").Value + : ""; + + mymountaintomorrow.Conditions = + mountaintomorrow.Element("conditions") != null + ? mountaintomorrow.Element("conditions").Value + : ""; + mymountaintomorrow.MountainImgurl = + mountaintomorrow.Element("imageURL") != null + ? mountaintomorrow.Element("imageURL").Value + : ""; + mymountaintomorrow.Moonrise = + mountaintomorrow.Elements("moonRise").Count() > 0 + ? mountaintomorrow.Element("moonRise").Value + : ""; + mymountaintomorrow.Moonset = + mountaintomorrow.Elements("moonSet").Count() > 0 + ? mountaintomorrow.Element("moonSet").Value + : ""; + mymountaintomorrow.Sunrise = + mountaintomorrow.Elements("sunRise").Count() > 0 + ? mountaintomorrow.Element("sunRise").Value + : ""; + mymountaintomorrow.Sunset = + mountaintomorrow.Elements("sunSet").Count() > 0 + ? mountaintomorrow.Element("sunSet").Value + : ""; + mymountaintomorrow.Reliability = + mountaintomorrow.Element("reliability") != null + ? mountaintomorrow.Element("reliability").Value + : ""; + mymountaintomorrow.Temp1000 = + mountaintomorrow.Element("temp1000") != null + ? Convert.ToInt32(mountaintomorrow.Element("temp1000").Value) + : 0; + mymountaintomorrow.Temp2000 = + mountaintomorrow.Element("temp2000") != null + ? Convert.ToInt32(mountaintomorrow.Element("temp2000").Value) + : 0; + mymountaintomorrow.Temp3000 = + mountaintomorrow.Element("temp3000") != null + ? Convert.ToInt32(mountaintomorrow.Element("temp3000").Value) + : 0; + mymountaintomorrow.Temp4000 = + mountaintomorrow.Element("temp4000") != null + ? Convert.ToInt32(mountaintomorrow.Element("temp4000").Value) + : 0; + + mymountaintomorrow.Northcode = mountaintomorrow + .Element("north") + .Element("code") + .Value; + mymountaintomorrow.Northdesc = mountaintomorrow + .Element("north") + .Element("description") + .Value; + mymountaintomorrow.Northimgurl = mountaintomorrow + .Element("north") + .Element("imageURL") + .Value; + mymountaintomorrow.Southcode = mountaintomorrow + .Element("south") + .Element("code") + .Value; + mymountaintomorrow.Southdesc = mountaintomorrow + .Element("south") + .Element("description") + .Value; + mymountaintomorrow.Southimgurl = mountaintomorrow + .Element("south") + .Element("imageURL") + .Value; + mymountaintomorrow.Windcode = mountaintomorrow + .Element("wind") + .Element("code") + .Value; + mymountaintomorrow.Winddesc = mountaintomorrow + .Element("wind") + .Element("description") + .Value; + mymountaintomorrow.WindImgurl = mountaintomorrow + .Element("wind") + .Element("imageURL") + .Value; myweather.Mountain.Add(mymountaintomorrow); } @@ -135,11 +294,20 @@ public static Weather ParsemyWeatherResponse(string lang, XDocument weatherdatax Conditions myconditiontoday = new Conditions(); myconditiontoday.date = Convert.ToDateTime(today.Element("date").Value); - myconditiontoday.WeatherCondition = today.Element("conditions") != null ? today.Element("conditions").Value : ""; - myconditiontoday.WeatherImgurl = today.Element("imageURL") != null ? today.Element("imageURL").Value : ""; - myconditiontoday.Weatherdesc = today.Element("weather") != null ? today.Element("weather").Value : ""; - myconditiontoday.Title = today.Element("title") != null ? today.Element("title").Value : ""; - myconditiontoday.Temperatures = today.Element("temperatures") != null ? today.Element("temperatures").Value : ""; + myconditiontoday.WeatherCondition = + today.Element("conditions") != null + ? today.Element("conditions").Value + : ""; + myconditiontoday.WeatherImgurl = + today.Element("imageURL") != null ? today.Element("imageURL").Value : ""; + myconditiontoday.Weatherdesc = + today.Element("weather") != null ? today.Element("weather").Value : ""; + myconditiontoday.Title = + today.Element("title") != null ? today.Element("title").Value : ""; + myconditiontoday.Temperatures = + today.Element("temperatures") != null + ? today.Element("temperatures").Value + : ""; myweather.Conditions.Add(myconditiontoday); } @@ -154,34 +322,65 @@ public static Weather ParsemyWeatherResponse(string lang, XDocument weatherdatax { Stationdata mystationdatatoday = new Stationdata(); - mystationdatatoday.date = Convert.ToDateTime(today.Element("date").Value); - - mystationdatatoday.Id = Convert.ToInt32(stationtoday.Element("Id").Value); - var mystationdatacity = weatherdataxml.Root.Elements("Station").Where(x => x.Attribute("Id").Value.Equals(stationtoday.Element("Id").Value)).FirstOrDefault(); - mystationdatatoday.CityName = mystationdatacity.Attribute("Name" + lang.ToUpper()).Value; + mystationdatatoday.date = Convert.ToDateTime( + today.Element("date").Value + ); + + mystationdatatoday.Id = Convert.ToInt32( + stationtoday.Element("Id").Value + ); + var mystationdatacity = weatherdataxml.Root + .Elements("Station") + .Where( + x => + x.Attribute("Id") + .Value.Equals(stationtoday.Element("Id").Value) + ) + .FirstOrDefault(); + mystationdatatoday.CityName = mystationdatacity + .Attribute("Name" + lang.ToUpper()) + .Value; if (lang == "en") { if (mystationdatatoday.CityName.Contains("/")) { - mystationdatatoday.CityName = mystationdatatoday.CityName.Replace("/", " / "); + mystationdatatoday.CityName = + mystationdatatoday.CityName.Replace("/", " / "); } } //mystationdatatoday.stationdatacityrid = mystationdatacity.Attribute("RID").Value; - mystationdatatoday.WeatherCode = stationtoday.Element("symbol").Element("code").Value; - mystationdatatoday.WeatherDesc = stationtoday.Element("symbol").Element("description").Value; - mystationdatatoday.WeatherImgUrl = stationtoday.Element("symbol").Element("imageURL").Value; + mystationdatatoday.WeatherCode = stationtoday + .Element("symbol") + .Element("code") + .Value; + mystationdatatoday.WeatherDesc = stationtoday + .Element("symbol") + .Element("description") + .Value; + mystationdatatoday.WeatherImgUrl = stationtoday + .Element("symbol") + .Element("imageURL") + .Value; if (urlfrom == "siag") { - mystationdatatoday.Maxtemp = Convert.ToInt32(stationtoday.Element("temperature").Element("max").Value); - mystationdatatoday.MinTemp = Convert.ToInt32(stationtoday.Element("temperature").Element("min").Value); + mystationdatatoday.Maxtemp = Convert.ToInt32( + stationtoday.Element("temperature").Element("max").Value + ); + mystationdatatoday.MinTemp = Convert.ToInt32( + stationtoday.Element("temperature").Element("min").Value + ); } else { - mystationdatatoday.Maxtemp = Convert.ToInt32(stationtoday.Element("max").Value); - mystationdatatoday.MinTemp = Convert.ToInt32(stationtoday.Element("min").Value); + mystationdatatoday.Maxtemp = Convert.ToInt32( + stationtoday.Element("max").Value + ); + mystationdatatoday.MinTemp = Convert.ToInt32( + stationtoday.Element("min").Value + ); } myweather.Stationdata.Add(mystationdatatoday); @@ -196,12 +395,29 @@ public static Weather ParsemyWeatherResponse(string lang, XDocument weatherdatax { Conditions myconditiontomorrow = new Conditions(); - myconditiontomorrow.date = Convert.ToDateTime(tomorrow.Element("date").Value); - myconditiontomorrow.WeatherCondition = tomorrow.Element("conditions") != null ? tomorrow.Element("conditions").Value : ""; - myconditiontomorrow.WeatherImgurl = tomorrow.Element("imageURL") != null ? tomorrow.Element("imageURL").Value : ""; - myconditiontomorrow.Weatherdesc = tomorrow.Element("weather") != null ? tomorrow.Element("weather").Value : ""; - myconditiontomorrow.Title = tomorrow.Element("title") != null ? tomorrow.Element("title").Value : ""; - myconditiontomorrow.Temperatures = tomorrow.Element("temperatures") != null ? tomorrow.Element("temperatures").Value : ""; + myconditiontomorrow.date = Convert.ToDateTime( + tomorrow.Element("date").Value + ); + myconditiontomorrow.WeatherCondition = + tomorrow.Element("conditions") != null + ? tomorrow.Element("conditions").Value + : ""; + myconditiontomorrow.WeatherImgurl = + tomorrow.Element("imageURL") != null + ? tomorrow.Element("imageURL").Value + : ""; + myconditiontomorrow.Weatherdesc = + tomorrow.Element("weather") != null + ? tomorrow.Element("weather").Value + : ""; + myconditiontomorrow.Title = + tomorrow.Element("title") != null + ? tomorrow.Element("title").Value + : ""; + myconditiontomorrow.Temperatures = + tomorrow.Element("temperatures") != null + ? tomorrow.Element("temperatures").Value + : ""; myweather.Conditions.Add(myconditiontomorrow); } @@ -219,34 +435,65 @@ public static Weather ParsemyWeatherResponse(string lang, XDocument weatherdatax { Stationdata mystationdatatomorrow = new Stationdata(); - mystationdatatomorrow.date = Convert.ToDateTime(tomorrow.Element("date").Value); - - mystationdatatomorrow.Id = Convert.ToInt32(stationtomorrow.Element("Id").Value); - var mystationdatacity = weatherdataxml.Root.Elements("Station").Where(x => x.Attribute("Id").Value.Equals(stationtomorrow.Element("Id").Value)).FirstOrDefault(); - mystationdatatomorrow.CityName = mystationdatacity.Attribute("Name" + lang.ToUpper()).Value; + mystationdatatomorrow.date = Convert.ToDateTime( + tomorrow.Element("date").Value + ); + + mystationdatatomorrow.Id = Convert.ToInt32( + stationtomorrow.Element("Id").Value + ); + var mystationdatacity = weatherdataxml.Root + .Elements("Station") + .Where( + x => + x.Attribute("Id") + .Value.Equals(stationtomorrow.Element("Id").Value) + ) + .FirstOrDefault(); + mystationdatatomorrow.CityName = mystationdatacity + .Attribute("Name" + lang.ToUpper()) + .Value; //mystationdatatomorrow.stationdatacityrid = mystationdatacity.Attribute("RID").Value; if (lang == "en") { if (mystationdatatomorrow.CityName.Contains("/")) { - mystationdatatomorrow.CityName = mystationdatatomorrow.CityName.Replace("/", " / "); + mystationdatatomorrow.CityName = + mystationdatatomorrow.CityName.Replace("/", " / "); } } - mystationdatatomorrow.WeatherCode = stationtomorrow.Element("symbol").Element("code").Value; - mystationdatatomorrow.WeatherDesc = stationtomorrow.Element("symbol").Element("description").Value; - mystationdatatomorrow.WeatherImgUrl = stationtomorrow.Element("symbol").Element("imageURL").Value; + mystationdatatomorrow.WeatherCode = stationtomorrow + .Element("symbol") + .Element("code") + .Value; + mystationdatatomorrow.WeatherDesc = stationtomorrow + .Element("symbol") + .Element("description") + .Value; + mystationdatatomorrow.WeatherImgUrl = stationtomorrow + .Element("symbol") + .Element("imageURL") + .Value; if (urlfrom == "siag") { - mystationdatatomorrow.Maxtemp = Convert.ToInt32(stationtomorrow.Element("temperature").Element("max").Value); - mystationdatatomorrow.MinTemp = Convert.ToInt32(stationtomorrow.Element("temperature").Element("min").Value); + mystationdatatomorrow.Maxtemp = Convert.ToInt32( + stationtomorrow.Element("temperature").Element("max").Value + ); + mystationdatatomorrow.MinTemp = Convert.ToInt32( + stationtomorrow.Element("temperature").Element("min").Value + ); } else { - mystationdatatomorrow.Maxtemp = Convert.ToInt32(stationtomorrow.Element("max").Value); - mystationdatatomorrow.MinTemp = Convert.ToInt32(stationtomorrow.Element("min").Value); + mystationdatatomorrow.Maxtemp = Convert.ToInt32( + stationtomorrow.Element("max").Value + ); + mystationdatatomorrow.MinTemp = Convert.ToInt32( + stationtomorrow.Element("min").Value + ); } myweather.Stationdata.Add(mystationdatatomorrow); @@ -263,12 +510,22 @@ public static Weather ParsemyWeatherResponse(string lang, XDocument weatherdatax } } - public static Weather ParsemyStationWeatherResponse(string lang, XDocument weatherdataxml, XDocument weatherresponse, string stationid, string urlfrom) + public static Weather ParsemyStationWeatherResponse( + string lang, + XDocument weatherdataxml, + XDocument weatherresponse, + string stationid, + string urlfrom + ) { Weather myweather = new Weather(); myweather.Id = Convert.ToInt32(weatherresponse.Root.Element("Id").Value); - myweather.date = Convert.ToDateTime(weatherresponse.Root.Element("date").Value.Replace("00:00:00", weatherresponse.Root.Element("hour").Value + ":00")); + myweather.date = Convert.ToDateTime( + weatherresponse.Root + .Element("date") + .Value.Replace("00:00:00", weatherresponse.Root.Element("hour").Value + ":00") + ); myweather.LicenseInfo = Helper.LicenseHelper.GetLicenseforWeather(); var today = weatherresponse.Root.Element("today"); @@ -281,39 +538,71 @@ public static Weather ParsemyStationWeatherResponse(string lang, XDocument weath if (stationstoday != null) { - foreach (XElement stationtoday in stationstoday.Where(x => x.Element("Id").Value == stationid)) + foreach ( + XElement stationtoday in stationstoday.Where( + x => x.Element("Id").Value == stationid + ) + ) { Stationdata mystationdatatoday = new Stationdata(); mystationdatatoday.date = Convert.ToDateTime(today.Element("date").Value); mystationdatatoday.Id = Convert.ToInt32(stationtoday.Element("Id").Value); - var mystationdatacity = weatherdataxml.Root.Elements("Station").Where(x => x.Attribute("Id").Value.Equals(stationtoday.Element("Id").Value)).FirstOrDefault(); - mystationdatatoday.CityName = mystationdatacity.Attribute("Name" + lang.ToUpper()).Value; + var mystationdatacity = weatherdataxml.Root + .Elements("Station") + .Where( + x => + x.Attribute("Id").Value.Equals(stationtoday.Element("Id").Value) + ) + .FirstOrDefault(); + mystationdatatoday.CityName = mystationdatacity + .Attribute("Name" + lang.ToUpper()) + .Value; if (lang == "en") { if (mystationdatatoday.CityName.Contains("/")) { - mystationdatatoday.CityName = mystationdatatoday.CityName.Replace("/", " / "); + mystationdatatoday.CityName = mystationdatatoday.CityName.Replace( + "/", + " / " + ); } } //mystationdatatoday.stationdatacityrid = mystationdatacity.Attribute("RID").Value; - mystationdatatoday.WeatherCode = stationtoday.Element("symbol").Element("code").Value; - mystationdatatoday.WeatherDesc = stationtoday.Element("symbol").Element("description").Value; - mystationdatatoday.WeatherImgUrl = stationtoday.Element("symbol").Element("imageURL").Value; + mystationdatatoday.WeatherCode = stationtoday + .Element("symbol") + .Element("code") + .Value; + mystationdatatoday.WeatherDesc = stationtoday + .Element("symbol") + .Element("description") + .Value; + mystationdatatoday.WeatherImgUrl = stationtoday + .Element("symbol") + .Element("imageURL") + .Value; if (urlfrom == "siag") { - mystationdatatoday.Maxtemp = Convert.ToInt32(stationtoday.Element("temperature").Element("max").Value); - mystationdatatoday.MinTemp = Convert.ToInt32(stationtoday.Element("temperature").Element("min").Value); + mystationdatatoday.Maxtemp = Convert.ToInt32( + stationtoday.Element("temperature").Element("max").Value + ); + mystationdatatoday.MinTemp = Convert.ToInt32( + stationtoday.Element("temperature").Element("min").Value + ); } else { - mystationdatatoday.Maxtemp = Convert.ToInt32(stationtoday.Element("max").Value); - mystationdatatoday.MinTemp = Convert.ToInt32(stationtoday.Element("min").Value); + mystationdatatoday.Maxtemp = Convert.ToInt32( + stationtoday.Element("max").Value + ); + mystationdatatoday.MinTemp = Convert.ToInt32( + stationtoday.Element("min").Value + ); } myweather.Stationdata.Add(mystationdatatoday); @@ -327,28 +616,55 @@ public static Weather ParsemyStationWeatherResponse(string lang, XDocument weath var stationstomorrow = tomorrow.Elements("stationData"); if (stationstomorrow != null) { - foreach (XElement stationtomorrow in stationstomorrow.Where(x => x.Element("Id").Value == stationid)) + foreach ( + XElement stationtomorrow in stationstomorrow.Where( + x => x.Element("Id").Value == stationid + ) + ) { Stationdata mystationdatatomorrow = new Stationdata(); - mystationdatatomorrow.date = Convert.ToDateTime(tomorrow.Element("date").Value); - - mystationdatatomorrow.Id = Convert.ToInt32(stationtomorrow.Element("Id").Value); - var mystationdatacity = weatherdataxml.Root.Elements("Station").Where(x => x.Attribute("Id").Value.Equals(stationtomorrow.Element("Id").Value)).FirstOrDefault(); - mystationdatatomorrow.CityName = mystationdatacity.Attribute("Name" + lang.ToUpper()).Value; + mystationdatatomorrow.date = Convert.ToDateTime( + tomorrow.Element("date").Value + ); + + mystationdatatomorrow.Id = Convert.ToInt32( + stationtomorrow.Element("Id").Value + ); + var mystationdatacity = weatherdataxml.Root + .Elements("Station") + .Where( + x => + x.Attribute("Id") + .Value.Equals(stationtomorrow.Element("Id").Value) + ) + .FirstOrDefault(); + mystationdatatomorrow.CityName = mystationdatacity + .Attribute("Name" + lang.ToUpper()) + .Value; if (lang == "en") { if (mystationdatatomorrow.CityName.Contains("/")) { - mystationdatatomorrow.CityName = mystationdatatomorrow.CityName.Replace("/", " / "); + mystationdatatomorrow.CityName = + mystationdatatomorrow.CityName.Replace("/", " / "); } } //mystationdatatomorrow.stationdatacityrid = mystationdatacity.Attribute("RID").Value; - mystationdatatomorrow.WeatherCode = stationtomorrow.Element("symbol").Element("code").Value; - mystationdatatomorrow.WeatherDesc = stationtomorrow.Element("symbol").Element("description").Value; - mystationdatatomorrow.WeatherImgUrl = stationtomorrow.Element("symbol").Element("imageURL").Value; + mystationdatatomorrow.WeatherCode = stationtomorrow + .Element("symbol") + .Element("code") + .Value; + mystationdatatomorrow.WeatherDesc = stationtomorrow + .Element("symbol") + .Element("description") + .Value; + mystationdatatomorrow.WeatherImgUrl = stationtomorrow + .Element("symbol") + .Element("imageURL") + .Value; if (urlfrom == "siag") { @@ -357,8 +673,12 @@ public static Weather ParsemyStationWeatherResponse(string lang, XDocument weath } else { - mystationdatatomorrow.Maxtemp = Convert.ToInt32(stationtomorrow.Element("max").Value); - mystationdatatomorrow.MinTemp = Convert.ToInt32(stationtomorrow.Element("min").Value); + mystationdatatomorrow.Maxtemp = Convert.ToInt32( + stationtomorrow.Element("max").Value + ); + mystationdatatomorrow.MinTemp = Convert.ToInt32( + stationtomorrow.Element("min").Value + ); } myweather.Stationdata.Add(mystationdatatomorrow); @@ -369,15 +689,25 @@ public static Weather ParsemyStationWeatherResponse(string lang, XDocument weath return myweather; } - public static BezirksWeather ParsemyBezirksWeatherResponse(string lang, XDocument weatherresponse, string urlfrom) + public static BezirksWeather ParsemyBezirksWeatherResponse( + string lang, + XDocument weatherresponse, + string urlfrom + ) { BezirksWeather myweather = new BezirksWeather(); - myweather.Id = Convert.ToInt32(weatherresponse.Root.Element("district").Element("Id").Value); + myweather.Id = Convert.ToInt32( + weatherresponse.Root.Element("district").Element("Id").Value + ); myweather.DistrictName = weatherresponse.Root.Element("district").Element("name").Value; myweather.LicenseInfo = Helper.LicenseHelper.GetLicenseforWeather(); - myweather.date = Convert.ToDateTime(weatherresponse.Root.Element("date").Value.Replace("00:00:00", weatherresponse.Root.Element("hour").Value + ":00")); + myweather.date = Convert.ToDateTime( + weatherresponse.Root + .Element("date") + .Value.Replace("00:00:00", weatherresponse.Root.Element("hour").Value + ":00") + ); var mybezirkforecasts = weatherresponse.Root.Elements("forecast"); @@ -386,65 +716,140 @@ public static BezirksWeather ParsemyBezirksWeatherResponse(string lang, XDocumen //Tomorrow info foreach (var mybezirkforecast in mybezirkforecasts) { - BezirksForecast bezirksforecast = new BezirksForecast(); bezirksforecast.date = Convert.ToDateTime(mybezirkforecast.Element("date").Value); - bezirksforecast.WeatherCode = mybezirkforecast.Element("symbol").Element("code").Value; - bezirksforecast.WeatherDesc = mybezirkforecast.Element("symbol").Element("description").Value; - bezirksforecast.WeatherImgUrl = mybezirkforecast.Element("symbol").Element("imageURL").Value; + bezirksforecast.WeatherCode = mybezirkforecast + .Element("symbol") + .Element("code") + .Value; + bezirksforecast.WeatherDesc = mybezirkforecast + .Element("symbol") + .Element("description") + .Value; + bezirksforecast.WeatherImgUrl = mybezirkforecast + .Element("symbol") + .Element("imageURL") + .Value; bezirksforecast.Freeze = Convert.ToInt16(mybezirkforecast.Element("freeze").Value); - bezirksforecast.RainFrom = Convert.ToInt16(mybezirkforecast.Element("rainFrom").Value); + bezirksforecast.RainFrom = Convert.ToInt16( + mybezirkforecast.Element("rainFrom").Value + ); bezirksforecast.RainTo = Convert.ToInt16(mybezirkforecast.Element("rainTo").Value); if (urlfrom == "siag") { - bezirksforecast.MaxTemp = Convert.ToInt16(mybezirkforecast.Element("temperature").Element("max").Value); - bezirksforecast.MinTemp = Convert.ToInt16(mybezirkforecast.Element("temperature").Element("min").Value); - - bezirksforecast.Part1 = mybezirkforecast.Element("part1") != null ? Convert.ToInt16(mybezirkforecast.Element("part1").Value) : 0; - bezirksforecast.Part2 = mybezirkforecast.Element("part2") != null ? Convert.ToInt16(mybezirkforecast.Element("part2").Value) : 0; - bezirksforecast.Part3 = mybezirkforecast.Element("part3") != null ? Convert.ToInt16(mybezirkforecast.Element("part3").Value) : 0; - bezirksforecast.Part4 = mybezirkforecast.Element("part4") != null ? Convert.ToInt16(mybezirkforecast.Element("part4").Value) : 0; - - if (mybezirkforecast.Element("part3") == null && mybezirkforecast.Element("part4") == null) + bezirksforecast.MaxTemp = Convert.ToInt16( + mybezirkforecast.Element("temperature").Element("max").Value + ); + bezirksforecast.MinTemp = Convert.ToInt16( + mybezirkforecast.Element("temperature").Element("min").Value + ); + + bezirksforecast.Part1 = + mybezirkforecast.Element("part1") != null + ? Convert.ToInt16(mybezirkforecast.Element("part1").Value) + : 0; + bezirksforecast.Part2 = + mybezirkforecast.Element("part2") != null + ? Convert.ToInt16(mybezirkforecast.Element("part2").Value) + : 0; + bezirksforecast.Part3 = + mybezirkforecast.Element("part3") != null + ? Convert.ToInt16(mybezirkforecast.Element("part3").Value) + : 0; + bezirksforecast.Part4 = + mybezirkforecast.Element("part4") != null + ? Convert.ToInt16(mybezirkforecast.Element("part4").Value) + : 0; + + if ( + mybezirkforecast.Element("part3") == null + && mybezirkforecast.Element("part4") == null + ) { - bezirksforecast.Part1 = mybezirkforecast.Element("part1") != null ? Convert.ToInt16(mybezirkforecast.Element("part1").Value) : 0; - bezirksforecast.Part2 = mybezirkforecast.Element("part1") != null ? Convert.ToInt16(mybezirkforecast.Element("part1").Value) : 0; - bezirksforecast.Part3 = mybezirkforecast.Element("part2") != null ? Convert.ToInt16(mybezirkforecast.Element("part2").Value) : 0; - bezirksforecast.Part4 = mybezirkforecast.Element("part2") != null ? Convert.ToInt16(mybezirkforecast.Element("part2").Value) : 0; + bezirksforecast.Part1 = + mybezirkforecast.Element("part1") != null + ? Convert.ToInt16(mybezirkforecast.Element("part1").Value) + : 0; + bezirksforecast.Part2 = + mybezirkforecast.Element("part1") != null + ? Convert.ToInt16(mybezirkforecast.Element("part1").Value) + : 0; + bezirksforecast.Part3 = + mybezirkforecast.Element("part2") != null + ? Convert.ToInt16(mybezirkforecast.Element("part2").Value) + : 0; + bezirksforecast.Part4 = + mybezirkforecast.Element("part2") != null + ? Convert.ToInt16(mybezirkforecast.Element("part2").Value) + : 0; } - bezirksforecast.Thunderstorm = Convert.ToInt16(mybezirkforecast.Element("thunderStorm").Value); + bezirksforecast.Thunderstorm = Convert.ToInt16( + mybezirkforecast.Element("thunderStorm").Value + ); } else { - bezirksforecast.MaxTemp = Convert.ToInt16(mybezirkforecast.Element("temperatureMax").Value); - bezirksforecast.MinTemp = Convert.ToInt16(mybezirkforecast.Element("temperatureMin").Value); - - bezirksforecast.Part1 = mybezirkforecast.Element("rainTimespan1") != null ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan1").Value) : 0; - bezirksforecast.Part2 = mybezirkforecast.Element("rainTimespan2") != null ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan2").Value) : 0; - bezirksforecast.Part3 = mybezirkforecast.Element("rainTimespan3") != null ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan3").Value) : 0; - bezirksforecast.Part4 = mybezirkforecast.Element("rainTimespan4") != null ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan4").Value) : 0; - - if (mybezirkforecast.Element("rainTimespan3") == null && mybezirkforecast.Element("rainTimespan4") == null) + bezirksforecast.MaxTemp = Convert.ToInt16( + mybezirkforecast.Element("temperatureMax").Value + ); + bezirksforecast.MinTemp = Convert.ToInt16( + mybezirkforecast.Element("temperatureMin").Value + ); + + bezirksforecast.Part1 = + mybezirkforecast.Element("rainTimespan1") != null + ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan1").Value) + : 0; + bezirksforecast.Part2 = + mybezirkforecast.Element("rainTimespan2") != null + ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan2").Value) + : 0; + bezirksforecast.Part3 = + mybezirkforecast.Element("rainTimespan3") != null + ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan3").Value) + : 0; + bezirksforecast.Part4 = + mybezirkforecast.Element("rainTimespan4") != null + ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan4").Value) + : 0; + + if ( + mybezirkforecast.Element("rainTimespan3") == null + && mybezirkforecast.Element("rainTimespan4") == null + ) { - bezirksforecast.Part1 = mybezirkforecast.Element("rainTimespan1") != null ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan1").Value) : 0; - bezirksforecast.Part2 = mybezirkforecast.Element("rainTimespan1") != null ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan1").Value) : 0; - bezirksforecast.Part3 = mybezirkforecast.Element("rainTimespan2") != null ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan2").Value) : 0; - bezirksforecast.Part4 = mybezirkforecast.Element("rainTimespan2") != null ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan2").Value) : 0; + bezirksforecast.Part1 = + mybezirkforecast.Element("rainTimespan1") != null + ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan1").Value) + : 0; + bezirksforecast.Part2 = + mybezirkforecast.Element("rainTimespan1") != null + ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan1").Value) + : 0; + bezirksforecast.Part3 = + mybezirkforecast.Element("rainTimespan2") != null + ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan2").Value) + : 0; + bezirksforecast.Part4 = + mybezirkforecast.Element("rainTimespan2") != null + ? Convert.ToInt16(mybezirkforecast.Element("rainTimespan2").Value) + : 0; } - bezirksforecast.Thunderstorm = Convert.ToInt16(mybezirkforecast.Element("storms").Value); + bezirksforecast.Thunderstorm = Convert.ToInt16( + mybezirkforecast.Element("storms").Value + ); } - //TODO no + //TODO no mybezirksforecastlist.Add(bezirksforecast); - } myweather.BezirksForecast = mybezirksforecastlist.ToList(); @@ -454,16 +859,24 @@ public static BezirksWeather ParsemyBezirksWeatherResponse(string lang, XDocumen //JSON Response Parser - public static Weather ParsemyWeatherJsonResponse(string lang, XDocument weatherdataxml, string weatherresponsejson) + public static Weather ParsemyWeatherJsonResponse( + string lang, + XDocument weatherdataxml, + string weatherresponsejson + ) { - var siagweather = JsonConvert.DeserializeObject(weatherresponsejson); - + var siagweather = JsonConvert.DeserializeObject( + weatherresponsejson + ); + try { Weather myweather = new Weather(); myweather.Id = Convert.ToInt32(siagweather.id); - myweather.date = Convert.ToDateTime(siagweather.date.ToShortDateString() + " " + siagweather.hour); + myweather.date = Convert.ToDateTime( + siagweather.date.ToShortDateString() + " " + siagweather.hour + ); myweather.evolution = siagweather.evolution; myweather.evolutiontitle = siagweather.evolutionTitle; myweather.language = lang; @@ -497,7 +910,9 @@ public static Weather ParsemyWeatherJsonResponse(string lang, XDocument weatherd mymountaintoday.date = siagweather.mountainToday.date; mymountaintoday.Title = siagweather.mountainToday.title; mymountaintoday.Zerolimit = siagweather.mountainToday.zeroLimit.ToString(); - mymountaintoday.Snowlimit = siagweather.mountainToday.snowLimit.Select(x => x.ToString()).ToList(); + mymountaintoday.Snowlimit = siagweather.mountainToday.snowLimit + .Select(x => x.ToString()) + .ToList(); mymountaintoday.Weatherdesc = siagweather.mountainToday.weather; @@ -533,8 +948,11 @@ public static Weather ParsemyWeatherJsonResponse(string lang, XDocument weatherd Mountain mymountaintomorrow = new Mountain(); mymountaintomorrow.date = siagweather.mountainTomorrow.date; mymountaintomorrow.Title = siagweather.mountainTomorrow.title; - mymountaintomorrow.Zerolimit = siagweather.mountainTomorrow.zeroLimit.ToString(); - mymountaintomorrow.Snowlimit = siagweather.mountainTomorrow.snowLimit.Select(x => x.ToString()).ToList(); + mymountaintomorrow.Zerolimit = + siagweather.mountainTomorrow.zeroLimit.ToString(); + mymountaintomorrow.Snowlimit = siagweather.mountainTomorrow.snowLimit + .Select(x => x.ToString()) + .ToList(); mymountaintomorrow.Weatherdesc = siagweather.mountainTomorrow.weather; @@ -544,11 +962,20 @@ public static Weather ParsemyWeatherJsonResponse(string lang, XDocument weatherd mymountaintomorrow.Moonset = siagweather.mountainTomorrow.moonSet; mymountaintomorrow.Sunrise = siagweather.mountainTomorrow.sunRise; mymountaintomorrow.Sunset = siagweather.mountainTomorrow.sunSet; - mymountaintomorrow.Reliability = siagweather.mountainTomorrow.reliability.ToString(); - mymountaintomorrow.Temp1000 = Convert.ToInt32(siagweather.mountainTomorrow.temp1000); - mymountaintomorrow.Temp2000 = Convert.ToInt32(siagweather.mountainTomorrow.temp3000); - mymountaintomorrow.Temp3000 = Convert.ToInt32(siagweather.mountainTomorrow.temp3000); - mymountaintomorrow.Temp4000 = Convert.ToInt32(siagweather.mountainTomorrow.temp4000); + mymountaintomorrow.Reliability = + siagweather.mountainTomorrow.reliability.ToString(); + mymountaintomorrow.Temp1000 = Convert.ToInt32( + siagweather.mountainTomorrow.temp1000 + ); + mymountaintomorrow.Temp2000 = Convert.ToInt32( + siagweather.mountainTomorrow.temp3000 + ); + mymountaintomorrow.Temp3000 = Convert.ToInt32( + siagweather.mountainTomorrow.temp3000 + ); + mymountaintomorrow.Temp4000 = Convert.ToInt32( + siagweather.mountainTomorrow.temp4000 + ); mymountaintomorrow.Northcode = siagweather.mountainTomorrow.north.code; mymountaintomorrow.Northdesc = siagweather.mountainTomorrow.north.description; @@ -560,15 +987,17 @@ public static Weather ParsemyWeatherJsonResponse(string lang, XDocument weatherd mymountaintomorrow.Winddesc = siagweather.mountainTomorrow.wind.description; mymountaintomorrow.WindImgurl = siagweather.mountainTomorrow.wind.imageUrl; - myweather.Mountain.Add(mymountaintomorrow); + myweather.Mountain.Add(mymountaintomorrow); } //Today Info if (siagweather.today != null) { Conditions myconditiontoday = new Conditions(); - - myconditiontoday.date = Convert.ToDateTime(siagweather.today.date.ToShortDateString() + " " + siagweather.today.hour); //TODO CHeck + + myconditiontoday.date = Convert.ToDateTime( + siagweather.today.date.ToShortDateString() + " " + siagweather.today.hour + ); //TODO CHeck myconditiontoday.WeatherCondition = siagweather.today.conditions; myconditiontoday.WeatherImgurl = siagweather.today.imageUrl; myconditiontoday.Weatherdesc = siagweather.today.weather; @@ -597,17 +1026,27 @@ public static Weather ParsemyWeatherJsonResponse(string lang, XDocument weatherd { Stationdata mystationdatatoday = new Stationdata(); - mystationdatatoday.date = Convert.ToDateTime(siagweather.today.date.ToShortDateString() + " " + siagweather.today.hour); //TODO CHeck + mystationdatatoday.date = Convert.ToDateTime( + siagweather.today.date.ToShortDateString() + + " " + + siagweather.today.hour + ); //TODO CHeck mystationdatatoday.Id = i; - var mystationdatacity = weatherdataxml.Root.Elements("Station").Where(x => x.Attribute("Id").Value.Equals(i.ToString())).FirstOrDefault(); - mystationdatatoday.CityName = mystationdatacity.Attribute("Name" + lang.ToUpper()).Value; + var mystationdatacity = weatherdataxml.Root + .Elements("Station") + .Where(x => x.Attribute("Id").Value.Equals(i.ToString())) + .FirstOrDefault(); + mystationdatatoday.CityName = mystationdatacity + .Attribute("Name" + lang.ToUpper()) + .Value; if (lang == "en") { if (mystationdatatoday.CityName.Contains("/")) { - mystationdatatoday.CityName = mystationdatatoday.CityName.Replace("/", " / "); + mystationdatatoday.CityName = + mystationdatatoday.CityName.Replace("/", " / "); } } //mystationdatatoday.stationdatacityrid = mystationdatacity.Attribute("RID").Value; @@ -617,7 +1056,7 @@ public static Weather ParsemyWeatherJsonResponse(string lang, XDocument weatherd mystationdatatoday.WeatherImgUrl = stationtoday.symbol.imageUrl; mystationdatatoday.Maxtemp = Convert.ToInt32(stationtoday.max); mystationdatatoday.MinTemp = Convert.ToInt32(stationtoday.min); - + myweather.Stationdata.Add(mystationdatatoday); i++; @@ -627,10 +1066,14 @@ public static Weather ParsemyWeatherJsonResponse(string lang, XDocument weatherd //Tomorrow info if (siagweather.tomorrow != null) - { + { Conditions myconditiontomorrow = new Conditions(); - myconditiontomorrow.date = Convert.ToDateTime(siagweather.tomorrow.date.ToShortDateString() + " " + siagweather.tomorrow.hour); //TODO CHeck + myconditiontomorrow.date = Convert.ToDateTime( + siagweather.tomorrow.date.ToShortDateString() + + " " + + siagweather.tomorrow.hour + ); //TODO CHeck myconditiontomorrow.WeatherCondition = siagweather.tomorrow.conditions; myconditiontomorrow.WeatherImgurl = siagweather.tomorrow.imageUrl; myconditiontomorrow.Weatherdesc = siagweather.tomorrow.weather; @@ -644,14 +1087,14 @@ public static Weather ParsemyWeatherJsonResponse(string lang, XDocument weatherd myconditiontomorrow.TempMinmax = Convert.ToInt32(siagweather.tomorrow.tMinMax); myconditiontomorrow.TempMinmin = Convert.ToInt32(siagweather.tomorrow.tMinMin); - myweather.Conditions.Add(myconditiontomorrow); + myweather.Conditions.Add(myconditiontomorrow); } //Stationdata today if (siagweather.tomorrow != null) - { + { var stationstomorrow = siagweather.tomorrow.stationData; - + if (stationstomorrow != null) { int j = 1; @@ -660,18 +1103,28 @@ public static Weather ParsemyWeatherJsonResponse(string lang, XDocument weatherd { Stationdata mystationdatatomorrow = new Stationdata(); - mystationdatatomorrow.date = Convert.ToDateTime(siagweather.tomorrow.date.ToShortDateString() + " " + siagweather.tomorrow.hour); + mystationdatatomorrow.date = Convert.ToDateTime( + siagweather.tomorrow.date.ToShortDateString() + + " " + + siagweather.tomorrow.hour + ); mystationdatatomorrow.Id = j; - var mystationdatacity = weatherdataxml.Root.Elements("Station").Where(x => x.Attribute("Id").Value.Equals(j.ToString())).FirstOrDefault(); - mystationdatatomorrow.CityName = mystationdatacity.Attribute("Name" + lang.ToUpper()).Value; + var mystationdatacity = weatherdataxml.Root + .Elements("Station") + .Where(x => x.Attribute("Id").Value.Equals(j.ToString())) + .FirstOrDefault(); + mystationdatatomorrow.CityName = mystationdatacity + .Attribute("Name" + lang.ToUpper()) + .Value; //mystationdatatomorrow.stationdatacityrid = mystationdatacity.Attribute("RID").Value; if (lang == "en") { if (mystationdatatomorrow.CityName.Contains("/")) { - mystationdatatomorrow.CityName = mystationdatatomorrow.CityName.Replace("/", " / "); + mystationdatatomorrow.CityName = + mystationdatatomorrow.CityName.Replace("/", " / "); } } @@ -686,7 +1139,7 @@ public static Weather ParsemyWeatherJsonResponse(string lang, XDocument weatherd j++; } - } + } } return myweather; @@ -696,6 +1149,5 @@ public static Weather ParsemyWeatherJsonResponse(string lang, XDocument weatherd return null; } } - } } diff --git a/STA/GetDataFromSTA.cs b/STA/GetDataFromSTA.cs index 218073115..75b5af4a8 100644 --- a/STA/GetDataFromSTA.cs +++ b/STA/GetDataFromSTA.cs @@ -41,7 +41,8 @@ public static Task> ImportCSVFromSTA(string? csvcon csv.ReadHeader(); records = csv.GetRecords(); - ParseResult myresult = new STA.ParseResult(); + ParseResult myresult = + new STA.ParseResult(); myresult.Success = true; myresult.Error = false; myresult.records = records.ToList(); @@ -59,7 +60,8 @@ public static Task> ImportCSVFromSTA(string? csvcon csv.ReadHeader(); records = csv.GetRecords(); - ParseResult myresult = new STA.ParseResult(); + ParseResult myresult = + new STA.ParseResult(); myresult.Success = true; myresult.Error = false; myresult.records = records.ToList(); @@ -68,9 +70,17 @@ public static Task> ImportCSVFromSTA(string? csvcon } } } - catch(Exception ex) + catch (Exception ex) { - return Task.FromResult(new ParseResult() { Error = true, Success = false, ErrorMessage = ex.Message, records = Enumerable.Empty() }); + return Task.FromResult( + new ParseResult() + { + Error = true, + Success = false, + ErrorMessage = ex.Message, + records = Enumerable.Empty() + } + ); } } diff --git a/STA/Models/STAVendingPoint.cs b/STA/Models/STAVendingPoint.cs index e559fca25..3c1558782 100644 --- a/STA/Models/STAVendingPoint.cs +++ b/STA/Models/STAVendingPoint.cs @@ -86,47 +86,47 @@ public class STAVendingPoint public string? Tel { get; set; } [Index(19)] - [Name("SEPA")] + [Name("SEPA")] public string? SEPA { get; set; } [Index(20)] - [Name("IBAN")] + [Name("IBAN")] public string? IBAN { get; set; } [Index(21)] - [Name("Parita IVA")] + [Name("Parita IVA")] public string? Parita_IVA { get; set; } [Index(22)] - [Name("VerkaufstellenID Gasser")] + [Name("VerkaufstellenID Gasser")] public string? VerkaufstellenID_Gasser { get; set; } [Index(23)] - [Name("Adresse DE")] + [Name("Adresse DE")] public string? Adresse_DE { get; set; } [Index(24)] - [Name("Adresse IT/EN/LAD")] + [Name("Adresse IT/EN/LAD")] public string? Adresse_IT_EN_LAD { get; set; } [Index(25)] - [Name("CAP")] + [Name("CAP")] public string? CAP { get; set; } [Index(26)] - [Name("Stadt")] + [Name("Stadt")] public string? Stadt { get; set; } [Index(27)] - [Name("città IT/EN/LAD")] + [Name("città IT/EN/LAD")] public string? cittaIT_EN_LAD { get; set; } [Index(29)] - [Name("CODICE ISTAT")] + [Name("CODICE ISTAT")] public string? CODICE_ISTAT { get; set; } [Index(30)] - [Name("Wochentags Beginn")] + [Name("Wochentags Beginn")] public string? Wochentags_Beginn { get; set; } [Index(31)] @@ -134,114 +134,114 @@ public class STAVendingPoint public string? Wochentags_Ende { get; set; } [Index(32)] - [Name("Pause Start")] + [Name("Pause Start")] public string? Pause_Start { get; set; } [Index(33)] - [Name("Pause Ende")] + [Name("Pause Ende")] public string? Pause_Ende { get; set; } [Index(34)] - [Name("Samstag Beginn")] + [Name("Samstag Beginn")] public string? Samstag_Beginn { get; set; } [Index(35)] - [Name("Samstag Ende")] + [Name("Samstag Ende")] public string? Samstag_Ende { get; set; } [Index(36)] - [Name("Pause Samstag Beginn")] + [Name("Pause Samstag Beginn")] public string? Pause_Samstag_Beginn { get; set; } [Index(37)] - [Name("Pause Samstag Ende")] + [Name("Pause Samstag Ende")] public string? Pause_Samstag_Ende { get; set; } [Index(38)] - [Name("Sonntag Beginn")] + [Name("Sonntag Beginn")] public string? Sonntag_Beginn { get; set; } [Index(39)] - [Name("Sonntag Ende")] + [Name("Sonntag Ende")] public string? Sonntag_Ende { get; set; } [Index(40)] - [Name("Pause Sonntag Beginn")] + [Name("Pause Sonntag Beginn")] public string? Pause_Sonntag_Beginn { get; set; } [Index(41)] - [Name("Pause Sonntag Ende")] + [Name("Pause Sonntag Ende")] public string? Pause_Sonntag_Ende { get; set; } [Index(42)] public string? LEER { get; set; } [Index(43)] - [Name("Zusatzinfo DE")] + [Name("Zusatzinfo DE")] public string? Zusatzinfo_DE { get; set; } [Index(44)] - [Name("Zusatzinfo IT")] + [Name("Zusatzinfo IT")] public string? Zusatzinfo_IT { get; set; } [Index(45)] - [Name("Zusatzinfo LAD")] + [Name("Zusatzinfo LAD")] public string? Zusatzinfo_LAD { get; set; } [Index(46)] - [Name("Zusatzinfo EN")] + [Name("Zusatzinfo EN")] public string? Zusatzinfo_EN { get; set; } [Index(47)] - [Name("lat")] + [Name("lat")] public string? latitude { get; set; } [Index(48)] - [Name("long")] + [Name("long")] public string? longitude { get; set; } [Index(49)] - [Name("* Südtirol Pass Dienste")] + [Name("* Südtirol Pass Dienste")] public string? SuedtirolPassDienste { get; set; } [Index(50)] - [Name("Südtirol Pass 65+ Beantragung")] + [Name("Südtirol Pass 65+ Beantragung")] public string? SuedtirolPass65PlusBeantragung { get; set; } [Index(51)] - [Name("** Duplikat")] + [Name("** Duplikat")] public string? Duplikat { get; set; } [Index(52)] - [Name("Wertkarte")] + [Name("Wertkarte")] public string? Wertkarte { get; set; } [Index(53)] - [Name("Stadtfahrkarte o. Citybus")] + [Name("Stadtfahrkarte o. Citybus")] public string? StadtfahrkarteoCitybus { get; set; } [Index(54)] - [Name("Mobilcard")] + [Name("Mobilcard")] public string? Mobilcard { get; set; } [Index(55)] - [Name("bikemobil Card")] + [Name("bikemobil Card")] public string? bikemobilCard { get; set; } [Index(56)] - [Name("Museumobil Card")] + [Name("Museumobil Card")] public string? MuseumobilCard { get; set; } [Index(57)] - [Name("Kartenkreislauf mobilcard")] + [Name("Kartenkreislauf mobilcard")] public string? Kartenkreislaufmobilcard { get; set; } [Index(58)] - [Name("Kartenkreislauf museummobil")] + [Name("Kartenkreislauf museummobil")] public string? Kartenkreislaufmuseummobil { get; set; } [Index(59)] - [Name("Kartenkreislauf bikemobil")] + [Name("Kartenkreislauf bikemobil")] public string? Kartenkreislaufbikemobil { get; set; } } } diff --git a/STA/Parser/ParseSTAPois.cs b/STA/Parser/ParseSTAPois.cs index ad22565e7..0d1671795 100644 --- a/STA/Parser/ParseSTAPois.cs +++ b/STA/Parser/ParseSTAPois.cs @@ -11,7 +11,9 @@ namespace STA { public class ParseSTAPois { - public static ODHActivityPoiLinked ParseSTAVendingPointToODHActivityPoi(STAVendingPoint vendingpoint) + public static ODHActivityPoiLinked ParseSTAVendingPointToODHActivityPoi( + STAVendingPoint vendingpoint + ) { //Integrate this data //Website @@ -30,30 +32,31 @@ public static ODHActivityPoiLinked ParseSTAVendingPointToODHActivityPoi(STAVendi //Long //Angebot von Leistungen(von AW bis BD) - var mypoi = new ODHActivityPoiLinked(); + var mypoi = new ODHActivityPoiLinked(); //ID var id = "salespoint_sta_" + vendingpoint.STA_ID; mypoi.Id = id; //ADD MAPPING - if (vendingpoint.STA_ID is { }) - { - var staid = new Dictionary() { { "sta_id", vendingpoint.STA_ID } }; - mypoi.Mapping.TryAddOrUpdate("sta", staid); + if (vendingpoint.STA_ID is { }) + { + var staid = new Dictionary() { { "sta_id", vendingpoint.STA_ID } }; + mypoi.Mapping.TryAddOrUpdate("sta", staid); } //GPSData var commaCulture = new CultureInfo("en") { - NumberFormat = - { - NumberDecimalSeparator = "," - } + NumberFormat = { NumberDecimalSeparator = "," } }; - double gpslat = !String.IsNullOrEmpty(vendingpoint.latitude) ? Convert.ToDouble(vendingpoint.latitude, commaCulture) : 0; - double gpslong = !String.IsNullOrEmpty(vendingpoint.longitude) ? Convert.ToDouble(vendingpoint.longitude, commaCulture) : 0; + double gpslat = !String.IsNullOrEmpty(vendingpoint.latitude) + ? Convert.ToDouble(vendingpoint.latitude, commaCulture) + : 0; + double gpslong = !String.IsNullOrEmpty(vendingpoint.longitude) + ? Convert.ToDouble(vendingpoint.longitude, commaCulture) + : 0; if (gpslat != 0 && gpslong != 0) { @@ -75,32 +78,68 @@ public static ODHActivityPoiLinked ParseSTAVendingPointToODHActivityPoi(STAVendi //Properties Parsing List mypoipropertylist = new List(); - - PoiProperty pPhasWebsite = new PoiProperty() { Name = "haswebsite", Value = vendingpoint.Website == "1" ? "True" : "False" }; + + PoiProperty pPhasWebsite = new PoiProperty() + { + Name = "haswebsite", + Value = vendingpoint.Website == "1" ? "True" : "False" + }; mypoipropertylist.Add(pPhasWebsite); - PoiProperty pPsuedtirolpassdienste = new PoiProperty() { Name = "suedtirolpass_services", Value = vendingpoint.SuedtirolPassDienste == "1" ? "True" : "False" }; + PoiProperty pPsuedtirolpassdienste = new PoiProperty() + { + Name = "suedtirolpass_services", + Value = vendingpoint.SuedtirolPassDienste == "1" ? "True" : "False" + }; mypoipropertylist.Add(pPsuedtirolpassdienste); - - PoiProperty pPsuedtirolpassover65 = new PoiProperty() { Name = "suedtirolpass_over65_apply", Value = vendingpoint.SuedtirolPass65PlusBeantragung == "1" ? "True" : "False" }; + + PoiProperty pPsuedtirolpassover65 = new PoiProperty() + { + Name = "suedtirolpass_over65_apply", + Value = vendingpoint.SuedtirolPass65PlusBeantragung == "1" ? "True" : "False" + }; mypoipropertylist.Add(pPsuedtirolpassover65); - - PoiProperty pPduplicate = new PoiProperty() { Name = "duplicate", Value = vendingpoint.Duplikat == "1" ? "True" : "False" }; + + PoiProperty pPduplicate = new PoiProperty() + { + Name = "duplicate", + Value = vendingpoint.Duplikat == "1" ? "True" : "False" + }; mypoipropertylist.Add(pPduplicate); - - PoiProperty pPHwertkarte = new PoiProperty() { Name = "chargecard", Value = vendingpoint.Wertkarte == "1" ? "True" : "False" }; + + PoiProperty pPHwertkarte = new PoiProperty() + { + Name = "chargecard", + Value = vendingpoint.Wertkarte == "1" ? "True" : "False" + }; mypoipropertylist.Add(pPHwertkarte); - - PoiProperty pPstadtfahrkartecitybus = new PoiProperty() { Name = "city_card_bus", Value = vendingpoint.StadtfahrkarteoCitybus == "1" ? "True" : "False" }; + + PoiProperty pPstadtfahrkartecitybus = new PoiProperty() + { + Name = "city_card_bus", + Value = vendingpoint.StadtfahrkarteoCitybus == "1" ? "True" : "False" + }; mypoipropertylist.Add(pPstadtfahrkartecitybus); - - PoiProperty pPmobilcard = new PoiProperty() { Name = "mobilecard", Value = vendingpoint.Mobilcard == "1" ? "True" : "False" }; + + PoiProperty pPmobilcard = new PoiProperty() + { + Name = "mobilecard", + Value = vendingpoint.Mobilcard == "1" ? "True" : "False" + }; mypoipropertylist.Add(pPmobilcard); - - PoiProperty pPbikemobilcard = new PoiProperty() { Name = "bike_mobilecard", Value = vendingpoint.bikemobilCard == "1" ? "True" : "False" }; + + PoiProperty pPbikemobilcard = new PoiProperty() + { + Name = "bike_mobilecard", + Value = vendingpoint.bikemobilCard == "1" ? "True" : "False" + }; mypoipropertylist.Add(pPbikemobilcard); - PoiProperty pPmobilecard = new PoiProperty() { Name = "museum_mobilecard", Value = vendingpoint.MuseumobilCard == "1" ? "True" : "False" }; + PoiProperty pPmobilecard = new PoiProperty() + { + Name = "museum_mobilecard", + Value = vendingpoint.MuseumobilCard == "1" ? "True" : "False" + }; mypoipropertylist.Add(pPmobilecard); mypoi.PoiProperty.TryAddOrUpdate("de", mypoipropertylist); @@ -120,7 +159,7 @@ public static ODHActivityPoiLinked ParseSTAVendingPointToODHActivityPoi(STAVendi detailde.AdditionalText = vendingpoint.Zusatzinfo_DE; mypoi.Detail.TryAddOrUpdate("de", detailde); - + Detail detailit = new Detail(); detailit.Language = "it"; detailit.Title = vendingpoint.Salepoint_Name_STA_IT; @@ -199,7 +238,7 @@ public static ODHActivityPoiLinked ParseSTAVendingPointToODHActivityPoi(STAVendi //Standard open all year? Make use of DB with Festive days and add them as closed? var operationschedule = ParseOperationScheduleFromCSV(vendingpoint); - if(operationschedule != null) + if (operationschedule != null) { mypoi.OperationSchedule = new List(); @@ -209,18 +248,18 @@ public static ODHActivityPoiLinked ParseSTAVendingPointToODHActivityPoi(STAVendi //END Openingtimes Parsing //TODO - //Categorization + //Categorization - //ODH Tags + //ODH Tags mypoi.SmgTags = new List(); mypoi.SmgTags.Add("mobilität"); mypoi.SmgTags.Add("verkaufstellen ticket oeffentliche verkehrsmittel"); //ODH Categorizations - //TODO LOAD Categorizations + //TODO LOAD Categorizations mypoi.Type = "Mobilität"; mypoi.SubType = "Verkaufstellen Ticket Oeffentliche Verkehrsmittel"; - + mypoi.SyncSourceInterface = "sta"; mypoi.SyncUpdateMode = "Full"; mypoi.Source = "sta"; @@ -228,7 +267,7 @@ public static ODHActivityPoiLinked ParseSTAVendingPointToODHActivityPoi(STAVendi mypoi.Active = true; mypoi.SmgActive = true; - mypoi.HasLanguage = new List() { "de","it","en","ld" }; + mypoi.HasLanguage = new List() { "de", "it", "en", "ld" }; mypoi.Shortname = mypoi.Detail["de"].Title; @@ -237,9 +276,15 @@ public static ODHActivityPoiLinked ParseSTAVendingPointToODHActivityPoi(STAVendi return mypoi; } - private static OperationSchedule? ParseOperationScheduleFromCSV(STAVendingPoint vendingpoint) + private static OperationSchedule? ParseOperationScheduleFromCSV( + STAVendingPoint vendingpoint + ) { - if (!String.IsNullOrEmpty(vendingpoint.Wochentags_Beginn) || !String.IsNullOrEmpty(vendingpoint.Samstag_Beginn) || !String.IsNullOrEmpty(vendingpoint.Sonntag_Beginn)) + if ( + !String.IsNullOrEmpty(vendingpoint.Wochentags_Beginn) + || !String.IsNullOrEmpty(vendingpoint.Samstag_Beginn) + || !String.IsNullOrEmpty(vendingpoint.Sonntag_Beginn) + ) { OperationSchedule myoperationschedule = new OperationSchedule(); myoperationschedule.OperationscheduleName = new Dictionary() @@ -254,51 +299,99 @@ public static ODHActivityPoiLinked ParseSTAVendingPointToODHActivityPoi(STAVendi ////Try Parsing Columns TimeSpan beginweekday = default(TimeSpan); - TimeSpan.TryParse(vendingpoint.Wochentags_Beginn, CultureInfo.InvariantCulture, out beginweekday); + TimeSpan.TryParse( + vendingpoint.Wochentags_Beginn, + CultureInfo.InvariantCulture, + out beginweekday + ); TimeSpan endweekdaynoon = default(TimeSpan); - TimeSpan.TryParse(vendingpoint.Pause_Start, CultureInfo.InvariantCulture, out endweekdaynoon); + TimeSpan.TryParse( + vendingpoint.Pause_Start, + CultureInfo.InvariantCulture, + out endweekdaynoon + ); TimeSpan beginweekdaynoon = default(TimeSpan); - TimeSpan.TryParse(vendingpoint.Pause_Ende, CultureInfo.InvariantCulture, out beginweekdaynoon); + TimeSpan.TryParse( + vendingpoint.Pause_Ende, + CultureInfo.InvariantCulture, + out beginweekdaynoon + ); TimeSpan endweekday = default(TimeSpan); - TimeSpan.TryParse(vendingpoint.Wochentags_Ende, CultureInfo.InvariantCulture, out endweekday); + TimeSpan.TryParse( + vendingpoint.Wochentags_Ende, + CultureInfo.InvariantCulture, + out endweekday + ); //Saturday TimeSpan beginsaturday = default(TimeSpan); - TimeSpan.TryParse(vendingpoint.Samstag_Beginn, CultureInfo.InvariantCulture, out beginsaturday); + TimeSpan.TryParse( + vendingpoint.Samstag_Beginn, + CultureInfo.InvariantCulture, + out beginsaturday + ); TimeSpan endsaturdaynoon = default(TimeSpan); - TimeSpan.TryParse(vendingpoint.Pause_Samstag_Beginn, CultureInfo.InvariantCulture, out endsaturdaynoon); + TimeSpan.TryParse( + vendingpoint.Pause_Samstag_Beginn, + CultureInfo.InvariantCulture, + out endsaturdaynoon + ); TimeSpan beginsaturdaynoon = default(TimeSpan); - TimeSpan.TryParse(vendingpoint.Pause_Samstag_Ende, CultureInfo.InvariantCulture, out beginsaturdaynoon); + TimeSpan.TryParse( + vendingpoint.Pause_Samstag_Ende, + CultureInfo.InvariantCulture, + out beginsaturdaynoon + ); TimeSpan endsaturday = default(TimeSpan); - TimeSpan.TryParse(vendingpoint.Samstag_Ende, CultureInfo.InvariantCulture, out endsaturday); + TimeSpan.TryParse( + vendingpoint.Samstag_Ende, + CultureInfo.InvariantCulture, + out endsaturday + ); //Sunday TimeSpan beginsunday = default(TimeSpan); - TimeSpan.TryParse(vendingpoint.Sonntag_Beginn, CultureInfo.InvariantCulture, out beginsunday); + TimeSpan.TryParse( + vendingpoint.Sonntag_Beginn, + CultureInfo.InvariantCulture, + out beginsunday + ); TimeSpan endsundaynoon = default(TimeSpan); - TimeSpan.TryParse(vendingpoint.Pause_Sonntag_Beginn, CultureInfo.InvariantCulture, out endsundaynoon); + TimeSpan.TryParse( + vendingpoint.Pause_Sonntag_Beginn, + CultureInfo.InvariantCulture, + out endsundaynoon + ); TimeSpan beginsundaynoon = default(TimeSpan); - TimeSpan.TryParse(vendingpoint.Pause_Sonntag_Ende, CultureInfo.InvariantCulture, out beginsundaynoon); + TimeSpan.TryParse( + vendingpoint.Pause_Sonntag_Ende, + CultureInfo.InvariantCulture, + out beginsundaynoon + ); TimeSpan endsunday = default(TimeSpan); - TimeSpan.TryParse(vendingpoint.Sonntag_Ende, CultureInfo.InvariantCulture, out endsunday); + TimeSpan.TryParse( + vendingpoint.Sonntag_Ende, + CultureInfo.InvariantCulture, + out endsunday + ); myoperationschedule.OperationScheduleTime = new List(); //Add openingtime for Weekday, Saturday and Sunday - if (beginweekday!= TimeSpan.Zero && endweekday != TimeSpan.Zero) - { + if (beginweekday != TimeSpan.Zero && endweekday != TimeSpan.Zero) + { //If no pause if (beginweekdaynoon == TimeSpan.Zero || endweekdaynoon == TimeSpan.Zero) { @@ -487,22 +580,29 @@ public static ODHActivityPoiLinked ParseSTAVendingPointToODHActivityPoi(STAVendi } //Exceptions, Closed on a certain day - if(!String.IsNullOrEmpty(vendingpoint.Zusatzinfo_EN)) + if (!String.IsNullOrEmpty(vendingpoint.Zusatzinfo_EN)) { - if(vendingpoint.Zusatzinfo_EN.EndsWith("closed")) + if (vendingpoint.Zusatzinfo_EN.EndsWith("closed")) { //Find out the day var myday = vendingpoint.Zusatzinfo_EN.Replace(" closed", ""); //var validdays = new List() { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; - var validdays = new List() { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" }; //Excluding Saturday and Sunday because they can set separately + var validdays = new List() + { + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday" + }; //Excluding Saturday and Sunday because they can set separately if (validdays.Contains(myday)) { //Add closed Schedule OperationScheduleTime myoptimeclosed = new OperationScheduleTime(); myoptimeclosed.Monday = myday == "Monday" ? true : false; - myoptimeclosed.Tuesday = myday == "Tuesday" ? true : false; + myoptimeclosed.Tuesday = myday == "Tuesday" ? true : false; myoptimeclosed.Wednesday = myday == "Wednesday" ? true : false; myoptimeclosed.Thuresday = myday == "Thursday" ? true : false; //myoptimeclosed.Thursday = myday == "Thursday" ? true : false; @@ -518,13 +618,9 @@ public static ODHActivityPoiLinked ParseSTAVendingPointToODHActivityPoi(STAVendi myoperationschedule.OperationScheduleTime.Add(myoptimeclosed); } - } } - - - return myoperationschedule; } else diff --git a/SuedtirolWein/GetSuedtirolWeinData.cs b/SuedtirolWein/GetSuedtirolWeinData.cs index 5e6cf7f65..b132d9088 100644 --- a/SuedtirolWein/GetSuedtirolWeinData.cs +++ b/SuedtirolWein/GetSuedtirolWeinData.cs @@ -8,8 +8,10 @@ namespace SuedtirolWein { public class GetSuedtirolWeinData { - public const string serviceurlcompanies = @"https://suedtirolwein.secure.consisto.net/companies.ashx"; - public const string serviceurlawards = @"https://suedtirolwein.secure.consisto.net/awards.ashx"; + public const string serviceurlcompanies = + @"https://suedtirolwein.secure.consisto.net/companies.ashx"; + public const string serviceurlawards = + @"https://suedtirolwein.secure.consisto.net/awards.ashx"; private static async Task RequestCompaniesAsync(string lang) { @@ -26,9 +28,12 @@ private static async Task RequestCompaniesAsync(string lang } catch (Exception ex) { - return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(ex.Message) }; + return new HttpResponseMessage + { + StatusCode = HttpStatusCode.BadRequest, + Content = new StringContent(ex.Message) + }; } - } private static async Task RequestAwardsAsync(string lang) @@ -43,11 +48,14 @@ private static async Task RequestAwardsAsync(string lang) return myresponse; } - } catch (Exception ex) { - return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, Content = new StringContent(ex.Message) }; + return new HttpResponseMessage + { + StatusCode = HttpStatusCode.BadRequest, + Content = new StringContent(ex.Message) + }; } } @@ -72,6 +80,5 @@ public static async Task GetSueditrolWineAwardsAsync(string lang) return myweatherresponse; } - } } diff --git a/SuedtirolWein/Parser/ParseAwardData.cs b/SuedtirolWein/Parser/ParseAwardData.cs index bfd4b7172..39e30a0da 100644 --- a/SuedtirolWein/Parser/ParseAwardData.cs +++ b/SuedtirolWein/Parser/ParseAwardData.cs @@ -27,7 +27,13 @@ public class ParseAwardData // // - public static Wine ParsetheAwardData(Wine mywine, XElement myawardde, XElement myawardit, XElement myawarden, List haslanguage) + public static Wine ParsetheAwardData( + Wine mywine, + XElement myawardde, + XElement myawardit, + XElement myawarden, + List haslanguage + ) { mywine.LastChange = DateTime.Now; @@ -37,7 +43,6 @@ public static Wine ParsetheAwardData(Wine mywine, XElement myawardde, XElement m var suedtirolweinid = new Dictionary() { { "id", mywine.Id } }; mywine.Mapping.TryAddOrUpdate("suedtirolwein", suedtirolweinid); - string titlede = myawardde.Element("title").Value; string winenamede = myawardde.Element("wine").Value; @@ -74,19 +79,20 @@ public static Wine ParsetheAwardData(Wine mywine, XElement myawardde, XElement m mywine.Detail.TryAddOrUpdate("en", mydetailen); } - mywine.Vintage = !String.IsNullOrEmpty(myawardde.Element("vintage").Value) ? Convert.ToInt32(myawardde.Element("vintage").Value) : 0; - mywine.Awardyear = !String.IsNullOrEmpty(myawardde.Element("awardyear").Value) ? Convert.ToInt32(myawardde.Element("awardyear").Value) : 0; + mywine.Vintage = !String.IsNullOrEmpty(myawardde.Element("vintage").Value) + ? Convert.ToInt32(myawardde.Element("vintage").Value) + : 0; + mywine.Awardyear = !String.IsNullOrEmpty(myawardde.Element("awardyear").Value) + ? Convert.ToInt32(myawardde.Element("awardyear").Value) + : 0; mywine.CompanyId = myawardde.Element("companyid").Value; mywine.Awards = myawardde.Element("awards").Value.Split(',').ToList(); mywine.CustomId = myawardde.Element("wineid").Value; - - if (!String.IsNullOrEmpty(myawardde.Element("media").Value)) { - List myimglist = new List(); if (mywine.ImageGallery != null) @@ -106,7 +112,10 @@ public static Wine ParsetheAwardData(Wine mywine, XElement myawardde, XElement m if (myimage.ImageUrl.StartsWith("https://www.suedtirolwein.secure.consisto.net/")) { - myimage.ImageUrl.Replace("https://www.suedtirolwein.secure.consisto.net/", "https://intranet.suedtirolwein.com/"); + myimage.ImageUrl.Replace( + "https://www.suedtirolwein.secure.consisto.net/", + "https://intranet.suedtirolwein.com/" + ); } myimage.Height = 0; @@ -121,6 +130,5 @@ public static Wine ParsetheAwardData(Wine mywine, XElement myawardde, XElement m return mywine; } - } } diff --git a/SuedtirolWein/Parser/ParseCompanyData.cs b/SuedtirolWein/Parser/ParseCompanyData.cs index 92ef59024..d1340c680 100644 --- a/SuedtirolWein/Parser/ParseCompanyData.cs +++ b/SuedtirolWein/Parser/ParseCompanyData.cs @@ -11,14 +11,25 @@ namespace SuedtirolWein.Parser { public class ParseCompanyData { - private static void ParseContactInfo(string language, XElement companydata, ODHActivityPoi mywinecompany) + private static void ParseContactInfo( + string language, + XElement companydata, + ODHActivityPoi mywinecompany + ) { ContactInfos contactinfo = new ContactInfos(); contactinfo.CompanyName = companydata.Element("title").Value; - contactinfo.Address = companydata.Element("address") != null ? companydata.Element("address").Value : null; - contactinfo.ZipCode = companydata.Element("zipcode") != null ? companydata.Element("zipcode").Value : null; - contactinfo.City = companydata.Element("place") != null ? companydata.Element("place").Value : null; + contactinfo.Address = + companydata.Element("address") != null + ? companydata.Element("address").Value + : null; + contactinfo.ZipCode = + companydata.Element("zipcode") != null + ? companydata.Element("zipcode").Value + : null; + contactinfo.City = + companydata.Element("place") != null ? companydata.Element("place").Value : null; string countryname = "Italy"; if (language == "de") @@ -28,24 +39,33 @@ private static void ParseContactInfo(string language, XElement companydata, ODHA contactinfo.CountryName = countryname; contactinfo.CountryCode = "IT"; - contactinfo.Phonenumber = companydata.Element("phone") != null ? companydata.Element("phone").Value : null; + contactinfo.Phonenumber = + companydata.Element("phone") != null ? companydata.Element("phone").Value : null; string webadresseIT = ""; //Webadress gschicht if (companydata.Element("homepage") != null) { - webadresseIT = companydata.Element("homepage").Value.Contains("http") ? companydata.Element("homepage").Value : "http://" + companydata.Element("homepage").Value; + webadresseIT = companydata.Element("homepage").Value.Contains("http") + ? companydata.Element("homepage").Value + : "http://" + companydata.Element("homepage").Value; } contactinfo.Url = webadresseIT; - contactinfo.Email = companydata.Element("email") != null ? companydata.Element("email").Value : null; - contactinfo.LogoUrl = companydata.Element("logo") != null ? companydata.Element("logo").Value : null; + contactinfo.Email = + companydata.Element("email") != null ? companydata.Element("email").Value : null; + contactinfo.LogoUrl = + companydata.Element("logo") != null ? companydata.Element("logo").Value : null; contactinfo.Language = language; mywinecompany.ContactInfos.TryAddOrUpdate(language, contactinfo); } - private static void ParseDetailInfo(string language, XElement companydata, ODHActivityPoi mywinecompany) + private static void ParseDetailInfo( + string language, + XElement companydata, + ODHActivityPoi mywinecompany + ) { //Detail IT Detail mydetail = new Detail(); @@ -54,21 +74,30 @@ private static void ParseDetailInfo(string language, XElement companydata, ODHAc if (mywinecompany.Detail.ContainsKey(language)) mydetail = mywinecompany.Detail[language]; - mydetail.Title = companydata.Element("title").Value; - mydetail.BaseText = companydata.Element("companydescription") != null ? companydata.Element("companydescription").Value : null; - - mydetail.Header = companydata.Element("slogan") != null ? companydata.Element("slogan").Value : null; - mydetail.SubHeader = companydata.Element("subtitle") != null ? companydata.Element("subtitle").Value : null; - mydetail.IntroText = companydata.Element("quote") != null ? companydata.Element("quote").Value : null; + mydetail.BaseText = + companydata.Element("companydescription") != null + ? companydata.Element("companydescription").Value + : null; + mydetail.Header = + companydata.Element("slogan") != null ? companydata.Element("slogan").Value : null; + mydetail.SubHeader = + companydata.Element("subtitle") != null + ? companydata.Element("subtitle").Value + : null; + mydetail.IntroText = + companydata.Element("quote") != null ? companydata.Element("quote").Value : null; mydetail.Language = language; mywinecompany.Detail.TryAddOrUpdate(language, mydetail); } - private static void ParseImageGalleryData(IDictionary companydata, ODHActivityPoi mywinecompany) + private static void ParseImageGalleryData( + IDictionary companydata, + ODHActivityPoi mywinecompany + ) { //ImageGallery List myimagegallerylist = new List(); @@ -87,13 +116,22 @@ private static void ParseImageGalleryData(IDictionary companyd //Image Title if (companydata["de"].Element("imagemetatitle") != null) - myimagegallery.ImageTitle.TryAddOrUpdate("de", companydata["de"].Element("imagemetatitle").Value); + myimagegallery.ImageTitle.TryAddOrUpdate( + "de", + companydata["de"].Element("imagemetatitle").Value + ); //Image Description if (companydata["de"].Element("imagemetadescription") != null) - myimagegallery.ImageDesc.TryAddOrUpdate("de", companydata["de"].Element("imagemetadescription").Value); + myimagegallery.ImageDesc.TryAddOrUpdate( + "de", + companydata["de"].Element("imagemetadescription").Value + ); //Image Alttext if (companydata["de"].Element("imagemetaalt") != null) - myimagegallery.ImageAltText.TryAddOrUpdate("de", companydata["de"].Element("imagemetaalt").Value); + myimagegallery.ImageAltText.TryAddOrUpdate( + "de", + companydata["de"].Element("imagemetaalt").Value + ); imageurlmedia = myimagegallery.ImageUrl; @@ -104,12 +142,26 @@ private static void ParseImageGalleryData(IDictionary companyd if (myimagegallerylist.Count == 1) { if (companydata["it"].Element("imagemetatitle") != null) - myimagegallerylist.FirstOrDefault().ImageTitle.TryAddOrUpdate("it", companydata["it"].Element("imagemetatitle").Value); + myimagegallerylist + .FirstOrDefault() + .ImageTitle.TryAddOrUpdate( + "it", + companydata["it"].Element("imagemetatitle").Value + ); if (companydata["it"].Element("imagemetadescription") != null) - myimagegallerylist.FirstOrDefault().ImageDesc.TryAddOrUpdate("it", companydata["it"].Element("imagemetadescription").Value); + myimagegallerylist + .FirstOrDefault() + .ImageDesc.TryAddOrUpdate( + "it", + companydata["it"].Element("imagemetadescription").Value + ); if (companydata["it"].Element("imagemetaalt") != null) - myimagegallerylist.FirstOrDefault().ImageAltText.TryAddOrUpdate("it", companydata["it"].Element("imagemetaalt").Value); - + myimagegallerylist + .FirstOrDefault() + .ImageAltText.TryAddOrUpdate( + "it", + companydata["it"].Element("imagemetaalt").Value + ); } } if (companydata["en"] != null && companydata["en"].Element("media") != null) @@ -117,11 +169,26 @@ private static void ParseImageGalleryData(IDictionary companyd if (myimagegallerylist.Count == 1) { if (companydata["en"].Element("imagemetatitle") != null) - myimagegallerylist.FirstOrDefault().ImageTitle.TryAddOrUpdate("en", companydata["en"].Element("imagemetatitle").Value); + myimagegallerylist + .FirstOrDefault() + .ImageTitle.TryAddOrUpdate( + "en", + companydata["en"].Element("imagemetatitle").Value + ); if (companydata["en"].Element("imagemetadescription") != null) - myimagegallerylist.FirstOrDefault().ImageDesc.TryAddOrUpdate("en", companydata["en"].Element("imagemetadescription").Value); + myimagegallerylist + .FirstOrDefault() + .ImageDesc.TryAddOrUpdate( + "en", + companydata["en"].Element("imagemetadescription").Value + ); if (companydata["en"].Element("imagemetaalt") != null) - myimagegallerylist.FirstOrDefault().ImageAltText.TryAddOrUpdate("en", companydata["en"].Element("imagemetaalt").Value); + myimagegallerylist + .FirstOrDefault() + .ImageAltText.TryAddOrUpdate( + "en", + companydata["en"].Element("imagemetaalt").Value + ); } } if (companydata["ru"] != null && companydata["ru"].Element("media") != null) @@ -129,11 +196,26 @@ private static void ParseImageGalleryData(IDictionary companyd if (myimagegallerylist.Count == 1) { if (companydata["ru"].Element("imagemetatitle") != null) - myimagegallerylist.FirstOrDefault().ImageTitle.TryAddOrUpdate("ru", companydata["ru"].Element("imagemetatitle").Value); + myimagegallerylist + .FirstOrDefault() + .ImageTitle.TryAddOrUpdate( + "ru", + companydata["ru"].Element("imagemetatitle").Value + ); if (companydata["ru"].Element("imagemetadescription") != null) - myimagegallerylist.FirstOrDefault().ImageDesc.TryAddOrUpdate("ru", companydata["ru"].Element("imagemetadescription").Value); + myimagegallerylist + .FirstOrDefault() + .ImageDesc.TryAddOrUpdate( + "ru", + companydata["ru"].Element("imagemetadescription").Value + ); if (companydata["ru"].Element("imagemetaalt") != null) - myimagegallerylist.FirstOrDefault().ImageAltText.TryAddOrUpdate("ru", companydata["ru"].Element("imagemetaalt").Value); + myimagegallerylist + .FirstOrDefault() + .ImageAltText.TryAddOrUpdate( + "ru", + companydata["ru"].Element("imagemetaalt").Value + ); } } if (companydata["jp"] != null && companydata["jp"].Element("media") != null) @@ -141,11 +223,26 @@ private static void ParseImageGalleryData(IDictionary companyd if (myimagegallerylist.Count == 1) { if (companydata["jp"].Element("imagemetatitle") != null) - myimagegallerylist.FirstOrDefault().ImageTitle.TryAddOrUpdate("jp", companydata["jp"].Element("imagemetatitle").Value); + myimagegallerylist + .FirstOrDefault() + .ImageTitle.TryAddOrUpdate( + "jp", + companydata["jp"].Element("imagemetatitle").Value + ); if (companydata["jp"].Element("imagemetadescription") != null) - myimagegallerylist.FirstOrDefault().ImageDesc.TryAddOrUpdate("jp", companydata["jp"].Element("imagemetadescription").Value); + myimagegallerylist + .FirstOrDefault() + .ImageDesc.TryAddOrUpdate( + "jp", + companydata["jp"].Element("imagemetadescription").Value + ); if (companydata["jp"].Element("imagemetaalt") != null) - myimagegallerylist.FirstOrDefault().ImageAltText.TryAddOrUpdate("jp", companydata["jp"].Element("imagemetaalt").Value); + myimagegallerylist + .FirstOrDefault() + .ImageAltText.TryAddOrUpdate( + "jp", + companydata["jp"].Element("imagemetaalt").Value + ); } } @@ -160,7 +257,7 @@ private static void ParseImageGalleryData(IDictionary companyd myimagegallery2.ListPosition = 1; myimagegallery2.CopyRight = "Suedtirol Wein"; - if(imageurlmedia != myimagegallery2.ImageUrl) + if (imageurlmedia != myimagegallery2.ImageUrl) myimagegallerylist.Add(myimagegallery2); } //if (companydata["de"].Element("logo") != null) @@ -179,7 +276,11 @@ private static void ParseImageGalleryData(IDictionary companyd mywinecompany.ImageGallery = myimagegallerylist; } - private static void ParsePropertyData(string language, XElement companydata, ODHActivityPoi mywinecompany) + private static void ParsePropertyData( + string language, + XElement companydata, + ODHActivityPoi mywinecompany + ) { //PROPS DE List mypropertylist = new List(); @@ -211,12 +312,12 @@ private static void ParsePropertyData(string language, XElement companydata, ODH myprop4.Value = companydata.Element("companyholiday").Value; mypropertylist.Add(myprop4); } - + if (companydata.Element("hasvisits") != null) { PoiProperty myprop5 = new PoiProperty(); myprop5.Name = "hasvisits"; - + myprop5.Value = companydata.Element("hasvisits").Value; mypropertylist.Add(myprop5); } @@ -364,7 +465,7 @@ private static void ParsePropertyData(string language, XElement companydata, ODH myprop22.Value = companydata.Element("h2").Value; mypropertylist.Add(myprop22); } - + //new quote if (companydata.Element("quote") != null) { @@ -437,7 +538,11 @@ private static void ParsePropertyData(string language, XElement companydata, ODH mywinecompany.PoiProperty.TryAddOrUpdate(language, mypropertylist); } - private static void ParseImporterData(string language, XElement companydata, ODHActivityPoi mywinecompany) + private static void ParseImporterData( + string language, + XElement companydata, + ODHActivityPoi mywinecompany + ) { List importercontactInfos = new List(); @@ -445,7 +550,11 @@ private static void ParseImporterData(string language, XElement companydata, ODH { if (companydata.Element("importers").Elements("importer") != null) { - foreach (var companyimporterde in companydata.Element("importers").Elements("importer")) + foreach ( + var companyimporterde in companydata + .Element("importers") + .Elements("importer") + ) { if (companyimporterde.HasElements) { @@ -455,23 +564,41 @@ private static void ParseImporterData(string language, XElement companydata, ODH ContactInfos myimportercontactinfode = new ContactInfos(); if (companyimporterde.Element("importername") != null) - myimportercontactinfode.CompanyName = companyimporterde.Element("importername").Value; + myimportercontactinfode.CompanyName = companyimporterde + .Element("importername") + .Value; if (companyimporterde.Element("importeraddress") != null) - myimportercontactinfode.Address = companyimporterde.Element("importeraddress").Value; + myimportercontactinfode.Address = companyimporterde + .Element("importeraddress") + .Value; if (companyimporterde.Element("importerzipcode") != null) - myimportercontactinfode.ZipCode = companyimporterde.Element("importerzipcode").Value; + myimportercontactinfode.ZipCode = companyimporterde + .Element("importerzipcode") + .Value; if (companyimporterde.Element("importerplace") != null) - myimportercontactinfode.City = companyimporterde.Element("importerplace").Value; + myimportercontactinfode.City = companyimporterde + .Element("importerplace") + .Value; if (companyimporterde.Element("importerphone") != null) - myimportercontactinfode.Phonenumber = companyimporterde.Element("importerphone").Value; + myimportercontactinfode.Phonenumber = companyimporterde + .Element("importerphone") + .Value; if (companyimporterde.Element("importeremail") != null) - myimportercontactinfode.Email = companyimporterde.Element("importeremail").Value; + myimportercontactinfode.Email = companyimporterde + .Element("importeremail") + .Value; if (companyimporterde.Element("importerhomepage") != null) - myimportercontactinfode.Url = companyimporterde.Element("importerhomepage").Value; + myimportercontactinfode.Url = companyimporterde + .Element("importerhomepage") + .Value; if (companyimporterde.Element("importercontactperson") != null) - myimportercontactinfode.Givenname = companyimporterde.Element("importercontactperson").Value; + myimportercontactinfode.Givenname = companyimporterde + .Element("importercontactperson") + .Value; if (companyimporterde.Element("importerdescription") != null) - myadditionalcontactde.Description = companyimporterde.Element("importerdescription").Value; + myadditionalcontactde.Description = companyimporterde + .Element("importerdescription") + .Value; myimportercontactinfode.Language = language; @@ -485,13 +612,18 @@ private static void ParseImporterData(string language, XElement companydata, ODH if (importercontactInfos.Count > 0) { if (mywinecompany.AdditionalContact == null) - mywinecompany.AdditionalContact = new Dictionary>(); + mywinecompany.AdditionalContact = + new Dictionary>(); mywinecompany.AdditionalContact.TryAddOrUpdate(language, importercontactInfos); } } - public static ODHActivityPoi ParsetheCompanyData(ODHActivityPoi mywinecompany, IDictionary companydata, List haslanguage) + public static ODHActivityPoi ParsetheCompanyData( + ODHActivityPoi mywinecompany, + IDictionary companydata, + List haslanguage + ) { mywinecompany.LastChange = DateTime.Now; @@ -542,16 +674,31 @@ public static ODHActivityPoi ParsetheCompanyData(ODHActivityPoi mywinecompany, I mywinecompany.PoiServices = poiServices; } - if (companydata["de"].Element("latidude") != null && companydata["de"].Element("longitude") != null) + if ( + companydata["de"].Element("latidude") != null + && companydata["de"].Element("longitude") != null + ) { - if (!companydata["de"].Element("latidude").Value.Contains("°") && !companydata["de"].Element("longitude").Value.Contains("°")) + if ( + !companydata["de"].Element("latidude").Value.Contains("°") + && !companydata["de"].Element("longitude").Value.Contains("°") + ) { - if (companydata["de"].Element("latidude").Value != "0" && companydata["de"].Element("longitude").Value != "0") + if ( + companydata["de"].Element("latidude").Value != "0" + && companydata["de"].Element("longitude").Value != "0" + ) { List gpsinfolist = new List(); GpsInfo mygps = new GpsInfo(); - mygps.Latitude = Convert.ToDouble(companydata["de"].Element("latidude").Value, CultureInfo.CurrentCulture); - mygps.Longitude = Convert.ToDouble(companydata["de"].Element("longitude").Value, CultureInfo.CurrentCulture); + mygps.Latitude = Convert.ToDouble( + companydata["de"].Element("latidude").Value, + CultureInfo.CurrentCulture + ); + mygps.Longitude = Convert.ToDouble( + companydata["de"].Element("longitude").Value, + CultureInfo.CurrentCulture + ); mygps.Gpstype = "position"; gpsinfolist.Add(mygps); mywinecompany.GpsInfo = gpsinfolist; @@ -1076,7 +1223,5 @@ public static ODHActivityPoi ParsetheCompanyData(ODHActivityPoi mywinecompany, I // return mywinecompany; //} - - } }