I have a Xamarin.Forms based application which uses operation with device contact like adding new contact and updating existing contact. Adding new contacts works, but update contact is not working. I used DependencyService of Xamarin.forms to update contacts on android. First i lookup for that contact and get its' Id if it exist.
Below is my code
void OnUpdate(){
var Id = LookupByPhone(phoneNumber, companyName+ " " + teamName);
if(Id!="0")
{
UpdateContact(phoneNumber, Id,companyName,teamName);
return;
}
}
string LookupByPhone(string phoneNumber, string query = "")
{
var Id = "0";
try
{
var context = MainActivity.Instance;
var uri = ContactsContract.Contacts.ContentUri;
uri = ContactsContract.CommonDataKinds.Phone.ContentUri;
string[] projection = {
ContactsContract.Contacts.InterfaceConsts.Id,
InterfaceConsts.DisplayName,
ContactsContract.CommonDataKinds.Phone.Number
};
var cursor = context.ContentResolver.Query(uri, projection, null, null, null);
if (cursor.MoveToFirst())
{
do
{
var id = cursor.GetString(cursor.GetColumnIndex(projection[0]));
var nm = cursor.GetString(cursor.GetColumnIndex(projection[1]));
var number = cursor.GetString(cursor.GetColumnIndex(projection[2]));
Id = id;
if (nm == query)
break;
//break;
} while (cursor.MoveToNext());
}
cursor.Close();
}
catch (Exception ex)
{
LogController.LogError(ex);
}
return Id;
}
void UpdateContact(string phonenumber, string id, string givenName, string familyName)
{
ContentProviderOperation.Builder builder = ContentProviderOperation.NewUpdate(ContactsContract.Data.ContentUri);
List<ContentProviderOperation> ops = new List<ContentProviderOperation>();
if (!string.IsNullOrWhiteSpace(givenName) && !string.IsNullOrWhiteSpace(familyName))
{
// Name
String nameSelection = ContactsContract.Data.InterfaceConsts.ContactId + " = ? AND "
+ ContactsContract.Data.InterfaceConsts.Mimetype + " = ? ";
String[] nameSelectionArgs = {
id.ToString(),
ContactsContract.CommonDataKinds.StructuredName.ContentItemType
};
builder.WithSelection(nameSelection, nameSelectionArgs);
builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.GivenName, givenName);
builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.FamilyName, familyName);
builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.DisplayName, givenName + " " + familyName);
ops.Add(builder.Build());
}
#region Phone update
// CellPhone
String phoneSelection = ContactsContract.Data.InterfaceConsts.ContactId + " = ? AND " +
ContactsContract.Data.InterfaceConsts.Mimetype + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type + " = ?";
String[] phoneselectionArgs = {
id.ToString(),
ContactsContract.CommonDataKinds.Phone.ContentItemType,
PhoneDataKind.Mobile.ToString()
};
builder = ContentProviderOperation.NewUpdate(ContactsContract.Data.ContentUri);
builder.WithSelection(phoneSelection, phoneselectionArgs);
builder.WithValue(ContactsContract.CommonDataKinds.Phone.Number, phonenumber);
builder.WithValue(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type, PhoneDataKind.Mobile.ToString());
ops.Add(builder.Build());
#endregion
// Update the contact
ContentProviderResult[] result;
try
{
// the result return count{0}
var result = MainActivity.Instance.ContentResolver.ApplyBatch(ContactsContract.Authority, ops);
}
catch (Exception ex)
{
LogController.LogError("Error updating phone:" + phonenumber,ex);
}
}
There are no error or exception. Any thought on this.
The method which gets the id should be like this (I removed the first parameter since it's not used in your method):
string LookupByPhone(string name)
{
string id = "0";
var uri = ContactsContract.Contacts.ContentUri;
var cursor = this.ContentResolver.Query(
uri,
new String[] { ContactsContract.Contacts.InterfaceConsts.Id },
ContactsContract.Contacts.InterfaceConsts.DisplayName +
"='" + name + "'", null, null);
if (cursor.MoveToNext())
{
id = cursor.GetString(cursor.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.Id));
}
cursor.Close();
return id;
}
You can see I get the id by query the name that is what you are using companyName + " " + teamName
Related
Below is the function where I am trying to execute a function in the background and then carry on without waiting for a result from it.
When debugging the task itself is executed but the actual function within it does not. The rest of the code then carries on like normal.
What could be the issue as there is no error produced after that to indicate otherwise?
This is on a page load.
public ActionResult ExceptionReport(int? id)
{
var ExceptionList = db.Invoices.Where(m => m.ExceptionFlag == true && m.GlobalInvoiceID == id);
if (ExceptionList.Count() == 0)
{
globalInvoice.Status = "Exception Verification";
db.Entry(globalInvoice).State = EntityState.Modified;
db.SaveChanges();
Task.Run(() => ExceptionFinalTests(globalInvoice)); //Function To run in the background
TempData["warning"] = "Verifying all exceptions fixed. A notification will be sent when the verifications are complete.";
return RedirectToAction("Index", "GlobalInvoices");
}
return View(ExceptionList);
}
private void ExceptionFinalTests(GlobalInvoice globalInvoice)
{
RunTests(globalInvoice, true);
decimal TotalPaymentAmount = db.Invoices.Where(m => m.GlobalInvoiceID == globalInvoice.Id).Sum(m => m.Invoice_Amount) ?? 0;
}
GlobalInvoicesController globalInvoicesController = new GlobalInvoicesController();
var ApproverList = globalInvoicesController.GetUserEmailsInRole(globalInvoice, "Reviewer");
globalInvoicesController.Dispose();
var exceptionExistCompulsoryTest = db.Invoices.Where(m => m.ExceptionFlag == true && m.GlobalInvoiceID == globalInvoice.Id);
if (exceptionExistCompulsoryTest.Count() > 0)
{
try
{
string baseUrl = ConfigurationManager.AppSettings["site"];
EmailExtension emailExtension = new EmailExtension();
foreach (var approver in ApproverList)
{
string approvalLink = baseUrl + "/Invoices/ExceptionReport/" + globalInvoice.Id;
StringBuilder mailbody = new StringBuilder();
mailbody.AppendFormat("Hi<br/>");
mailbody.AppendFormat("There are " + exceptionExistCompulsoryTest.Count() + " exceptions for invoice #" + globalInvoice.Id + "that need attention before proceeding. - <a href='" + approvalLink + "'>Click Here</a> <br/><br/>");
mailbody.AppendFormat("Exception Count: {0}<br/>", exceptionExistCompulsoryTest.Count());
mailbody.AppendFormat("Invoice Amount: {0}<br/>", TotalPaymentAmount.ToString("C"));
mailbody.AppendFormat("Reviewed By: {0} <br/>", "");
mailbody.AppendFormat("Approved By: {0} <br/>", "");
EmailVM emailVM = new EmailVM()
{
Subject = "Invoice - #" + globalInvoice.Id,
EmailAddress = approver,
Message = mailbody.ToString()
};
emailExtension.SendEmail(emailVM);
}
}
catch (Exception ex)
{
LogWriter.WriteLog(ex.Message);
LogWriter.WriteLog(ex.StackTrace);
}
}
}
private void RunTests(GlobalInvoice globalInvoice, bool retestFlag = false)
{
List<Invoice> invoices;
var vendorTests = globalInvoice.Vendor.VendorTests;
string[] testsToRun = vendorTests.Split(',');
if (retestFlag == true)
{
if (globalInvoice.Vendor.VendorHasHierarchy == true)
{
testsToRun = new string[] { "Account Number", "Hierarchy" };
}
else
{
testsToRun = new string[] { "Account Number" };
}
}
using (var context = new MyContext())
{
invoices = context.Invoices.Where(m => m.GlobalInvoiceID == globalInvoiceToTestID).ToList();
}
foreach (var test in testsToRun)
{
if (test == "Account Number")
{
LogWriter.WriteLog("Starting Account Number Check : Invoice Batch ID - " + globalInvoice.Id);
AccountNumberCheck(invoices, globalInvoice.VendorID);
LogWriter.WriteLog("Account Number Check Complete : Invoice Batch ID - " + globalInvoice.Id);
}
if (test == "Hierarchy")
{
LogWriter.WriteLog("Starting Hierarchy Check : Invoice Batch ID - " + globalInvoice.Id);
BillingHierarchyCheck(invoices);
LogWriter.WriteLog("Hierarchy Check Complete : Invoice Batch ID - " + globalInvoice.Id);
}
}
}
Been looking at this for the past few days now and I'm no closer to a solution. The code below is based on the CortanaVoiceCommand sample at https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/CortanaVoiceCommand and the code works perfectly on desktop but the background task is crashing on mobile each time.
In OnTaskCanceled the BackgroundTaskCancellationReason always reports as SystemPolicy but I'm no closer to finding a solution.
Appreciate any help anyone can suggest.
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.AppService;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.VoiceCommands;
namespace TramTimesVoice
{
public sealed class VoiceCommandService : IBackgroundTask
{
private BackgroundTaskDeferral backgroundTaskDeferral;
private IEnumerable services;
private Service service;
private Stop stop;
private VoiceCommandServiceConnection voiceCommandServiceConnection;
public async void Run(IBackgroundTaskInstance taskInstance)
{
backgroundTaskDeferral = taskInstance.GetDeferral();
taskInstance.Canceled += OnTaskCanceled;
AppServiceTriggerDetails triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
if (triggerDetails != null && triggerDetails.Name == "VoiceCommandService")
{
try
{
voiceCommandServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
voiceCommandServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;
VoiceCommand voiceCommand = await voiceCommandServiceConnection.GetVoiceCommandAsync();
if (voiceCommand.CommandName == "getServices")
{
await SendCompletionMessageForServices(voiceCommand.Properties["stop"][0]);
}
else
{
LaunchAppInForeground();
}
}
catch (Exception ex)
{
throw new Exception("Handling Voice Command Failed: " + ex.ToString());
}
}
}
private async void LaunchAppInForeground()
{
VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage();
userMessage.SpokenMessage = "Launching Tram Times";
VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userMessage);
response.AppLaunchArgument = "";
await voiceCommandServiceConnection.RequestAppLaunchAsync(response);
}
private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
if (backgroundTaskDeferral != null)
{
backgroundTaskDeferral.Complete();
}
}
private void OnVoiceCommandCompleted(VoiceCommandServiceConnection sender, VoiceCommandCompletedEventArgs args)
{
if (backgroundTaskDeferral != null)
{
backgroundTaskDeferral.Complete();
}
}
private async Task SendCompletionMessageForServices(String input)
{
await ShowProgressScreen("Working On It");
IEnumerable stops = new Stops().Get();
foreach (Stop item in stops)
{
if (input == item.Voice)
{
stop = new Stop()
{
Code = item.Code,
Name = item.Name,
Latitude = item.Latitude,
Longitude = item.Longitude,
ApiCodes = item.ApiCodes,
City = item.City,
Lines = item.Lines,
Voice = item.Voice
};
break;
}
}
if (stop.City == "Blackpool")
{
services = await new Blackpool().Get(stop.ApiCodes);
}
else if (stop.City == "Edinburgh")
{
services = await new Edinburgh().Get(stop.ApiCodes);
}
else if (stop.City == "London")
{
services = await new London().Get(stop.ApiCodes);
}
else if (stop.City == "Manchester")
{
services = await new Manchester().Get(stop.ApiCodes);
}
else if (stop.City == "Midland")
{
services = await new Midland().Get(stop.ApiCodes);
}
else if (stop.City == "Nottingham")
{
services = await new Nottingham().Get(stop.ApiCodes);
}
else if (stop.City == "Sheffield")
{
services = await new Sheffield().Get(stop.ApiCodes);
}
ObservableCollection<Service> data = new ObservableCollection<Service>();
foreach (Service item in services)
{
if (item.DestinationScheduled != null)
{
service = new Service()
{
Destination = item.Destination,
DestinationRealtime = item.DestinationRealtime,
DestinationRealtimeFull = item.DestinationRealtimeFull,
DestinationScheduled = item.DestinationScheduled,
DestinationScheduledFull = item.DestinationScheduledFull
};
data.Add(service);
}
else
{
service = new Service()
{
Destination = item.Destination,
DestinationRealtime = item.DestinationRealtime,
DestinationRealtimeFull = item.DestinationRealtimeFull,
DestinationScheduled = item.DestinationRealtime,
DestinationScheduledFull = item.DestinationRealtimeFull
};
data.Add(service);
}
}
data = new ObservableCollection<Service>(data.OrderBy(service => service.DestinationScheduledFull).ThenBy(service => service.Destination));
VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage();
userMessage.DisplayMessage = "I Found These Services";
userMessage.SpokenMessage = "I found these services from " + stop.Voice + ". ";
Collection<VoiceCommandContentTile> tiles = new Collection<VoiceCommandContentTile>();
VoiceCommandContentTile tile = new VoiceCommandContentTile();
tile.AppLaunchArgument = stop.Name;
tile.ContentTileType = VoiceCommandContentTileType.TitleWithText;
tile.Title = stop.Name;
if (data.Count > 0)
{
if (data[0].DestinationRealtime != null)
{
tile.TextLine1 = data[0].DestinationRealtime + " " + data[0].Destination;
userMessage.SpokenMessage += data[0].DestinationRealtime + " to " + data[0].Destination + ". ";
}
else
{
tile.TextLine1 = data[0].DestinationScheduled + " " + data[0].Destination;
userMessage.SpokenMessage += data[0].DestinationScheduled + " to " + data[0].Destination + ". ";
}
}
if (data.Count > 1)
{
if (data[1].DestinationRealtime != null)
{
tile.TextLine2 = data[1].DestinationRealtime + " " + data[1].Destination;
userMessage.SpokenMessage += data[1].DestinationRealtime + " to " + data[1].Destination + ". ";
}
else
{
tile.TextLine2 = data[1].DestinationScheduled + " " + data[1].Destination;
userMessage.SpokenMessage += data[1].DestinationScheduled + " to " + data[1].Destination + ". ";
}
}
if (data.Count > 2)
{
if (data[2].DestinationRealtime != null)
{
tile.TextLine3 = data[2].DestinationRealtime + " " + data[2].Destination;
userMessage.SpokenMessage += data[2].DestinationRealtime + " to " + data[2].Destination + ". ";
}
else
{
tile.TextLine3 = data[2].DestinationScheduled + " " + data[2].Destination;
userMessage.SpokenMessage += data[2].DestinationScheduled + " to " + data[2].Destination + ". ";
}
}
tiles.Add(tile);
VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userMessage, tiles);
response.AppLaunchArgument = "";
await voiceCommandServiceConnection.ReportSuccessAsync(response);
}
private async Task ShowProgressScreen(String message)
{
var userProgressMessage = new VoiceCommandUserMessage();
userProgressMessage.DisplayMessage = message;
userProgressMessage.SpokenMessage = message;
VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userProgressMessage);
await voiceCommandServiceConnection.ReportProgressAsync(response);
}
}
}
i am trying to get the list of programs from database. error is
ArgumentNullException was unhandled by user code in cacheUtilites GetTrainingProgram Method.
Here is my Controller code:
[HttpGet]
[Authorize(Roles = "Affiliate")]
public ActionResult GetTrainingPrograms(int? affiliateId, string searchStr, bool? active, string sort, int? start, int? limit)
{
int affId = UserData.AffiliateID;
if (affiliateId != null && affiliateId.Value > 0)
{
affId = affiliateId.Value;
}
string searchStrLower = string.Empty;
string queryStr = String.Concat(affId);
// The start point in the list of Training Programs
if (start != null)
{
queryStr = String.Concat(queryStr, "-", start.Value);
}
// To find Active or Inactive at the Current Time
if (active != null)
{
queryStr = String.Concat(queryStr, "-", active);
}
if (sort == null)
{
sort = "trainingProgramName";
}
queryStr = String.Concat(queryStr, "-", sort);
if (limit != null)
{
queryStr = String.Concat(queryStr, "-", limit.Value);
}
//The keywords used to find a Training Program
if (!string.IsNullOrEmpty(searchStr))
{
searchStrLower = searchStr.ToLower();
queryStr = String.Concat(queryStr, "-", searchStrLower);
}
logger.Debug("trainingProgramListKey: " + queryStr);
TrainingProgramList reloadData = CacheUtilities.Instance.GetTrainingProgramList(affiliateId);
logger.Debug("reloadData: " + reloadData + ", affId: " + affId + ", queryStr: " + queryStr);
string trainingProgramCacheKey = CbConstants.TrainingProgramCacheKey + queryStr;
TrainingProgramList trainingProgramList = null;
int totalCount = 0;
// Checks the List is null or not to Display
if (trainingProgramList == null)
{
logger.Debug("Cache miss for TrainingProgram list: " + trainingProgramCacheKey);
trainingProgramList = new TrainingProgramList();
trainingProgramList.AffiliateID = affId;
totalCount = TrainingProgramRepository.Instance.GetTrainingProgramsCount(affId, searchStrLower, active);
trainingProgramList.Entries = TrainingProgramRepository.Instance.GetTrainingPrograms(affId, searchStrLower, active, sort, start, limit);
HttpRuntime.Cache.Insert(trainingProgramCacheKey, trainingProgramList, null, Cache.NoAbsoluteExpiration, CbConstants.CacheSlidingExpirationOneDay);
}
CbJsonResponse response = new CbJsonResponse();
response.Data.Add(trainingProgramList);
response.Status = "success";
response.Meta.Add("total", Convert.ToString(totalCount));
return Json(response, "application/json", System.Text.Encoding.UTF8, JsonRequestBehavior.AllowGet);
}
}
}
CacheUtilities Code:
public TrainingProgramList GetTrainingProgramList(int? affiliateID)
{
string trainingprofCacheKey = CbConstants.TrainingProgramCacheKey + affiliateID;
TrainingProgramList trainingprogram = (TrainingProgramList)HttpRuntime.Cache[trainingprofCacheKey];
if (trainingprogram != null)
{
logger.Debug("Cache hit for AffProfile Entity: " + trainingprofCacheKey);
}
else
{
logger.Debug("Cache miss for AffProfile Entity: " + trainingprofCacheKey);
// trainingprogram = TrainingProgramRepository.Instance.GetTrainingPrograms(AffiliateID);
HttpRuntime.Cache.Insert(trainingprofCacheKey, trainingprogram, null, Cache.NoAbsoluteExpiration, CbConstants.CacheSlidingExpirationTwoHours);
}
return trainingprogram;
}
I'm working with a third-party who are posting information via HTTP POST to a .NET site I host locally. The POST is successful but I need to have the site send a success/failure response to the POST.
I have looked around but have been unable to find any suggestions to meet this need.
Please let me know if I can further clarify anything.
Thank you.
Edit: To include the code.
if (!string.IsNullOrEmpty(nvc["id"]) )
{
/* Populate the variables with the POST data
* Check first that the data is not empty or null */
if (!string.IsNullOrEmpty(nvc["id"]))
{ leadID = nvc["id"]; }
if (!string.IsNullOrEmpty(nvc["FN"]))
{ fn = nvc["FN"]; }
if (!string.IsNullOrEmpty(nvc["LN"]))
{ ln = nvc["LN"]; }
if (!string.IsNullOrEmpty(nvc["EMAIL"]))
{ email = nvc["EMAIL"]; }
if (!string.IsNullOrEmpty(nvc["PHONE"]))
{ phone = nvc["PHONE"]; }
if (!string.IsNullOrEmpty(nvc["ADDRESS"]))
{ address = nvc["ADDRESS"]; }
if (!string.IsNullOrEmpty(nvc["CITY"]))
{ city = nvc["CITY"]; }
if (!string.IsNullOrEmpty(nvc["STATE"]))
{ state = nvc["STATE"]; }
if (!string.IsNullOrEmpty(nvc["ZIP"]))
{ zip = nvc["ZIP"]; }
if (!string.IsNullOrEmpty(nvc["GENDER"]))
{ gender = nvc["GENDER"]; }
if (!string.IsNullOrEmpty(nvc["BIRTHDAY"]))
{ birthday = nvc["BIRTHDAY"]; }
if (!string.IsNullOrEmpty(nvc["TB"]))
{ tobacco = nvc["tobacco"]; }
// if (!string.IsNullOrEmpty(nvc["PPCSource"]))
// { PPCSource = nvc["PPCSource"]; }
if (!string.IsNullOrEmpty(nvc["GC_Source"]))
{ GC_Source__c = nvc["GC_Source"]; }
if (!string.IsNullOrEmpty(nvc["GC_Medium"]))
{ GC_Medium__c = nvc["GC_Medium"]; }
if (!string.IsNullOrEmpty(nvc["GC_Term"]))
{ GC_Term__c = nvc["GC_Term"]; }
if (!string.IsNullOrEmpty(nvc["GC_Content"]))
{ GC_Content__c = nvc["GC_Content"]; }
if (!string.IsNullOrEmpty(nvc["GC_Campaign"]))
{ GC_Campaign__c = nvc["GC_Campaign"]; }
if (!string.IsNullOrEmpty(nvc["GC_Custom_Segment"]))
{ GC_Custom_Segment__c = nvc["GC_Custom_Segment"]; }
if (!string.IsNullOrEmpty(nvc["GC_Num_of_Visits"]))
{ GC_Num_of_Visits__c = nvc["GC_Num_of_Visits"]; }
googleCookie = "Source: " + GC_Source__c + "; Medium: " + GC_Medium__c + "; Term: " + GC_Term__c + "; Content: " + GC_Content__c + "; Camp: " + GC_Campaign__c + "; Segment: " + GC_Custom_Segment__c + "; Visits: " + GC_Num_of_Visits__c;
GC_Source__c = "PPCSource";
if (ln != null & !string.IsNullOrEmpty(ln))
{
/* Call SetClientFunction with the POST Parameters Passed */
string result = SetClient(leadID, fn, ln, email, phone, address,city, state, zip, gender, birthday, tobacco, PPCSource, googleCookie, 0, GC_Source__c, GC_Medium__c, GC_Term__c);
SendNotice(GC_Source__c, fn, ln, result);
}
While sending email via System.Net.Mail to multiple recipients (one single email with multiple recipients), if one recipients address fail, will the rest reach the email?
There might be duplicates of the same question, but I'm asking something different in contrast.
For prompting such question, I was taken into consideration of Email clients available like Outlook where such does not happen even if one single address failed. Perhaps, System.Net.Mail is a lightweight client and does not allow such functionality? Or is it the way I'm writing my code incorrectly.
I was asked as if why this happens, hope I can get an explanation so that I can pass it by.
I was running such a scenario from my code below:
public void sendBusinessEmail(communication.email.business.config.BusinessEmailList[] aEmailList)
{
System.Net.Mail.MailMessage objMsg = null;
string[] aEmail = null;
System.Net.Mail.SmtpClient objSmtpClient = null;
int iRetries = 0;
if (aEmailList == null)
{
return;
}
try
{
if (Properties.Settings.Default.IS_SMTP_TLS)
{
objSmtpClient = getSMTP_TLS_Client();
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
}
else
{
objSmtpClient = getSMTP_Default_Client();
}
foreach (communication.email.business.config.BusinessEmailList obj in aEmailList)
{
try
{
objMsg = new System.Net.Mail.MailMessage();
objMsg.From = new System.Net.Mail.MailAddress("jkstock#keells.com", "JKSB Business Services");
aEmail = obj.Emails;
if (Properties.Settings.Default.TO_TEST_EMAIL)
{
objMsg.To.Add(Properties.Settings.Default.TO_TEST_EMAIL_ADDRESS.ToString());
for (int i = 0; i < aEmail.Length; i++)
{
objMsg.Body += aEmail[i] + Environment.NewLine;
}
}
else
{
for (int i = 0; i < aEmail.Length; i++)
{
objMsg.To.Add(new System.Net.Mail.MailAddress(aEmail[i]));
}
objMsg.Body = obj.EmailBody;
}
objMsg.Subject = checkAllReadySent(obj.EmailSubject);
objMsg.Attachments.Add(new System.Net.Mail.Attachment(obj.AttachmentPath, (System.IO.Path.GetExtension(obj.AttachmentPath) == ".pdf" ? System.Net.Mime.MediaTypeNames.Application.Pdf : System.Net.Mime.MediaTypeNames.Application.Octet)));
//sending emails
//send for 5 times if error persists, unless otherwise success
for (int i = 0; i < 5; i++)
{
try
{
objSmtpClient.Send(objMsg);
obj.updateLog("OK", (i+1));
break;
}
catch (Exception e)
{
if (i == 4)
{
obj.updateLog(e.Message, (i+1));
}
}
}
objMsg = null;
}
catch (System.Net.Mail.SmtpFailedRecipientsException e0)
{
obj.updateLog("Invalid Recipient(s)",0);
}
catch (Exception e1)
{
obj.updateLog("Error",0);
}
}
objSmtpClient = null;
}
catch (Exception e2)
{
MessageBox.Show(e2.Message);
objMsg = null;
objSmtpClient = null;
}
}
References for the above code:
public abstract class BusinessEmailList
{
private string _accountid = string.Empty;
private string _attachmentPath = string.Empty;
private string _emailsubject = string.Empty;
private string _agentid = string.Empty;
private string _response = string.Empty;
private string _ccTo = string.Empty;
private string _bccTo = string.Empty;
protected string _additionalBody = string.Empty;
private string[] _aEmail = null;
public string AccountID
{
get { return _accountid; }
set { _accountid = value; }
}
public string AgentID
{
get { return _agentid; }
set { _agentid = value; }
}
public string Response
{
get { return _response; }
set { _response = value; }
}
public string AttachmentPath
{
get { return _attachmentPath; }
set
{
if (System.IO.File.Exists(value))
{
_attachmentPath = value;
}
else { throw (new Exception("Attachment Not Found")); }
}
}
public string EmailSubject
{
get { return _emailsubject; }
set { _emailsubject = value; }
}
public string[] Emails
{
get { return getEmail(); }
}
public string EmailBody
{
get { return getMsgBody(); }
set { _additionalBody = value; }
}
public string ccTo
{
get { return _ccTo; }
set { _ccTo = value; }
}
public string bccTo
{
get { return _bccTo; }
set { _bccTo = value; }
}
public virtual string[] getEmail()
{
return null;
}
public virtual string getMsgBody()
{
if (System.IO.Path.GetExtension(this.AttachmentPath) == ".pdf")
{
return "Dear Sir/Madam, " +
Environment.NewLine +
Environment.NewLine +
"With kind Reference to the above, details as per attachment." +
Environment.NewLine +
Environment.NewLine +
"To view the attached PDF files you need Adobe Acrobat Reader installed in your computer. Download Adobe Reader from http://get.adobe.com/reader/ " +
Environment.NewLine +
Environment.NewLine +
"Thank you," +
Environment.NewLine +
"John Keells Stock Brokers (Pvt) Ltd.";
}
else
{
return "Dear Sir/Madam, " +
Environment.NewLine +
Environment.NewLine +
"With kind Reference to the above, details as per attachment." +
Environment.NewLine +
Environment.NewLine +
"Thank you," +
Environment.NewLine +
"John Keells Stock Brokers (Pvt) Ltd.";
}
}
public void updateLog(string status, int retries)
{
try
{
using (OracleConnection oracleConn = new OracleConnection(EquityBroker32.Properties.Settings.Default.JKSB_CONN_ORA.ToString()))
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "JKSBSCHEMA.EMAILLOG_ADD_PROC";
string[] aEmail = this.Emails;
OracleParameter p = null;
foreach (string s in aEmail)
{
cmd.Parameters.Clear();
p = new OracleParameter("pemail", OracleType.VarChar);
p.Value = s;
cmd.Parameters.Add(p);
p = new OracleParameter("psubject", OracleType.VarChar);
p.Value = this.EmailSubject;
cmd.Parameters.Add(p);
p = new OracleParameter("pattachement", OracleType.VarChar);
p.Value = this.AttachmentPath;
cmd.Parameters.Add(p);
p = new OracleParameter("presponse", OracleType.VarChar);
p.Value = status;
cmd.Parameters.Add(p);
p = new OracleParameter("pseqno", OracleType.Number);
p.Direction = ParameterDirection.InputOutput;
p.Value = "0";
cmd.Parameters.Add(p);
p = new OracleParameter("pretries", OracleType.Number);
p.Value = retries;
cmd.Parameters.Add(p);
oracleConn.Open();
cmd.ExecuteNonQuery();
oracleConn.Close();
}
}
}
catch (Exception er)
{
this.Response = er.Message;
}
}
}
public class BusinessClientEmailList : BusinessEmailList
{
public override string[] getEmail()
{
string[] aEmail;
//if (Properties.Settings.Default.TO_TEST_EMAIL == false)
//{
try
{
using (OracleConnection oracleConn = new OracleConnection(EquityBroker32.Properties.Settings.Default.JKSB_CONN_ORA.ToString()))
{
string sql = "SELECT EMAIL " +
"FROM " +
"(" +
"SELECT A.EMAIL AS EMAIL " +
"FROM JKSBSCHEMA.AGENTEMAIL A " +
"WHERE A.AGENTID = '" + this.AgentID + "' " +
"AND A.AGENTID != 'JKSB' "+
"AND A.ISACTIVE = 1 " +
"UNION " +
"SELECT B.EMAILID AS EMAIL " +
"FROM JKSBSCHEMA.CLIENTACCOUNTEMAIL B " +
"WHERE B.CLIENTACCOUNTID = '" + this.AccountID + "' " +
"AND B.IS_CONFIRMATION = 1 " +
") " +
"GROUP BY EMAIL";
int i = 0;
DataTable tbl = new DataTable();
OracleCommand cmd = new OracleCommand(sql, oracleConn);
cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(tbl);
aEmail = new string[tbl.Rows.Count];
foreach (DataRow rw in tbl.Rows)
{
aEmail[i] = rw[0].ToString();
i++;
}
}
}
catch (Exception)
{
aEmail = null;
}
//}
//else
//{
// aEmail = new string[1];
// aEmail[0] = Properties.Settings.Default.TO_TEST_EMAIL_ADDRESS.ToString();
//}
return aEmail;
}
public override string getMsgBody()
{
return base.getMsgBody();
}
}