private void Send() { //Trace.WriteLine(context.Database.Connection.ConnectionString); try { int successfullyProcessed = 0; int failedProcessed = 0; var failedEmails = new StringBuilder(); var emailBody = new StringBuilder(); List<Int32> listOfFailedRecurringBillingId = new List<Int32>(); emailBody.AppendLine(@"Recurring Billing Consolidated Report\r\n\r\n"); emailBody.AppendLine(String.Format(@"Current date: {0}\r\n\r\n\r\n", registDt)); Console.WriteLine("Fetching users for recurring billing..."); DateTime dtRecur = registDt.Date.AddDays(addDays); var recurringBillings = GetUsersEligibleForRenewal(dtRecur); Console.WriteLine(String.Format("Total users eligible for renewal: {0}", recurringBillings.Count())); if (recurringBillings != null) { if (recurringBillings.Count > 0) { using (var context = new IPTV2Entities()) { var gomsService = new GomsTfcTv(); try { gomsService.TestConnect(); Console.WriteLine("Test Connect success"); } catch (Exception) { Console.WriteLine("Test Connect failed."); } foreach (var i in recurringBillings) { using (var context3 = new IPTV2Entities()) { var user = context3.Users.FirstOrDefault(u => u.UserId == i.UserId); var recurringBilling = context3.RecurringBillings.Find(i.RecurringBillingId); var product = context3.Products.Find(i.ProductId); string productName = String.Empty; Console.WriteLine(String.Format("Processing user {0} with productId {1}, endDate {2}", user.EMail, product.Description, recurringBilling.EndDate)); try { ProductPrice priceOfProduct = context3.ProductPrices.FirstOrDefault(p => p.CurrencyCode == user.Country.CurrencyCode && p.ProductId == product.ProductId); if (priceOfProduct == null) priceOfProduct = context3.ProductPrices.FirstOrDefault(p => p.CurrencyCode == DefaultCurrencyCode && p.ProductId == product.ProductId); Purchase purchase = CreatePurchase(registDt, "Payment via Credit Card"); user.Purchases.Add(purchase); PurchaseItem item = CreatePurchaseItem(user.UserId, product, priceOfProduct); purchase.PurchaseItems.Add(item); var cardType = user.CreditCards.LastOrDefault(c => c.StatusId == 1).CardType; CreditCardPaymentTransaction transaction = new CreditCardPaymentTransaction() { Amount = priceOfProduct.Amount, Currency = priceOfProduct.CurrencyCode, Reference = cardType.ToUpper(), Date = registDt, Purchase = purchase, OfferingId = offeringId, StatusId = 1 }; var response = gomsService.CreateOrderViaRecurringPayment(context3, user.UserId, transaction); if (response.IsSuccess) { DateTime endDate = registDt; item.SubscriptionProduct = (SubscriptionProduct)product; if (item.SubscriptionProduct is PackageSubscriptionProduct) { PackageSubscriptionProduct subscription = (PackageSubscriptionProduct)product; foreach (var package in subscription.Packages) { string packageName = package.Package.Description; string ProductNameBought = packageName; productName = ProductNameBought; PackageEntitlement currentPackage = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId); EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, product, String.Format("{0}-{1}", "CC", cardType), response.TransactionId.ToString(), registDt); if (currentPackage != null) { request.StartDate = currentPackage.EndDate; currentPackage.EndDate = GetEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt)); endDate = currentPackage.EndDate; currentPackage.LatestEntitlementRequest = request; request.EndDate = endDate; } else { PackageEntitlement entitlement = CreatePackageEntitlement(request, subscription, package, registDt); request.EndDate = entitlement.EndDate; user.PackageEntitlements.Add(entitlement); } user.EntitlementRequests.Add(request); item.EntitlementRequest = request; //UPDATED: November 22, 2012 } recurringBilling.EndDate = endDate; recurringBilling.NextRun = endDate.AddDays(-3).Date; recurringBilling.UpdatedOn = registDt; recurringBilling.GomsRemarks = null; recurringBilling.NumberOfAttempts = 0; } Console.WriteLine(user.EMail + ": renewal process complete!"); if (context3.SaveChanges() > 0) { successfullyProcessed += 1; Console.WriteLine("Saving changes..."); } //Send email to user; try { SendConfirmationEmails(user, user, transaction, productName, product, endDate, registDt, "Credit Card", (DateTime)endDate.AddDays(-4).Date); } catch (Exception e) { recurringBilling.GomsRemarks = e.Message; } } else { using (var context2 = new IPTV2Entities()) { var failedRecurring = context2.RecurringBillings.FirstOrDefault(r => r.RecurringBillingId == recurringBilling.RecurringBillingId); if (failedRecurring != null) { failedRecurring.GomsRemarks = response.StatusMessage; failedRecurring.NumberOfAttempts += 1; listOfFailedRecurringBillingId.Add(failedRecurring.RecurringBillingId); if (failedRecurring.NumberOfAttempts == 2) { //Send failure email try { SendConfirmationEmails(user, user, transaction, productName, product, registDt, registDt, "Credit Card", registDt, response.StatusMessage); } catch (Exception e) { failedRecurring.GomsRemarks = e.Message; } } string failedSpecificsCopy = String.Format("RBId: {0}\r\n\r\nEmail: {1}\r\n\r\nProduct: {2}\r\n\r\nError: {3}\r\n\r\n", failedRecurring.RecurringBillingId, user.EMail, product.Description, response.StatusMessage); failedEmails.AppendLine(failedSpecificsCopy); failedEmails.AppendLine("--------------------------------------------------\r\n\r\n"); failedProcessed += 1; if (context2.SaveChanges() > 0) Console.WriteLine("Saving error..."); } } throw new Exception(user.EMail + ": " + response.StatusMessage); } } catch (Exception e) { Console.WriteLine("Inner Exception: " + e.Message); } } } //if (context.SaveChanges() > 0) //{ // Console.WriteLine("Saving changes..."); Console.WriteLine("Processing of eligible users for recurring billing has completed"); //} //Finish the copy of the email emailBody.AppendLine(String.Format(@"Total number of successful transactions: {0}\r\n\r\n", successfullyProcessed)); emailBody.AppendLine(String.Format(@"Total number of failed transactions (GOMS): {0}\r\n\r\n\r\n", failedProcessed)); if (failedEmails.Length > 0) { emailBody.AppendLine(@"Specifics can be found below\r\n\r\n\r\n"); emailBody.AppendLine(String.Format(@"{0}\r\n\r\n\r\n", failedEmails.ToString())); } emailBody.AppendLine("=================================================================\r\n\r\n\r\n"); //Get total numbers of recurring billing that have reached processing threshold //var reachedThreshold = context.RecurringBillings.Where(r => r.StatusId == 1 && r.NumberOfAttempts == 3); //if (reachedThreshold != null) //{ // emailBody.AppendLine(String.Format(@"Total number of failed transactions (MAX ATTEMPT): {0}\r\n\r\n", reachedThreshold.Count())); // foreach (var item in reachedThreshold) // { // string failedSpecificsCopy = String.Format("RBId: {0}\r\n\r\nEmail: {1}\r\n\r\nProduct: {2}\r\n\r\nLast error received: {3}\r\n\r\n", item.RecurringBillingId, item.User.EMail, item.Product.Description, item.GomsRemarks); // emailBody.AppendLine(failedSpecificsCopy); // emailBody.AppendLine("--------------------------------------------------\r\n\r\n"); // } //} failedEmails.AppendLine("=================================================================\r\n\r\n\r\n"); emailBody.AppendLine("Report ends here."); var newEmailBody = new StringBuilder(); newEmailBody.AppendLine("<!DOCTYPE html><html><body style=\"font-family: \"Trebuchet MS\", Arial, sans-serif;color:#000; font-size: 14px;\">"); newEmailBody.AppendLine("<h3>Report summary</h3>"); newEmailBody.AppendLine(String.Format("DateTime of processing (UTC): {0}", UtcDt)); newEmailBody.AppendLine(String.Format("<p style=\"font-size: 16px; font-weight: bold;\">Total number of successful transactions: {0}</p>", successfullyProcessed)); newEmailBody.AppendLine(String.Format("<p style=\"font-size: 16px; font-weight: bold;\">Total number of failed transactions: {0}</p>", failedProcessed)); newEmailBody.AppendLine(CreateConsolidatedReport(1, "GOMS", listOfFailedRecurringBillingId)); newEmailBody.AppendLine("<hr />"); newEmailBody.AppendLine(CreateConsolidatedReport(3, "MAX ATTEMPT", null)); newEmailBody.AppendLine("<p style=\"font-size: 16px; font-weight: bold;\">Report ends here.</p>"); newEmailBody.AppendLine("</body></html>"); if (IsSendConsolidatedReportsEnabled) { var receivers = consolidatedReportReceivers.Split(','); try { //SendEmailViaSendGrid(null, NoReplyEmail, "TFC.tv Recurring Billing: Consolidated Report", emailBody.ToString(), MailType.TextOnly, emailBody.ToString(), receivers); //SendEmailViaSendGrid(null, NoReplyEmail, "TFC.tv Recurring Billing: Consolidated Report", newEmailBody.ToString(), MailType.HtmlOnly, newEmailBody.ToString(), receivers); SendEmailViaSendGrid(toRecipient, NoReplyEmail, "TFC.tv Recurring Billing: Consolidated Report", newEmailBody.ToString(), MailType.HtmlOnly, newEmailBody.ToString(), receivers); Console.WriteLine("Sending of consolidated report is successful!"); } catch (Exception) { Console.WriteLine("Sending of consolidated report failed!"); } } //CANCELL ALL RECURRING try { var cancellation_list = GetUsersEligibleForCancellation(dtRecur); foreach (var i in cancellation_list) { try { gomsService.CancelRecurringPayment(i.User, i.Product); } catch (Exception) { } } } catch (Exception) { } } } else Console.WriteLine("Nothing to process.."); } } catch (Exception e) { Console.WriteLine("Outer Exception: " + e.Message); } }
//private void Send() //{ // //Trace.WriteLine(context.Database.Connection.ConnectionString); // try // { // var context = new IPTV2Entities(); // context.Database.Connection.ConnectionString = RoleEnvironment.GetConfigurationSettingValue("Iptv2Entities"); // Trace.TraceInformation("Fetching users for recurring..."); // DateTime dtRecur = registDt.Date.AddDays(Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("numOfDaysRecurringProcess"))); // var recurringBillings = context.RecurringBillings.Where(r => r.StatusId == 1 && r.NextRun < dtRecur); // Trace.TraceInformation(String.Format("Total Users For Recurring: {0}", recurringBillings.Count())); // if (recurringBillings != null) // { // var gomsService = new GomsTfcTv(); // //Set Goms Values via Azure // gomsService.UserId = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvUserId"); // gomsService.Password = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvPassword"); // gomsService.ServiceUserId = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServiceUserId"); // gomsService.ServicePassword = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServicePassword"); // gomsService.ServiceUrl = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServiceUrl"); // gomsService.ServiceId = Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServiceId")); // gomsService.GSapikey = RoleEnvironment.GetConfigurationSettingValue("GSapikey"); // gomsService.GSsecretkey = RoleEnvironment.GetConfigurationSettingValue("GSsecretkey"); // foreach (var i in recurringBillings) // { // Trace.TraceInformation(String.Format("Processing user {0} with productId {1}, endDate {2}", i.User.EMail, i.Product.Description, i.EndDate)); // try // { // ProductPrice priceOfProduct = i.Product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == i.User.Country.CurrencyCode); // if (priceOfProduct == null) // priceOfProduct = i.Product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == DefaultCurrencyCode); // Purchase purchase = CreatePurchase(registDt, "Payment via Credit Card"); // i.User.Purchases.Add(purchase); // PurchaseItem item = CreatePurchaseItem(i.UserId, i.Product, priceOfProduct); // purchase.PurchaseItems.Add(item); // var cardType = i.User.CreditCards.LastOrDefault(c => c.StatusId == 1).CardType; // CreditCardPaymentTransaction transaction = new CreditCardPaymentTransaction() // { // Amount = priceOfProduct.Amount, // Currency = priceOfProduct.CurrencyCode, // Reference = cardType.ToUpper(), // Date = registDt, // Purchase = purchase, // OfferingId = offeringId, // StatusId = 1 // }; // var response = gomsService.CreateOrderViaRecurringPayment(context, i.UserId, transaction); // if (response.IsSuccess) // { // DateTime endDate = registDt; // item.SubscriptionProduct = (SubscriptionProduct)i.Product; // if (item.SubscriptionProduct is PackageSubscriptionProduct) // { // PackageSubscriptionProduct subscription = (PackageSubscriptionProduct)i.Product; // foreach (var package in subscription.Packages) // { // string packageName = package.Package.Description; // string ProductNameBought = packageName; // PackageEntitlement currentPackage = i.User.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId); // EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, i.Product, String.Format("{0}-{1}", "CC", cardType), response.TransactionId.ToString(), registDt); // if (currentPackage != null) // { // request.StartDate = currentPackage.EndDate; // currentPackage.EndDate = GetEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt)); // endDate = currentPackage.EndDate; // currentPackage.LatestEntitlementRequest = request; // request.EndDate = endDate; // } // else // { // PackageEntitlement entitlement = CreatePackageEntitlement(request, subscription, package, registDt); // request.EndDate = entitlement.EndDate; // i.User.PackageEntitlements.Add(entitlement); // } // i.User.EntitlementRequests.Add(request); // item.EntitlementRequest = request; //UPDATED: November 22, 2012 // } // i.EndDate = endDate; // i.NextRun = endDate.AddDays(-3).Date; // i.UpdatedOn = registDt; // } // } // else // throw new Exception(response.StatusMessage); // } // catch (Exception e) // { // Trace.TraceError(e.Message); // i.GomsRemarks = e.Message; // // TFCTV.Helpers.MyUtility.LogException(e, "Recurring Billing Scheduled Task"); // } // } // context.SaveChanges(); // } // } // catch (Exception e) // { // //TFCTV.Helpers.MyUtility.LogException(e); // Trace.TraceInformation("Error: " + e.Message); // Trace.TraceInformation("Inner Exception: " + e.InnerException.Message); // } //} private void Send() { //Trace.WriteLine(context.Database.Connection.ConnectionString); try { Trace.TraceInformation("Fetching users for recurring..."); DateTime dtRecur = registDt.Date.AddDays(Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("numOfDaysRecurringProcess"))); var recurringBillings = GetUsersEligibleForRenewal(dtRecur); Trace.TraceInformation(String.Format("Total Users For Recurring: {0}", recurringBillings.Count())); if (recurringBillings != null) { using (var context = new IPTV2Entities()) { context.Database.Connection.ConnectionString = RoleEnvironment.GetConfigurationSettingValue("Iptv2Entities"); var gomsService = new GomsTfcTv(); SetGomsServiceVariables(gomsService); try { gomsService.TestConnect(); Console.WriteLine("Test Connect success"); } catch (Exception) { Console.WriteLine("Test Connect failed."); } foreach (var i in recurringBillings) { var user = context.Users.FirstOrDefault(u => u.UserId == i.UserId); var recurringBilling = context.RecurringBillings.Find(i.RecurringBillingId); var product = context.Products.Find(i.ProductId); Trace.TraceInformation(String.Format("Processing user {0} with productId {1}, endDate {2}", user.EMail, product.Description, i.EndDate)); try { ProductPrice priceOfProduct = context.ProductPrices.FirstOrDefault(p => p.CurrencyCode == user.Country.CurrencyCode && p.ProductId == product.ProductId); if (priceOfProduct == null) priceOfProduct = context.ProductPrices.FirstOrDefault(p => p.CurrencyCode == DefaultCurrencyCode && p.ProductId == product.ProductId); Purchase purchase = CreatePurchase(registDt, "Payment via Credit Card"); user.Purchases.Add(purchase); PurchaseItem item = CreatePurchaseItem(user.UserId, product, priceOfProduct); purchase.PurchaseItems.Add(item); var cardType = user.CreditCards.LastOrDefault(c => c.StatusId == 1).CardType; CreditCardPaymentTransaction transaction = new CreditCardPaymentTransaction() { Amount = priceOfProduct.Amount, Currency = priceOfProduct.CurrencyCode, Reference = cardType.ToUpper(), Date = registDt, Purchase = purchase, OfferingId = offeringId, StatusId = 1 }; var response = gomsService.CreateOrderViaRecurringPayment(context, user.UserId, transaction); if (response.IsSuccess) { DateTime endDate = registDt; item.SubscriptionProduct = (SubscriptionProduct)product; if (item.SubscriptionProduct is PackageSubscriptionProduct) { PackageSubscriptionProduct subscription = (PackageSubscriptionProduct)product; foreach (var package in subscription.Packages) { string packageName = package.Package.Description; string ProductNameBought = packageName; PackageEntitlement currentPackage = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId); EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, product, String.Format("{0}-{1}", "CC", cardType), response.TransactionId.ToString(), registDt); if (currentPackage != null) { request.StartDate = currentPackage.EndDate; currentPackage.EndDate = GetEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt)); endDate = currentPackage.EndDate; currentPackage.LatestEntitlementRequest = request; request.EndDate = endDate; } else { PackageEntitlement entitlement = CreatePackageEntitlement(request, subscription, package, registDt); request.EndDate = entitlement.EndDate; user.PackageEntitlements.Add(entitlement); } user.EntitlementRequests.Add(request); item.EntitlementRequest = request; //UPDATED: November 22, 2012 } recurringBilling.EndDate = endDate; recurringBilling.NextRun = endDate.AddDays(-3).Date; recurringBilling.UpdatedOn = registDt; recurringBilling.GomsRemarks = String.Empty; recurringBilling.NumberOfAttempts = 0; } Trace.TraceInformation(user.EMail + ": renewal process complete!"); } else { recurringBilling.GomsRemarks = response.StatusMessage; recurringBilling.NumberOfAttempts += 1; throw new Exception(user.EMail + ": " + response.StatusMessage); } } catch (Exception e) { Trace.TraceError("INNER ERROR: " + e.Message); } if (context.SaveChanges() > 0) Trace.TraceInformation("Saving changes..."); } } } } catch (Exception e) { Trace.TraceError("ERROR: " + e.Message); } }
private static void TestConnectivity() { var service = new GomsTfcTv(); service.TestConnect(); }