Browse Source

Changes for logging

Release
Hema Janoti 1 year ago
parent
commit
c1e949b333
  1. 4
      Source/DealerSelection.Api.Models/WebEngageEvent.cs
  2. 28
      Source/DealerSelection.Api/AssignDealerApi.cs
  3. 16
      Source/DealerSelection.Api/CCAvenueApi.cs
  4. 6
      Source/DealerSelection.Api/MulesoftApi.cs
  5. 16
      Source/DealerSelection.Api/YellowAIApi.cs
  6. 8
      Source/DealerSelection.Common/CommonBaseClass/ExceptionFilterBase.cs
  7. 31
      Source/DealerSelection.Common/CommonBaseClass/StartupBase.cs
  8. 4
      Source/DealerSelection.DependencyInjection/ApiRegistry.cs
  9. 5
      Source/DealerSelection.DependencyInjection/InfrastructureRegistry.cs
  10. 4
      Source/DealerSelection.Infrastructure/CustomerDetail/Repository.cs
  11. 2
      Source/DealerSelection.Infrastructure/Mulesoft/MulesoftCustomerInfoDto.cs
  12. 4
      Source/DealerSelection.WebApi/Controllers/BatchJobController.cs
  13. 8
      Source/DealerSelection.WebApi/appsettings.json
  14. 6
      Source/WebJobService/IRepository.cs
  15. 83
      Source/WebJobService/Program.cs
  16. 33
      Source/WebJobService/Repository.cs
  17. 7
      Source/WebJobService/SelectedData.cs
  18. 126
      Source/WebJobService/Service.cs
  19. 140
      Source/WebJobService/ServiceBackUp.cs
  20. 20
      Source/WebJobService/WebJobService.csproj
  21. 8
      Source/WebJobService/appsettings.Development.json
  22. 14
      Source/WebJobService/appsettings.json

4
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;

28
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<MulesoftApi> logger)
IHttpClientHandler clientHandler, IMemoryCache memoryCache, ILogger<AssignDealerApi> 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)
{

16
Source/DealerSelection.Api/CCAvenueApi.cs

@ -28,13 +28,8 @@ public class CCAvenueApi : ICCAvenueApi
}
public async Task<RefundApiResponse> 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<string> SendRequestToGateWay(string queryUrl, string urlParam)
private async Task<string> 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;

6
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}");
}

16
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<ModelDetail> 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;
}

8
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);
}
}

31
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<string>("ValidateAudience", true) == "True")
{
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
// bool validateAudience = false;
//if (Configuration.ConfigurationHelper.GetSetting<string>("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<string>(audiences),
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
}
}
private void SetupSwaggerOptions(WebApplicationBuilder builder)

4
Source/DealerSelection.DependencyInjection/ApiRegistry.cs

@ -40,5 +40,9 @@ public class ApiRegistry : ServiceRegistry
.Use<YellowAIApi>()
.Singleton();
For<IBatchJobApi>()
.Use<BatchJobApi>()
.Singleton();
}
}

5
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<string>().Is("BOOKING")
.Transient();
For<BatchJob.IRepository>()
.Use<BatchJob.Repository>()
.Ctor<string>().Is("BOOKING")
.Transient();
}
}

4
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}.");
}
}

2
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; }

4
Source/DealerSelection.WebApi/Controllers/BatchJobController.cs

@ -20,8 +20,8 @@ public class BatchJobController : ControllerBase
///
/// </summary>
/// <returns></returns>
[Authorize]
[HttpPost]
// [Authorize]
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[SwaggerOperation(Tags = new[] { "Process24HrOldRecords" })]
[Route("BatchJob")]

8
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"

6
Source/WebJobService/IRepository.cs

@ -0,0 +1,6 @@
namespace WebJobService;
public interface IRepository
{
Task<List<SelectedData>> GetDealerSelectionDataForJobAsync();
}

83
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<Program> logger;
private IServiceProvider serviceProvider;
static void Main()
{
var container=new Container(x=>
{
x.AddSingleton<IService, Service>();
x.AddSingleton<IHttpClientHandler, MyHttpClientHandler>();
x.For<IService>().Use<Service>().Ctor<string>("cxnName").Is("BOOKING").Singleton();
});
//IHttpClientHandler clientHandler = container.GetInstance<IHttpClientHandler>();
//ILogger logger = container.GetInstance<ILogger>();
IService service = container.GetInstance<IService>();
// IHttpClientHandler clientHandler = container.GetInstance<IHttpClientHandler>();
//ILogger logger = container.GetInstance<ILogger>();
var registry = new ServiceRegistry();
registry.AddSingleton<IHttpClientHandler, MyHttpClientHandler>();
registry.AddSingleton<IRepository, Repository>();
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<ApplicationInsightsLoggerProvider>("traces", LogLevel.Trace));
registry.For<IRepository>()
.Use<Repository>()
.Ctor<string>().Is("BOOKING")
.Transient();
registry.For<IService>().Use<Service>().Singleton();
//IServiceCollection services1 = new ServiceCollection();
//var CHANNEL1 = new ServerTelemetryChannel();
//services1.Configure<TelemetryConfiguration>((config) =>
//{
// config.TelemetryChannel = CHANNEL1;
//});
//services1.AddLogging(builder => { builder.AddApplicationInsights(aiUrl); });
//var provider=services1.BuildServiceProvider();
//var logger=provider.GetService<ILogger<Program>>();
//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<IService>();
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<ApplicationInsightsLoggerProvider>("traces", LogLevel.Trace);
}
}

33
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<Repository> logger) : base(cxnName)
{
_logger = logger;
}
public async Task<List<SelectedData>> GetDealerSelectionDataForJobAsync()
{
try
{
using SqlConnection cxn = await OpenCxnAsync();
IEnumerable<SelectedData> recordsToProcess = await cxn.QueryAsync<SelectedData>("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;
}
}
}

7
Source/WebJobService/SelectedData.cs

@ -0,0 +1,7 @@
namespace WebJobService;
public class SelectedData
{
public int BuId { get; set; }
public int RecordId { get; set; }
}

126
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<Service> 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<SelectedData> recordsToProcess = await cxn.QueryAsync<SelectedData>("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<bool>("IsRequestSuccessfull"))
//{
// var response = (JObject)resultObject.Value<JArray>("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; }
}
}

140
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<SelectedData> recordsToProcess = await cxn.QueryAsync<SelectedData>("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;
}
}

20
Source/WebJobService/WebJobService.csproj

@ -8,20 +8,40 @@
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.Development.json" />
<None Remove="appsettings.json" />
<None Remove="connectionString.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="connectionString.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Lamar" Version="12.1.0" />
<PackageReference Include="Lamar.Microsoft.DependencyInjection" Version="12.1.0" />
<PackageReference Include="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" Version="2.22.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.ApplicationInsights" Version="2.22.0" />
</ItemGroup>
<ItemGroup>

8
Source/WebJobService/appsettings.Development.json

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

14
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/"
}
Loading…
Cancel
Save