diff --git a/Source/DealerSelection.Api.Models/WebEngageEvent.cs b/Source/DealerSelection.Api.Models/WebEngageEvent.cs index c04415d..6f3a281 100644 --- a/Source/DealerSelection.Api.Models/WebEngageEvent.cs +++ b/Source/DealerSelection.Api.Models/WebEngageEvent.cs @@ -4,9 +4,9 @@ namespace DealerSelection.Api.Models; public class WebEngageEventData { - public WebEngageEventData(string bookingID, string bookingStatus, string bookingAmount,string dealerFlag, string fullName, string phoneNumber, + public WebEngageEventData(string bookingID, string bookingStatus, string bookingAmount, string bookingReceiptLink,string dealerFlag, string fullName, string phoneNumber, string motorcycleName, string motorcycleCode, string location, string dealerName, - string dealerPhoneNumber, string bookingReceiptLink) + string dealerPhoneNumber) { BookingID = bookingID; BookingStatus = bookingStatus; diff --git a/Source/DealerSelection.Api/AssignDealerApi.cs b/Source/DealerSelection.Api/AssignDealerApi.cs index 2842b28..d973481 100644 --- a/Source/DealerSelection.Api/AssignDealerApi.cs +++ b/Source/DealerSelection.Api/AssignDealerApi.cs @@ -72,7 +72,7 @@ public class AssignDealerApi : IAssignDealerApi private readonly IMemoryCache _memoryCache; public AssignDealerApi(DealerSelection.Api.Infrastructure.AssignDealer.IRepository repository, IMulesoftApi mulesoftApi, CustomerDetailRepo.IRepository customerRepo, - IHttpClientHandler clientHandler, IMemoryCache memoryCache, ILogger logger) + IHttpClientHandler clientHandler, IMemoryCache memoryCache, ILogger logger) { Repository = repository; MulesoftApi = mulesoftApi; @@ -98,10 +98,11 @@ public class AssignDealerApi : IAssignDealerApi private async Task AssignDealers(MulesoftCustomerInfoDto customerInfo) { + _logger.LogInformation($"DS Api:-AssignDealers Started BuId:- { customerInfo.BuId} RecordId: {customerInfo.RecordId}" ); try { CustomCfg cfg = CustomCfg.GetCustomCfg(customerInfo.BuId); - MulesoftResponse dealerResponse = await MulesoftApi.GetDealers(customerInfo.BuId, customerInfo.BuCode, customerInfo.CustomerLat, customerInfo.CustomerLong); + MulesoftResponse dealerResponse = await MulesoftApi.GetDealers(customerInfo.BuId, cfg.BuCode, customerInfo.CustomerLat, customerInfo.CustomerLong); if (dealerResponse != null && dealerResponse.IsRequestSuccessfull) { @@ -110,7 +111,7 @@ public class AssignDealerApi : IAssignDealerApi { if (obj["Data"].Count() == 1) { - _logger.LogInformation($"DS Api:- BU:- {customerInfo.BuId} Api:- AssignDealers with 1 Dealer"); + _logger.LogInformation($"DS Api:- BU:- {customerInfo.BuId} RecordId: {customerInfo.RecordId} Api:- AssignDealers with 1 Dealer"); //Save dealer Detail and Send to LSQ JToken jArrResultData = (JToken)obj["Data"][0]; if (jArrResultData != null) @@ -123,9 +124,9 @@ public class AssignDealerApi : IAssignDealerApi } else if (obj["Data"].Count() > 1) { - _logger.LogInformation($"DS Api:- BU:- {customerInfo.BuId} Api:- Inititate Bot more then 1 Dealer"); + _logger.LogInformation($"DS Api:- BU:- {customerInfo.BuId} RecordId: {customerInfo.RecordId} Api:- Inititate Bot more then 1 Dealer"); - // Send to Webengage to Initiate BOT + // Send Message to Webengage to Initiate BOT WebEngageEventData eventData = new WebEngageEventData(customerInfo.BookingId, "SUCCESS", customerInfo.AmountPaid, "", "N", customerInfo.CustomerName, customerInfo.MobileNumber, customerInfo.ModelName, customerInfo.ModelCode, customerInfo.CustomerLat, "", ""); @@ -161,15 +162,20 @@ public class AssignDealerApi : IAssignDealerApi RestResponse response = await client.ExecuteAsync(request); var content = response.Content; - JObject obj = JObject.Parse(content); - if (obj != null && obj["response"] != null) + _logger.LogInformation($"DS Api:-WebEngageEventsAPICall End: " + content); + + if (content != null) { - JToken jArrResultData = (JToken)obj["response"]["status"]; - if (jArrResultData != null && Convert.ToString(((JValue)jArrResultData).Value) == "queued") - await CustomerDetailRepository.UpdateDealerSelectionJobStatus(cfg.BuId, recordId, DealerSelectionJobStatus.SentToBot); + JObject obj = JObject.Parse(content); + if (obj != null && obj["response"] != null) + { + JToken jArrResultData = (JToken)obj["response"]["status"]; + if (jArrResultData != null && Convert.ToString(((JValue)jArrResultData).Value) == "queued") + await CustomerDetailRepository.UpdateDealerSelectionJobStatus(cfg.BuId, recordId, DealerSelectionJobStatus.SentToBot); + } } - _logger.LogInformation($"DS Api:-WebEngageEventsAPICall End: " + content); + } catch (Exception ex) { diff --git a/Source/DealerSelection.Api/CCAvenueApi.cs b/Source/DealerSelection.Api/CCAvenueApi.cs index 2cd58af..5865621 100644 --- a/Source/DealerSelection.Api/CCAvenueApi.cs +++ b/Source/DealerSelection.Api/CCAvenueApi.cs @@ -28,13 +28,8 @@ public class CCAvenueApi : ICCAvenueApi } public async Task RefundOrder(string bookingId, string transactionId) { - Dto customerInfo = await Repository.GetBookingDetail(bookingId, transactionId); - //Dto customerInfo = new Dto() - //{ - // AmountPaid = "4499", - // BuId = 1, - // RecordId = 800 - //}; + _logger.LogInformation($"DS Api:-RefundOrder Started BookingId:- {bookingId} + TransactionId:- {transactionId} "); + Dto customerInfo = await Repository.GetBookingDetail(bookingId, transactionId); RefundApiResponse response = null; if (customerInfo != null) @@ -128,10 +123,11 @@ public class CCAvenueApi : ICCAvenueApi response.Status = "1"; } + _logger.LogInformation($"DS Api:-RefundOrder End BookingId:- {bookingId} + TransactionId:- {transactionId} Response {response}"); return response; } - private static async Task SendRequestToGateWay(string queryUrl, string urlParam) + private async Task SendRequestToGateWay(string queryUrl, string urlParam) { string message = ""; @@ -154,13 +150,14 @@ public class CCAvenueApi : ICCAvenueApi } catch (Exception ex) { + _logger.LogError($"DS Api:-SendRequestToGateWay {ex.StackTrace}"); throw ex; } return message; } - private static NameValueCollection GetResponseCollection(string message) + private NameValueCollection GetResponseCollection(string message) { NameValueCollection Params = new NameValueCollection(); try @@ -182,6 +179,7 @@ public class CCAvenueApi : ICCAvenueApi } catch (Exception ex) { + _logger.LogError($"DS Api:-GetResponseCollection {ex.StackTrace}"); throw ex; } return Params; diff --git a/Source/DealerSelection.Api/MulesoftApi.cs b/Source/DealerSelection.Api/MulesoftApi.cs index 065631f..1219d6c 100644 --- a/Source/DealerSelection.Api/MulesoftApi.cs +++ b/Source/DealerSelection.Api/MulesoftApi.cs @@ -122,7 +122,7 @@ public class MulesoftApi : IMulesoftApi var cacheKey = "getDealerDetails_" + buId + dealerCode; if (!_memoryCache.TryGetValue(cacheKey, out response)) { - AzureLogHelper.LogMessage("Api:- GetAndInsertDealerDetails:- API:- " + cacheKey); + _logger.LogInformation("Api:- GetAndInsertDealerDetails:- API:- " + cacheKey); string authToken = await MulesoftTokenApi.FetchToken(); string message = "{\"branchCode\": \"" + dealerCode + @@ -253,7 +253,7 @@ public class MulesoftApi : IMulesoftApi if (string.IsNullOrEmpty(pincode)) pincode = "400070"; - string message = "{\"bu\": \"" + customerInfo.BuCode + "\", \"model_Code\": \"" + customerInfo.ModelCode + "\"," + + string message = "{\"bu\": \"" + cfg.BuCode + "\", \"model_Code\": \"" + customerInfo.ModelCode + "\"," + "\"color\": \"" + customerInfo.ColorCode + "\"," + "\"customer_Name\": \"" + customerInfo.CustomerName + "\"" + ", \"location_of_the_customer\": \"\", \"dealer_Code\": \"" + dealerCode + "\", " + @@ -521,6 +521,7 @@ public class MulesoftApi : IMulesoftApi private async Task UpdateDetails(MulesoftCustomerInfoDto customerInfo, DealerSelectionJobStatus jobStatus) { + _logger.LogInformation($"DS Api:-UpdateDetails Started:- {customerInfo} JobStatus {jobStatus}"); try { @@ -543,6 +544,7 @@ public class MulesoftApi : IMulesoftApi { _logger.LogError($"DS Api:- UpdateDetails:- " + ex.Message.ToString()); } + _logger.LogInformation($"DS Api:-UpdateDetails End:- {customerInfo} JobStatus {jobStatus}"); } diff --git a/Source/DealerSelection.Api/YellowAIApi.cs b/Source/DealerSelection.Api/YellowAIApi.cs index 251ccd7..d3bf388 100644 --- a/Source/DealerSelection.Api/YellowAIApi.cs +++ b/Source/DealerSelection.Api/YellowAIApi.cs @@ -1,13 +1,12 @@ -using CustomerDetailRepo = DealerSelection.Api.Infrastructure.CustomerDetail; -using DealerSelection.Api.Infrastructure.YellowAI; +using DealerSelection.Api.Infrastructure.YellowAI; using DealerSelection.Api.Interface; using DealerSelection.Api.Models; +using DealerSelection.Api.Models.Enum; using DealerSelection.Common.Exceptions; using Microsoft.Extensions.Logging; using System.Text.RegularExpressions; +using CustomerDetailRepo = DealerSelection.Api.Infrastructure.CustomerDetail; using MulesoftRepo = DealerSelection.Api.Infrastructure.Mulesoft; -using static iTextSharp.text.pdf.AcroFields; -using DealerSelection.Api.Models.Enum; namespace DealerSelection.Api; public class YellowAIApi : IYellowAIApi @@ -28,6 +27,8 @@ public class YellowAIApi : IYellowAIApi public async Task UpdateSelectedDealer(CustomerDealerInfoRequest request) { + _logger.LogInformation($"DS Api:-UpdateSelectedDealer Started :- MobileNumber {request.MobileNumber} BuCode {request.BuCode} BuSubType {request.BuSubType}" + + $"DealerCode {request.DealerCode} DealerName {request.DealerName} PinCode {request.PinCode} CustomerLat {request.Latitude} CustomerLong {request.Longitude} "); try { if (IsValidData(request.MobileNumber, request.DealerCode, request.DealerName)) @@ -52,16 +53,20 @@ public class YellowAIApi : IYellowAIApi throw new ValidationException("Invalid data."); } } + catch(Exception ex) { _logger.LogError($"Some error occured: {ex.StackTrace}."); throw new ValidationException($"Some error occured: {ex.StackTrace}."); } + _logger.LogInformation($"DS Api:-UpdateSelectedDealer End :- MobileNumber {request.MobileNumber} BuCode {request.BuCode} BuSubType {request.BuSubType}" + + $"DealerCode {request.DealerCode} DealerName {request.DealerName} PinCode {request.PinCode} CustomerLat {request.Latitude} CustomerLong {request.Longitude} "); } public async Task GetModelDetails(string mobileNumber, string buCode, string buSubType) { + _logger.LogInformation($"DS Api:-GetModelDetails Started :- MobileNumber {mobileNumber} BuCode {buCode} BuSubType {buSubType} "); ModelDetailDto dto = await Repository.GetModelDetails(mobileNumber, buCode, buSubType); ModelDetail response = null; if (dto !=null) @@ -69,7 +74,8 @@ public class YellowAIApi : IYellowAIApi response = new ModelDetail(dto.ModelCode); } - + _logger.LogInformation($"DS Api:-GetModelDetails End :- MobileNumber {mobileNumber} BuCode {buCode} BuSubType {buSubType} Response {response}"); + return response; } diff --git a/Source/DealerSelection.Common/CommonBaseClass/ExceptionFilterBase.cs b/Source/DealerSelection.Common/CommonBaseClass/ExceptionFilterBase.cs index 1dc4400..bd1f013 100644 --- a/Source/DealerSelection.Common/CommonBaseClass/ExceptionFilterBase.cs +++ b/Source/DealerSelection.Common/CommonBaseClass/ExceptionFilterBase.cs @@ -32,7 +32,7 @@ public class ExceptionFilterBase : ExceptionFilterAttribute, IExceptionFilter if (exception.StackTrace != null) { string exceptionStack = exception.StackTrace.StandardizeText(true); - context.HttpContext.Request.Headers.Add("BajaBooking-Custom-ExceptionStack", exceptionStack); + context.HttpContext.Request.Headers.Add("DealerSelection-Custom-ExceptionStack", exceptionStack); } HttpStatusCode httpStatusCode = Mappings.ContainsKey(exception.GetType()) @@ -50,17 +50,17 @@ public class ExceptionFilterBase : ExceptionFilterAttribute, IExceptionFilter try { if (context.Exception.InnerException != null) - context.HttpContext.Request.Headers.Add("BajaBooking-Custom-InnerException", context.Exception.InnerException.ToString().StandardizeText(true)); + context.HttpContext.Request.Headers.Add("DealerSelection-Custom-InnerException", context.Exception.InnerException.ToString().StandardizeText(true)); } catch (Exception ex) { try { - context.HttpContext.Request.Headers.Add("BajaBooking-Custom-InnerException", "Cannot add detailed error to header because: " + ex.Message); + context.HttpContext.Request.Headers.Add("DealerSelection-Custom-InnerException", "Cannot add detailed error to header because: " + ex.Message); } catch { - context.HttpContext.Request.Headers.Add("BajaBooking-Custom-InnerException", "Cannot add detailed error to header for unknown reason: " + ex.Message); + context.HttpContext.Request.Headers.Add("DealerSelection-Custom-InnerException", "Cannot add detailed error to header for unknown reason: " + ex.Message); } } diff --git a/Source/DealerSelection.Common/CommonBaseClass/StartupBase.cs b/Source/DealerSelection.Common/CommonBaseClass/StartupBase.cs index 23b9ae0..b288b6b 100644 --- a/Source/DealerSelection.Common/CommonBaseClass/StartupBase.cs +++ b/Source/DealerSelection.Common/CommonBaseClass/StartupBase.cs @@ -15,7 +15,9 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.ApplicationInsights; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; +using Org.BouncyCastle.Asn1.Ocsp; using System.IO.Compression; +using System.Net.Http; using System.Reflection; using System.Text; using System.Text.Json.Serialization; @@ -73,6 +75,7 @@ public abstract class StartupBase ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); + app.UseAuthentication(); app.UseAuthorization(); app.UseStaticFiles(); @@ -150,9 +153,13 @@ public abstract class StartupBase { audiences.Add(audience); } - if (Configuration.ConfigurationHelper.GetSetting("ValidateAudience", true) == "True") - { - builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => + // bool validateAudience = false; + //if (Configuration.ConfigurationHelper.GetSetting("ValidateAudience", true) == "True") + //{ + // validateAudience = true; + //} + + builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { @@ -165,23 +172,7 @@ public abstract class StartupBase IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])) }; }); - } - else - { - builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => - { - options.TokenValidationParameters = new TokenValidationParameters - { - ValidateIssuer = true, - ValidateAudience = false, - ValidateLifetime = true, - ValidateIssuerSigningKey = true, - ValidIssuer = builder.Configuration["Jwt:Issuer"], - ValidAudiences = new List(audiences), - IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])) - }; - }); - } + } private void SetupSwaggerOptions(WebApplicationBuilder builder) diff --git a/Source/DealerSelection.DependencyInjection/ApiRegistry.cs b/Source/DealerSelection.DependencyInjection/ApiRegistry.cs index 26929e7..28a33de 100644 --- a/Source/DealerSelection.DependencyInjection/ApiRegistry.cs +++ b/Source/DealerSelection.DependencyInjection/ApiRegistry.cs @@ -40,5 +40,9 @@ public class ApiRegistry : ServiceRegistry .Use() .Singleton(); + For() + .Use() + .Singleton(); + } } diff --git a/Source/DealerSelection.DependencyInjection/InfrastructureRegistry.cs b/Source/DealerSelection.DependencyInjection/InfrastructureRegistry.cs index 43eb1a4..e349e21 100644 --- a/Source/DealerSelection.DependencyInjection/InfrastructureRegistry.cs +++ b/Source/DealerSelection.DependencyInjection/InfrastructureRegistry.cs @@ -6,6 +6,7 @@ using AssignDealerRepo = DealerSelection.Api.Infrastructure.AssignDealer; using Customerdetail = DealerSelection.Api.Infrastructure.CustomerDetail; using JwtRepo = DealerSelection.Api.Infrastructure.Jwt; using CCAvenue = DealerSelection.Api.Infrastructure.CCAvenue; +using BatchJob = DealerSelection.Api.Infrastructure.BatchJob; namespace DealerSelection.DependencyInjection; public class InfrastructureRegistry : ServiceRegistry @@ -43,6 +44,10 @@ public class InfrastructureRegistry : ServiceRegistry .Ctor().Is("BOOKING") .Transient(); + For() + .Use() + .Ctor().Is("BOOKING") + .Transient(); } } diff --git a/Source/DealerSelection.Infrastructure/CustomerDetail/Repository.cs b/Source/DealerSelection.Infrastructure/CustomerDetail/Repository.cs index c6c70b9..f736749 100644 --- a/Source/DealerSelection.Infrastructure/CustomerDetail/Repository.cs +++ b/Source/DealerSelection.Infrastructure/CustomerDetail/Repository.cs @@ -117,8 +117,8 @@ public class Repository : RepositoryBaseDapperAsync, IRepository } catch (Exception ex) { - _logger.LogError($"DS Repo:- Error at Repository:CustomerDetail in IsDuplicateMobileNumber for MobileNumber: {mobileNumber}. ErrorMessage", ex.StackTrace); - throw new DuplicateException($"Error at Repository:CustomerDetail in IsDuplicateMobileNumber for MobileNumber: {mobileNumber}."); + _logger.LogError($"DS Repo:- Error at Repository:CustomerDetail in GetCustomerDetailByBuCode for MobileNumber: {mobileNumber}. ErrorMessage", ex.StackTrace); + throw new DuplicateException($"Error at Repository:CustomerDetail in GetCustomerDetailByBuCode for MobileNumber: {mobileNumber}."); } } diff --git a/Source/DealerSelection.Infrastructure/Mulesoft/MulesoftCustomerInfoDto.cs b/Source/DealerSelection.Infrastructure/Mulesoft/MulesoftCustomerInfoDto.cs index adc135e..fc5c12d 100644 --- a/Source/DealerSelection.Infrastructure/Mulesoft/MulesoftCustomerInfoDto.cs +++ b/Source/DealerSelection.Infrastructure/Mulesoft/MulesoftCustomerInfoDto.cs @@ -4,7 +4,7 @@ namespace DealerSelection.Api.Infrastructure.Mulesoft; public class MulesoftCustomerInfoDto { public int BuId { get; set; } - public string BuCode { get; set; } + //public string BuCode { get; set; } public int RecordId { get; set; } public string BookingId { get; set; } public string CustomerName { get; set; } diff --git a/Source/DealerSelection.WebApi/Controllers/BatchJobController.cs b/Source/DealerSelection.WebApi/Controllers/BatchJobController.cs index 1be8506..01ad541 100644 --- a/Source/DealerSelection.WebApi/Controllers/BatchJobController.cs +++ b/Source/DealerSelection.WebApi/Controllers/BatchJobController.cs @@ -20,8 +20,8 @@ public class BatchJobController : ControllerBase /// /// /// - [Authorize] - [HttpPost] + // [Authorize] + [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] [SwaggerOperation(Tags = new[] { "Process24HrOldRecords" })] [Route("BatchJob")] diff --git a/Source/DealerSelection.WebApi/appsettings.json b/Source/DealerSelection.WebApi/appsettings.json index 1c5b7be..0779b91 100644 --- a/Source/DealerSelection.WebApi/appsettings.json +++ b/Source/DealerSelection.WebApi/appsettings.json @@ -1,6 +1,6 @@ { "BrowseSwagger": true, - "ValidateAudience": false, + "ValidateAudience": true, "CCAvenueApiPayUrl": "https://apitest.ccavenue.com", "WebsiteDomain": "https://www.ktm-uat2.bajajauto.com", "aZureWorkspaceId": "4247310d-8a93-4d54-8da5-505aa28817f1", @@ -37,7 +37,7 @@ "KtmCfg": { "Buid": 1, "BuCode": "PB", - "DefaultDealerCode": "test", + "DefaultDealerCode": "Bajaj", "CCAvenueAccessCode": "AVLM05KI16AB00MLBA", "CCAvenueMerchantCode": "350479", "CCAvenueWorkingKey": "F40694C5358CF9D2826C4545D6FAE337", @@ -49,7 +49,7 @@ "BajajCfg": { "Buid": 2, "BuCode": "MC", - "DefaultDealerCode": "test", + "DefaultDealerCode": "Bajaj", "CCAvenueAccessCode": "AVNL05KI17AO76LNOA", "CCAvenueMerchantCode": "350479", "CCAvenueWorkingKey": "6FD791AC3A7177E9139215B32278AFDB", @@ -73,7 +73,7 @@ "ClientId": "5ef10013c846424cbe32aaffbdc2d408", "ClientSecret": "4ca8d784dc9d4b8db9113d04770c0a7a", "Key": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9", - "Audience": "https://www.ktm-uat2.bajajauto.com,https://apidev.bajajauto.com", + "Audience": "https://apidev.bajajauto.com", "Issuer": "https://dealerselection-dev.bajajauto.com", "Role": "Admin", "ExpireMinutes": "30" diff --git a/Source/WebJobService/IRepository.cs b/Source/WebJobService/IRepository.cs new file mode 100644 index 0000000..7c5ceaf --- /dev/null +++ b/Source/WebJobService/IRepository.cs @@ -0,0 +1,6 @@ +namespace WebJobService; + +public interface IRepository +{ + Task> GetDealerSelectionDataForJobAsync(); +} \ No newline at end of file diff --git a/Source/WebJobService/Program.cs b/Source/WebJobService/Program.cs index c411e8a..84a5ef7 100644 --- a/Source/WebJobService/Program.cs +++ b/Source/WebJobService/Program.cs @@ -1,35 +1,88 @@ using DealerSelection.Common.HttpClient; using DealerSelection.Common.Interfaces.HttpClient; using Lamar; +using Microsoft.ApplicationInsights.Extensibility; +using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.ApplicationInsights; namespace WebJobService; public class Program : ServiceRegistry { - private IHttpClientHandler HttpClientHandler { get; set; } - private ILogger logger; - private IServiceProvider serviceProvider; + static void Main() { - var container=new Container(x=> - { - x.AddSingleton(); - x.AddSingleton(); - x.For().Use().Ctor("cxnName").Is("BOOKING").Singleton(); - }); - //IHttpClientHandler clientHandler = container.GetInstance(); - //ILogger logger = container.GetInstance(); - IService service = container.GetInstance(); - // IHttpClientHandler clientHandler = container.GetInstance(); - //ILogger logger = container.GetInstance(); + var registry = new ServiceRegistry(); + registry.AddSingleton(); + registry.AddSingleton(); + + var builder = new ConfigurationBuilder().AddJsonFile($"appsettings.json", true, true); + var config = builder.Build(); + var aiUrl = config["AZURE_LOGGING"]; + + registry.AddLogging(x => x.AddApplicationInsights( + configureTelemetryConfiguration: (config) => config.ConnectionString = + aiUrl, configureApplicationInsightsLoggerOptions: (options) => { } + ).AddFilter("traces", LogLevel.Trace)); + + + + registry.For() + .Use() + .Ctor().Is("BOOKING") + .Transient(); + + registry.For().Use().Singleton(); + + //IServiceCollection services1 = new ServiceCollection(); + //var CHANNEL1 = new ServerTelemetryChannel(); + //services1.Configure((config) => + //{ + // config.TelemetryChannel = CHANNEL1; + //}); + + //services1.AddLogging(builder => { builder.AddApplicationInsights(aiUrl); }); + //var provider=services1.BuildServiceProvider(); + //var logger=provider.GetService>(); + //logger.LogInformation("Its a Test"); + //Host.CreateDefaultBuilder(args) + // .ConfigureWebHostDefaults(webBuilder => + // { + // webBuilder.UseStartup(); + // }) + // .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration + // .ReadFrom.Configuration(hostingContext.Configuration) + // .WriteTo.ApplicationInsights(new TelemetryConfiguration { InstrumentationKey = "xxxxxxxxx" }, TelemetryConverter.Traces) + // ); + + var container = new Container(registry); + + + IService service = container.GetInstance(); service.Run(); + // Handling finalizing when process is ended + } - + private void AzureLogging(WebApplicationBuilder builder) + { + builder.Logging.AddApplicationInsights( + configureTelemetryConfiguration: (config) => config.ConnectionString = + builder.Configuration.GetConnectionString("AZURE_LOGGING"), + configureApplicationInsightsLoggerOptions: (options) => { } + ); + builder.Logging.AddFilter("traces", LogLevel.Trace); + } + + } diff --git a/Source/WebJobService/Repository.cs b/Source/WebJobService/Repository.cs new file mode 100644 index 0000000..6c521e2 --- /dev/null +++ b/Source/WebJobService/Repository.cs @@ -0,0 +1,33 @@ +using Dapper; +using DealerSelection.Common.Data.Dapper; +using Microsoft.Extensions.Logging; +using System.Data; +using System.Data.SqlClient; + +namespace WebJobService; + +public class Repository : RepositoryBaseDapperAsync, IRepository +{ + private readonly ILogger _logger; + public Repository(string cxnName, ILogger logger) : base(cxnName) + { + _logger = logger; + } + + public async Task> GetDealerSelectionDataForJobAsync() + { + try + { + using SqlConnection cxn = await OpenCxnAsync(); + IEnumerable recordsToProcess = await cxn.QueryAsync("DealerSelection.usp_get_dealer_selection_for_job", + commandType: CommandType.StoredProcedure); + return recordsToProcess.ToList(); + } + catch (Exception ex) + { + _logger.LogError($"WJ:-Repo:-Error at Repository:GetDealerSelectionDataForJobAsync.", ex.StackTrace); + throw; + } + } + +} \ No newline at end of file diff --git a/Source/WebJobService/SelectedData.cs b/Source/WebJobService/SelectedData.cs new file mode 100644 index 0000000..e1b71eb --- /dev/null +++ b/Source/WebJobService/SelectedData.cs @@ -0,0 +1,7 @@ +namespace WebJobService; + +public class SelectedData +{ + public int BuId { get; set; } + public int RecordId { get; set; } +} diff --git a/Source/WebJobService/Service.cs b/Source/WebJobService/Service.cs index 37325ba..7ca90e8 100644 --- a/Source/WebJobService/Service.cs +++ b/Source/WebJobService/Service.cs @@ -1,122 +1,89 @@ -using Dapper; -using DealerSelection.Common.Data.Dapper; +using DealerSelection.Common.Interfaces.HttpClient; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; -using Newtonsoft.Json.Linq; +using Microsoft.VisualBasic; using Newtonsoft.Json; -using System.Configuration; -using System.Data; using System.Data.SqlClient; using System.Net; -using System.Text; using System.Net.Http.Headers; -using DealerSelection.Common.Interfaces.HttpClient; -using static System.Net.Mime.MediaTypeNames; -using System.Net.Http; -using Microsoft.VisualBasic; +using System.Text; namespace WebJobService; -public class Service : RepositoryBaseDapperAsync, IService +public class Service : IService { - private readonly ILogger _logger; - private IHttpClientHandler ClientHandler { get; } - public Service(string cxnName, IHttpClientHandler clientHandler) : base(cxnName) + private ILogger _logger; + private IHttpClientHandler ClientHandler { get; } + private IRepository Repository { get; } + public Service(IHttpClientHandler clientHandler, ILogger logger, IRepository repository) { - //_logger = logger; + _logger = logger; ClientHandler = clientHandler; + Repository = repository; } public void Run() { - Console.WriteLine($"Service Started: {DateTime.Now}."); - ////_logger.LogInformation($"DS Api:-($"Service Started: {DateTime.Now}."); - GetRecordToProcess().Wait(); - Console.WriteLine($"Service Completed: {DateTime.Now}."); - ////_logger.LogInformation($"DS Api:-($"Service Completed: {DateTime.Now}."); + _logger.LogError($"WJ:-Service Started"); + // GetRecordToProcess().Wait(); + _logger.LogInformation($"WJ:-Service Completed"); } private async Task GetRecordToProcess() - { + { try { - using (SqlConnection cxn = await OpenCxnAsync()) + var recordList = await Repository.GetDealerSelectionDataForJobAsync();// recordsToProcess.ToList(); + _logger.LogInformation($"WJ:-Records to Process: {recordList.Count}"); + foreach (var item in recordList) { - IEnumerable recordsToProcess = await cxn.QueryAsync("DealerSelection.usp_get_dealer_selection_for_job", - commandType: CommandType.StoredProcedure); - var recordList = recordsToProcess.ToList(); - Console.WriteLine($"Records to Process: {recordList.Count}."); - //_logger.LogInformation($"DS Api:-($"Records to Process: {recordList.Count}."); - foreach (var item in recordList) - { - HitDeleareSelectionApi(item); - } - Console.WriteLine($"Records processed sucessfully: {recordList.Count}."); + await HitDeleareSelectionApi(item); } - + _logger.LogInformation($"WJ:-Records processed sucessfully: {recordList.Count}."); } catch (Exception exp) { - throw exp; + _logger.LogError($"WJ:-Error at GetRecordToProcess {exp.StackTrace}"); + throw ; } } private async Task HitDeleareSelectionApi(SelectedData item) { - //item.BuId, item.RecorId + var builder = new ConfigurationBuilder().AddJsonFile($"appsettings.json", true, true); + var config = builder.Build(); + var baseApiUrl = config["BaseApiUrl"]; + string jwtToken = GenerateToken(baseApiUrl, config["ClientId"], config["ClientSecret"]); - string jwtToken = GenerateToken(); - string url = string.Format($"https://dealerselection-dev.bajajauto.com/DealerSelection?buId={item.BuId}&recordId={item.RecordId}"); + string url = string.Format($"{baseApiUrl}/DealerSelection?buId={item.BuId}&recordId={item.RecordId}"); try { - //using (var webClient = new WebClient { Encoding = Encoding.UTF8 }) - //{ - // webClient.Headers.Add("Content-Type", "application/json"); - // webClient.Headers.Add("Authorization", "Bearer " + jwtToken); - // resultJson = webClient.DownloadString(modelDetailsApi); - //} - //var resultObject = JObject.Parse(resultJson); - //if (resultObject.Value("IsRequestSuccessfull")) - //{ - // var response = (JObject)resultObject.Value("Data")[0]; - // Console.WriteLine(response.ToString()); - //} - - - //var data = "{\"buId\": \"" + item.BuId + "\"}"; - - //var data = new - //{ - // item.BuId, - // item.RecorId, - //}; - - //string requestJson = JsonConvert.SerializeObject(data); - - Console.WriteLine($"Deler Selection URl Request: {url}."); - HttpClient request = ClientHandler.GetHttpClient(); - Uri requestUri = new (url); + + _logger.LogInformation($"WJ:-Deler Selection URl Request: {url}."); + HttpClient request = ClientHandler.GetHttpClient(); + Uri requestUri = new(url); var httpContent = new MultipartFormDataContent(); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); request.DefaultRequestHeaders.Add("Authorization", "Bearer " + jwtToken); - HttpResponseMessage response = request.PostAsync(url, null).Result; - var contents = await response.Content.ReadAsStringAsync(); - Console.WriteLine($"Deler Selection URl Response: {contents}"); + HttpResponseMessage response = request.PostAsync(url, null).Result; + _logger.LogInformation($"WJ:-Deler Selection URl ResponseStatus: {response}"); } catch (Exception ex) { - Console.WriteLine(ex.StackTrace); + _logger.LogError($"WJ:-Error at GetRecordToProcess:- {ex.StackTrace}"); + throw; } } - private string GenerateToken() + private string GenerateToken(string baseApiUrl, string client_Id, string client_secret) { - Console.WriteLine($"GenerateToken Started: {DateAndTime.Now}"); - string jwtTokenApiUrl = string.Format("{0}/jwtauth/gettoken", "https://dealerselection-dev.bajajauto.com"); + _logger.LogInformation($"WJ:-GenerateToken Started."); + string jwtTokenApiUrl = string.Format($"{baseApiUrl}/jwtauth/gettoken"); var requestBody = new { - client_id = "5ef10013c846424cbe32aaffbdc2d408", - client_secret = "4ca8d784dc9d4b8db9113d04770c0a7a" + client_id = client_Id, + client_secret }; string requestJson = JsonConvert.SerializeObject(requestBody); @@ -143,20 +110,15 @@ public class Service : RepositoryBaseDapperAsync, IService { jwtToken = reader.ReadToEnd(); } - Console.WriteLine($"GenerateToken End: {DateAndTime.Now} - Token :{jwtToken}"); + _logger.LogInformation($"WJ:-GenerateToken End: {DateAndTime.Now} - Token :{jwtToken}"); } - + catch (Exception ex) { - Console.WriteLine($"Exception at GenerateToken :- {ex.StackTrace}"); + _logger.LogError($"WJ:-Error at GenerateToken:- {ex.StackTrace}"); + throw; } return jwtToken; } - - class SelectedData - { - public int BuId { get; set; } - public int RecordId { get; set; } - } } \ No newline at end of file diff --git a/Source/WebJobService/ServiceBackUp.cs b/Source/WebJobService/ServiceBackUp.cs new file mode 100644 index 0000000..8a11984 --- /dev/null +++ b/Source/WebJobService/ServiceBackUp.cs @@ -0,0 +1,140 @@ +using Dapper; +using DealerSelection.Common.Data.Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json; +using System.Configuration; +using System.Data; +using System.Data.SqlClient; +using System.Net; +using System.Text; +using System.Net.Http.Headers; +using DealerSelection.Common.Interfaces.HttpClient; +using static System.Net.Mime.MediaTypeNames; +using System.Net.Http; +using Microsoft.VisualBasic; +using Microsoft.Extensions.Configuration; + +namespace WebJobService; + +public class ServiceBackUp : RepositoryBaseDapperAsync, IService +{ + private ILogger _logger; + + private IHttpClientHandler ClientHandler { get; } + public ServiceBackUp(string cxnName, IHttpClientHandler clientHandler,ILogger logger) : base(cxnName) + { + _logger = logger; + ClientHandler = clientHandler; + } + + public void Run() + { + + Console.WriteLine($"Service Started: {DateTime.Now}."); + _logger.LogInformation($"Service Started: {DateTime.Now}."); + GetRecordToProcess().Wait(); + Console.WriteLine($"Service Completed: {DateTime.Now}."); + _logger.LogInformation($"Service Completed: {DateTime.Now}."); + } + + private async Task GetRecordToProcess() + { + try + { + using (SqlConnection cxn = await OpenCxnAsync()) + { + IEnumerable recordsToProcess = await cxn.QueryAsync("DealerSelection.usp_get_dealer_selection_for_job", + commandType: CommandType.StoredProcedure); + + + var recordList = recordsToProcess.ToList(); + Console.WriteLine($"Records to Process: {recordList.Count}."); + //_logger.LogInformation($"DS Api:-($"Records to Process: {recordList.Count}."); + foreach (var item in recordList) + { + HitDeleareSelectionApi(item); + } + Console.WriteLine($"Records processed sucessfully: {recordList.Count}."); + } + + } + catch (Exception exp) + { + throw exp; + } + } + + private async Task HitDeleareSelectionApi(SelectedData item) + { + var builder = new ConfigurationBuilder().AddJsonFile($"appsettings.json", true, true); + var config = builder.Build(); + var baseApiUrl = config["BaseApiUrl"]; + string jwtToken = GenerateToken(baseApiUrl, config["ClientId"], config["ClientSecret"]); + + string url = string.Format($"{baseApiUrl}/DealerSelection?buId={item.BuId}&recordId={item.RecordId}"); + try + { + + Console.WriteLine($"Deler Selection URl Request: {url}."); + HttpClient request = ClientHandler.GetHttpClient(); + Uri requestUri = new(url); + var httpContent = new MultipartFormDataContent(); + httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + request.DefaultRequestHeaders.Add("Authorization", "Bearer " + jwtToken); + HttpResponseMessage response = request.PostAsync(url, null).Result; + var contents = await response.Content.ReadAsStringAsync(); + Console.WriteLine($"Deler Selection URl Response: {contents}"); + } + catch (Exception ex) + { + Console.WriteLine(ex.StackTrace); + } + } + + private string GenerateToken(string baseApiUrl, string client_Id, string client_secret) + { + Console.WriteLine($"GenerateToken Started: {DateAndTime.Now}"); + string jwtTokenApiUrl = string.Format($"{baseApiUrl}/jwtauth/gettoken"); + + var requestBody = new + { + client_id = client_Id, + client_secret = client_secret + }; + + string requestJson = JsonConvert.SerializeObject(requestBody); + byte[] bodyBytes = Encoding.UTF8.GetBytes(requestJson); + + HttpWebRequest request = WebRequest.Create(jwtTokenApiUrl) as HttpWebRequest; + request.Method = "POST"; + request.ContentType = "application/json"; + request.ContentLength = bodyBytes.Length; + + string jwtToken = string.Empty; + try + { + using (var dataStream = request.GetRequestStream()) + { + dataStream.Write(bodyBytes, 0, bodyBytes.Length); + dataStream.Close(); + } + + HttpWebResponse response = request.GetResponse() as HttpWebResponse; + Stream responseStream = response.GetResponseStream(); + + using (StreamReader reader = new StreamReader(responseStream)) + { + jwtToken = reader.ReadToEnd(); + } + Console.WriteLine($"GenerateToken End: {DateAndTime.Now} - Token :{jwtToken}"); + } + + catch (Exception ex) + { + Console.WriteLine($"Exception at GenerateToken :- {ex.StackTrace}"); + } + return jwtToken; + } + +} \ No newline at end of file diff --git a/Source/WebJobService/WebJobService.csproj b/Source/WebJobService/WebJobService.csproj index 4593667..261fee5 100644 --- a/Source/WebJobService/WebJobService.csproj +++ b/Source/WebJobService/WebJobService.csproj @@ -8,20 +8,40 @@ + + + + PreserveNewest + true + PreserveNewest + + + Always + true + PreserveNewest + Always true PreserveNewest + + + PreserveNewest + + + + + diff --git a/Source/WebJobService/appsettings.Development.json b/Source/WebJobService/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/Source/WebJobService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Source/WebJobService/appsettings.json b/Source/WebJobService/appsettings.json new file mode 100644 index 0000000..9dfa2a5 --- /dev/null +++ b/Source/WebJobService/appsettings.json @@ -0,0 +1,14 @@ +{ + + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "BaseApiUrl": "https://dealerselection-dev.bajajauto.com", + "ClientId": "5ef10013c846424cbe32aaffbdc2d408", + "ClientSecret": "4ca8d784dc9d4b8db9113d04770c0a7a", + "AZURE_LOGGING": "InstrumentationKey=2fead737-737a-4241-9e66-dfc5391583ba;IngestionEndpoint=https://centralindia-0.in.applicationinsights.azure.com/;LiveEndpoint=https://centralindia.livediagnostics.monitor.azure.com/" + +}