error in displaying the list from database - c#

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

Related

Execute Task.Run() in ASP.NET ActionResult without waiting for result

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

Xamarin.forms Device contact is not getting updated

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

How to update querystring without using response.redirect which affects on performace of application

Given code is working properly but while checking page url on redirect checker,it gives error as too many redirections which may affect on performace of app.
if (Request.QueryString[null] != null)
{
string LastIndexOFUrl = Request.RawUrl.Substring(Request.RawUrl.LastIndexOf('/') + 1);
if (lang == "eng")
{
//Session["ServiceName"] = Request.QueryString[null].ToString();
//
dt2 = FEManager.GetOurServiceByID(CommonFunction.GetLangType(), LastIndexOFUrl);
if (dt2.Rows.Count > 0)
{
string Name_En = dt2.Rows[0]["URLEng"].ToString();
Name_En = Regex.Replace(Name_En, "[^0-9A-Za-z -]", "").ToLower().Replace(' ', '-');
if (Convert.ToString(Session["ServiceName"]) != Name_En)
{
Session["ServiceName"] = Name_En;
Response.Redirect(CommonFunction.GetLangWiseRedirectLink(1428, 1429) + "/" + Name_En);
}
else
Session["ServiceName"] = Name_En;
}
//
}
else
{
Session["ServiceName"] = Request.RawUrl.Substring(Request.RawUrl.LastIndexOf('/') + 1);
//temp code:
dt1 = FEManager.GetOurServiceByID(CommonFunction.GetLangType(), Session["ServiceName"].ToString());
if (dt1.Rows.Count > 0)
{
if (Session["ServiceName"].ToString() != dt1.Rows[0]["URLAr"].ToString())
{
Response.Redirect(CommonFunction.GetLangWiseRedirectLink(1428, 1429) + "/" + dt1.Rows[0]["URLAr"].ToString());
}
Session["ServiceName"] = dt1.Rows[0]["URLAr"].ToString();
}
}
string sessionData1 = Session["ServiceName"].ToString();
}
else
{
if (Session["ServiceName"] == null)
{
Response.Redirect(CommonFunction.GetLangWiseRedirectLink(1342, 1343));
}
else
{
Response.Redirect(CommonFunction.GetLangWiseRedirectLink(1428, 1429) + "/" + Session["ServiceName"].ToString());
}
}
dt = FEManager.GetOurServiceByID(CommonFunction.GetLangType(), Session["ServiceName"].ToString());
if (dt.Rows.Count > 0)
{
ltContent.Text = dt.Rows[0]["longDesc"].ToString();
ltHeader.Text = dt.Rows[0]["name"].ToString();
hdnID.Value = dt.Rows[0]["ID"].ToString();
((DotNetNuke.Framework.CDefault)this.Page).Title = dt.Rows[0]["pageTitle"].ToString();
}
If you get "too many redirects" it's almost always because you have created an infinite loop of redirects by redirecting to the same page.
Step through the code in a debugger and carefully check the redirect urls.

Using EWS how to get the meeting organizer working hours start and end time

I am using the EWS managed API to pull data from Exchange to a sharePoint application. I am usign the GetUserAvailability method to retrieve the information. Unfortunatly exchange is returning time even outside business hours. The problem is more evident when lets say organizer is in EST and attendee is in Australia time. Both of their working hour is set to local time in there country for example 8 AM to 5 PM local time. So when searching for a common time there should not be any overlap but exchange return the time considering the organizers time zone, which is not the expected outcome. The below code is given for reference.
public List<Week> RefineParams(string strLoginID, string strUserIds, DateTime StartTime, DateTime EndTime, int intNumberOfWeeks, int intMeetDur, bool includeNonBusHr, string strTimeZoneOffSet, string upn)
{
List<Week> weeks = null;
try
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "RefineParams started");
ExchangeService _ews = null;
string strTimeZoneID = GetTimeZoneStringFromOffset(strTimeZoneOffSet);
_ews = new ExchangeService(ExchangeVersion.Exchange2010, TimeZoneInfo.FindSystemTimeZoneById(strTimeZoneID));
// Override certificate check (due to lab environment using self-signed certs)
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
string name = WindowsIdentity.GetCurrent().Name;
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "EWS Credential " + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "Authentication Type " + System.Security.Principal.WindowsIdentity.GetCurrent().AuthenticationType);
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//IClaimsIdentity identity = (ClaimsIdentity)Thread.CurrentPrincipal.Identity;
//string upn = null;
//foreach (Claim claim in identity.Claims)
//{
// if (StringComparer.Ordinal.Equals(ClaimTypes.Upn, claim.ClaimType))
// {
// upn = claim.Value;
// KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), " UPN Value= " + upn + " for user: " + name);
// }
//}
// Perform the UPN logon through the c2WTS.
WindowsIdentity windowsIdentity = null;
if (!String.IsNullOrEmpty(upn))
{
try
{
windowsIdentity = S4UClient.UpnLogon(upn);
if (windowsIdentity != null)
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Windows indentity created for UPN: " + upn);
}
else
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Failed to create Windows indentity");
}
}
catch (SecurityAccessDeniedException)
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Could not map the upn claim to a valid windows identity.name : " + name);
}
}
else
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Refine Params: No UPN claim found");
throw new Exception("No UPN claim found");
}
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Before impeosonation Thread.Current.Name: " + Thread.CurrentPrincipal.Identity.Name);
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Before impeosonation WindowsIdentity.GetCurrent().Name: " + WindowsIdentity.GetCurrent().Name);
string strOrganizer = GetEmailForLoginName(strLoginID);
string strAttendeeEmails = GetEmailForUserID(strUserIds);
using (WindowsImpersonationContext ctxt = windowsIdentity.Impersonate())
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "After impeosonation Thread.Current.Name: " + Thread.CurrentPrincipal.Identity.Name);
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "After impeosonation WindowsIdentity.GetCurrent().Name: " + WindowsIdentity.GetCurrent().Name);
string strEWSServiceURL = ConfigurationManager.AppSettings.Get("EWSServiceURL");
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "EWS URL " + strEWSServiceURL);
_ews.Url = new Uri(strEWSServiceURL);
// Create a list of attendees.
List<AttendeeInfo> attendees = new List<AttendeeInfo>();
string[] arrUserID = null;
strUserIds = strUserIds.Trim(',');
arrUserID = strAttendeeEmails.Split(',');
attendees.Add(new AttendeeInfo()
{
//email address.
SmtpAddress = strOrganizer,
AttendeeType = MeetingAttendeeType.Organizer,
ExcludeConflicts = true
});
for (int i = 0; i < arrUserID.Length; i++)
{
if (!string.IsNullOrWhiteSpace(arrUserID[i]) && arrUserID[i].Contains("#"))
{
attendees.Add(new AttendeeInfo()
{
//email address.
SmtpAddress = Convert.ToString(arrUserID[i]),
AttendeeType = MeetingAttendeeType.Required,
ExcludeConflicts = true
});
}
}
foreach (AttendeeInfo aa in attendees)
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Attendee " + aa.SmtpAddress + "Attendeee type "+ aa.AttendeeType);
}
// Specify suggested meeting time options.
AvailabilityOptions meetingOptions = new AvailabilityOptions();
meetingOptions.MeetingDuration = intMeetDur;
if (includeNonBusHr)
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Viewing business hours "+includeNonBusHr);
meetingOptions.MaximumNonWorkHoursSuggestionsPerDay = 48;
meetingOptions.MaximumSuggestionsPerDay = 48;
}
else
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Viewing business hours " + includeNonBusHr);
meetingOptions.MaximumNonWorkHoursSuggestionsPerDay = 0;
meetingOptions.MaximumSuggestionsPerDay = Convert.ToInt32(ConfigurationManager.AppSettings.Get("MaximumSuggestionsPerDay"));
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "MaximumSuggestionsPerDay " + meetingOptions.MaximumSuggestionsPerDay);
}
meetingOptions.GoodSuggestionThreshold = Convert.ToInt32(ConfigurationManager.AppSettings.Get("GoodSuggestionThreshold"));
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "MaximumSuggestionsPerDay " + meetingOptions.GoodSuggestionThreshold);
meetingOptions.MinimumSuggestionQuality = SuggestionQuality.Good;
EndTime = EndTime.AddDays(1);
meetingOptions.DetailedSuggestionsWindow = new TimeWindow(StartTime, EndTime);
meetingOptions.RequestedFreeBusyView = FreeBusyViewType.FreeBusy;
// Return a set of of suggested meeting times.
GetUserAvailabilityResults results = _ews.GetUserAvailability(attendees,
new TimeWindow(StartTime, EndTime),
AvailabilityData.FreeBusyAndSuggestions,
meetingOptions);
weeks = new List<Week>();
List<DateTime> mtTimesColl = new List<DateTime>();
if (results != null)
{
foreach (Suggestion suggestion in results.Suggestions)
{
int cnt = suggestion.TimeSuggestions.Count;
foreach (TimeSuggestion tmesugg in suggestion.TimeSuggestions)
{
if (tmesugg.MeetingTime != null)
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "ConsiderTimeZone Value " + ConfigurationManager.AppSettings["ConsiderTimeZone"].ToString().Trim().ToLower());
if (ConfigurationManager.AppSettings["ConsiderTimeZone"].ToString().Trim().ToLower().CompareTo("true")==0)
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Within if statement : ConsiderTimeZone");
//List<ArrayList> attendeeColl = new List<ArrayList>();
List<List<DateTime>> attendeeColl = new List<List<DateTime>>();
if (results.AttendeesAvailability[0] != null)
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Organizer object found");
if (results.AttendeesAvailability[0].WorkingHours != null)
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "WorkingHours " + results.AttendeesAvailability[0].WorkingHours.ToString());
if (results.AttendeesAvailability[0].WorkingHours.TimeZone != null)
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Time Zone " + results.AttendeesAvailability[0].WorkingHours.TimeZone.ToString());
if (results.AttendeesAvailability[0].WorkingHours.TimeZone.BaseUtcOffset != null)
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "base utc" + results.AttendeesAvailability[0].WorkingHours.TimeZone.BaseUtcOffset.ToString());
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "within base utc off set not null");
var organizerTimeZone = results.AttendeesAvailability[0].WorkingHours.TimeZone.BaseUtcOffset;
KGSGLogger.LogError("Organizer time zone: ", organizerTimeZone.ToString());//till here
foreach (AttendeeAvailability aa in results.AttendeesAvailability)
{
//ArrayList singleAttendeeSlots = new ArrayList();
List<DateTime> singleAttendeeSlots = new List<DateTime>();
//var singleAttendeeSlots = new ArrayList();
KGSGLogger.LogError("Atteendee timezone base offset", (aa.WorkingHours.TimeZone.BaseUtcOffset.ToString()));
KGSGLogger.LogError("Converted start time to organizer timezone ", (Convert.ToDateTime(aa.WorkingHours.StartTime.ToString()).Add(organizerTimeZone - aa.WorkingHours.TimeZone.BaseUtcOffset)).ToString());
KGSGLogger.LogError("Converted end time to organizer timezone ", (Convert.ToDateTime(aa.WorkingHours.EndTime.ToString()).Add(organizerTimeZone - aa.WorkingHours.TimeZone.BaseUtcOffset)).ToString());
if ((Convert.ToDateTime(results.AttendeesAvailability[0].WorkingHours.StartTime.ToString())
<= (Convert.ToDateTime(aa.WorkingHours.StartTime.ToString()).Add(organizerTimeZone - aa.WorkingHours.TimeZone.BaseUtcOffset)))
&& (Convert.ToDateTime(results.AttendeesAvailability[0].WorkingHours.EndTime.ToString()))
>= (Convert.ToDateTime(aa.WorkingHours.EndTime.ToString()).Add(organizerTimeZone - aa.WorkingHours.TimeZone.BaseUtcOffset)))
{
DateTime dtConv = tmesugg.MeetingTime;
//mtTimesColl.Add(dtConv);
singleAttendeeSlots.Add(dtConv);
KGSGLogger.LogError("TimeZone consideration taken ", dtConv.ToString());
}
attendeeColl.Add(singleAttendeeSlots);
}
var TimeSLots = attendeeColl.Cast<IEnumerable<DateTime>>().Aggregate((x, y) => x.Intersect(y));
foreach (DateTime meetingTime in TimeSLots)
{
mtTimesColl.Add(meetingTime);
KGSGLogger.LogError("meeting slots ", meetingTime.ToString());
}
}
else
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "base utc is null");
}
}
else
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Time ZOne is null");
}
}
else
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "WorkingHours is null");
}
}
else
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "organizer is null");
}
}
else
{
KGSGLogger.LogError(SPCustomCategory.kGSGMeetingScheduler.ToString(),
"Within else statement : ConsiderTimeZone");
if (results.AttendeesAvailability[0].WorkingHours != null)
{
DateTime dtConv = tmesugg.MeetingTime;
mtTimesColl.Add(dtConv);
KGSGLogger.LogError("NO TIMEZONE CONVERSION Available slot: ", dtConv.ToString());
}
}
}
}
}
mtTimesColl.Sort((x, y) => x.CompareTo(y));
weeks.Add(GetAvailableSlots(StartTime, EndTime, intNumberOfWeeks, mtTimesColl));
}
else
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "Refine Params: GetUserAvailabilityResults is null");
throw new Exception("Refine Params: GetUserAvailabilityResults is null");
}
}
});
}
catch (Exception ex)
{
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), string.Format("Error in RefineParams(); " + "{0}/n{1}/n{2}", ex.Message, ex.StackTrace ?? string.Empty, ex.InnerException == null ? string.Empty : ex.InnerException.Message));
}
KGSGLogger.LogError(SPCustomCategory.kGSGService.ToString(), "RefineParams ends");
return weeks;
}

Sending Multiple Recepients in a single mail: Consequences

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

Categories