How can I check if a IUser has nickname? - c#

if (user.IsBot == false && (user.Nickname.ToString().Equals(buffer) || user.Username.ToString().Equals(buffer)))
{
await ReplyAsync(Context.User.Mention + message[new Random().Next(5)] + user.Mention);
}
If user doesn't have a nickname it says Object reference not set to an instance of an object.

You should check if Nickname is null first. In this case I would propose something like:
if (user.Nickname != null && user.IsBot == false)
{
if (user.Nickname.ToString().Equals(buffer) || user.Username.ToString().Equals(buffer)))
{
await ReplyAsync(Context.User.Mention + message[new Random().Next(5)] + user.Mention);
}
}
Or even:
if (user != null)
{
if (user.Nickname != null && user.IsBot == false)
{
if (user.Nickname.ToString().Equals(buffer) || user.Username.ToString().Equals(buffer)))
{
await ReplyAsync(Context.User.Mention + message[new Random().Next(5)] + user.Mention);
}
}
}
if user can be null too.

Related

A second operation started on this context before a previous asynchronous

hai im new on c# actually i have an issue with my code which i couldnt find the error. I making a controller which i can see the details that user sumbit. When im debug it say that " Use 'await' to ensure that any asynchronous operations". i try to put await every each of line but doesnt working.
plus in my cases i dont use for each method
here is my code :-
public async Task<ActionResult> Details(int id, string currentFilter)
{
try
{
BizRepMaster bizRepmaster = _bizRepMasterService.Find(id);
if (bizRepmaster.RepCountry != null)
ViewBag.BizCountry = _countryMasterService.Find(bizRepmaster.RepCountry).tCountry;
else
ViewBag.BizCountry = "";
if (bizRepmaster.RepState == null)
{
ViewBag.State = "";
}
else
{
if (bizRepmaster.RepState == "Oth")
{
ViewBag.State = "Others";
}
else
{
ViewBag.State = GetStateName(bizRepmaster.RepCountry, bizRepmaster.RepState);
}
}
if (bizRepmaster.MailState == null)
{
ViewBag.MailState = "";
}
else
{
if (bizRepmaster.RepState == "Oth")
{
ViewBag.MailState = "Others";
}
else
{
ViewBag.MailState = GetBizStateName(bizRepmaster.RepCountry, bizRepmaster.MailState);
}
}
ViewBag.AMNationality = _countryMasterService.GetCountryMaster()
.Where(a => a.tISO == bizRepmaster.RepNationality).Single().tCountry;
ViewBag.AMIdType = _idTypeService.GetIdTypes()
.Where(a => a.TypeID == bizRepmaster.RepIdType).Single().LabelName;
if (bizRepmaster.DialCode != null)
{
ViewBag.DialCode = _unitOfWorkAsync.Repository<Country>().Find(bizRepmaster.DialCode).tDialCode;
}
if (bizRepmaster.NatureOfBusiness != null)
{
}
ViewBag.AMResType = _unitOfWorkAsync.Repository<ResidencyType>().Find(bizRepmaster.RepResidencyType).LabelName;
ViewBag.AMJobType = _unitOfWorkAsync.Repository<SenderJobType>().Find(bizRepmaster.RepJobType).LabelName;
ViewBag.StateList = new SelectList(_stateService.GetStates(), "nId", "tStateDesc");
if (bizRepmaster.IdType != null)
ViewBag.IdTypeList = _idTypeService.Find(Convert.ToInt32(bizRepmaster.RepIdType)).LabelName;
ViewBag.CreatedUserName = _userProfileService.GetUserProfile().Where(a => a.UserID == Convert.ToInt32(bizRepmaster.CreatedBy)).Single().LoginId;
if (bizRepmaster.ApprovedBy != null)
{
ViewBag.ApprovedUserName = _userProfileService.GetUserProfile().Where(a => a.UserID == Convert.ToInt32(bizRepmaster.ApprovedBy)).Single().LoginId;
}
if (bizRepmaster.LastUpdatedBy != null)
{
ViewBag.LastUpdatedName = _userProfileService.GetUserProfile().Where(a => a.UserID == Convert.ToInt32(bizRepmaster.LastUpdatedBy)).Single().LoginId;
}
if (bizRepmaster.LastApprovedBy != null)
{
ViewBag.LastApprovedName = _userProfileService.GetUserProfile().Where(a => a.UserID == Convert.ToInt32(bizRepmaster.LastApprovedBy)).Single().LoginId;
}
ViewBag.SenderId1 = bizRepmaster.SenderId;
return View("_BizRepDetails", bizRepmaster);
}
catch (Exception ex)
{
return PartialView("_ErrorMessageView");
}
}

Method if condition logic

This logic checks accessGroup and if accessGroup is equal to "Admin" then it only checks if result.Admin or baccess is true but if accessGroup is anything else it will need to check two other objects result.Admin == true || result.PowerUser.
Is there any other way to do this if condition?
if (accessGroup == "Admin")
{
if (baccess == true || result.Admin == true)
{
var FileInfo = GetFile(fileManagerGuidId);
if (FileInfo != null)
{
FileManagerLog _filemanagerLog = new FileManagerLog();
_filemanagerLog.CustomerId =Request.Cookies["customerid"] != null ? Convert.ToInt32(Request.Cookies["customerid"].Value) : 0;
_filemanagerLog.FileManagerGuid = new Guid(fileManagerGuidId);
SaveFileManagerLog(_filemanagerLog);
byte[] fileBytes = FileInfo.FileData;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, FileInfo.FileName);
}
else
{
return null;
}
}
}
else
{
if (baccess == true || result.Admin == true || result.PowerUser)
{
var FileInfo = GetFile(fileManagerGuidId);
if (FileInfo != null)
{
FileManagerLog _filemanagerLog = new FileManagerLog();
_filemanagerLog.CustomerId =Request.Cookies["customerid"] != null ? Convert.ToInt32(Request.Cookies["customerid"].Value) : 0;
_filemanagerLog.FileManagerGuid = new Guid(fileManagerGuidId);
SaveFileManagerLog(_filemanagerLog);
byte[] fileBytes = FileInfo.FileData;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, FileInfo.FileName);
}
else
{
return null;
}
}
}
Using Enum flags is really great in ur case,
create an enum with
admin = 1
poweruser = 2
normaluser = 4
and check on the result you have
"== true" is useless, writing the boolean itself is enough
if (baccess|| result.Admin || result.PowerUser)
second solution :
if powerUse is only for normal user, you can use Or state
Boolean allowed = false;
if (baccess || result.Admin)
{
if (accessGroup == "Admin")
{
allowed = true;
}
else
{
allowed =result.PowerUser
}
}
if(allowed)
{
var FileInfo = GetFile(fileManagerGuidId);
if (FileInfo == null)
{
FileManagerLog _filemanagerLog = new FileManagerLog();
_filemanagerLog.CustomerId =Request.Cookies["customerid"] != null ? Convert.ToInt32(Request.Cookies["customerid"].Value) : 0;
_filemanagerLog.FileManagerGuid = new Guid(fileManagerGuidId);
SaveFileManagerLog(_filemanagerLog);
byte[] fileBytes = FileInfo.FileData;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, FileInfo.FileName);
}
else
{
return null;
}
}
There are lots of ways to do this some better than others
however looking at the logic i think you can drop most of it
as you are ORing all the fields then
if they have bacess the code runs regardless of anything else
if they
have result.Admin the code runs regardless of anything else
if they
have accessGroup == "Admin" the code runs regardless of anything else
if they have result.PowerUser the code runs regardless of anything
else
the only way this code wont run is if !baccess & !result.Admin & !result.PowerUser & accessGroup != "Admin"
so this is exactly the same
if (baccess || result.Admin || (accessGroup != "Admin" && Result.PowerUser))
{
var FileInfo = GetFile(fileManagerGuidId);
if (FileInfo != null)
{
FileManagerLog _filemanagerLog = new FileManagerLog();
_filemanagerLog.CustomerId =Request.Cookies["customerid"] != null ? Convert.ToInt32(Request.Cookies["customerid"].Value) : 0;
_filemanagerLog.FileManagerGuid = new Guid(fileManagerGuidId);
SaveFileManagerLog(_filemanagerLog);
byte[] fileBytes = FileInfo.FileData;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, FileInfo.FileName);
}
else
{
return null;
}
}
though i suspect you actually wanting to AND (&&) the fields together
which would look like
if (baccess && (result.Admin || (accessGroup != "Admin" && result.PowerUser))
ie if they have access and are an admin or a poweruser

getting error while fetching fields from Dynamics CRM(Online Sales) from different server location

I am trying to fetch all account entity fields from an organization.(https://democrm365.crm4.dynamics.com).
Also, I created some custom fields in account and added into form. After that when I run the following code I am getting all fields related to account.
IOrganizationService service = (IOrganizationService)serviceProxy;
RetrieveEntityRequest request = new RetrieveEntityRequest()
{
EntityFilters = EntityFilters.Attributes,
RetrieveAsIfPublished = false,
LogicalName = "account"
};
RetrieveEntityResponse res = (RetrieveEntityResponse)service.Execute(request);
EntityMetadata currentEntity = res.EntityMetadata;
foreach (AttributeMetadata attribute in currentEntity.Attributes)
{
if (attribute.DisplayName.UserLocalizedLabel != null && attribute.AttributeType != null && attribute.LogicalName != "" && attribute.AttributeType != null && attribute.IsValidForRead.Value == true)
{
if (_allowedFieldTypes.Contains(attribute.AttributeType.ToString().ToLower()))
{
EntityField ef = new EntityField();
ef.AttributeType = attribute.AttributeType.ToString() ?? "";
ef.DisplayName = attribute.DisplayName.UserLocalizedLabel.Label;
ef.IsCustomField = attribute.IsCustomAttribute ?? false;
ef.IsAllowUpdate = attribute.IsValidForUpdate ?? false;
ef.LogicalName = attribute.LogicalName;
if (attribute.AttributeType.ToString().ToLower() == "picklist")
{
PicklistAttributeMetadata pm = (PicklistAttributeMetadata)attribute;
foreach (OptionMetadata x in pm.OptionSet.Options)
{
ef.Items.Add(x.Label.UserLocalizedLabel.Label);
}
}
else if (attribute.AttributeType.ToString().ToLower() == "virtual")
{
if (attribute.AttributeTypeName.Value == "MultiSelectPicklistType")
{
MultiSelectPicklistAttributeMetadata pm = (MultiSelectPicklistAttributeMetadata)attribute;
foreach (OptionMetadata x in pm.OptionSet.Options)
{
ef.Items.Add(x.Label.UserLocalizedLabel.Label);
}
}
}
if (Add)
{
fieldLst.Add(ef);
}
}
}
}
Again, I tested the same code on different organization (https://zoho5.crm.dynamics.com) with all above mentioned steps, then
below code is not working.
if (attribute.DisplayName.UserLocalizedLabel != null && attribute.AttributeType != null && attribute.LogicalName != "" && attribute.AttributeType != null && attribute.IsValidForRead.Value == true)
attribute.DisplayName.UserLocalizedLabel is null for all fields like (Account Name, Account No. Etc)
After some test runs, I removed the custom fields from account form and publish form. Then the above code is working fine.
Try this. You may have to get the label from LocalizedLabels when UserLocalizedLabel is null.
foreach (AttributeMetadata attribute in currentEntity.Attributes)
{
if (attribute.AttributeType != null && attribute.LogicalName != "" && attribute.AttributeType != null && attribute.IsValidForRead.Value == true)
{
string attributeName = attribute.LogicalName;
if (attribute.DisplayName.UserLocalizedLabel != null)
{
attributeName = attribute.DisplayName.UserLocalizedLabel.Label;
}
if (attributeName == attribute.LogicalName && attribute.DisplayName.LocalizedLabels.Count > 0)
{
attributeName = attribute.DisplayName.LocalizedLabels[0].Label;
}
}
}

How validate many fields in code behind?

I have a signup page that have many filed. Many of them should filled by user.
I use RequiredFieldValidator and RegularExpressionValidator for validate in client side.
Should I validate them in server side? How?
I wrote this code. I use many if and else if. Is this correct?
CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
if (CaptchaControl1.UserValidated)
{
if (txtFName.Text != string.Empty && txtLName.Text != string.Empty && txtUserName.Text != string.Empty && txtEmail.Text != string.Empty && txtPass.Text != string.Empty && txtCPass.Text != string.Empty && txtSecureImg.Text != string.Empty)
{
if (RegEx.EmailValidate(txtEmail.Text) == 1 && RegEx.PasswordValidate(txtPass.Text) == 1 && RegEx.UserName(txtUserName.Text) == 1)
{
try
{
// insert in database
}
catch (Exception)
{
lblMsg.Text = "Error";
}
}
else if(RegEx.EmailValidate(txtEmail.Text) == 0)
{
EmailRegularExpression.Visible = true;
}
else if(RegEx.PasswordValidate(txtPass.Text) == 0)
{
passRegularExpression.Visible = true;
}
else if(RegEx.UserName(txtUserName.Text) == 0)
{
UnameRegularExpression.Visible = true;
}
}
else if(txtFName.Text == string.Empty)
{
RequiredFieldValidator1.Visible = true;
}
// continue like above for another filed
}
else
{
lblMsg.Text = "Please insert Secure Image";
}
And :
public static int EmailValidate(string Mail)
{
int i = 0;
Regex regExEmail = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (regExEmail.IsMatch(Mail))
i = 1;
return i;
}
I'm assuming this is Web Forms...
The validation is run automatically. You can just use the Page.IsValid property: msdn
You'll still need to manually check the captcha field though.
CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
if (CaptchaControl1.UserValidated && Page.IsValid)
{
// Insert in db.
}
Since you use those validators, then you don't need to validate form in server side again like your codes.
But you should call Page.Validate()and then check page with Page.IsValid method.
from here
example

savechanges() saving one entity and not other

A weird situation has struck me this code was running successfully two days back, but i dont know why its not running as before now :
public static void ChangeStatus(int sessionID, int? participantID, Guid? temporaryParticipantID, int statustypeID)
{
using (EMSEntities entities = new EMSEntities())
using (TransactionScope ts = new TransactionScope())
{
try
{
SessionParticipant sessionParticipant = null;
CurrentSessionSeatsStatu sessionCurrentStatus = null;
if (participantID != null)
{
sessionParticipant = entities.SessionParticipants
.Where(a => a.SessionID == sessionID && a.ParticipantID == participantID)
.FirstOrDefault();
}
else if (temporaryParticipantID != null)
{
sessionParticipant = entities.SessionParticipants
.Where(a => a.SessionID == sessionID && a.TemporaryParticipantID == temporaryParticipantID)
.FirstOrDefault();
}
if (sessionParticipant != null)
{
sessionParticipant.StatusTypeID = statustypeID; // Status Changed here
}
**if (sessionParticipant.StatusTypeID == 2) // verified status
{
sessionCurrentStatus = entities.CurrentSessionSeatsStatus
.Where(a => a.SessionID == sessionID)
.FirstOrDefault();
if (sessionCurrentStatus.SeatsLeft > 0)
{
sessionCurrentStatus.SeatsLeft = sessionCurrentStatus.SeatsLeft - 1;
}
}**
entities.SaveChanges();
ts.Complete();
}
catch (Exception ex)
{
ts.Dispose();
}
}
}
The problem is that changes(in StatusTypeID) for sessionParticipant are not saved in database but sessionCurrentStatus changes are !
no error thrown nothing !
Edit: I have discovered that the change in sessionparticipant is happening in all cases except when the status is changed to verified.
ie. when the other table viz. sessioncurrentstatus is updated in the if block.
That is whenever it goes in this if block(bold in code) the problem takes place.
Finally i found the problem and i think its because of the below code however it would be good if someone can explain the exact reason:
EMS.DAL.DALHelper.AttachAndSaveChanges(sessionParticipant, System.Data.EntityState.Modified); // the position of this code line can be found in the below code
below is the code which called the ChangesStatus method:
protected void ddlStatuses_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < gridViewEvents.VisibleRowCount; i++)
{
if (gridViewEvents.Selection.IsRowSelected(i))
{
EMS.DAL.SessionParticipant sessionParticipant = (EMS.DAL.SessionParticipant)gridViewEvents.GetRow(i);
EMS.DAL.Session session = EMS.DAL.DALHelper.GetSessionById(sessionParticipant.SessionID);
EMS.DAL.DALHelper.ChangeStatus(sessionParticipant.SessionID, sessionParticipant.ParticipantID, sessionParticipant.TemporaryParticipantID, Convert.ToInt32(ddlStatuses.SelectedItem.Value));
if (ddlStatuses.SelectedItem.Value == "2" || ddlStatuses.SelectedItem.Value == "3") // if accepted or rejected
{
if (ddlStatuses.SelectedItem.Value == "2") // verified/accepted
{
EMS.DAL.DALHelper.SendMail("Congratulations! your participation for " + session.Name + " event has been confirmed.", "", sessionParticipant.Email, "");
// AT THIS POINT THE 'sessionParticipant' did not have the changed status which was set in the ChangeStatus method
sessionParticipant.IsNotified = true;
EMS.DAL.DALHelper.AttachAndSaveChanges(sessionParticipant, System.Data.EntityState.Modified); // culprit as per me
List<EMS.DAL.SessionAttendanceList> attendanceList = EMS.DAL.DALHelper.GetSessionAttendanceList(session.ID);
attendanceList.ForEach(a =>
{
EMS.DAL.AttendanceListDetail attendanceListDetail = a.AttendanceListDetails.Where(p => p.ParticipantID == sessionParticipant.ParticipantID).FirstOrDefault();
if (attendanceListDetail == null)
{
attendanceListDetail.AttendanceListID = a.ID;
attendanceListDetail.ParticipantID = sessionParticipant.ParticipantID.Value;
attendanceListDetail.IsPresent = false;
EMS.DAL.DALHelper.AttachAndSaveChanges(attendanceListDetail, System.Data.EntityState.Added);
}
});
}
else if (ddlStatuses.SelectedItem.Value == "3") // denied/rejected
{
EMS.DAL.DALHelper.SendMail("Your participation for " + session.Name + " event has been denied.", "", sessionParticipant.Email, "");
sessionParticipant.IsNotified = true;
EMS.DAL.DALHelper.AttachAndSaveChanges(sessionParticipant, System.Data.EntityState.Modified);
List<EMS.DAL.SessionAttendanceList> attendanceList = EMS.DAL.DALHelper.GetSessionAttendanceList(session.ID);
attendanceList.ForEach(a =>
{
EMS.DAL.AttendanceListDetail attendanceListDetail = a.AttendanceListDetails.Where(p => p.ParticipantID == sessionParticipant.ParticipantID).FirstOrDefault();
if (attendanceListDetail != null)
{
EMS.DAL.DALHelper.AttachAndSaveChanges(attendanceListDetail, System.Data.EntityState.Deleted);
}
});
}
}
else
{
List<EMS.DAL.SessionAttendanceList> attendanceList = EMS.DAL.DALHelper.GetSessionAttendanceList(session.ID);
attendanceList.ForEach(a =>
{
EMS.DAL.AttendanceListDetail attendanceListDetail = a.AttendanceListDetails.Where(p => p.ParticipantID == sessionParticipant.ParticipantID).FirstOrDefault();
if (attendanceListDetail != null)
{
EMS.DAL.DALHelper.DeleteAttendanceListDetail(attendanceListDetail);
}
});
attendanceList.ForEach(a =>
{
EMS.DAL.DALHelper.DeleteSessionAttendanceList(a);
});
}
}
}
gridViewEvents.DataBind();
RefreshSeats();
}

Categories

Resources