I have an smtp (System.Net.Mail) issue. On debug mode (developing) my smtp code runs perfectly. No errors. But when I publish the Blazor App an error occurs. Upon investigation I got this error Object reference not set to an instance of an object. It seems my email address variable is Null.
My code below:
@code {
//=============== email message ================
private string Message { get; set; } = "";
private string emailAddress { get; set; } = "";
//==============
bool isSubmitting;
//SF Dialog Declations
SfDialog GenericDialog;
SfDialog DialogDelete;
SfDialog DialogEndEMR;
SfDialog DialogRemoveResponder;
SfDialog DialogAddEditCall;
SfDialog DialogAddEditResponder;
private string GenericMessage = "";
//Call Variable declarations
IEnumerable<CallModel> calls;
private int SelectedCallID;
CallModel AddEditCall = new CallModel();
string HeaderText = "";
string DeleteItem = "";
string DisableText = "";
string EndEMRText = "";
//string DeleteResponderText = "";
int isCompleted = 0;
string ResponderName = "";
//Responder Variable declarations
IEnumerable<ResponderModel> responders;
private int SelectedResponderID;
ResponderModel AddEditResponder = new ResponderModel();
string RefNo = "";
//Duty Variable declarations
IEnumerable<DutyModel> availableEmrs;
//sfgrid variable declarations
private List<ItemModel> Toolbaritems = new List<ItemModel>();
//sfgrid variable declarations
private List<ItemModel> Toolbaritems2 = new List<ItemModel>();
//====== synfuxsion ====================
private DialogEffect AnimationEffect = DialogEffect.Zoom;
//Priority Variable Declarations
IEnumerable<PriorityModel> priorities;
private int SelectedPriorityID;
//NOE Variable Declarations
IEnumerable<NatureOfEmergencyModel> natureOfEmergencies;
private int SelectedNatureOfEmergencyID;
protected override async Task OnInitializedAsync()
{
//Populate Priority list
priorities = await PriorityService.PriorityList();
//Populate NOE
natureOfEmergencies = await NatureOfEmergencyService.NatureOfEmergencyList();
//Populate Call list
calls = await CallService.CallList(DateTime.Today);
//Populate responder list
responders = await ResponderService.ResponderList(SelectedCallID);
//Populate toolbaritems for SFGrid
Toolbaritems.Add(new ItemModel() { Text = "Add", TooltipText = "Add a new Call", PrefixIcon = "e-add" });
Toolbaritems.Add(new ItemModel() { Text = "Edit", TooltipText = "Edit selected Call", PrefixIcon = "e-edit" });
Toolbaritems.Add(new ItemModel() { Text = "Cancel", TooltipText = "Cancel selected Call", PrefixIcon = "e-delete" });
Toolbaritems.Add(new ItemModel() { Text = "End EMR", TooltipText = "End Emergency", PrefixIcon = "e-cancel" });
//Populate toolbaritems2 for SFGrid
Toolbaritems2.Add(new ItemModel() { Text = "Add", TooltipText = "Add Responders", PrefixIcon = "e-add" });
Toolbaritems2.Add(new ItemModel() { Text = "Delete", TooltipText = "Delete Responder", PrefixIcon = "e-delete" });
//Refresh deployed responders
StartTimer();
}
//============ Grid Toolbaritems Add Edit Delete Code SHOW ONLY ============================
public async Task ToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
{
if (args.Item.Text == "Add")
{
SelectedCallID = 0;
AddEditCall = new CallModel();
HeaderText = "Add Call";
await this.DialogAddEditCall.ShowAsync();
}
if (args.Item.Text == "Edit")
{
if (SelectedCallID == 0)
{
GenericMessage = "Please select a Call to Edit.";
await this.GenericDialog.ShowAsync();
}
else
{
//populate AddEditCall object for data editing
HeaderText = "Edit Call";
AddEditCall = await CallService.Call_GetOne(SelectedCallID);
await this.DialogAddEditCall.ShowAsync();
}
}
if (args.Item.Text == "Cancel")
{
if (isCompleted != 1)
{
//code for deleting
if (SelectedCallID > 0)
{
await this.DialogDelete.ShowAsync();
}
else
{
//no record selected
GenericMessage = "Please select a Call to Cancel";
await this.GenericDialog.ShowAsync();
}
}
else
{
GenericMessage = "Completed Emergency Call cannot be cancelled.";
await this.GenericDialog.ShowAsync();
}
}
if (args.Item.Text == "End EMR")
{
//code for deleting
if (SelectedCallID > 0)
{
await this.DialogEndEMR.ShowAsync();
}
else
{
//no record selected
GenericMessage = "Please select a Call to End EMR";
await this.GenericDialog.ShowAsync();
}
}
}
//====== code to get CallID from the Grid ===================
public async Task RowSelectHandler(RowSelectEventArgs<CallModel> args)
{
//{args.Data} returns the current selected records.
if (args != null)
{
SelectedCallID = args.Data.CallID;
DeleteItem = args.Data.NameOfCaller;
RefNo = "Deploying EMR Presonnel to Call Ref No: " + args.Data.CallID + " | Caller: " + args.Data.NameOfCaller;
EndEMRText = "Caller: " + args.Data.NameOfCaller + " Ref No: " + args.Data.CallID;
isCompleted = args.Data.isCompleted;
//Populate responder list
responders = await ResponderService.ResponderList(SelectedCallID);
//Populate available EMR's
availableEmrs = await DutyService.AvailablePersonnelList(SelectedCallID);
if (args.Data.isCancelled == "Cancelled")
{
DisableText = "Enable";
}
else
{
DisableText = "Cancel";
}
}
}
//============= Close Generic Dialog ================
private async Task CloseGenericDialog()
{
await this.GenericDialog.HideAsync();
}
//===== code for deleting record =============
public async Task ConfirmDeleteYes()
{
if (isCompleted != 1)
{
int Success = await CallService.CallDelete(SelectedCallID);
if (Success != 0)
{
GenericMessage = "Call can't be deleted";
await this.GenericDialog.ShowAsync();
}
else
{
await this.DialogDelete.HideAsync();
calls = await CallService.CallList(DateTime.Today);
SelectedCallID = 0;
responders = await ResponderService.ResponderList(SelectedCallID);
StateHasChanged();
}
}
else
{
GenericMessage = "Cannot cancel a Completed Emergency Call";
await this.GenericDialog.ShowAsync();
}
}
//===== code for end emr record =============
public async Task ConfirmEndEMRYes()
{
int Success = await CallService.CallEndEMR(SelectedCallID);
if (Success != 0)
{
GenericMessage = "Somthing went wrong";
await this.GenericDialog.ShowAsync();
}
else
{
await this.DialogEndEMR.HideAsync();
calls = await CallService.CallList(DateTime.Today);
StateHasChanged();
}
}
//===== code for end emr record =============
public async Task ConfirmRemoveResponderYes()
{
int Success = await ResponderService.ResponderDelete(SelectedResponderID);
if (Success != 0)
{
GenericMessage = "Somthing went wrong";
await this.GenericDialog.ShowAsync();
}
else
{
await this.DialogRemoveResponder.HideAsync();
responders = await ResponderService.ResponderList(SelectedCallID);
StateHasChanged();
}
}
//==== cancel delete Record ============
public async void ConfirmDeleteNo()
{
await this.DialogDelete.HideAsync();
}
//==== cancel End EMR Record ============
public async void ConfirmEndEMRNo()
{
await this.DialogEndEMR.HideAsync();
}
//==== cancel End EMR Record ============
public async void ConfirmRemoveResponderRNo()
{
await this.DialogRemoveResponder.HideAsync();
}
//====== code add/edit User Record SAVING DATA =====================
protected async Task CallAddEditSave()
{
if (isSubmitting)
return;
isSubmitting = true;
try
{
//===== code adding user record if selected userid is 0
if (SelectedCallID == 0)
{
int Success = await CallService.CallInsert(AddEditCall.LocationOfEmergency,
AddEditCall.MapAddress,
AddEditCall.NatureOfEmergencyID,
AddEditCall.InjuriesAndSymptoms,
AddEditCall.HowManyPeopleInvolved,
AddEditCall.ConsciousAndBreathing,
AddEditCall.AreaSituation,
AddEditCall.SpecialNeedsSituation,
AddEditCall.NameOfCaller,
AddEditCall.CallerContactInfo,
AddEditCall.PriorityID,
0,
Global.UserID);
if (Success != 0)
{
//error
GenericMessage = "Something went wrong.";
await this.GenericDialog.ShowAsync();
}
else
{
await this.DialogAddEditCall.HideAsync();
calls = await CallService.CallList(DateTime.Today);
this.StateHasChanged();
}
}
else
{
int Success = await CallService.CallUpdate(AddEditCall.CallID,
AddEditCall.LocationOfEmergency,
AddEditCall.MapAddress,
AddEditCall.NatureOfEmergencyID,
AddEditCall.InjuriesAndSymptoms,
AddEditCall.HowManyPeopleInvolved,
AddEditCall.ConsciousAndBreathing,
AddEditCall.AreaSituation,
AddEditCall.SpecialNeedsSituation,
AddEditCall.NameOfCaller,
AddEditCall.CallerContactInfo,
AddEditCall.PriorityID,
0,
Global.UserID);
if (Success != 0)
{
//error
GenericMessage = "Something went wrong";
await this.GenericDialog.ShowAsync();
}
else
{
await this.DialogAddEditCall.HideAsync();
calls = await CallService.CallList(DateTime.Today);
this.StateHasChanged();
}
}
}
finally
{
isSubmitting = false;
}
}
//============== Role Combox Code on Change Combobox ===========================
public void OnChangeNoE(Syncfusion.Blazor.DropDowns.ChangeEventArgs<int, NatureOfEmergencyModel> args)
{
SelectedNatureOfEmergencyID = args.ItemData.NatureOfEmergencyID; ;
this.AddEditCall.NatureOfEmergencyID = SelectedNatureOfEmergencyID;
}
//============== Role Combox Code on Change Combobox ===========================
public void OnChangePriority(Syncfusion.Blazor.DropDowns.ChangeEventArgs<int, PriorityModel> args)
{
SelectedPriorityID = args.ItemData.PriorityID; ;
this.AddEditCall.PriorityID = SelectedPriorityID;
}
//Close AddEdit
private async Task CloseDialogAddEdit()
{
await this.DialogAddEditCall.HideAsync();
}
//Close AddEdit
private async Task CloseDialogAddEdit2()
{
await this.DialogAddEditResponder.HideAsync();
}
//============ Grid Toolbaritems Add Edit Delete Code SHOW ONLY ============================
public async Task ToolbarClickHandler2(Syncfusion.Blazor.Navigations.ClickEventArgs args)
{
if (args.Item.Text == "Add")
{
if (isCompleted == 0)
{
if (SelectedCallID > 0)
{
//Populate available EMR's
availableEmrs = await DutyService.AvailablePersonnelList(SelectedCallID);
SelectedResponderID = 0;
AddEditResponder = new ResponderModel();
HeaderText = "Add Responder";
await this.DialogAddEditResponder.ShowAsync();
}
else
{
{
//no record selected
GenericMessage = "Please select a Emergency Call from the grid";
await this.GenericDialog.ShowAsync();
}
}
}
else
{
{
//no record selected
GenericMessage = "Emergency Call is already completed. No deployment needed.";
await this.GenericDialog.ShowAsync();
}
}
}
if (args.Item.Text == "Delete")
{
//code for deleting
if (SelectedResponderID > 0)
{
await this.DialogRemoveResponder.ShowAsync();
}
else
{
//no record selected
GenericMessage = "Please select a Responder to Delete";
await this.GenericDialog.ShowAsync();
}
}
}
//====== code to get CallID from the Grid ===================
public void RowSelectHandler2(RowSelectEventArgs<ResponderModel> args)
{
//{args.Data} returns the current selected records.
if (args != null)
{
SelectedResponderID = args.Data.ResponderID;
ResponderName = args.Data.FullName;
}
}
//====== code add/edit emr Record SAVING DATA =====================
protected async Task ResponderAddEditSave()
{
if (isSubmitting)
return;
isSubmitting = true;
try
{
var selectedEMR = availableEmrs.Where(p => p.isSelected == true);
foreach (var emr in selectedEMR)
{
int Success = await ResponderService.ResponderInsert(SelectedCallID,
emr.DutyID,
Global.UserID);
string emrname = emr.FullName;
string refno = calls.First().CallID.ToString();
string calldate = calls.First().CallDate.ToString();
string natureofemergency = calls.First().NatureOfEmergency; ;
string location = calls.First().LocationOfEmergency; ;
string maplocation = calls.First().MapAddress;
string emralert = "https://emrdispatch.ncst.edu.ph/";
StringBuilder prompt = new StringBuilder();
prompt.AppendLine("<p>Email Date : " + DateTime.Today + "</p>");
prompt.AppendLine("<p>Attention : " + emrname + "</p>");
prompt.AppendLine("<p>Ref No : " + refno + "</p>");
prompt.AppendLine("<p>Date of Emergency : " + calldate + "</p>");
prompt.AppendLine("<p>Nature of Emergency : " + natureofemergency + "</p>");
prompt.AppendLine("<p>Location : " + location + "</p>");
prompt.AppendLine("<p>Map Address :" + maplocation + "</p>");
prompt.AppendLine("<p>EMR Alert :" + emralert + "</p>");
Message = prompt.ToString();
emailAddress = emr.Email;
SendMail();
if (Success != 0)
{
//error
GenericMessage = "Something went wrong.";
await this.GenericDialog.ShowAsync();
}
else
{
await this.DialogAddEditResponder.HideAsync();
responders = await ResponderService.ResponderList(SelectedCallID);
this.StateHasChanged();
}
}
}
finally
{
isSubmitting = false;
}
}
public void CustomizeCallCell(QueryCellInfoEventArgs<CallModel> args)
{
if (args.Column.Field == "EMRStatus")
{
if (args.Data.EMRStatus == $"<span style=\"color:#17a2b8;font-weight:700;background-color:lightyellow;\">On Going</span>")
{
args.Cell.AddClass(new string[] { "blink" });
}
}
}
public void CustomizeCell(QueryCellInfoEventArgs<ResponderModel> args)
{
if (args.Column.Field == "Status")
{
if (args.Data.Status == $"<span style=\"color:#17a2b8;font-weight:700;background-color:lightyellow;\">Standing By</span>")
{
args.Cell.AddClass(new string[] { "blink" });
}
}
}
/// <summary>
/// /TIMER CODE
/// </summary>
private Timer timer;
public void Dispose()
{
timer.Dispose();
}
private void StartTimer()
{
timer = new Timer();
timer.Interval = 3000;
timer.Elapsed += OnTimerElapsed;
timer.Enabled = true;
}
private async void OnTimerElapsed(object? sender, ElapsedEventArgs e)
{
responders = await ResponderService.ResponderList(SelectedCallID);
await InvokeAsync(() =>
{
StateHasChanged();
});
}
private void SendMail()
{
try
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("fictitiousmail.com");
mail.To.Add(emailAddress.ToString());
mail.Subject = "Emergency Call Alert";
mail.Body = "<div class=\"m-0\">" + Message + "</div>";
mail.IsBodyHtml = true;
using (SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.Credentials = new System.Net.NetworkCredential("fictitiousmail.com", "asdfasdfasdfagsdfg");
smtpClient.UseDefaultCredentials = false;
smtpClient.EnableSsl = true;
smtpClient.Send(mail);
Message = "Mail Sent";
}
}
}
catch (Exception ex)
{
Message = ex.Message;
js.InvokeVoidAsync("alert", Message);
}
}
}
I cant seem to fix the issue when in debug mode my emailAddress
variable will store a value from the emr
object. But when published and hosted to the server the emailaddress
variable becomes null.
Any help is highly appreciated.
Oliver
Running the Blazor server app on debug mode over and over again gave me no issues. Only after I publish the Blazor Server app gave me an Error (emailAddress = null)