public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}"); try { JObject data = await req.Content.ReadAsAsync <JObject>(); log.Verbose($"received data :={data}", "JE.RMS.Services.AssignUserRoles"); List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@userID", Convert.ToInt32(data.SelectToken("UserID").ToString().TrimStart('{').TrimEnd('}')))); objprm.Add(new SqlParameter("@userName", data.SelectToken("UserName").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@firstName", data.SelectToken("FirstName").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@lastName", data.SelectToken("LastName").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@email", data.SelectToken("Email").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@createdBy", Convert.ToInt32(data.SelectToken("CreatedBy").ToString().TrimStart('{').TrimEnd('}')))); objprm.Add(new SqlParameter("@updatedBy", Convert.ToInt32(data.SelectToken("UpdatedBy").ToString().TrimStart('{').TrimEnd('}')))); objprm.Add(new SqlParameter("@isActive", data.SelectToken("IsActive").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@roleID", Convert.ToInt32(data.SelectToken("RoleID").ToString().TrimStart('{').TrimEnd('}')))); log.Verbose($"calling sp", "JE.RMS.Services.AssignUserRoles"); var obj = MSSQLConnection.ExecuteStoredProcedure <string>(Common.Constants.USPContstants.AssignUserRoles, objprm); log.Verbose($"received response:={obj}", "JE.RMS.Services.AssignUserRoles"); return(req.CreateResponse(HttpStatusCode.OK, obj)); } catch (Exception ex) { log.Error($"Exception ={ex}"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}"); try { JObject data = await req.Content.ReadAsAsync <JObject>(); log.Verbose($"received data :={data}", "JE.RMS.Services.GetJurisdictionList"); List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@countryIDs", data.SelectToken("countryID").ToString().TrimStart('{').TrimEnd('}'))); log.Verbose($"calling sp", "JE.RMS.Services.GetJurisdictionList"); List <Common.Model.Jurisdiction> obj = MSSQLConnection.ExecuteStoredProcedure <Common.Model.Jurisdiction>(Common.Constants.USPContstants.GetJurisdictionList, objprm); log.Verbose($"received response:={obj}", "JE.RMS.Services.GetJurisdictionList"); return(req.CreateResponse(HttpStatusCode.OK, obj)); } catch (Exception ex) { log.Error($"Exception ={ex}"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}", "JE.RMS.Services.DMEEUserToCustomer"); // Get request body try { using (HttpClient httpClient = new HttpClient()) { //Add Basic Authentication header httpClient.BaseAddress = new System.Uri(ConfigurationManager.AppSettings["EnergyEarthBaseUrl"].ToString()); var auth = Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["EEUserName"].ToString() + ":" + ConfigurationManager.AppSettings["EEPassword"].ToString()); httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(auth)); string GetUsersUrl = ConfigurationManager.AppSettings["GetUsersUrl"].ToString(); //Get Users from Energy Earth API var response = await httpClient.GetAsync(GetUsersUrl); //Convert Users from Energy earth to Customer List Model var customerList = JsonConvert.DeserializeObject <EECustomerList>(await response.Content.ReadAsStringAsync()); log.Verbose("Started migration of EE users to Customer Table", "JE.RMS.Services.DMEEUserToCustomer"); foreach (var customer in customerList.Users) { List <SqlParameter> CustomerParams = new List <SqlParameter>(); CustomerParams.Add(new SqlParameter("@Email", customer.Email)); CustomerParams.Add(new SqlParameter("@FirstName", customer.FirstName)); CustomerParams.Add(new SqlParameter("@LastName", customer.LastName)); CustomerParams.Add(new SqlParameter("@CompanyName", customer.CompanyName)); CustomerParams.Add(new SqlParameter("@UniqueID", customer.UserID)); CustomerParams.Add(new SqlParameter("@AccountAcceptanceDate", customer.AccountAcceptanceDate)); CustomerParams.Add(new SqlParameter("@StartingPointBalance", customer.StartingPointBalance)); CustomerParams.Add(new SqlParameter("@AvailablePointBalance", customer.AvailablePointBalance)); CustomerParams.Add(new SqlParameter("@AvailablePointBalanceDollars", customer.AvailablePointBalanceDollars)); CustomerParams.Add(new SqlParameter("@NumberofTransactions", customer.NumberofTransactions)); CustomerParams.Add(new SqlParameter("@AccountStatus", customer.AccountStatus)); CustomerParams.Add(new SqlParameter("@NextRewardDueDate", customer.NextRewardDueDate)); CustomerParams.Add(new SqlParameter("@ProgramName", customer.Program)); var RMSRewardID = MSSQLConnection.ExecuteStoredProcedure <string>(USPContstants.SaveCustomerFromEnergyEarth, CustomerParams); } log.Verbose("Completed migration of EE users to Customer Table", "JE.RMS.Services.DMEEUserToCustomer"); return(response); } } catch (Exception ex) { log.Error("Something went wrong while DMEEUserToCustomer", ex, "JE.RMS.Services.DMEEUserToCustomer"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public static async void Run(TimerInfo updateCustomerExtendedTimer, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# Timer trigger function processed a request", "JE.RMS.Services.ScheduledUpdateCustomerExtended"); try { log.Verbose($"Update Customer Extended started on : {DateTime.Now.ToString()}", "JE.RMS.Services.ScheduledUpdateCustomerExtended"); //Get All Customer Unique IDs List <string> ListCustomerUniqueIDs = MSSQLConnection.ExecuteStoredProcedure <string>(Common.Constants.USPContstants.GetAllCustomerUniqueID).ToList(); //Fetch Customers and update customer extended foreach (var uniqueId in ListCustomerUniqueIDs) { using (HttpClient httpClient = new HttpClient()) { //Add Basic Authentication header httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["GetUserFunctionUrl"].ToString()); string GetUserFunctionUrl = ConfigurationManager.AppSettings["GetUserFunctionCode"].ToString() + uniqueId; var response = await httpClient.GetAsync(GetUserFunctionUrl); if (response.IsSuccessStatusCode) { var responseUser = JsonConvert.DeserializeObject <CustomerExtendedList>(await response.Content.ReadAsStringAsync()); var userData = responseUser.Users.FirstOrDefault(); List <SqlParameter> CustomerExtendedParams = new List <SqlParameter>(); CustomerExtendedParams.Add(new SqlParameter("@CustomerID", string.Empty)); CustomerExtendedParams.Add(new SqlParameter("@UniqueID", uniqueId)); CustomerExtendedParams.Add(new SqlParameter("@AccountAcceptanceDate", userData.AccountAcceptanceDate)); CustomerExtendedParams.Add(new SqlParameter("@StartingPointBalance", userData.StartingPointBalance)); CustomerExtendedParams.Add(new SqlParameter("@AvailablePointBalance", userData.AvailablePointBalance)); CustomerExtendedParams.Add(new SqlParameter("@AvailablePointBalanceDollars", userData.AvailablePointBalanceDollars)); CustomerExtendedParams.Add(new SqlParameter("@NumberofTransactions", userData.NumberofTransactions)); CustomerExtendedParams.Add(new SqlParameter("@AccountStatus", userData.AccountStatus)); CustomerExtendedParams.Add(new SqlParameter("@NextRewardDueDate", userData.NextRewardDueDate)); var customerExtendedID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveCustomerExtended, CustomerExtendedParams); } else { errormessage.Add(response.Content.ReadAsStringAsync().Result); } } } log.Verbose($"Update Customer Extended completed on : {DateTime.Now.ToString()}", "JE.RMS.Services.ScheduledUpdateCustomerExtended"); } catch (Exception ex) { log.Error("Something went wrong while UpdateCustomerExtended", ex, "JE.RMS.Services.ScheduledUpdateCustomerExtended"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); } }
public static void Run(TimerInfo evaluateRewardsTrxTimer, ICollector <string> errormessage, TraceWriter log) { if (evaluateRewardsTrxTimer.IsPastDue) { log.Verbose("Timer is running late!", "JE.RMS.Services.GetRewardsTrxReceived"); } try { List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@RewardTrxStatus", "Received")); List <GetRewardsRequest> lstRewardsTrx = MSSQLConnection.ExecuteStoredProcedure <GetRewardsRequest>(USPContstants.GetRewardsTrx, objprm).ToList(); log.Verbose($"Get RewardsTrx Received:={lstRewardsTrx.Count}", "JE.RMS.Services.GetRewardsTrxReceived"); // Retrieve storage account from connection string CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["jermsstorage_STORAGE"].ToString()); // Create the queue client CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); // Retrieve a reference to a queue CloudQueue queue = queueClient.GetQueueReference("rewardfulfillmentrequestqueue"); // Create the queue if it doesn't already exist. queue.CreateIfNotExists(); foreach (GetRewardsRequest item in lstRewardsTrx) { var reqObject = JsonConvert.SerializeObject(item); log.Verbose($"Push message in a queue:= {reqObject}", "JE.RMS.Services.GetRewardsTrxReceived"); // Create a message and add it to the queue. CloudQueueMessage message = new CloudQueueMessage(reqObject.ToString()); queue.AddMessage(message); //Call stored procedure to Save RewardTrxChangeLog List <SqlParameter> RewardTrxChangeLogParams = new List <SqlParameter>(); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardsTrxID", item.RewardTrxID.ToString())); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardTrxStatus", "Received - Ready for fulfillment")); RewardTrxChangeLogParams.Add(new SqlParameter("@Comment", string.Empty)); RewardTrxChangeLogParams.Add(new SqlParameter("@RMSRewardID", null)); var RewardTrxChangeLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveRewardTrxChangeLog, RewardTrxChangeLogParams); } log.Verbose($"C# Timer trigger function executed at: {DateTime.Now}", "JE.RMS.Services.GetRewardsTrxReceived"); } catch (Exception ex) { log.Error($"Exception ={ex}", ex, "JE.RMS.Services.GetRewardsTrxReceived"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); } }
public static void Run(string errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request"); try { //JObject data = await req.Content.ReadAsAsync<JObject>(); List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@message", errormessage)); List <Common.Model.SystemLog> obj = MSSQLConnection.ExecuteStoredProcedure <Common.Model.SystemLog>(Common.Constants.USPContstants.SystemLogs, objprm); log.Verbose($"Save systemlog successfully."); } catch (System.Exception ex) { log.Error($"Exception ={ex}"); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}"); try { JObject data = await req.Content.ReadAsAsync <JObject>(); log.Verbose($"received data :={data}", "JE.RMS.Services.GetCustomers"); List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@pageNumber", Convert.ToInt32(data.SelectToken("pageNumber").ToString().TrimStart('{').TrimEnd('}')))); objprm.Add(new SqlParameter("@pageSize", Convert.ToInt32(data.SelectToken("pageSize").ToString().TrimStart('{').TrimEnd('}')))); objprm.Add(new SqlParameter("@searchText", data.SelectToken("searchText") == null?"" : data.SelectToken("searchText").ToString().TrimStart('{').TrimEnd('}'))); log.Verbose($"calling sp", "JE.RMS.Services.GetCustomers"); List <Common.Model.Customer> retobj = MSSQLConnection.ExecuteStoredProcedure <Common.Model.Customer>(Common.Constants.USPContstants.GetCustomers, objprm); Common.Model.CustomerList obj = new Common.Model.CustomerList(); if (retobj.Count > 0) { obj.TotalRows = retobj.FirstOrDefault().TotalRows; } else { obj.TotalRows = 0; } obj.Users = new List <Common.Model.Customer>(); obj.Users = retobj; log.Verbose($"received response:={obj}", "JE.RMS.Services.GetCustomers"); var CustomerResponse = req.CreateResponse(HttpStatusCode.OK); CustomerResponse.Content = new StringContent(JsonConvert.SerializeObject(obj), System.Text.Encoding.UTF8, "application/json"); return(CustomerResponse); //return req.CreateResponse(HttpStatusCode.OK, obj); } catch (Exception ex) { log.Error($"Exception ={ex}"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger GetRoles function processed a request. RequestUri={req.RequestUri}", "JE.RMS.Services.GetRoles"); try { var roles = MSSQLConnection.ExecuteStoredProcedure <Role>(Common.Constants.USPContstants.GetRoles); log.Verbose($"received response:={roles}", "JE.RMS.Services.GetRoles"); return(req.CreateResponse(HttpStatusCode.OK, roles)); } catch (Exception ex) { log.Error("Something went wrong while GetRoles", ex, "JE.RMS.Services.GetRoles"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public static void Run(FulfillmentResponse responsemessage, ICollector <string> errormessage, TraceWriter log) { try { log.Verbose($"C# trigger queue function processed a request. inputmessage={responsemessage}", "JE.RMS.Services.OnRewardsResponseRecieved"); #region Update Audit Fields //Update timestapm in Audit fields List <SqlParameter> AuditParam = new List <SqlParameter>(); AuditParam.Add(new SqlParameter("@RMSRewardID", responsemessage.RMSRewardID)); var RMSRewardID = MSSQLConnection.ExecuteStoredProcedure <string>(USPContstants.UpdateAuditFieldsInRewardsTrx, AuditParam); log.Verbose($"FulfillmentResponseTimestamp updated successfully. RMSRewardID={RMSRewardID[0]}", "JE.RMS.Services.OnRewardsResponseRecieved"); string RewardTrxStatus = "Fulfillment completed"; if (responsemessage.Status == "Fail") { RewardTrxStatus = "Error"; } List <SqlParameter> MessageLogParams = new List <SqlParameter>(); MessageLogParams.Add(new SqlParameter("@RMSRewardID", responsemessage.RMSRewardID)); MessageLogParams.Add(new SqlParameter("@MessageType", MessageType.RewardFulfillmentResponse.GetDescription())); MessageLogParams.Add(new SqlParameter("@IPAddress", responsemessage.ClientIP)); MessageLogParams.Add(new SqlParameter("@Message", JsonConvert.SerializeObject(responsemessage))); MessageLogParams.Add(new SqlParameter("@RewardsTrxID", null)); var ErrorMessageLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveMessageLog, MessageLogParams); log.Verbose($"MessageLog stored successfully. MessageLogID={ErrorMessageLogID[0]}", "JE.RMS.Services.ProcessFulfillmentForEnergyEarth"); ////Call stored procedure to Save RewardTrxChangeLog List <SqlParameter> RewardTrxChangeLogParams = new List <SqlParameter>(); RewardTrxChangeLogParams.Add(new SqlParameter("@RMSRewardID", responsemessage.RMSRewardID)); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardTrxStatus", RewardTrxStatus)); RewardTrxChangeLogParams.Add(new SqlParameter("@Comment", string.Empty)); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardsTrxID", null)); var RewardTrxChangeLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveRewardTrxChangeLog, RewardTrxChangeLogParams); log.Verbose($"RewardTrxChangeLog stored successfully. RewardTrxChangeLogID={RewardTrxChangeLogID[0]}", "JE.RMS.Services.OnRewardsResponseRecieved"); #endregion } catch (Exception ex) { log.Error($"Exception ={ex}", ex, "JE.RMS.Services.OnRewardsRequestRecieved"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}"); try { JObject data = await req.Content.ReadAsAsync <JObject>(); log.Verbose($"calling sp", "JE.RMS.Services.GetProgramCodes"); List <Common.Model.Program> obj = MSSQLConnection.ExecuteStoredProcedure <Common.Model.Program>(Common.Constants.USPContstants.GetPrograms); log.Verbose($"received response:={obj}", "JE.RMS.Services.GetProgramCodes"); return(req.CreateResponse(HttpStatusCode.OK, obj)); } catch (Exception ex) { log.Error($"Exception ={ex}"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}", "JE.RMS.Services.SubmitRewardsRequest"); try { // Get request body /*JObject data = await req.Content.ReadAsAsync<JObject>(); * string FulfillmentChannel = (string)data.SelectToken("FulfillmentChannel");*/ string ChannelCode = req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "ChannelCode", true) == 0).Value; if (!string.IsNullOrEmpty(ChannelCode)) { //Call stored procedure to Update RewardTrx List <SqlParameter> FulfillmentChanneParams = new List <SqlParameter>(); FulfillmentChanneParams.Add(new SqlParameter("@FulfillmentChannel", ChannelCode)); var FulfillmentChannelID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.GetFulfillmentChannelID, FulfillmentChanneParams); if (FulfillmentChannelID.Count == 0) { return(req.CreateResponse(HttpStatusCode.BadRequest, "Invalid channel code.")); } log.Verbose($"FulfillmentChannelID={FulfillmentChannelID[0]}", "JE.RMS.Services.GetRewardFulfillmentRequest"); RewardFulfillmentResponseList res = new RewardFulfillmentResponseList(); RewardFulfillmentResponseList resp = GetMessagesFromSubscription(FulfillmentChannelID[0], res, log); return(req.CreateResponse(HttpStatusCode.OK, resp)); } else { return(req.CreateResponse(HttpStatusCode.BadRequest, "Required ChannelCode as request parameters.")); } } catch (Exception ex) { log.Error($"Exception ={ex}", ex, "JE.RMS.Services.SubmitRewardsRequest"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}"); try { // Get request body JObject data = await req.Content.ReadAsAsync <JObject>(); log.Verbose($"received data :={data}", "JE.RMS.Services.SearchRewardsTrx"); List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@startDate", data.SelectToken("startDate").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@endDate", data.SelectToken("endDate").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@ssUniqueID", data.SelectToken("ssUniqueID").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@email", data.SelectToken("email").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@sourceSystem", data.SelectToken("sourceSystem").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@countryids", data.SelectToken("countryids").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@jurisdiction", data.SelectToken("jurisdiction").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@transType", data.SelectToken("transType").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@transStatus", data.SelectToken("transStatus").ToString().TrimStart('{').TrimEnd('}'))); objprm.Add(new SqlParameter("@pageNumber", Convert.ToInt32(data.SelectToken("pageNumber").ToString().TrimStart('{').TrimEnd('}')))); objprm.Add(new SqlParameter("@pageSize", Convert.ToInt32(data.SelectToken("pageSize").ToString().TrimStart('{').TrimEnd('}')))); log.Verbose($"calling sp", "JE.RMS.Services.SearchRewardsTrx"); var obj = MSSQLConnection.ExecuteStoredProcedure <Common.Model.SearchRewardTrx>(Common.Constants.USPContstants.SearchRewardsTrx, objprm); log.Verbose($"received response:={obj}", "JE.RMS.Services.SearchRewardsTrx"); return(req.CreateResponse(HttpStatusCode.OK, obj)); } catch (Exception ex) { log.Error($"Exception ={ex}"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}"); try { // Get request body string reqString = await req.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject <SearchRewardTrxRequest>(reqString); log.Verbose($"received data :={data}", "JE.RMS.Services.SearchRewardTransactions"); string errmsg = ""; bool flgvalidate = true; if (data.SourceSystemUniqueID != null && data.SourceSystemUniqueIDTypes != null && flgvalidate) { if (string.IsNullOrEmpty(data.SourceSystemUniqueID) && string.IsNullOrEmpty(data.SourceSystemUniqueIDTypes)) { flgvalidate = true; } else { if (data.SourceSystemUniqueID.ToString() != "") { if (data.SourceSystemUniqueIDTypes.ToString() != "") { flgvalidate = true; } else { flgvalidate = false; errmsg = "Validation Failed : SourceSystemUniqueID & sourceSystemUniqueIDTypes either none or both are required."; } } if (data.SourceSystemUniqueIDTypes.ToString() != "") { if (data.SourceSystemUniqueID.ToString() != "") { flgvalidate = true; } else { flgvalidate = false; errmsg = "Validation Failed : SourceSystemUniqueID & sourceSystemUniqueIDTypes either none or both are required."; } } } } else if (data.SourceSystemUniqueID != null && flgvalidate) { if (data.SourceSystemUniqueIDTypes != null) { } else { if (data.SourceSystemUniqueID != "") { flgvalidate = false; errmsg = "Validation Failed : SourceSystemUniqueID & sourceSystemUniqueIDTypes either none or both are required."; } } } else if (data.SourceSystemUniqueIDTypes != null && flgvalidate) { if (data.SourceSystemUniqueID != null) { } else { if (data.SourceSystemUniqueIDTypes != "") { flgvalidate = false; errmsg = "Validation Failed : SourceSystemUniqueID & sourceSystemUniqueIDTypes either none or both are required."; } } } if (data.SourceSystemIDs != null && flgvalidate) { string isvalidids = data.SourceSystemIDs.ToString(); if (isvalidids != "") { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^(\d+(,\d+)*)?$"); System.Text.RegularExpressions.Match match = regex.Match(isvalidids); if (!match.Success) { flgvalidate = false; errmsg = "Validation Failed : all comma separated values for sourceSystemIDs must be numeric."; } } } if (data.CountryIDs != null && flgvalidate) { string isvalidids = data.CountryIDs.ToString(); if (isvalidids != "") { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^(\d+(,\d+)*)?$"); System.Text.RegularExpressions.Match match = regex.Match(isvalidids); if (!match.Success) { flgvalidate = false; errmsg = "Validation Failed : all comma separated values for countryIDs must be numeric."; } } } if (data.JurisdictionIDs != null && flgvalidate) { string isvalidids = data.JurisdictionIDs.ToString(); if (isvalidids != "") { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^(\d+(,\d+)*)?$"); System.Text.RegularExpressions.Match match = regex.Match(isvalidids); if (!match.Success) { flgvalidate = false; errmsg = "Validation Failed : all comma separated values for jurisdictionIDs must be numeric."; } } } if (data.TransactionTypeIDs != null && flgvalidate) { string isvalidids = data.TransactionTypeIDs.ToString(); if (isvalidids != "") { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^(\d+(,\d+)*)?$"); System.Text.RegularExpressions.Match match = regex.Match(isvalidids); if (!match.Success) { flgvalidate = false; errmsg = "Validation Failed : all comma separated values for transactionTypeIDs must be numeric."; } } } if (data.TransactionStatusIDs != null && flgvalidate) { string isvalidids = data.TransactionStatusIDs.ToString(); if (isvalidids != "") { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^(\d+(,\d+)*)?$"); System.Text.RegularExpressions.Match match = regex.Match(isvalidids); if (!match.Success) { flgvalidate = false; errmsg = "Validation Failed : all comma separated values for transactionStatusIDs must be numeric."; } } } if (flgvalidate) { List <SqlParameter> objprmlookup = new List <SqlParameter>(); objprmlookup.Add(new SqlParameter("@sourceSystemNames", data.SourceSystemNames == null ? "" : data.SourceSystemNames.ToString())); objprmlookup.Add(new SqlParameter("@transactionTypes", data.TransactionTypes == null ? "" : data.TransactionTypes.ToString())); objprmlookup.Add(new SqlParameter("@transactionStatuses", data.TransactionStatuses == null ? "" : data.TransactionStatuses.ToString())); var objvalidate = MSSQLConnection.ExecuteStoredProcedure <string>(Common.Constants.USPContstants.CheckLookupValidation, objprmlookup); var Message = ""; if (objvalidate.Count == 1) { if (!objvalidate[0].ToString().ToLower().Equals("all validation passed")) { Message = objvalidate[0].ToString(); return(req.CreateResponse(HttpStatusCode.BadRequest, new { Message })); } } else { foreach (var temp in objvalidate) { Message += temp.ToString(); } return(req.CreateResponse(HttpStatusCode.BadRequest, new { Message })); } List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@startDate", data.StartDate == null ? "" : data.StartDate.ToString())); objprm.Add(new SqlParameter("@endDate", data.EndDate == null ? "" : data.EndDate.ToString())); objprm.Add(new SqlParameter("@sourceSystemUniqueID", data.SourceSystemUniqueID == null ? "" : data.SourceSystemUniqueID.ToString())); objprm.Add(new SqlParameter("@email", data.Email == null ? "" : data.Email.ToString())); objprm.Add(new SqlParameter("@sourceSystemIDs", data.SourceSystemIDs == null ? "" : data.SourceSystemIDs.ToString())); objprm.Add(new SqlParameter("@countryIDs", data.CountryIDs == null ? "" : data.CountryIDs.ToString())); objprm.Add(new SqlParameter("@jurisdictionIDs", data.JurisdictionIDs == null ? "" : data.JurisdictionIDs.ToString())); objprm.Add(new SqlParameter("@transactionTypeIDs", data.TransactionTypeIDs == null ? "" : data.TransactionTypeIDs.ToString())); objprm.Add(new SqlParameter("@transactionStatusIDs", data.TransactionStatusIDs == null ? "" : data.TransactionStatusIDs.ToString())); objprm.Add(new SqlParameter("@sourceSystemNames", data.SourceSystemNames == null ? "" : data.SourceSystemNames.ToString())); objprm.Add(new SqlParameter("@transactionTypes", data.TransactionTypes == null ? "" : data.TransactionTypes.ToString())); objprm.Add(new SqlParameter("@transactionStatuses", data.TransactionStatuses == null ? "" : data.TransactionStatuses.ToString())); objprm.Add(new SqlParameter("@sourceSystemUniqueIDTypes", data.SourceSystemUniqueIDTypes == null ? "" : data.SourceSystemUniqueIDTypes.ToString())); objprm.Add(new SqlParameter("@pageNumber", data.PageNumber == null ? 1 : Convert.ToInt32(data.PageNumber.ToString()))); objprm.Add(new SqlParameter("@pageSize", data.PageSize == null ? 50 : Convert.ToInt32(data.PageSize.ToString()))); log.Verbose($"calling sp", "JE.RMS.Services.SearchRewardTransactions"); List <Common.Model.RewardTrx> retobj = MSSQLConnection.ExecuteStoredProcedure <Common.Model.RewardTrx>(Common.Constants.USPContstants.SearchRewardsTrx, objprm); Common.Model.SearchRewardTrx obj = new Common.Model.SearchRewardTrx(); if (retobj.Count > 0) { //JsonConvert.DeserializeObject obj.TotalRows = retobj.FirstOrDefault().TotalRows; obj.RewardTransactions = new List <Common.Model.RewardTrx>(); obj.RewardTransactions = retobj; //var rewardobjJSON= JsonConvert.SerializeObject(obj); var RewardResponse = req.CreateResponse(HttpStatusCode.OK); RewardResponse.Content = new StringContent(JsonConvert.SerializeObject(obj), System.Text.Encoding.UTF8, "application/json"); return(RewardResponse); } else { //JsonConvert.DeserializeObject obj.TotalRows = 0; obj.RewardTransactions = new List <Common.Model.RewardTrx>(); obj.RewardTransactions = retobj; //var rewardobjJSON= JsonConvert.SerializeObject(obj); var RewardResponse = req.CreateResponse(HttpStatusCode.OK); RewardResponse.Content = new StringContent(JsonConvert.SerializeObject(obj), System.Text.Encoding.UTF8, "application/json"); return(RewardResponse); } //return req.CreateResponse(HttpStatusCode.OK, rewardobjJSON); } else { log.Verbose($"validation failed", "JE.RMS.Services.SearchCustomers"); return(req.CreateErrorResponse(HttpStatusCode.BadRequest, errmsg)); } } catch (Exception ex) { log.Error($"Exception ={ex}"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
private static SaveRewardResponse SaveRewardTrx(RewardsRequest item, ICollector <string> errormessage, TraceWriter log) { SaveRewardResponse saveRewardResponse = new SaveRewardResponse(); saveRewardResponse.RewardTrxID = 0; try { using (var connection = MSSQLConnection.CreateConnection()) { connection.Open(); // Call stored procedure to Save Customer Customer Customers = new Customer(); GetRewardsRequest SaveRewardTrx = new GetRewardsRequest(); if (item.IsValid) { RewardTrxStatus = RewardTrxStatusEnum.ReadyForFulfillmentImmediate.GetDescription(); } if (string.IsNullOrEmpty(item.Customer.SourceSystemUniqueIDType)) { RewardTrxStatus = "Validation error"; item.ValidationMessage += " Source system is not supported."; } if (item.Reward != null && !string.IsNullOrEmpty(item.Reward.ProductValue) && !Decimal.TryParse(item.Reward.ProductValue, out ProductValue)) { RewardTrxStatus = "Validation error"; item.ValidationMessage += " Required numeric value for ProductValue field."; } if (!string.IsNullOrEmpty(item.Customer.SourceSystemID)) { int.TryParse(item.Customer.SourceSystemID, out SourceSystemID); if (SourceSystemID <= 0) { item.IsValid = false; RewardTrxStatus = RewardTrxStatusEnum.ValidationError.GetDescription(); item.ValidationMessage += "Validation Failed : SourceSystemID must be numeric;"; } } if (SourceSystemID > 0 || !string.IsNullOrEmpty(item.Customer.SourceSystemName)) { List <SqlParameter> SSIDprm = new List <SqlParameter>(); SSIDprm.Add(new SqlParameter("@SourceSystemShortName", item.Customer.SourceSystemName)); SSIDprm.Add(new SqlParameter("@SourceSystemID", item.Customer.SourceSystemID)); SourceSystemID = MSSQLConnection.ExecuteStoredProcedure <int>(USPContstants.GetSourceSystemID, SSIDprm).FirstOrDefault(); if (SourceSystemID == 0) { item.IsValid = false; RewardTrxStatus = RewardTrxStatusEnum.ValidationError.GetDescription(); item.ValidationMessage += "Validation Failed : Please provide valid SourceSystemID or SourceSystemName (if both are provided they must match);"; } } else if (item.IsOrder == false) { item.IsValid = false; RewardTrxStatus = RewardTrxStatusEnum.ValidationError.GetDescription(); item.ValidationMessage += "Validation Failed : Required value for at least one of 'SourceSystemID' or 'SourceSystemName'. Path: SourceSystemID or SourceSystemName;"; } item.ValidationMessage = item.ValidationMessage.TrimStart(';'); DynamicParameters CustomerTrxParams = new DynamicParameters(); CustomerTrxParams.Add("@SourceSystemID", SourceSystemID.ToString()); CustomerTrxParams.Add("@SourceSystemUniqueID", item.Customer.SourceSystemUniqueID); CustomerTrxParams.Add("@SourceSystemUniqueIDType", item.Customer.SourceSystemUniqueIDType); CustomerTrxParams.Add("@MasterID", item.Customer.MasterID); CustomerTrxParams.Add("@Email", item.Customer.Email); CustomerTrxParams.Add("@FirstName", item.Customer.FirstName); CustomerTrxParams.Add("@LastName", item.Customer.LastName); CustomerTrxParams.Add("@CompanyName", item.Customer.CompanyName); CustomerTrxParams.Add("@AddressLine1", item.Customer.AddressLine1); CustomerTrxParams.Add("@AddressLine2", item.Customer.AddressLine2); CustomerTrxParams.Add("@City", item.Customer.City); CustomerTrxParams.Add("@StateProvince", item.Customer.StateProvince); CustomerTrxParams.Add("@ZipPostalCode", item.Customer.ZipPostalCode); CustomerTrxParams.Add("@Phone1", item.Customer.Phone1); CustomerTrxParams.Add("@Product", item.Customer.Product); CustomerTrxParams.Add("@Language", item.Customer.Language); CustomerTrxParams.Add("@RequestID", item.RequestId); CustomerTrxParams.Add("@TransactionType", item.TransactionType); CustomerTrxParams.Add("@ProductCode", (item.Reward != null && !string.IsNullOrEmpty(item.Reward.ProductCode)) ? item.Reward.ProductCode : string.Empty); CustomerTrxParams.Add("@ProductValue", ProductValue); CustomerTrxParams.Add("@ProgramName", (item.Reward != null && !string.IsNullOrEmpty(item.Reward.ProgramName)) ? item.Reward.ProgramName : string.Empty); if (item.Reward != null) { CustomerTrxParams.Add("@EffectiveDate", item.Reward.EffectiveDate); } else { CustomerTrxParams.Add("@EffectiveDate", string.Empty); } CustomerTrxParams.Add("@SourceIP", item.SourceIP); CustomerTrxParams.Add("@RewardsRequestReceiveTimestamp", item.RewardsRequestReceiveTimestamp); CustomerTrxParams.Add("@RMSRewardID", item.RMSRewardID); var additionalDataJSON = JsonConvert.SerializeObject(item.AdditionalData); CustomerTrxParams.Add("@AdditionalData", additionalDataJSON); CustomerTrxParams.Add("@RewardType", (!string.IsNullOrEmpty(item.Reward.RewardType)) ? item.Reward.RewardType : string.Empty); CustomerTrxParams.Add("@MessageType", MessageType.RewardRequest.GetDescription()); CustomerTrxParams.Add("@Message", Message); CustomerTrxParams.Add("@RewardTrxStatus", RewardTrxStatus); CustomerTrxParams.Add("@Comment", item.ValidationMessage); SaveRewardTrx = connection.Query <GetRewardsRequest>(Common.Constants.USPContstants.SaveRewards, CustomerTrxParams, null, true, null, CommandType.StoredProcedure).FirstOrDefault(); log.Verbose($"SaveRewardTrx sucessfully ={SaveRewardTrx.RewardTrxID}", "JE.RMS.Services.SaveRewardsTrx"); saveRewardResponse.Status = SaveRewardTrx.RewardTrxStatus; saveRewardResponse.RewardTrxID = SaveRewardTrx.RewardTrxID; saveRewardResponse.IsValid = item.IsValid; //Hack : SP returns validation message in Reward type field (this is internal) saveRewardResponse.ValidationMessage = item.ValidationMessage + SaveRewardTrx.RewardType; } return(saveRewardResponse); } catch (Exception ex) { log.Error($"Exception={ex}", ex, "JE.RMS.Services.ApplyReward"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); saveRewardResponse.IsValid = false; saveRewardResponse.ValidationMessage = ex.Message; saveRewardResponse.Status = RewardTrxStatusEnum.Error.GetDescription(); return(saveRewardResponse); } }
private static EvaluateRuleResponse EvaluateRewardsTrxMessage(string rewardfulfillmentrequest, TraceWriter log) { //Get FulFillmentRule from DB var FulfillmentRulesList = MSSQLConnection.ExecuteStoredProcedure <FulfillmentRules>(USPContstants.GetFulfillmentRules, null); var lstRewardsTrx = JsonConvert.DeserializeObject <GetRewardsRequest[]>(rewardfulfillmentrequest); foreach (GetRewardsRequest item in lstRewardsTrx) { List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@Email", item.Email)); objprm.Add(new SqlParameter("@ProductID", item.ProductID)); objprm.Add(new SqlParameter("@ProgramID", item.ProgramID)); objprm.Add(new SqlParameter("@RewardTrxID", item.RewardTrxID)); var FulfillmentDataPerCust = MSSQLConnection.ExecuteStoredProcedure <FulfillmentRules>(USPContstants.GetFulFillmentDataPerCustomer, objprm); item.RewardTrxStatus = string.Empty; string Comment = string.Empty; if (item.TransactionType == TransactionTypeEnum.ProgramUpdateSourceSystem.GetDescription() || item.TransactionType == TransactionTypeEnum.Qualify.GetDescription() || item.TransactionType == TransactionTypeEnum.Reactivate.GetDescription() || item.TransactionType == TransactionTypeEnum.Terminate.GetDescription()) { objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@FulfillmentChannel", FulfillmentChannel.EnergyEarth.GetDescription())); var FulfillmentChannelID = MSSQLConnection.ExecuteStoredProcedure <int>(USPContstants.GetFulfillmentChannelID, objprm).FirstOrDefault(); item.FulfillmentChannelID = FulfillmentChannelID; item.RewardTrxStatus = "Ready for fulfillment"; } else { foreach (FulfillmentRules fulfillmentRule in FulfillmentRulesList) { if (fulfillmentRule.ProductID == item.ProductID && fulfillmentRule.ProgramID == item.ProgramID) { item.RewardTrxStatus = "Ready for fulfillment"; if (item.IsFulfillImmediate == true) { item.RewardTrxStatus = RewardTrxStatusEnum.ReadyForFulfillmentImmediate.GetDescription(); } if (fulfillmentRule.RequireApproval) { item.RewardTrxStatus = "Waiting for approval"; Comment = "Reward Trx is Waiting for approval."; } else if (fulfillmentRule.MaxOccurrencePerYear > 0 && FulfillmentDataPerCust[0].MaxOccurrencePerYear >= fulfillmentRule.MaxOccurrencePerYear) { item.RewardTrxStatus = "Rejected - System"; Comment = "Max occurrence per year is exceeds."; } else if (fulfillmentRule.MaxOccurrencePerCustomer > 0 && FulfillmentDataPerCust[0].MaxOccurrencePerCustomer >= fulfillmentRule.MaxOccurrencePerCustomer) { item.RewardTrxStatus = "Rejected - System"; Comment = "Max occurrence per customer is exceeds."; } else if (fulfillmentRule.MaxRewardValue > 0 && item.ProductValue > fulfillmentRule.MaxRewardValue) { item.RewardTrxStatus = "Rejected - System"; Comment = "Max reward value is exceeds."; } else if (fulfillmentRule.MaxCumulativeRewardValuePerYear > 0 && FulfillmentDataPerCust[0].MaxCumulativeRewardValuePerYear + item.ProductValue > fulfillmentRule.MaxCumulativeRewardValuePerYear) { item.RewardTrxStatus = "Rejected - System"; Comment = "Max cumulative reward value per year is exceeds."; } if (fulfillmentRule.FulfillmentChannelID > 0) { item.FulfillmentChannelID = fulfillmentRule.FulfillmentChannelID; } else { item.RewardTrxStatus = string.Empty; } break; } } } if (item.RewardTrxStatus != string.Empty) { //Call stored procedure to Update RewardTrx List <SqlParameter> RewardTrxParams = new List <SqlParameter>(); RewardTrxParams.Add(new SqlParameter("@RewardTrxID", item.RewardTrxID)); RewardTrxParams.Add(new SqlParameter("@FulfillmentChannelID", item.FulfillmentChannelID)); log.Verbose($"item.FulfillmentChannelID={item.FulfillmentChannelID}", "JE.RMS.Services.EvaluateRewardsTrx"); var RewardTrxID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.UpdateFulfillmentChannelIDInRewardsTrx, RewardTrxParams); log.Verbose($"RewardTrx updated successfully. RewardTrID={RewardTrxID[0]}", "JE.RMS.Services.EvaluateRewardsTrx"); //Call stored procedure to Save RewardTrxChangeLog List <SqlParameter> RewardTrxChangeLogParams = new List <SqlParameter>(); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardsTrxID", item.RewardTrxID.ToString())); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardTrxStatus", item.RewardTrxStatus)); RewardTrxChangeLogParams.Add(new SqlParameter("@Comment", Comment)); RewardTrxChangeLogParams.Add(new SqlParameter("@RMSRewardID", null)); var RewardTrxChangeLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveRewardTrxChangeLog, RewardTrxChangeLogParams); log.Verbose($"RewardTrxChangeLog stored successfully. RewardTrxChangeLogID={RewardTrxChangeLogID[0]}", "JE.RMS.Services.EvaluateRewardsTrx"); } else { item.RewardTrxStatus = "Validation Error"; Comment = $"No fulfillment rule found for Program Code: { item.ProgramName } and Product Code: { item.ProductCode}. "; //Call stored procedure to Save RewardTrxChangeLog List <SqlParameter> RewardTrxChangeLogParams = new List <SqlParameter>(); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardsTrxID", item.RewardTrxID.ToString())); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardTrxStatus", RewardTrxStatusEnum.ValidationError.GetDescription())); RewardTrxChangeLogParams.Add(new SqlParameter("@Comment", Comment)); RewardTrxChangeLogParams.Add(new SqlParameter("@RMSRewardID", null)); var RewardTrxChangeLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveRewardTrxChangeLog, RewardTrxChangeLogParams); log.Verbose($"RewardTrxChangeLog stored successfully. RewardTrxChangeLogID={RewardTrxChangeLogID[0]}", "JE.RMS.Services.EvaluateRewardsTrx"); } Response.Comment = Comment; Response.RequestID = item.RequestId; Response.Status = item.RewardTrxStatus; } return(Response); }
private static string ProcessRequest(List <GetRewardsRequest> lstRewardsTrx, ICollector <string> errormessage, TraceWriter log) { try { RewardFulfillmentRequest RewardsRequestObj = new RewardFulfillmentRequest(); foreach (GetRewardsRequest item in lstRewardsTrx) { RewardFulfillmentRequestList rewardFulfillmentRequestList = new RewardFulfillmentRequestList(); rewardFulfillmentRequestList.RewardFulfillmentRequest = new RewardFulfillmentRequest(); RewardsRequestObj.RequestId = item.RequestId; RewardsRequestObj.TransactionType = item.TransactionType; RewardsRequestObj.RMSRewardID = item.RMSRewardID; RewardsRequestObj.Reward = new Reward(); RewardsRequestObj.Reward.ProductCode = item.ProductCode; RewardsRequestObj.Reward.ProductValue = item.ProductValue.ToString(); RewardsRequestObj.Reward.ProgramName = item.ProgramName; RewardsRequestObj.Reward.EffectiveDate = item.EffectiveDate; RewardsRequestObj.Reward.RewardType = item.RewardType; RewardsRequestObj.Customer = new CustomerJSON(); RewardsRequestObj.Customer.CustomerID = item.CustomerID; RewardsRequestObj.Customer.SourceSystemID = item.DBSourceSystemID.ToString(); RewardsRequestObj.Customer.SourceSystemName = item.SourceSystemShortName; RewardsRequestObj.Customer.SourceSystemUniqueID = item.SourceSystemUniqueID; RewardsRequestObj.Customer.SourceSystemUniqueIDType = item.SourceSystemUniqueIDType; RewardsRequestObj.Customer.MasterID = item.MasterID; RewardsRequestObj.Customer.Email = item.Email; RewardsRequestObj.Customer.FirstName = item.FirstName; RewardsRequestObj.Customer.LastName = item.LastName; RewardsRequestObj.Customer.CompanyName = item.CompanyName; RewardsRequestObj.Customer.AddressLine1 = item.AddressLine1; RewardsRequestObj.Customer.AddressLine2 = item.AddressLine2; RewardsRequestObj.Customer.City = item.City; RewardsRequestObj.Customer.StateProvince = item.StateProvince; RewardsRequestObj.Customer.ZipPostalCode = item.ZipPostalCode; RewardsRequestObj.Customer.Phone1 = item.Phone1; RewardsRequestObj.Customer.Product = item.Product; RewardsRequestObj.Customer.Language = item.LanguageCode; RewardsRequestObj.AdditionalData = JsonConvert.DeserializeObject <AdditionalData[]>(item.AdditionalData); rewardFulfillmentRequestList.RewardFulfillmentRequest = RewardsRequestObj; var reqObject = JsonConvert.SerializeObject(rewardFulfillmentRequestList); //Call stored procedure to Update RewardTrx List <SqlParameter> RewardTrxParams = new List <SqlParameter>(); RewardTrxParams.Add(new SqlParameter("@RewardTrxID", item.RewardTrxID)); var RewardTrxID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.UpdateFulfillmentRequestTimestamp, RewardTrxParams); log.Verbose($"RewardTrx updated successfully. RewardTrID={RewardTrxID[0]}", "JE.RMS.Services.ApplyReward"); //Call stored procedure to Save MessageLog List <SqlParameter> MessageLogParams = new List <SqlParameter>(); MessageLogParams.Add(new SqlParameter("@RewardsTrxID", item.RewardTrxID)); MessageLogParams.Add(new SqlParameter("@MessageType", MessageType.RewardFulfillmentRequest.GetDescription())); MessageLogParams.Add(new SqlParameter("@IPAddress", "")); MessageLogParams.Add(new SqlParameter("@Message", reqObject)); MessageLogParams.Add(new SqlParameter("@RMSRewardID", null)); var MessageLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveMessageLog, MessageLogParams); log.Verbose($"MessageLog stored successfully. MessageLogID={MessageLogID[0]}", "JE.RMS.Services.ApplyReward"); //Call stored procedure to Save RewardTrxChangeLog List <SqlParameter> RewardTrxChangeLogParams = new List <SqlParameter>(); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardsTrxID", item.RewardTrxID.ToString())); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardTrxStatus", "Sent for fulfillment")); RewardTrxChangeLogParams.Add(new SqlParameter("@Comment", string.Empty)); RewardTrxChangeLogParams.Add(new SqlParameter("@RMSRewardID", null)); var RewardTrxChangeLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveRewardTrxChangeLog, RewardTrxChangeLogParams); log.Verbose($"RewardTrxChangeLog stored successfully. RewardTrxChangeLogID={RewardTrxChangeLogID[0]}", "JE.RMS.Services.ApplyReward"); if (item.FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.EnergyEarth) { using (HttpClient httpClient = new HttpClient()) { //Add Basic Authentication header httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["ProcessFulfillmentUrl"].ToString()); var response = httpClient.PostAsJsonAsync(string.Empty, rewardFulfillmentRequestList).Result; if (response.IsSuccessStatusCode) { log.Verbose($"Success : Process fulfillment for EE", "JE.RMS.Services.ApplyReward"); } else { log.Error($"Error : Process fulfillment for EE", null, "JE.RMS.Services.ApplyReward"); return(response.Content.ReadAsStringAsync().Result); } } } } return("Success"); } catch (Exception ex) { log.Error($"Exception={ex}", ex, "JE.RMS.Services.ApplyReward"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return("Fail"); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}", "JE.RMS.Services.SubmitRewardFulfillmentResponse"); try { string clientIP = ((HttpContextWrapper)req.Properties["MS_HttpContext"]).Request.UserHostAddress; log.Verbose($"clientIP:={clientIP}", "JE.RMS.Services.SubmitRewardFulfillmentResponse"); string Message = await req.Content.ReadAsStringAsync(); var RewardFulfillmentResponse = JsonConvert.DeserializeObject <FulfillmentResponse>(Message); if (RewardFulfillmentResponse == null) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Null Request object.")); } JSchema schema = JSchema.Parse(RewardRequestSchema.FulfillmentResponseSchema); IList <string> messages; JObject inputJSON = JObject.Parse(Message); bool valid = inputJSON.IsValid(schema, out messages); log.Info($"Valid ={valid}"); log.Info($"Validation message ={messages}"); var messageJSON = ""; if (messages.Count > 0) { messageJSON = JsonConvert.SerializeObject(messages); } List <SqlParameter> validateParam = new List <SqlParameter>(); validateParam.Add(new SqlParameter("@RMSRewardID", RewardFulfillmentResponse.RMSRewardID)); var RMSRewardIDCount = MSSQLConnection.ExecuteStoredProcedure <int>(USPContstants.ValidateRMSRewardID, validateParam).FirstOrDefault(); if (RMSRewardIDCount == 0) { messageJSON = messageJSON + RewardFulfillmentResponse.RMSRewardID + " does not exist or fulfillment already processed. Path: RMSRewardID;"; } if (!string.IsNullOrEmpty(messageJSON)) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, messageJSON)); } var connectionString = ConfigurationManager.AppSettings["MyServiceBusReader"].ToString(); var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); #region Create Subscrptions for the first time //// Create a "AllFulfillmentResponseSubscription" for all subscription. if (!namespaceManager.SubscriptionExists("fulfillmentresponse", "AllFulfillmentResponseSubscription")) { namespaceManager.CreateSubscription("fulfillmentresponse", "AllFulfillmentResponseSubscription"); } #endregion RewardFulfillmentResponse.ClientIP = clientIP; var FulfillmentResponseTopicClient = TopicClient.CreateFromConnectionString(connectionString, "fulfillmentresponse"); BrokeredMessage message = new BrokeredMessage(RewardFulfillmentResponse); //Send message to Topic FulfillmentResponseTopicClient.Send(message); #region Update Audit Fields //Update timestapm in Audit fields List <SqlParameter> AuditParam = new List <SqlParameter>(); AuditParam.Add(new SqlParameter("@RMSRewardID", RewardFulfillmentResponse.RMSRewardID)); var RMSRewardID = MSSQLConnection.ExecuteStoredProcedure <string>(USPContstants.UpdateAuditFieldsInRewardsTrx, AuditParam); log.Verbose($"FulfillmentResponseTimestamp updated successfully. RMSRewardID={RMSRewardID[0]}", "JE.RMS.Services.SubmitRewardFulfillmentResponse"); #endregion var Status = "Success"; return(req.CreateResponse(HttpStatusCode.OK, new { Status }, JsonMediaTypeFormatter.DefaultMediaType)); } catch (Exception ex) { log.Error($"Exception ={ex}", ex, "JE.RMS.Services.SubmitRewardFulfillmentResponse"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, "Fail", ex)); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}", "JE.RMS.Services.ApplyReward"); try { //To obtain client IP Address clientIP = ((HttpContextWrapper)req.Properties["MS_HttpContext"]).Request.UserHostAddress; log.Verbose($"clientIP:={clientIP}", "JE.RMS.Services.ApplyReward"); //Read request object as string string reqString = await req.Content.ReadAsStringAsync(); reqMessage = JObject.Parse(reqString); var RewardCount = reqMessage["RewardsRequest"].Count(); if (reqMessage["ChannelCode"] != null) { ChannelCode = reqMessage["ChannelCode"].ToString(); if (string.IsNullOrEmpty(ChannelCode) || ChannelCode != FulfillmentChannel.EnergyEarth.GetDescription()) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Only Energy Earth transactions are allowed. You provided ChannelCode:" + ChannelCode)); } } else { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Required value for ChannelCode. Path: ChannelCode;")); } if (RewardCount == 1) { foreach (JObject x in reqMessage["RewardsRequest"]) { //Added Audit fields in request object x.Add("SourceIP", clientIP); x.Add("RMSRewardID", Guid.NewGuid().ToString()); x.Add("RewardsRequestReceiveTimestamp", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); JObject inputJSON = JObject.Parse(JsonConvert.SerializeObject(x)); JSchema objectschema = new JSchema(); objectschema = JSchema.Parse(Common.Constants.RewardRequestSchema.RequestSchema); if (inputJSON["TransactionType"].ToString() == TransactionTypeEnum.Qualify.GetDescription() || inputJSON["TransactionType"].ToString() == TransactionTypeEnum.Terminate.GetDescription() || inputJSON["TransactionType"].ToString() == TransactionTypeEnum.Reactivate.GetDescription()) { objectschema = JSchema.Parse(Common.Constants.RewardRequestSchema.Terminate_Reactivate_Qualify_Schema); } else if (inputJSON["TransactionType"].ToString() == TransactionTypeEnum.Reward.GetDescription()) { //objectschema = JSchema.Parse(Common.Constants.RewardRequestSchema.RewardSchema); string product = inputJSON.SelectToken("Reward.ProductCode").ToString().Replace("{", "").Replace("}", ""); string program = inputJSON.SelectToken("Reward.ProgramName").ToString().Replace("{", "").Replace("}", ""); if (product != null && program != null) { List <SqlParameter> GetFulfillmentRuleParams = new List <SqlParameter>(); GetFulfillmentRuleParams.Add(new SqlParameter("@Product", product.ToString())); GetFulfillmentRuleParams.Add(new SqlParameter("@Program", program.ToString())); var ApiName = MSSQLConnection.ExecuteStoredProcedure <string>(USPContstants.GetFulfillmentRule, GetFulfillmentRuleParams).FirstOrDefault(); if (ApiName == "Order") { objectschema = JSchema.Parse(Common.Constants.RewardRequestSchema.OrderRewardSchema); inputJSON.Add("IsOrder", true); } else { objectschema = JSchema.Parse(Common.Constants.RewardRequestSchema.RewardSchema); } } } else if (inputJSON["TransactionType"].ToString() == TransactionTypeEnum.ProgramUpdateSourceSystem.GetDescription()) { objectschema = JSchema.Parse(Common.Constants.RewardRequestSchema.ProgramUpdateSchema); } else { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, inputJSON["TransactionType"].ToString() + " not supported.Path: TransactionType; Only Energy Earth transactions are allowed.")); } //Message schema validation valid = inputJSON.IsValid(objectschema, out messages); log.Verbose($"Valid ={valid}", "JE.RMS.Services.ApplyReward"); inputJSON.Add("IsValid", valid); var messageJSON = ""; if (messages.Count > 0) { messageJSON = JsonConvert.SerializeObject(messages); } inputJSON.Add("ValidationMessage", messageJSON); log.Verbose($"Validation message = {messageJSON}", "JE.RMS.Services.ApplyReward"); saverewardsobj = inputJSON.ToString(); log.Verbose($"Published message ={saverewardsobj}", "JE.RMS.Services.ApplyReward"); var reqObject = JsonConvert.DeserializeObject <RewardsRequest>(saverewardsobj); // Call SaveRewardsTrx to save rewards transaction. var SaveRewardTrxResponse = SaveRewardTrx(reqObject, errormessage, log); //RewardTrxID > 0 means reward request is saved successfully & we can process further if (SaveRewardTrxResponse.RewardTrxID > 0 && SaveRewardTrxResponse.IsValid == true && SaveRewardTrxResponse.Status != RewardTrxStatusEnum.ValidationError.GetDescription()) { //Fetch from database with State 'Ready for fulfillment - Immediate' List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@RewardTrxStatus", RewardTrxStatusEnum.ReadyForFulfillmentImmediate.GetDescription())); List <GetRewardsRequest> lstRewardsTrx = MSSQLConnection.ExecuteStoredProcedure <GetRewardsRequest>(USPContstants.GetRewardsTrx, objprm).ToList(); log.Verbose($"Get RewardsTrx Received:={lstRewardsTrx.Count}", "JE.RMS.Services.ApplyReward"); //Now create RewardFulfillmentRequest string rewardfulfillmentrequest = "["; foreach (var item in lstRewardsTrx) { item.IsFulfillImmediate = true; rewardfulfillmentrequest += JsonConvert.SerializeObject(item) + ","; } rewardfulfillmentrequest += "]"; //Evaluate Reward Trx (HTTP) using (HttpClient client = new HttpClient()) { var EvaluateRewardsTrxEndpoint = ConfigurationManager.AppSettings["EvaluateRewardsTrx"].ToString(); var accept = "application/json"; client.DefaultRequestHeaders.Add("Accept", accept); using (var response = await client.PostAsync(EvaluateRewardsTrxEndpoint, new StringContent(rewardfulfillmentrequest, Encoding.UTF8, "application/x-www-form-urlencoded"))) { var result = await response.Content.ReadAsStringAsync(); var evaluateResponse = JsonConvert.DeserializeObject <EvaluateRuleResponse>(result); if (response.IsSuccessStatusCode && (evaluateResponse.Status == RewardTrxStatusEnum.ReadyForFulfillmentImmediate.GetDescription() || evaluateResponse.Status == RewardTrxStatusEnum.WaitingForApproval.GetDescription() || evaluateResponse.Status == RewardTrxStatusEnum.SentForFulfillment.GetDescription())) { if (evaluateResponse.Status == RewardTrxStatusEnum.WaitingForApproval.GetDescription()) { Message = "Reward submitted successfully, waiting for approval."; } if (evaluateResponse.Status == RewardTrxStatusEnum.SentForFulfillment.GetDescription()) { Message = "Reward submitted successfully, Sent for fulfillment."; } List <SqlParameter> RewardTrxParams = new List <SqlParameter>(); RewardTrxParams.Add(new SqlParameter("@RewardTrxID", SaveRewardTrxResponse.RewardTrxID)); var RewardTrxID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.UpdateFulfillmentRequestTimestamp, RewardTrxParams); //Now again fetch from database to have updated record post evaluation. List <SqlParameter> objprm1 = new List <SqlParameter>(); objprm1.Add(new SqlParameter("@RewardTrxStatus", RewardTrxStatusEnum.ReadyForFulfillmentImmediate.GetDescription())); List <GetRewardsRequest> lstRewardsTrx1 = MSSQLConnection.ExecuteStoredProcedure <GetRewardsRequest>(USPContstants.GetRewardsTrx, objprm1).ToList(); if (lstRewardsTrx1.Count > 0) { lstRewardsTrx1 = lstRewardsTrx1.Where(p => p.RewardTrxID == SaveRewardTrxResponse.RewardTrxID).ToList(); //Process Fulfillment for Energy Earth var ProcessResult = ProcessRequest(lstRewardsTrx1, errormessage, log); if (ProcessResult != "Success") { return(CreateErrorResponse(req, "Error while processing Reward : " + ProcessResult)); } } log.Verbose($"Response ={result}", "JE.RMS.Services.ApplyReward"); } else { if (evaluateResponse.Status == RewardTrxStatusEnum.Error.GetDescription() || evaluateResponse.Status == RewardTrxStatusEnum.RejectedSystem.GetDescription() || evaluateResponse.Status == RewardTrxStatusEnum.ValidationError.GetDescription()) { return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, result)); } else { return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, new Exception(result))); } } } } } else { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, SaveRewardTrxResponse.ValidationMessage)); } } } else { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Only 1 reward request is allowed. You provided :" + RewardCount.ToString())); } Status = "Success"; if (Message == string.Empty) { Message = "Reward applied successfully."; } return(req.CreateResponse(HttpStatusCode.OK, new { Status, Message }, JsonMediaTypeFormatter.DefaultMediaType)); } catch (Exception ex) { log.Error($"Exception ={ex}", ex, "JE.RMS.Services.ApplyReward"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message, ex)); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}", "JE.RMS.Services.GetPoints"); bool isValid = true; string validationMessage = string.Empty; int SourceSystemID = 0; int SSID = 0; try { string reqString = await req.Content.ReadAsStringAsync(); var GetPointsRequest = JsonConvert.DeserializeObject <GetPointsRequest>(reqString); if (!string.IsNullOrEmpty(GetPointsRequest.SourceSystemID)) { int.TryParse(GetPointsRequest.SourceSystemID, out SourceSystemID); if (SourceSystemID <= 0) { isValid = false; validationMessage = validationMessage + "Validation Failed : SourceSystemID must be numeric;"; } } if (string.IsNullOrEmpty(GetPointsRequest.ChannelCode)) { isValid = false; validationMessage = validationMessage + "Validation Failed : Channel Code is required;"; } else if (GetPointsRequest.ChannelCode != FulfillmentChannel.EnergyEarth.GetDescription()) { isValid = false; validationMessage = validationMessage + "Validation Failed : Channel code not supported;"; } if ((!string.IsNullOrEmpty(GetPointsRequest.SourceSystemUniqueID) && string.IsNullOrEmpty(GetPointsRequest.SourceSystemUniqueIDType)) || (string.IsNullOrEmpty(GetPointsRequest.SourceSystemUniqueID) && !string.IsNullOrEmpty(GetPointsRequest.SourceSystemUniqueIDType))) { isValid = false; validationMessage = validationMessage + "Validation Failed : SourceSystemUniqueID & SourceSystemUniqueIDType both are required;"; } if (SourceSystemID > 0 || !string.IsNullOrEmpty(GetPointsRequest.SourceSystemName)) { List <SqlParameter> SSIDprm = new List <SqlParameter>(); SSIDprm.Add(new SqlParameter("@SourceSystemShortName", GetPointsRequest.SourceSystemName)); SSIDprm.Add(new SqlParameter("@SourceSystemID", SourceSystemID)); SSID = MSSQLConnection.ExecuteStoredProcedure <int>(USPContstants.GetSourceSystemID, SSIDprm).FirstOrDefault(); if (SSID == 0) { isValid = false; validationMessage = validationMessage + "Validation Failed : Please provide valid SourceSystemID or SourceSystemName (if both are provided they must match);"; } } if (!string.IsNullOrEmpty(GetPointsRequest.Email)) { GetPointsRequest.SourceSystemUniqueID = string.Empty; GetPointsRequest.SourceSystemUniqueIDType = string.Empty; GetPointsRequest.MasterID = string.Empty; } if (!string.IsNullOrEmpty(GetPointsRequest.MasterID)) { GetPointsRequest.SourceSystemUniqueID = string.Empty; GetPointsRequest.SourceSystemUniqueIDType = string.Empty; } if (isValid == false) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, validationMessage)); } //Get All Customer Unique IDs List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@email", GetPointsRequest.Email)); objprm.Add(new SqlParameter("@masterID", GetPointsRequest.MasterID)); objprm.Add(new SqlParameter("@sourceSystemUniqueID", GetPointsRequest.SourceSystemUniqueID)); objprm.Add(new SqlParameter("@sourceSystemUniqueIDType", GetPointsRequest.SourceSystemUniqueIDType)); objprm.Add(new SqlParameter("@channelCode", GetPointsRequest.ChannelCode)); objprm.Add(new SqlParameter("@SourceSystemID", SSID)); var ListCustomers = MSSQLConnection.ExecuteStoredProcedure <CustomerPointsResponse>(Common.Constants.USPContstants.GetCustomerPoints, objprm).ToList(); //Fetch Customers and update customer extended foreach (var item in ListCustomers) { if (!string.IsNullOrEmpty(item.UniqueID)) { using (HttpClient httpClient = new HttpClient()) { //Add Basic Authentication header httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["GetPointsFunctionUrl"].ToString()); string GetPointsFunctionCode = ConfigurationManager.AppSettings["GetPointsFunctionCode"].ToString(); string GetPointsFunctionUrl = GetPointsFunctionCode + "&UserId=" + item.UniqueID; var response = await httpClient.GetAsync(GetPointsFunctionUrl); if (response.IsSuccessStatusCode) { item.Points = Math.Round(Convert.ToDouble(response.Content.ReadAsStringAsync().Result) * 100, 2); item.SourceSystemUniqueID = GetPointsRequest.SourceSystemUniqueID; item.SourceSystemUniqueIDType = GetPointsRequest.SourceSystemUniqueIDType; item.MasterID = GetPointsRequest.MasterID; item.ChannelCode = GetPointsRequest.ChannelCode; item.SourceSystemID = GetPointsRequest.SourceSystemID; item.SourceSystemName = GetPointsRequest.SourceSystemName; } else { errormessage.Add(response.Content.ReadAsStringAsync().Result); } } } } log.Verbose($"Update Customer Extended completed on : {DateTime.Now.ToString()}", "JE.RMS.Services.GetPoints"); var PointResponse = req.CreateResponse(HttpStatusCode.OK); PointResponse.Content = new StringContent(JsonConvert.SerializeObject(ListCustomers), System.Text.Encoding.UTF8, "application/json"); return(PointResponse); } catch (Exception ex) { log.Error("Something went wrong while UpdateCustomerExtended", ex, "JE.RMS.Services.GetPoints"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public static async void Run(TimerInfo rewardsResponseTimer, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# timer function processed a request.", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); try { //Service bus queue names and connection stringsAllFulfillmentResponseSubscription var connectionString = ConfigurationManager.AppSettings["MyServiceBusReader"].ToString(); SubscriptionClient AllFulfillmentResponseSubscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, "fulfillmentresponse", "AllFulfillmentResponseSubscription"); var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); int BatchSize = Convert.ToInt32(ConfigurationManager.AppSettings["RewardFulfillmentResponseBatchSize"]); IEnumerable <BrokeredMessage> RecievedMessage = null; long MessageCount = namespaceManager.GetSubscription("fulfillmentresponse", "AllFulfillmentResponseSubscription").MessageCount; if (MessageCount > 0) { RecievedMessage = AllFulfillmentResponseSubscriptionClient.ReceiveBatch(BatchSize); } log.Verbose($"After the reading of queue message = {MessageCount}", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); List <Guid> messageLockTokenList = new List <System.Guid>(); if (RecievedMessage != null && RecievedMessage.Count() > 0) { foreach (BrokeredMessage message in RecievedMessage) { var responsemessage = message.GetBody <FulfillmentResponse>(); //var responsemessage = JsonConvert.DeserializeObject<FulfillmentResponse>(raw); log.Verbose($"C# trigger queue function processed a request. inputmessage={responsemessage}", "JE.RMS.Services.OnRewardsResponseRecieved"); #region Update Audit Fields //Update timestapm in Audit fields List <SqlParameter> AuditParam = new List <SqlParameter>(); AuditParam.Add(new SqlParameter("@RMSRewardID", responsemessage.RMSRewardID)); var RMSRewardID = MSSQLConnection.ExecuteStoredProcedure <string>(USPContstants.UpdateAuditFieldsInRewardsTrx, AuditParam); log.Verbose($"FulfillmentResponseTimestamp updated successfully. RMSRewardID={RMSRewardID[0]}", "JE.RMS.Services.OnRewardsResponseRecieved"); string RewardTrxStatus = "Fulfillment completed"; if (responsemessage.Status == "Fail") { RewardTrxStatus = "Error"; } List <SqlParameter> MessageLogParams = new List <SqlParameter>(); MessageLogParams.Add(new SqlParameter("@RMSRewardID", responsemessage.RMSRewardID)); MessageLogParams.Add(new SqlParameter("@MessageType", MessageType.RewardFulfillmentResponse.GetDescription())); MessageLogParams.Add(new SqlParameter("@IPAddress", responsemessage.ClientIP)); MessageLogParams.Add(new SqlParameter("@Message", JsonConvert.SerializeObject(responsemessage))); MessageLogParams.Add(new SqlParameter("@RewardsTrxID", null)); var ErrorMessageLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveMessageLog, MessageLogParams); log.Verbose($"MessageLog stored successfully. MessageLogID={ErrorMessageLogID[0]}", "JE.RMS.Services.ProcessFulfillmentForEnergyEarth"); ////Call stored procedure to Save RewardTrxChangeLog List <SqlParameter> RewardTrxChangeLogParams = new List <SqlParameter>(); RewardTrxChangeLogParams.Add(new SqlParameter("@RMSRewardID", responsemessage.RMSRewardID)); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardTrxStatus", RewardTrxStatus)); RewardTrxChangeLogParams.Add(new SqlParameter("@Comment", string.Empty)); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardsTrxID", null)); var RewardTrxChangeLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveRewardTrxChangeLog, RewardTrxChangeLogParams); log.Verbose($"RewardTrxChangeLog stored successfully. RewardTrxChangeLogID={RewardTrxChangeLogID[0]}", "JE.RMS.Services.OnRewardsResponseRecieved"); #endregion messageLockTokenList.Add(message.LockToken); } AllFulfillmentResponseSubscriptionClient.CompleteBatch(messageLockTokenList); } } catch (Exception ex) { log.Error($"Exception ={ex}", ex, "JE.RMS.Services.OnRewardsRequestRecieved"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}"); try { // Get request body string reqString = await req.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject <SearchCustomerRequest>(reqString); log.Verbose($"received data :={data}", "JE.RMS.Services.SearchCustomers"); string errmsg = ""; string tempsourceSystemId = "0"; bool flgvalidate = true, flgdone = false; if (data.SourceSystemUniqueID != null && data.SourceSystemUniqueIDType != null && flgvalidate) { if (string.IsNullOrEmpty(data.SourceSystemUniqueID) && string.IsNullOrEmpty(data.SourceSystemUniqueIDType)) { flgvalidate = true; } else { if (data.SourceSystemUniqueID != "") { if (data.SourceSystemUniqueIDType != "") { flgvalidate = true; } else { flgvalidate = false; flgdone = true; errmsg += "Validation Failed : SourceSystemUniqueID & SourceSystemUniqueIDType, either none or both are required."; } } else { flgvalidate = false; if (!flgdone) { errmsg += "Validation Failed : SourceSystemUniqueID & SourceSystemUniqueIDType, either none or both are required."; flgdone = true; } } if (data.SourceSystemUniqueIDType != "") { if (data.SourceSystemUniqueID != "") { flgvalidate = true; } else { flgvalidate = false; if (!flgdone) { errmsg += "Validation Failed : SourceSystemUniqueID & SourceSystemUniqueIDType, either none or both are required."; flgdone = true; } } } else { flgvalidate = false; if (!flgdone) { errmsg += "Validation Failed : SourceSystemUniqueID & SourceSystemUniqueIDType, either none or both are required."; flgdone = true; } } } } else if (data.SourceSystemUniqueID != null && flgvalidate) { if (data.SourceSystemUniqueIDType != null) { } else { flgvalidate = false; if (!flgdone) { if (data.SourceSystemUniqueID != "") { errmsg += "Validation Failed : SourceSystemUniqueID & SourceSystemUniqueIDType, either none or both are required."; flgdone = true; } } } } else if (data.SourceSystemUniqueIDType != null && flgvalidate) { if (data.SourceSystemUniqueID != null) { } else { flgvalidate = false; if (!flgdone) { if (data.SourceSystemUniqueIDType != "") { errmsg += "Validation Failed : SourceSystemUniqueID & SourceSystemUniqueIDType, either none or both are required."; flgdone = true; } } } } if (data.SourceSystemID != null && flgvalidate) { tempsourceSystemId = data.SourceSystemID.ToString(); if (tempsourceSystemId != "" && tempsourceSystemId != "0") { try { int tid = 0; int.TryParse(tempsourceSystemId, out tid); if (tid <= 0) { flgvalidate = false; errmsg += "Validation Failed : SourceSystemID must be numeric"; } } catch (Exception ex) { flgvalidate = false; errmsg += "Validation Failed : sourceSystemID must be numeric"; } } else { tempsourceSystemId = "0"; } } if (flgvalidate) { List <SqlParameter> objprmlookup = new List <SqlParameter>(); objprmlookup.Add(new SqlParameter("@sourceSystemID", data.SourceSystemID == null ? "0" : data.SourceSystemID.ToString())); objprmlookup.Add(new SqlParameter("@sourceSystemNames", data.SourceSystemName == null ? "" : data.SourceSystemName.ToString())); var objvalidate = MSSQLConnection.ExecuteStoredProcedure <string>(Common.Constants.USPContstants.CheckLookupValidation, objprmlookup); var Message = ""; if (objvalidate.Count == 1) { if (!objvalidate[0].ToString().ToLower().Equals("all validation passed")) { Message = objvalidate[0].ToString(); return(req.CreateResponse(HttpStatusCode.BadRequest, new { Message })); } } else { foreach (var temp in objvalidate) { Message += temp.ToString(); } return(req.CreateResponse(HttpStatusCode.BadRequest, new { Message })); } List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@email", data.Email == null ? "" : data.Email.ToString())); objprm.Add(new SqlParameter("@masterID", data.MasterID == null ? "" : data.MasterID.ToString())); objprm.Add(new SqlParameter("@sourceSystemUniqueID", data.SourceSystemUniqueID == null ? "" : data.SourceSystemUniqueID)); objprm.Add(new SqlParameter("@sourceSystemUniqueIDType", data.SourceSystemUniqueIDType == null ? "" : data.SourceSystemUniqueIDType)); objprm.Add(new SqlParameter("@sourceSystemID", data.SourceSystemID == null ? "0" : tempsourceSystemId)); objprm.Add(new SqlParameter("@sourceSystemName", data.SourceSystemName == null ? "" : data.SourceSystemName.ToString())); log.Verbose($"calling sp", "JE.RMS.Services.SearchCustomers"); List <Common.Model.CustomerTemp> retobj = MSSQLConnection.ExecuteStoredProcedure <Common.Model.CustomerTemp>(Common.Constants.USPContstants.SearchCustomers, objprm); Common.Model.SearchCustomerExtended ceobj; Common.Model.SearchCustomers obj = new Common.Model.SearchCustomers(); List <Common.Model.SearchCustomers> objlist = new List <Common.Model.SearchCustomers>(); int previd = -1; if (retobj.Count > 0) { foreach (var temp in retobj) { ceobj = new Common.Model.SearchCustomerExtended(); if (temp.CustomerID == previd) { if (temp.CustomerExtendedID != null) { ceobj.AccountAcceptanceDate = temp.AccountAcceptanceDate; ceobj.AccountStatus = temp.AccountStatus; ceobj.AvailablePointBalance = temp.AvailablePointBalance; ceobj.AvailablePointBalanceDollars = temp.AvailablePointBalanceDollars; ceobj.ChannelCode = temp.ChannelCode; ceobj.ChannelName = temp.ChannelName; ceobj.NextRewardDueDate = temp.NextRewardDueDate; ceobj.NumberofTransactions = temp.NumberofTransactions; ceobj.StartingPointBalance = temp.StartingPointBalance; ceobj.UniqueID = temp.UniqueID; obj.CustomerExtended.Add(ceobj); } } else { obj = new Common.Model.SearchCustomers(); obj.CustomerExtended = new List <Common.Model.SearchCustomerExtended>(); obj.AddressLine1 = temp.AddressLine1; obj.AddressLine2 = temp.AddressLine2; obj.City = temp.City; obj.CompanyName = temp.CompanyName; obj.Email = temp.Email; obj.FirstName = temp.FirstName; obj.Language = temp.Language; obj.LastName = temp.LastName; obj.MasterID = temp.MasterID; obj.Phone1 = temp.Phone1; obj.Product = temp.Product; obj.StateProvince = temp.StateProvince; obj.ZipPostalCode = temp.ZipPostalCode; obj.CustomerStatus = temp.CustomerStatus; obj.Jurisdiction = temp.Jurisdiction; obj.Country = temp.Country; if (temp.CustomerExtendedID != null) { ceobj.AccountAcceptanceDate = temp.AccountAcceptanceDate; ceobj.AccountStatus = temp.AccountStatus; ceobj.AvailablePointBalance = temp.AvailablePointBalance; ceobj.AvailablePointBalanceDollars = temp.AvailablePointBalanceDollars; ceobj.ChannelCode = temp.ChannelCode; ceobj.ChannelName = temp.ChannelName; ceobj.NextRewardDueDate = temp.NextRewardDueDate; ceobj.NumberofTransactions = temp.NumberofTransactions; ceobj.StartingPointBalance = temp.StartingPointBalance; ceobj.UniqueID = temp.UniqueID; obj.CustomerExtended.Add(ceobj); } objlist.Add(obj); } previd = temp.CustomerID; } } log.Verbose($"final response", "JE.RMS.Services.SearchCustomers"); return(req.CreateResponse(HttpStatusCode.OK, objlist)); } else { log.Verbose($"validation failed", "JE.RMS.Services.SearchCustomers"); return(req.CreateErrorResponse(HttpStatusCode.BadRequest, errmsg)); } } catch (Exception ex) { log.Error($"Exception ={ex}"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public static RewardFulfillmentResponseList GetMessagesFromSubscription(long FulfillmentChannelID, RewardFulfillmentResponseList resp, TraceWriter log) { IEnumerable <BrokeredMessage> RecievedMessage = null; long MessageCount = 0; if (resp.RewardFulfillmentRequest == null) { resp.RewardFulfillmentRequest = new List <RewardFulfillmentRequest>(); } BatchSize = BatchSize - resp.RewardFulfillmentRequest.Count; if (FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.GBASSTariff) { MessageCount = namespaceManager.GetSubscription("fulfillmentrequest", "GBASSTariffSubscription").MessageCount; if (MessageCount > 0) { RecievedMessage = GBASSTariffSubscription.ReceiveBatch(BatchSize, new TimeSpan(0, 0, 0)); } } else if (FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.GBASSCTLAdj) { MessageCount = namespaceManager.GetSubscription("fulfillmentrequest", "GBASSCTLAdjSubscription").MessageCount; if (MessageCount > 0) { RecievedMessage = GBASSCTLAdjSubscription.ReceiveBatch(BatchSize, new TimeSpan(0, 0, 0)); } } else if (FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.Cheque) { MessageCount = namespaceManager.GetSubscription("fulfillmentrequest", "SmartConnectSubscription").MessageCount; if (MessageCount > 0) { RecievedMessage = SmartConnectSubscriptionClient.ReceiveBatch(BatchSize, new TimeSpan(0, 0, 0)); } } List <Guid> messageLockTokenList = new List <System.Guid>(); resp.HasMoreMessages = false; if (RecievedMessage != null && RecievedMessage.Count() > 0) { foreach (BrokeredMessage message in RecievedMessage) { var raw = message.GetBody <string>(); var RewardFulfillmentRequestObj = JsonConvert.DeserializeObject <RewardFulfillmentRequestList>(raw); string RMSRewardID = RewardFulfillmentRequestObj.RewardFulfillmentRequest.RMSRewardID; ////Call stored procedure to Update RewardTrx List <SqlParameter> RewardTrxParams = new List <SqlParameter>(); RewardTrxParams.Add(new SqlParameter("@RMSRewardID", RMSRewardID)); var UpdatedRewardTrxID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.UpdateProcessFulfillmentTimestamp, RewardTrxParams).FirstOrDefault(); log.Verbose($"RewardTrx updated successfully. RewardTrID={UpdatedRewardTrxID}", "JE.RMS.Services.GetRewardFulfillmentRequest"); resp.RewardFulfillmentRequest.Add(RewardFulfillmentRequestObj.RewardFulfillmentRequest); messageLockTokenList.Add(message.LockToken); } if (FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.GBASSTariff) { GBASSTariffSubscription.CompleteBatch(messageLockTokenList); } else if (FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.GBASSCTLAdj) { GBASSCTLAdjSubscription.CompleteBatch(messageLockTokenList); } else if (FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.Cheque) { SmartConnectSubscriptionClient.CompleteBatch(messageLockTokenList); } } resp.HasMoreMessages = MessageCount > resp.RewardFulfillmentRequest.Count ? true : false; if (resp.HasMoreMessages && resp.RewardFulfillmentRequest.Count < RepeatCallSize) { GetMessagesFromSubscription(FulfillmentChannelID, resp, log); } resp.TotalRecord = MessageCount; return(resp); }
public static void Run(TimerInfo getRewardsTrxReadyForFulfillmentTimer, ICollector <string> errormessage, TraceWriter log) { try { if (getRewardsTrxReadyForFulfillmentTimer.IsPastDue) { log.Verbose("Timer is running late!", "JE.RMS.Services.GetRewardsTrxReadyForFulfillment"); } //Get RewardsTrx Ready for fulfillment List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@RewardTrxStatus", "Ready for fulfillment")); List <Common.Model.GetRewardsRequest> lstRewardsTrx = MSSQLConnection.ExecuteStoredProcedure <Common.Model.GetRewardsRequest>(Common.Constants.USPContstants.GetRewardsTrx, objprm).ToList(); log.Verbose($"Get RewardsTrx Ready for fulfillment:={lstRewardsTrx.Count}", "JE.RMS.Services.GetRewardsTrxReadyForFulfillment"); //Service bus queue names and connection strings var connectionString = ConfigurationManager.AppSettings["MyServiceBusReader"].ToString(); var FulfillmentRequestTopicClient = TopicClient.CreateFromConnectionString(connectionString, "fulfillmentrequest"); var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); #region Create Subscrptions for the first time //// Create a "EnergyEarthSubscription" filtered subscription. if (!namespaceManager.SubscriptionExists("fulfillmentrequest", "EnergyEarthSubscription")) { SqlFilter energyEarthFilter = new SqlFilter("channelType = 'EnergyEarth'"); namespaceManager.CreateSubscription("fulfillmentrequest", "EnergyEarthSubscription", energyEarthFilter); } //// Create a "GBASSSubscription" filtered subscription. if (!namespaceManager.SubscriptionExists("fulfillmentrequest", "GBASSCTLAdjSubscription")) { SqlFilter GBASSFilter = new SqlFilter("channelType = 'GBASSCTLAdj'"); namespaceManager.CreateSubscription("fulfillmentrequest", "GBASSCTLAdjSubscription", GBASSFilter); } if (!namespaceManager.SubscriptionExists("fulfillmentrequest", "GBASSTariffSubscription")) { SqlFilter GBASSFilter = new SqlFilter("channelType = 'GBASSTariff'"); namespaceManager.CreateSubscription("fulfillmentrequest", "GBASSTariffSubscription", GBASSFilter); } //// Create a "CRMSubscription" filtered subscription. if (!namespaceManager.SubscriptionExists("fulfillmentrequest", "CRMSubscription")) { SqlFilter CRMFilter = new SqlFilter("channelType = 'CRM'"); namespaceManager.CreateSubscription("fulfillmentrequest", "CRMSubscription", CRMFilter); } //// Create a "SmartConnectSubscription" filtered subscription. if (!namespaceManager.SubscriptionExists("fulfillmentrequest", "SmartConnectSubscription")) { SqlFilter SmartConnectFilter = new SqlFilter("channelType = 'SmartConnectCheque'"); namespaceManager.CreateSubscription("fulfillmentrequest", "SmartConnectSubscription", SmartConnectFilter); } #endregion RewardFulfillmentRequest RewardsRequestObj = new RewardFulfillmentRequest(); foreach (Common.Model.GetRewardsRequest item in lstRewardsTrx) { RewardFulfillmentRequestList rewardFulfillmentRequestList = new RewardFulfillmentRequestList(); rewardFulfillmentRequestList.RewardFulfillmentRequest = new RewardFulfillmentRequest(); RewardsRequestObj.RequestId = item.RequestId; RewardsRequestObj.TransactionType = item.TransactionType; RewardsRequestObj.RMSRewardID = item.RMSRewardID; RewardsRequestObj.Reward = new Reward(); RewardsRequestObj.Reward.ProductCode = item.ProductCode; RewardsRequestObj.Reward.ProductValue = item.ProductValue.ToString(); RewardsRequestObj.Reward.ProgramName = item.ProgramName; RewardsRequestObj.Reward.EffectiveDate = item.EffectiveDate; RewardsRequestObj.Reward.RewardType = item.RewardType; RewardsRequestObj.Customer = new CustomerJSON(); RewardsRequestObj.Customer.CustomerID = item.CustomerID; RewardsRequestObj.Customer.SourceSystemID = item.DBSourceSystemID.ToString(); RewardsRequestObj.Customer.SourceSystemName = item.SourceSystemShortName; RewardsRequestObj.Customer.SourceSystemUniqueID = item.SourceSystemUniqueID; RewardsRequestObj.Customer.SourceSystemUniqueIDType = item.SourceSystemUniqueIDType; RewardsRequestObj.Customer.MasterID = item.MasterID; RewardsRequestObj.Customer.Email = item.Email; RewardsRequestObj.Customer.FirstName = item.FirstName; RewardsRequestObj.Customer.LastName = item.LastName; RewardsRequestObj.Customer.CompanyName = item.CompanyName; RewardsRequestObj.Customer.AddressLine1 = item.AddressLine1; RewardsRequestObj.Customer.AddressLine2 = item.AddressLine2; RewardsRequestObj.Customer.City = item.City; RewardsRequestObj.Customer.StateProvince = item.StateProvince; RewardsRequestObj.Customer.ZipPostalCode = item.ZipPostalCode; RewardsRequestObj.Customer.Phone1 = item.Phone1; RewardsRequestObj.Customer.Product = item.Product; RewardsRequestObj.Customer.Language = item.LanguageCode; RewardsRequestObj.AdditionalData = JsonConvert.DeserializeObject <AdditionalData[]>(item.AdditionalData); rewardFulfillmentRequestList.RewardFulfillmentRequest = RewardsRequestObj; var reqObject = JsonConvert.SerializeObject(rewardFulfillmentRequestList); if (item.FulfillmentChannelID != (int)Common.Constants.FulfillmentChannel.EnergyEarth) { var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(reqObject); var serializedJson = (JObject)JsonConvert.DeserializeObject(reqObject); foreach (var response in serializedJson["RewardFulfillmentRequest"]["Customer"]) { if (response.Path.Contains("CustomerID")) { response.Remove(); break; } } reqObject = JsonConvert.SerializeObject(serializedJson); } log.Verbose($"Reward fulfillment request push to different channel :={reqObject.ToString()}", "JE.RMS.Services.GetRewardsTrxReadyForFulfillment"); var message = new BrokeredMessage(reqObject); if (item.FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.EnergyEarth) { message.Properties["channelType"] = FulfillmentChannel.EnergyEarth.ToString(); FulfillmentRequestTopicClient.Send(message); } else if (item.FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.GBASSTariff) { message.Properties["channelType"] = FulfillmentChannel.GBASSTariff.ToString(); FulfillmentRequestTopicClient.Send(message); } else if (item.FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.GBASSCTLAdj) { message.Properties["channelType"] = FulfillmentChannel.GBASSCTLAdj.ToString(); FulfillmentRequestTopicClient.Send(message); } else if (item.FulfillmentChannelID == (int)Common.Constants.FulfillmentChannel.Cheque) { message.Properties["channelType"] = "SmartConnectCheque"; FulfillmentRequestTopicClient.Send(message); } //Call stored procedure to Update RewardTrx List <SqlParameter> RewardTrxParams = new List <SqlParameter>(); RewardTrxParams.Add(new SqlParameter("@RewardTrxID", item.RewardTrxID)); var RewardTrxID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.UpdateFulfillmentRequestTimestamp, RewardTrxParams); log.Verbose($"RewardTrx updated successfully. RewardTrID={RewardTrxID[0]}", "JE.RMS.Services.EvaluateRewardsTrx"); //Call stored procedure to Save MessageLog List <SqlParameter> MessageLogParams = new List <SqlParameter>(); MessageLogParams.Add(new SqlParameter("@RewardsTrxID", item.RewardTrxID)); MessageLogParams.Add(new SqlParameter("@MessageType", MessageType.RewardFulfillmentRequest.GetDescription())); MessageLogParams.Add(new SqlParameter("@IPAddress", "")); MessageLogParams.Add(new SqlParameter("@Message", reqObject)); MessageLogParams.Add(new SqlParameter("@RMSRewardID", null)); var MessageLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveMessageLog, MessageLogParams); log.Verbose($"MessageLog stored successfully. MessageLogID={MessageLogID[0]}", "JE.RMS.Services.GetRewardsTrxReadyForFulfillment"); //Call stored procedure to Save RewardTrxChangeLog List <SqlParameter> RewardTrxChangeLogParams = new List <SqlParameter>(); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardsTrxID", item.RewardTrxID.ToString())); RewardTrxChangeLogParams.Add(new SqlParameter("@RewardTrxStatus", "Sent for fulfillment")); RewardTrxChangeLogParams.Add(new SqlParameter("@Comment", string.Empty)); RewardTrxChangeLogParams.Add(new SqlParameter("@RMSRewardID", null)); var RewardTrxChangeLogID = MSSQLConnection.ExecuteStoredProcedure <long>(USPContstants.SaveRewardTrxChangeLog, RewardTrxChangeLogParams); log.Verbose($"RewardTrxChangeLog stored successfully. RewardTrxChangeLogID={RewardTrxChangeLogID[0]}", "JE.RMS.Services.GetRewardsTrxReadyForFulfillment"); } log.Verbose($"C# Timer trigger function executed at: {DateTime.Now}", "JE.RMS.Services.GetRewardsTrxReadyForFulfillment"); } catch (Exception ex) { log.Error($"Exception ={ex}", ex, "JE.RMS.Services.GetRewardsTrxReadyForFulfillment"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}", "JE.RMS.Services.SaveRewardsTrx"); try { string Message = await req.Content.ReadAsStringAsync(); var item = JsonConvert.DeserializeObject <RewardsRequest>(await req.Content.ReadAsStringAsync()); using (var connection = MSSQLConnection.CreateConnection()) { connection.Open(); // Call stored procedure to Save Customer Customer Customers = new Customer(); GetRewardsRequest SaveRewardTrx = new GetRewardsRequest(); log.Verbose($"In SaveRewardTrx, Message={Message}", "JE.RMS.Services.SaveRewardsTrx"); log.Verbose($"In SaveRewardTrx, IsValid={item.IsValid}", "JE.RMS.Services.SaveRewardsTrx"); if (item.IsValid == true && item.IsValid.ToString().ToLower() == "true") { RewardTrxStatus = "Received"; } else { RewardTrxStatus = "Validation error"; } log.Verbose($"In SaveRewardTrx, RewardTrxStatus={RewardTrxStatus}", "JE.RMS.Services.SaveRewardsTrx"); if (item.Reward != null && !string.IsNullOrEmpty(item.Reward.ProductValue) && !Decimal.TryParse(item.Reward.ProductValue, out ProductValue)) { RewardTrxStatus = "Validation error"; item.ValidationMessage += " Required numeric value for ProductValue field."; } if (!item.IsOrder) { if (string.IsNullOrEmpty(item.Customer.SourceSystemUniqueIDType)) { RewardTrxStatus = "Validation error"; item.ValidationMessage += " Source system is not supported."; } if (!string.IsNullOrEmpty(item.Customer.SourceSystemID)) { int.TryParse(item.Customer.SourceSystemID, out SourceSystemID); if (SourceSystemID <= 0) { item.IsValid = false; RewardTrxStatus = RewardTrxStatusEnum.ValidationError.GetDescription(); item.ValidationMessage += "Validation Failed : SourceSystemID must be numeric;"; } } if (SourceSystemID > 0 || !string.IsNullOrEmpty(item.Customer.SourceSystemName)) { List <SqlParameter> SSIDprm = new List <SqlParameter>(); SSIDprm.Add(new SqlParameter("@SourceSystemShortName", item.Customer.SourceSystemName)); SSIDprm.Add(new SqlParameter("@SourceSystemID", item.Customer.SourceSystemID)); SourceSystemID = MSSQLConnection.ExecuteStoredProcedure <int>(USPContstants.GetSourceSystemID, SSIDprm).FirstOrDefault(); if (SourceSystemID == 0) { item.IsValid = false; RewardTrxStatus = RewardTrxStatusEnum.ValidationError.GetDescription(); item.ValidationMessage += "Validation Failed : Please provide valid SourceSystemID or SourceSystemName (if both are provided they must match);"; } } else { item.IsValid = false; RewardTrxStatus = RewardTrxStatusEnum.ValidationError.GetDescription(); item.ValidationMessage += "Validation Failed : Required value for at least one of 'SourceSystemID' or 'SourceSystemName'. Path: SourceSystemID or SourceSystemName;"; } } item.ValidationMessage = item.ValidationMessage.TrimStart(';'); DynamicParameters CustomerTrxParams = new DynamicParameters(); CustomerTrxParams.Add("@SourceSystemID", SourceSystemID.ToString()); CustomerTrxParams.Add("@SourceSystemUniqueID", item.Customer.SourceSystemUniqueID); CustomerTrxParams.Add("@SourceSystemUniqueIDType", item.Customer.SourceSystemUniqueIDType); CustomerTrxParams.Add("@MasterID", item.Customer.MasterID); CustomerTrxParams.Add("@Email", item.Customer.Email); CustomerTrxParams.Add("@FirstName", item.Customer.FirstName); CustomerTrxParams.Add("@LastName", item.Customer.LastName); CustomerTrxParams.Add("@CompanyName", item.Customer.CompanyName); CustomerTrxParams.Add("@AddressLine1", item.Customer.AddressLine1); CustomerTrxParams.Add("@AddressLine2", item.Customer.AddressLine2); CustomerTrxParams.Add("@City", item.Customer.City); CustomerTrxParams.Add("@StateProvince", item.Customer.StateProvince); CustomerTrxParams.Add("@ZipPostalCode", item.Customer.ZipPostalCode); CustomerTrxParams.Add("@Phone1", item.Customer.Phone1); CustomerTrxParams.Add("@Product", item.Customer.Product); CustomerTrxParams.Add("@Language", item.Customer.Language); CustomerTrxParams.Add("@RequestID", item.RequestId); CustomerTrxParams.Add("@TransactionType", item.TransactionType); CustomerTrxParams.Add("@ProductCode", (item.Reward != null && !string.IsNullOrEmpty(item.Reward.ProductCode)) ? item.Reward.ProductCode : string.Empty); CustomerTrxParams.Add("@ProductValue", ProductValue); CustomerTrxParams.Add("@ProgramName", (item.Reward != null && !string.IsNullOrEmpty(item.Reward.ProgramName)) ? item.Reward.ProgramName : string.Empty); if (item.Reward != null) { CustomerTrxParams.Add("@EffectiveDate", item.Reward.EffectiveDate); } else { CustomerTrxParams.Add("@EffectiveDate", string.Empty); } CustomerTrxParams.Add("@SourceIP", item.SourceIP); CustomerTrxParams.Add("@RewardsRequestReceiveTimestamp", item.RewardsRequestReceiveTimestamp); CustomerTrxParams.Add("@RMSRewardID", item.RMSRewardID); var additionalDataJSON = JsonConvert.SerializeObject(item.AdditionalData); CustomerTrxParams.Add("@AdditionalData", additionalDataJSON); CustomerTrxParams.Add("@RewardType", (!string.IsNullOrEmpty(item.Reward.RewardType)) ? item.Reward.RewardType : string.Empty); CustomerTrxParams.Add("@MessageType", MessageType.RewardRequest.GetDescription()); CustomerTrxParams.Add("@Message", Message); CustomerTrxParams.Add("@RewardTrxStatus", RewardTrxStatus); CustomerTrxParams.Add("@Comment", item.ValidationMessage); if (item.AdditionalData != null && item.AdditionalData.Where(p => p.Name == "OldEmailAddress") != null && item.AdditionalData.Where(p => p.Name == "OldEmailAddress").Count() > 0) { CustomerTrxParams.Add("@OldEmailAddress", item.AdditionalData.Where(p => p.Name == "OldEmailAddress").FirstOrDefault().Value); } CustomerTrxParams.Add("@IsOrder", item.IsOrder); log.Verbose($"Before calling SaveRewards stored proc, RewardTrxStatus={RewardTrxStatus}", "JE.RMS.Services.SaveRewardsTrx"); SaveRewardTrx = connection.Query <GetRewardsRequest>(Common.Constants.USPContstants.SaveRewards, CustomerTrxParams, null, true, null, CommandType.StoredProcedure).FirstOrDefault(); log.Verbose($"SaveRewardTrx sucessfully ={SaveRewardTrx.RewardTrxID}", "JE.RMS.Services.SaveRewardsTrx"); } return(req.CreateResponse(HttpStatusCode.OK, true)); } catch (Exception ex) { log.Error($"Exception={ex}", ex, "JE.RMS.Services.SaveRewardsTrx"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}"); bool isValid = true, isSourceSystemUniqueID = true; string validationMessage = string.Empty; int SourceSystemID = 0; int SSID = 0; try { string reqString = await req.Content.ReadAsStringAsync(); var getFulfillmentChannelLogRequest = JsonConvert.DeserializeObject <GetFulfillmentChannelLogRequest>(reqString); if (!string.IsNullOrEmpty(getFulfillmentChannelLogRequest.SourceSystemID)) { int.TryParse(getFulfillmentChannelLogRequest.SourceSystemID, out SourceSystemID); if (SourceSystemID <= 0) { isValid = false; validationMessage = validationMessage + "Validation Failed : SourceSystemID must be numeric;"; } } if (string.IsNullOrEmpty(getFulfillmentChannelLogRequest.FulfillmentChannel)) { isValid = false; validationMessage = validationMessage + "Validation Failed : Fulfillment Channel is required;"; } if ((!string.IsNullOrEmpty(getFulfillmentChannelLogRequest.SourceSystemUniqueID) && string.IsNullOrEmpty(getFulfillmentChannelLogRequest.SourceSystemUniqueIDType)) || (string.IsNullOrEmpty(getFulfillmentChannelLogRequest.SourceSystemUniqueID) && !string.IsNullOrEmpty(getFulfillmentChannelLogRequest.SourceSystemUniqueIDType))) { isValid = false; validationMessage = validationMessage + "Validation Failed : SourceSystemUniqueID & SourceSystemUniqueIDType both are required;"; } else if (string.IsNullOrEmpty(getFulfillmentChannelLogRequest.SourceSystemUniqueID) || string.IsNullOrEmpty(getFulfillmentChannelLogRequest.SourceSystemUniqueIDType)) { isSourceSystemUniqueID = false; } DateTime StartDate, EndDate; if (!isSourceSystemUniqueID) { if (string.IsNullOrEmpty(getFulfillmentChannelLogRequest.StartDate) || string.IsNullOrEmpty(getFulfillmentChannelLogRequest.EndDate)) { isValid = false; validationMessage = validationMessage + "Validation Failed : StartDate & EndDate are required;"; } else if (!DateTime.TryParseExact(getFulfillmentChannelLogRequest.StartDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out StartDate) || !DateTime.TryParseExact(getFulfillmentChannelLogRequest.EndDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out EndDate)) { isValid = false; validationMessage = validationMessage + "Validation Failed : StartDate & EndDate required in YYYY-MM-DD format;"; } else if (Convert.ToDateTime(getFulfillmentChannelLogRequest.StartDate) > Convert.ToDateTime(getFulfillmentChannelLogRequest.EndDate)) { isValid = false; validationMessage = validationMessage + "Validation Failed : StartDate must be less then EndDate;"; } } if (!string.IsNullOrEmpty(getFulfillmentChannelLogRequest.SourceSystemID) || !string.IsNullOrEmpty(getFulfillmentChannelLogRequest.SourceSystemName)) { List <SqlParameter> SSIDprm = new List <SqlParameter>(); SSIDprm.Add(new SqlParameter("@SourceSystemShortName", getFulfillmentChannelLogRequest.SourceSystemName)); SSIDprm.Add(new SqlParameter("@SourceSystemID", SourceSystemID)); SSID = MSSQLConnection.ExecuteStoredProcedure <int>(Common.Constants.USPContstants.GetSourceSystemID, SSIDprm).FirstOrDefault(); if (SSID == 0) { isValid = false; validationMessage = validationMessage + "Validation Failed : Please provide valid SourceSystemID or SourceSystemName (if both are provided they would match a SourceSystem);"; } } if (isValid == false) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, validationMessage)); } JObject data = await req.Content.ReadAsAsync <JObject>(); log.Verbose($"received data :={data}", "JE.RMS.Services.GetFulfillmentChannelLog"); List <SqlParameter> objprm = new List <SqlParameter>(); objprm.Add(new SqlParameter("@startDate", getFulfillmentChannelLogRequest.StartDate == string.Empty ? null : getFulfillmentChannelLogRequest.StartDate)); objprm.Add(new SqlParameter("@endDate", getFulfillmentChannelLogRequest.EndDate == string.Empty ? null : getFulfillmentChannelLogRequest.EndDate)); objprm.Add(new SqlParameter("@fulfillmentChannel", getFulfillmentChannelLogRequest.FulfillmentChannel)); objprm.Add(new SqlParameter("@sourceSystemID", SSID)); objprm.Add(new SqlParameter("@sourceSystemUniqueID", getFulfillmentChannelLogRequest.SourceSystemUniqueID)); objprm.Add(new SqlParameter("@sourceSystemUniqueIDType", getFulfillmentChannelLogRequest.SourceSystemUniqueIDType)); log.Verbose($"calling sp", "JE.RMS.Services.GetFulfillmentChannelLog"); List <FulfillmentChannelTransactionLog> obj = MSSQLConnection.ExecuteStoredProcedure <FulfillmentChannelTransactionLog>(Common.Constants.USPContstants.GetFulfillmentChannelTransactionLog, objprm); log.Verbose($"received response:={obj}", "JE.RMS.Services.GetFulfillmentChannelLog"); if (obj.Count > 0 && obj[0].FulfillmentChannelID == 0) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Validation Failed : Fulfillment Channel not supported;")); } string transactionString = "{\"Transactions\":["; JObject Transactions = new JObject(); foreach (var item in obj) { transactionString += item.TransactionData + ","; } transactionString = transactionString.TrimEnd(','); transactionString = transactionString + "]}"; var jObject = JObject.Parse(transactionString); var response = req.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(jObject.ToString(), Encoding.UTF8, "application/json"); return(response); } catch (Exception ex) { log.Error($"Exception ={ex}"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public static async void Run(TimerInfo rewardsRequestTrxTimer, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# timer function processed a request.", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); try { // Retrieve storage account from connection string CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["jermsstorage_STORAGE"].ToString()); // Create the queue client CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); // Retrieve a reference to a queue CloudQueue queue = queueClient.GetQueueReference("submitrewardsrequestqueue"); // Get the next message IEnumerable <CloudQueueMessage> retrievedMessage = queue.GetMessages(Convert.ToInt32(ConfigurationManager.AppSettings["ReadRewardsRequestReceivedFromQueueBatchSize"])); log.Verbose($"After the reading of queue message = {retrievedMessage.Count()}", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); foreach (var item in retrievedMessage) { string inputmessage = item.AsString; //Process the message in less than 30 seconds, and then delete the message queue.DeleteMessage(item.Id, item.PopReceipt); JObject inputJSON = JObject.Parse(inputmessage); JSchema objectschema = new JSchema(); objectschema = JSchema.Parse(Common.Constants.RewardRequestSchema.RequestSchema); if (inputJSON["TransactionType"] != null) { if (inputJSON["TransactionType"].ToString() == TransactionTypeEnum.Qualify.GetDescription() || inputJSON["TransactionType"].ToString() == TransactionTypeEnum.Terminate.GetDescription() || inputJSON["TransactionType"].ToString() == TransactionTypeEnum.Reactivate.GetDescription()) { objectschema = JSchema.Parse(Common.Constants.RewardRequestSchema.Terminate_Reactivate_Qualify_Schema); } if (inputJSON["TransactionType"].ToString() == TransactionTypeEnum.Reward.GetDescription()) { string product = inputJSON.SelectToken("Reward.ProductCode").ToString().Replace("{", "").Replace("}", ""); string program = inputJSON.SelectToken("Reward.ProgramName").ToString().Replace("{", "").Replace("}", ""); if (product != null && program != null) { List <SqlParameter> GetFulfillmentRuleParams = new List <SqlParameter>(); GetFulfillmentRuleParams.Add(new SqlParameter("@Product", product.ToString())); GetFulfillmentRuleParams.Add(new SqlParameter("@Program", program.ToString())); var ApiName = MSSQLConnection.ExecuteStoredProcedure <string>(USPContstants.GetFulfillmentRule, GetFulfillmentRuleParams).FirstOrDefault(); log.Verbose($"APIName ={ApiName}", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); log.Verbose($"Program ={program}", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); log.Verbose($"Product ={product}", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); if (ApiName == "Order") { objectschema = JSchema.Parse(Common.Constants.RewardRequestSchema.OrderRewardSchema); inputJSON.Add("IsOrder", true); } else { objectschema = JSchema.Parse(Common.Constants.RewardRequestSchema.RewardSchema); } } } if (inputJSON["TransactionType"].ToString() == TransactionTypeEnum.ProgramUpdateSourceSystem.GetDescription()) { objectschema = JSchema.Parse(Common.Constants.RewardRequestSchema.ProgramUpdateSchema); } } //Message schema validation valid = inputJSON.IsValid(objectschema, out messages); log.Verbose($"Valid ={valid}", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); inputJSON.Add("IsValid", valid); var messageJSON = ""; if (messages.Count > 0) { messageJSON = JsonConvert.SerializeObject(messages); } inputJSON.Add("ValidationMessage", messageJSON); log.Verbose($"Validation message = {messageJSON}", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); saverewardsobj = inputJSON.ToString(); log.Verbose($"Published message ={saverewardsobj}", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); // Call SaveRewardsTrx to save rewards transaction. using (HttpClient client = new HttpClient()) { var SaveRewardsTrxEndpoint = ConfigurationManager.AppSettings["SaveRewardsTrxEndpoint"].ToString(); var accept = "application/json"; client.DefaultRequestHeaders.Add("Accept", accept); using (var response = await client.PostAsync(SaveRewardsTrxEndpoint, new StringContent(saverewardsobj, Encoding.UTF8, "application/x-www-form-urlencoded"))) { if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync().Result; log.Verbose($"Response ={result}", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); } else { var result = response.Content.ReadAsStringAsync().Result; log.Verbose($"StatusCode ={response.StatusCode} ReasonPhrase ={response.ReasonPhrase}", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); log.Verbose($"Response ={result}", "JE.RMS.Services.ScheduledReadRewardsRequestRecieved"); } } } } } catch (Exception ex) { log.Error($"Exception ={ex}", ex, "JE.RMS.Services.OnRewardsRequestRecieved"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); } }
public static async void Run(TimerInfo getPointTransactionTimer, ICollector <string> errormessage, TraceWriter log) { log.Verbose($"C# Timer trigger function processed a request", "JE.RMS.Services.ScheduledGetPointTransactionLog"); try { List <SqlParameter> objParams = new List <SqlParameter>(); objParams.Add(new SqlParameter("@ProcessName", "GetPointTransactionLog")); ProcessLog DateLog = MSSQLConnection.ExecuteStoredProcedure <ProcessLog>(Common.Constants.USPContstants.GetLastDateOfTransactionLog, objParams).FirstOrDefault(); log.Verbose($"Get Points transaction called with start date = {DateLog.StartDate.Date.ToString()}, end date = {DateLog.EndDate.Date.ToString()}", "JE.RMS.Services.GetTransactionLogFromEnergyEarth"); //Check if start date & end date is provided if (DateLog.StartDate != null && DateLog.EndDate != null) { if (DateLog.StartDate > DateLog.EndDate) { log.Verbose($"Function seems to be already executed before. Provided startdate : {DateLog.StartDate} and EndDate : {DateLog.EndDate}"); } using (HttpClient httpClient = new HttpClient()) { //Add Basic Authentication header httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["EnergyEarthBaseUrl"].ToString()); var auth = Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["EEUserName"].ToString() + ":" + ConfigurationManager.AppSettings["EEPassword"].ToString()); httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(auth)); startDate = DateLog.StartDate.ToString("MM/dd/yyyy"); endDate = DateLog.EndDate.ToString("MM/dd/yyyy"); string GetPointTransactionsUrl = ConfigurationManager.AppSettings["GetTransactionLogFromEnergyEarthUrl"].ToString() + "?startDate=" + startDate + "&endDate=" + endDate; var response = await httpClient.GetStringAsync(GetPointTransactionsUrl); log.Verbose($"Success : Get Points transaction start date={DateLog.StartDate.Date.ToString()}, end date = {DateLog.EndDate.Date.ToString()}.", "JE.RMS.Services.GetTransactionLogFromEnergyEarth"); //Convert Users from Energy earth to Customer List Model using (var conn = MSSQLConnection.CreateConnection()) { log.Verbose("Started migration of EE users to Customer Table", "JE.RMS.Services.DMEEUserToCustomer"); conn.Open(); string deleteQuery = "DELETE FROM [dbo].[FulfillmentChannelTransactionLog] WHERE RecordDate BetWeen @StartDate AND @EndDate"; conn.Execute(deleteQuery, new { StartDate = DateLog.StartDate, EndDate = DateLog.EndDate }); string getFulfillmentChannelIDQuery = "SELECT FulfillmentChannelID FROM [dbo].[FulfillmentChannel] WHERE ChannelName = 'EnergyEarth'"; int FID = conn.Query <int>(getFulfillmentChannelIDQuery).FirstOrDefault(); //Convert Users from Energy earth to Customer List Model var transactionList = JObject.Parse(response); List <FulfillmentChannelTransactionLog> transactionLogList = new List <FulfillmentChannelTransactionLog>(); foreach (JObject x in transactionList["Transactions"]) { // Where 'obj' and 'obj["otherObject"]' are both JObjects FulfillmentChannelTransactionLog transactionLog = new FulfillmentChannelTransactionLog(); transactionLog.CreatedDate = DateTime.Now; transactionLog.TransactionData = x.ToString(); transactionLog.FulfillmentChannelID = FID; string date = x.SelectToken("OrderDate").ToString(); string date1 = x.SelectToken("ShipDate").ToString(); transactionLog.RecordDate = string.IsNullOrEmpty(date) ? DateTime.Now : Convert.ToDateTime(date); transactionLogList.Add(transactionLog); } string processQuery = "INSERT INTO [dbo].[FulfillmentChannelTransactionLog] (FulfillmentChannelID,TransactionData,RecordDate,CreatedDate) VALUES (@FulfillmentChannelID, @TransactionData, @RecordDate, @CreatedDate)"; conn.Execute(processQuery, transactionLogList); var Log = MSSQLConnection.ExecuteStoredProcedure <ProcessLog>(Common.Constants.USPContstants.UpdateProcessLog, objParams).FirstOrDefault(); log.Verbose("Completed migration of EE users to Customer Table", "JE.RMS.Services.ScheduledGetPointTransactionLog"); } } } else //Bad request : Start Date or End Date is not provided. { log.Error("Missing Parameter for GetTransactionLogFromEnergyEarth : startDate/endDate", null, "JE.RMS.Services.ScheduledGetPointTransactionLog"); } } catch (Exception ex) { log.Error("Something went wrong while GetTransactionLogFromEnergyEarth", ex, "JE.RMS.Services.ScheduledGetPointTransactionLog"); errormessage.Add(JsonConvert.SerializeObject(ex).ToString()); } }