update entity in DDD with EFCore 3 - c#

i have senario for change Active Status property use . IsActive .
i have problem with update entity in asp core and DomainDriven Desogn .
when i change the IsActive to True or False it create a new record inctance a update that recoed .
i put here my code :
Step One :
this is my controller , in this controller i call the Command :
public async Task<ApiReturn> ChangeUserActiveStatus(long id)
{
var result = await dispatchers.SendAsync(new UserActiveStateCommand { id = id });
if(result.Success)
{
return Ok();
}
return BadRequest(result.Exception);
}
step Two :
i send a request to the database and give The desired record :
public class UserActiveStateCommandHandler : ICommandHandler<UserActiveStateCommand, OperationResult<string>>, IScopedDepency
{
private readonly IDomainUnitOfWork unitOfWork;
private readonly IDispatchers dispatchers;
public UserActiveStateCommandHandler(IDomainUnitOfWork unitOfWork, IDispatchers dispatchers)
{
this.unitOfWork = unitOfWork;
this.dispatchers = dispatchers;
}
public async Task<OperationResult<string>> HandlerAsync(UserActiveStateCommand command)
{
var user = await dispatchers.QueryAsync(new GetUserByIdQuery { id = command.id });
if (user != null)
{
var u = new User();
var value = u.SetUser(user.Result.Id, user.Result.Email, user.Result.LastName, user.Result.Photo, user.Result.FirstName, user.Result.UserName, user.Result.PhoneNumber, !user.Result.IsActive);
await dispatchers.CallEvent(new UserActiveStateEvent { User = value });
return OperationResult<string>.BuildSuccessResult("success");
}
else
{
return OperationResult<string>.BuildFailure("fail");
}
}
}
}
this is that recoed and its correct :
"email": "kiadr9372#gmail.com",
"photo": null,
"lastName": "Dortaj",
"firstName": "Kianoush",
"userName": "kia9372",
"phoneNumber": "09159810616",
"securityStamp": "e7cd82a5-71f3-41a1-b239-4d705b6d5d35",
"isActive": false,
"phoneConfirm": false,
"emailConfirm": false,
"isLockOut": false,
"lockOutEnd": null,
"isFailurAccount": 0,
"userRoles": null,
"id": 1
step there :
i call Event for Update Record in database :
public class UserActiveStatusEventHandler : IEventHandler<UserActiveStateEvent> , IScopedDepency
{
private readonly IDomainUnitOfWork unitOfWork;
public UserActiveStatusEventHandler(IDomainUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
public async Task HandelEventAsync(UserActiveStateEvent #event)
{
var state = await unitOfWork.UserRepository.UpdateUser(#event.User);
if (state.Success)
{
unitOfWork.Commit();
}
}
}
this is the update code in repository :
public async Task<OperationResult<bool>> UpdateUser(User user)
{
if (user != null)
{
try
{
context.Update(user);
return OperationResult<bool>.BuildSuccessResult(true);
}
catch (Exception ex)
{
return OperationResult<bool>.BuildFailure(ex);
}
}
return OperationResult<bool>.BuildFailure("user Cannot be null");
}
and this is the commit code :
public void Commit()
{
context.SaveChanges();
}
this is User Aggregate :
public class User : AggregrateRoot, IAggregate
{
#region Backing Field
private string _email;
private string _photo;
private string _userName;
private string _phoneNumber;
private string _firstName;
private string _lastName;
private Guid _securityStamp;
private bool _isActive;
private bool _phoneConfirm;
private bool _emailConfirm;
private bool _isLockOut;
private DateTimeOffset? _lockOutEnd;
private int _isFailurAccount;
#endregion
#region Properies
public string Email
{
get
{
return _email;
}
private set
{
_email = value;
SetNotification();
}
}
public string Photo
{
get
{
return _photo;
}
set
{
_photo = value;
SetNotification();
}
}
public string LastName
{
get
{
return _lastName;
}
private set
{
_lastName = value;
SetNotification();
}
}
public string FirstName
{
get
{
return _firstName;
}
private set
{
_firstName = value;
SetNotification();
}
}
public string UserName
{
get
{
return _userName;
}
private set
{
_userName = value;
SetNotification();
}
}
public string PhoneNumber
{
get
{
return _phoneNumber;
}
private set
{
_phoneNumber = value;
SetNotification();
}
}
public Guid SecurityStamp
{
get
{
return _securityStamp;
}
private set
{
_securityStamp = value;
SetNotification();
}
}
public bool IsActive
{
get
{
return _isActive;
}
private set
{
_isActive = value;
SetNotification();
}
}
public bool PhoneConfirm
{
get
{
return _phoneConfirm;
}
private set
{
_phoneConfirm = value;
SetNotification();
}
}
public bool EmailConfirm
{
get
{
return _emailConfirm;
}
private set
{
_emailConfirm = value;
SetNotification();
}
}
public bool IsLockOut
{
get
{
return _isLockOut;
}
private set
{
_isLockOut = value;
SetNotification();
}
}
public DateTimeOffset? LockOutEnd
{
get
{
return _lockOutEnd;
}
private set
{
_lockOutEnd = value;
SetNotification();
}
}
public int IsFailurAccount
{
get
{
return _isFailurAccount;
}
private set
{
_isFailurAccount = value;
SetNotification();
}
}
public ICollection<UserRole> UserRoles { get; set; }
#endregion
public User()
{
}
#region Private Constructor
private User(long id,string Email, string LastName, string photo, string FirstName, string UserName, string PhoneNumber, bool isActive)
{
this.Email = Email;
this.Photo = photo;
this.LastName = LastName;
this.FirstName = FirstName;
this.UserName = UserName;
this.PhoneNumber = PhoneNumber;
this.SecurityStamp = Guid.NewGuid();
this.IsActive = isActive;
this.PhoneConfirm = false;
this.EmailConfirm = false;
this.IsLockOut = false;
this.LockOutEnd = null;
this.IsFailurAccount = 0;
}
#endregion
#region Methonds
public User SetUser(string email, string lastName, string photo, string firstName, string userName, string phoneNumber, bool isActive = false)
{
var user = new User(email, lastName, firstName, photo, userName, phoneNumber, isActive);
return user;
}
public UserRole AddUserRole(long userId, long roleId)
{
return new UserRole().AddUserRole(userId, roleId);
}
#endregion
}
but problem is here : i create a new recoed in datebase but i need update that recoed . how can i solve this problem ???

I guess your problem occurs in UserActiveStateCommandHandler class.
You're fetching User from DB which should be tracked by EF by default.
Later you're creating new User object instance and provide changes on new object which is not recognized by EF as existing one.
You should update data directly on object returned from your query...

Related

How to pass Bound properties as parameters without manual setup

Here is my App.xaml.cs
protected override Task OnInitializeAsync(IActivatedEventArgs args) {
Container.RegisterInstance(SessionStateService);
Container.RegisterInstance(NavigationService);
Container.RegisterType<IUserRepository, UserRespository>(new ContainerControlledLifetimeManager());
Container.RegisterType<UserSettingsContext>(new ContainerControlledLifetimeManager());
Container.RegisterType<IUserSettings, UserSettings>(new ContainerControlledLifetimeManager());
var userSettings = this.Container.Resolve<UserSettingsContext>();
userSettings.Database.EnsureCreated();
return base.OnInitializeAsync(args);
}
This is my UserSettings
using using Prism.Windows.Validation;
public class UserSettings : ValidatableBindableBase, IUserSettings {
private string _firstName;
public string FirstName {
get { return _firstName; }
set { SetProperty(ref _firstName, value); }
}
private string _lastName;
public string LastName {
get { return _lastName; }
set { SetProperty(ref _lastName, value); }
}
private UserType _userType;
public UserType UserType {
get { return _userType; }
set { SetProperty(ref _userType, value); }
}
private string _username;
[Required(ErrorMessage = "Required.")]
public string Username {
get { return _username; }
set { SetProperty(ref _username, value); }
}
private string _password;
[Required(ErrorMessage = "Required.")]
public string Password {
get { return _password; }
set { SetProperty(ref _password, value); }
}
}
ViewModel:
public class TestViewModel : UserSettings {
private UserSettings user;
public UserSettings User => user;
public async void SaveSettings() {
//It will work with this line
// var user = new UserSettings() {
// Username= this.Username,
// Password= this.Password,
// UserType= this.UserType,
// FirstName= this.FirstName,
// LastName= this.LastName
// };
//null properties
await loginService.SaveUserSettings(user);
}
}
When I tried to pass the 'user' the properties are null ,even user input data from UI(View), It will work if I setup the UserSettings using the code above, but I want to simplify this without that, how can I do that?
Thanks
You want to write await loginService.SaveUserSettings(this); because this seems to be the target that's filled with data.

C# LINQ to SQL Invalid Object Name

public class AMCOMDB : DataContext
{
public Table<student> allStudents;
public Table<aClass> allClasses;
public AMCOMDB(string connection) : base(connection) { }
}
[Table(Name = "student")]
public class student
{
private string _studentName;
[Column(IsPrimaryKey =true,Storage ="_studentName")]
public string studentName
{
get { return this._studentName; }
set { this._studentName = value; }
}
private string _LARType;
[Column(Storage ="_LARType")]
public string LARType
{
get { return this._LARType; }
set { this._LARType = value; }
}
private string _studentType;
[Column(Storage = "_studentType")]
public string studentType
{
get { return this._studentType; }
set { this._studentType = value; }
}
private string _aviationLevel;
[Column(Storage = "_aviationLevel")]
public string aviationLevel
{
get { return this._aviationLevel; }
set { this._aviationLevel = value; }
}
private string _airDefenseLevel;
[Column(Storage = "_airDefenseLevel")]
public string airDefenseLevel
{
get
{
return this._airDefenseLevel;
}
set
{
this._airDefenseLevel = value;
}
}
private string _emergencyContact;
[Column(Storage = "_emergencyContact")]
public string emergencyContact
{
get
{
return this._emergencyContact;
}
set
{
this._emergencyContact = value;
}
}
[Table(Name = "grades")]
public class grades
{
private string _studentName;
[Column(IsPrimaryKey = true, Storage = "_studentName")]
public string studentName
{
get
{
return this._studentName;
}
set
{
this._studentName = value;
}
}
private int _ET;
[Column(Storage = "_ET")]
public int ET
{
get
{
return this._ET;
}
set
{
this._ET = value;
}
}
private int _CP;
[Column(Storage = "_CP")]
public int CP
{
get
{
return this._CP;
}
set
{
this._CP = value;
}
}
private int _SB;
[Column(Storage = "_SB")]
public int SB
{
get
{
return this._SB;
}
set
{
this._SB = value;
}
}
private int _EC;
[Column(Storage = "_EC")]
public int EC
{
get
{
return this._EC;
}
set
{
this._EC = value;
}
}
private int _finalGrade;
[Column(Storage = "_finalGrade")]
public int finalGrade
{
get
{
return this._finalGrade;
}
set
{
this._finalGrade = value;
}
}
}
[Table(Name = "classes")]
public class aClass
{
private string _classNumber;
[Column(IsPrimaryKey = true, Storage = "_classNumber")]
public string classNumber
{
get
{
return this._classNumber;
}
set
{
this._classNumber = value;
}
}
private string _courseSeries;
[Column(Storage = "_courseSeries")]
public string courseSeries
{
get
{
return this._courseSeries;
}
set
{
this._courseSeries = value;
}
}
private string _courseNumber;
[Column(Storage = "_courseNumber")]
public string courseNumber
{
get
{
return this._courseNumber;
}
set
{
this._courseNumber = value;
}
}
private string _distanceLearning;
[Column(Storage = "_distanceLearning")]
public string distanceLearning
{
get
{
return this._distanceLearning;
}
set
{
this._distanceLearning = value;
}
}
private string _classStartDate;
[Column(Storage = "_classStartDate")]
public string classStartDate
{
get
{
return this._classStartDate;
}
set
{
this._classStartDate = value;
}
}
private string _classEndDate;
[Column(Storage = "_classEndDate")]
public string classEndDate
{
get
{
return this._classEndDate;
}
set
{
this._classEndDate = value;
}
}
private string _primaryInstructor;
[Column(Storage = "_primaryInstructor")]
public string primaryInstructor
{
get
{
return this._primaryInstructor;
}
set
{
this._primaryInstructor = value;
}
}
private string _secondaryInstructor;
[Column(Storage = "_secondaryInstructor")]
public string secondaryInstructor
{
get
{
return this._secondaryInstructor;
}
set
{
this._secondaryInstructor = value;
}
}
private string _location;
[Column(Storage = "_location")]
public string location
{
get
{
return this._location;
}
set
{
this._location = value;
}
}
private string _TDYCosts;
[Column(Storage = "_TDYCosts")]
public string TDYCosts
{
get
{
return this._TDYCosts;
}
set
{
this._TDYCosts = value;
}
}
private string _studentCount;
[Column(Storage = "_studentCount")]
public string studentCount
{
get
{
return this._studentCount;
}
set
{
this._studentCount = value;
}
}
private List<grades> _classGrades;
[Column(Storage = "_classGrades")]
public List<grades> classGrades
{
get
{
return this._classGrades;
}
set
{
this._classGrades = value;
}
}
AMCOMDB ADB = new AMCOMDB(connectionString);
if (ADB.DatabaseExists())
{
var stud = ADB.GetTable<student>();
var clas = ADB.GetTable<aClass>();
IQueryable<string> query = from c in stud
where c.studentName.Length > 5
orderby c.studentName.Length
select c.studentName.ToUpper();
foreach (string name in query)
{
}
//var q = from a in ADB.GetTable<student>()
// select a;
//dtStudents = LinqQuerytoDataTable(q);
//var q1 = from a in ADB.GetTable<aClass>()
// select a;
//aClass c = new aClass();
//dtClasses = reformatDataTable(q1);
}
I receive the following when I try to get information from the database at (foreach (string name in query))
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid object name 'student'.
I also get this when I first create the database:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.Linq.dll
Additional information: Unable to determine SQL type for 'System.Collections.Generic.List`1[WindowsFormsApplication1.Form1+grades]'.
remove the word Name that is what worked for me
[Table("student")]
public class student

Json data deserialzation returning null value for a property

private static int DefaultApiClientTimeout = 30;
public WorkItemDetail GetWorkItemDetail(
int userNumber, int userNumberExternal, string applicationId,
short computerNumber, DateTime wiDate, int wiSequence,
int wiDetailSequence, bool includeImage)
{
string uri = string.Format("api/work-item-detail?userNumber={0}&userNumberExternal={1}&applicationId={2}&computerNumber={3}&wiDate={4}&wiSequence={5}&wiDetailSequence={6}&includeImage={7}", userNumber, userNumberExternal, applicationId, computerNumber, wiDate, wiSequence, wiDetailSequence, includeImage);
WorkItemDetail result = ProcessRequest<object, WorkItemDetail>(uri, "GET", null);
return result;
}
public ResponseType ProcessRequest<RequestType, ResponseType>(
string uri,
string method = "GET",
RequestType reqtype = default(RequestType))
where RequestType : new()
{
var result = ProcessRequest<RequestType>(uri, method, reqtype);
return JsonConvert.DeserializeObject<ResponseType>(result);
}
public string ProcessRequest<RequestType>(
string uri,
string method = "GET",
RequestType reqtype = default(RequestType))
where RequestType : new()
{
var request = CreateWebRequest(uri, method);
var x = (HttpWebResponse)request.GetResponse(); //the exception :(
var strResult = new StreamReader(x.GetResponseStream()).ReadToEnd();
return strResult;
}
public WebRequest CreateWebRequest(string uri, string method = "GET")
{
string url = "http://localhost:3144/" + uri;
var request = WebRequest.Create(url);
request.ContentType = "application/json; charset=utf-8";
request.Method = method;
//Convert minutes to milliseconds.
request.Timeout = DefaultApiClientTimeout * 60000;
return request;
}
above is my entire code.
I have a problem in deserialzing jsondata. from my web api method data is returning correctly but when coming to client result i.e., above code while deserializing jsondata ImageInBytes property is getting null.
[Serializable]
public class WorkItemDetail : IWorkItemKey
{
private byte[] thumbnailImage;
private byte[] image;
private short wiDetailSequence;
private string workItemDetailType;
private int networkShare;
private string networkSharePath;
private string filePath;
private string displayImageFileName;
private string imagePath;
private DateTime workItemDate;
private string documentOcr;
#region Work Item Members
/// <summary>
/// This will actually be a ShortDate from the database
/// </summary>
public DateTime WorkItemDate
{
get { return workItemDate; }
set { workItemDate = value; }
}
private int wiSequence;
public int WISequence
{
get { return wiSequence; }
set { wiSequence = value; }
}
public short WIDetailSequence
{
get { return wiDetailSequence; }
set { wiDetailSequence = value; }
}
private short _otherSideWIDetailSequence;
public short OtherSideWIDetailSequence
{
get { return _otherSideWIDetailSequence; }
set { _otherSideWIDetailSequence = value; }
}
private string sourceType;
public string SourceType
{
get { return sourceType; }
set { sourceType = value; }
}
private string sourceIdentifier;
public string SourceIdentifier
{
get { return sourceIdentifier; }
set { sourceIdentifier = value; }
}
#endregion
private int _reason;
public int Reason
{
get { return _reason; }
set { _reason = value; }
}
private short _computerNumber;
public short ComputerNumber
{
get { return _computerNumber; }
set { _computerNumber = value; }
}
private string _computerName;
public string ComputerName
{
get { return _computerName; }
set { _computerName = value; }
}
private DateTime? _WIDateDest;
public DateTime? WIDateDest
{
get { return _WIDateDest; }
set { _WIDateDest = value; }
}
private int? _WISequenceDest;
public int? WISequenceDest
{
get { return _WISequenceDest; }
set { _WISequenceDest = value; }
}
private short? _WIDetailSequenceDest;
public short? WIDetailSequenceDest
{
get { return _WIDetailSequenceDest; }
set { _WIDetailSequenceDest = value; }
}
private short? _OtherSideWIDetailSequenceDest;
public short? OtherSideWIDetailSequenceDest
{
get { return _OtherSideWIDetailSequenceDest; }
set { _OtherSideWIDetailSequenceDest = value; }
}
public string WorkItemDetailType
{
get { return workItemDetailType; }
set { workItemDetailType = value; }
}
public int NetworkShare
{
get { return networkShare; }
set { networkShare = value; }
}
public string NetworkSharePath
{
get { return networkSharePath; }
set { networkSharePath = value; }
}
public string FilePath
{
get { return filePath; }
set { filePath = value; }
}
public string DisplayImageFileName
{
get { return displayImageFileName; }
set { displayImageFileName = value; }
}
public string ImagePath
{
get { return imagePath; }
set { imagePath = value; }
}
public byte[] ImageInBytes
{
get { return image; }
set { image = value; }
}
public byte[] ThumbnailImage
{
get { return thumbnailImage; }
set { thumbnailImage = value; }
}
private string ocrData;
public string OCRData
{
get { return ocrData; }
set { ocrData = value; }
}
private string _userName;
public string UserName
{
get { return _userName; }
set { _userName = value; }
}
private bool? _isCorrespondence;
public bool? IsCorrespondence
{
get { return _isCorrespondence; }
set { _isCorrespondence = value; }
}
private bool? isCorrespondenceDBValue;
public bool? IsCorrespondenceDBValue
{
get { return isCorrespondenceDBValue; }
set { isCorrespondenceDBValue = value; }
}
private Guid? wfInstanceId;
public Guid? WFInstanceId
{
get { return wfInstanceId; }
set { wfInstanceId = value; }
}
private DateTime _transactionTime;
public DateTime TransactionTime
{
get { return _transactionTime; }
set { _transactionTime = value; }
}
private DateTime _endTime;
public DateTime EndTime
{
get { return _endTime; }
set { _endTime = value; }
}
private string _transactionType;
public string TransactionType
{
get { return _transactionType; }
set { _transactionType = value; }
}
private string _applicationId;
public string ApplicationId
{
get { return _applicationId; }
set { _applicationId = value; }
}
private string _applicationName;
public string ApplicationName
{
get { return _applicationName; }
set { _applicationName = value; }
}
private bool isFront;
public bool IsFront
{
get { return isFront; }
set { isFront = value; }
}
private int _userNumber;
public int UserNumber
{
get { return _userNumber; }
set { _userNumber = value; }
}
private string barcode1;
public string BarCode1
{
get { return barcode1; }
set { barcode1 = value; }
}
private string barcode2;
public string BarCode2
{
get { return barcode2; }
set { barcode2 = value; }
}
private string barcode3;
public string BarCode3
{
get { return barcode3; }
set { barcode3 = value; }
}
private string barcode4;
public string BarCode4
{
get { return barcode4; }
set { barcode4 = value; }
}
private string barcode5;
public string BarCode5
{
get { return barcode5; }
set { barcode5 = value; }
}
private bool? markSense1;
public bool? MarkSense1
{
get { return markSense1; }
set { markSense1 = value; }
}
private bool? markSense2;
public bool? MarkSense2
{
get { return markSense2; }
set { markSense2 = value; }
}
private bool? markSense3;
public bool? MarkSense3
{
get { return markSense3; }
set { markSense3 = value; }
}
private bool? markSense4;
public bool? MarkSense4
{
get { return markSense4; }
set { markSense4 = value; }
}
private bool? markSense5;
public bool? MarkSense5
{
get { return markSense5; }
set { markSense5 = value; }
}
private bool? markSense6;
public bool? MarkSense6
{
get { return markSense6; }
set { markSense6 = value; }
}
private bool? markSense7;
public bool? MarkSense7
{
get { return markSense7; }
set { markSense7 = value; }
}
private bool? markSense8;
public bool? MarkSense8
{
get { return markSense8; }
set { markSense8 = value; }
}
private bool? markSense9;
public bool? MarkSense9
{
get { return markSense9; }
set { markSense9 = value; }
}
private bool? markSense10;
public bool? MarkSense10
{
get { return markSense10; }
set { markSense10 = value; }
}
private string data;
public string Data
{
get { return data; }
set { data = value; }
}
private string auditTrail;
public string AuditTrail
{
get { return auditTrail; }
set { auditTrail = value; }
}
private short? displayImageHorizontalPixels;
public short? DisplayImageHorizontalPixels
{
get { return displayImageHorizontalPixels; }
set { displayImageHorizontalPixels = value; }
}
private short? displayImageVerticalPixels;
public short? DisplayImageVerticalPixels
{
get { return displayImageVerticalPixels; }
set { displayImageVerticalPixels = value; }
}
private short? displayImageHorizontalResolution;
public short? DisplayImageHorizontalResolution
{
get { return displayImageHorizontalResolution; }
set { displayImageHorizontalResolution = value; }
}
private short? displayImageVerticalResolution;
public short? DisplayImageVerticalResolution
{
get { return displayImageVerticalResolution; }
set { displayImageVerticalResolution = value; }
}
private byte? displayImageColorDepth;
public byte? DisplayImageColorDepth
{
get { return displayImageColorDepth; }
set { displayImageColorDepth = value; }
}
private int displayImageBytes;
public int DisplayImageBytes
{
get { return displayImageBytes; }
set { displayImageBytes = value; }
}
private byte[] displayImageMD5Hash;
public byte[] DisplayImageMD5Hash
{
get { return displayImageMD5Hash; }
set { displayImageMD5Hash = value; }
}
private string iclImageFileName;
public string ICLImageFileName
{
get { return iclImageFileName; }
set { iclImageFileName = value; }
}
private short? iCLImageHorizontalPixels;
public short? ICLImageHorizontalPixels
{
get { return iCLImageHorizontalPixels; }
set { iCLImageHorizontalPixels = value; }
}
private short? iCLImageVerticalPixels;
public short? ICLImageVerticalPixels
{
get { return iCLImageVerticalPixels; }
set { iCLImageVerticalPixels = value; }
}
private short? iCLImageHorizontalResolution;
public short? ICLImageHorizontalResolution
{
get { return iCLImageHorizontalResolution; }
set { iCLImageHorizontalResolution = value; }
}
private short? iCLImageVerticalResolution;
public short? ICLImageVerticalResolution
{
get { return iCLImageVerticalResolution; }
set { iCLImageVerticalResolution = value; }
}
private byte? iCLImageColorDepth;
public byte? ICLImageColorDepth
{
get { return iCLImageColorDepth; }
set { iCLImageColorDepth = value; }
}
private int iCLImageBytes;
public int ICLImageBytes
{
get { return iCLImageBytes; }
set { iCLImageBytes = value; }
}
private byte[] iCLImageMD5Hash;
public byte[] ICLImageMD5Hash
{
get { return iCLImageMD5Hash; }
set { iCLImageMD5Hash = value; }
}
private string preparedFilePath;
public string PreparedFilePath
{
get { return preparedFilePath; }
set { preparedFilePath = value; }
}
private string displayImageFullPath;
public string DisplayImageFullPath
{
get { return displayImageFullPath; }
set { displayImageFullPath = value; }
}
/// <summary>
/// The results of full page OCR for this image, if available. This field may
/// not always be populated depending on the service method invoked and/or configuration
/// of document OCR for the particular site.
/// </summary>
public string DocumentOcr
{
get { return documentOcr; }
set { documentOcr = value; }
}
private OcrDataRecord _ocrrecord;
/// <summary>
/// Fully parsed ocr data.
/// </summary>
public OcrDataRecord OcrRecord
{
get { return _ocrrecord; }
set { _ocrrecord = value; }
}
private string _workItemLogNote;
public string WorkItemLogNote
{
get { return _workItemLogNote; }
set { _workItemLogNote = value; }
}
private bool _isDeleted;
public bool IsDeleted
{
get { return _isDeleted; }
set { _isDeleted = value; }
}
public override string ToString()
{
return string.Format("WIDate: {0} ,WISequence: {1}, WIDetailSequence: {2}, WIDetailType: {3}",
WorkItemDate.ToShortDateString(), WISequence, WIDetailSequence, WorkItemDetailType);
}
private DateTime? _batchStartDate;
public DateTime? BatchStartDate
{
get { return _batchStartDate; }
set { _batchStartDate = value; }
}
private short? _batchSeqNum;
public short? BatchSeqNum
{
get { return _batchSeqNum; }
set { _batchSeqNum = value; }
}
private short? _envelopeSequence;
public short? EnvelopeSequence
{
get { return _envelopeSequence; }
set { _envelopeSequence = value; }
}
}
other code to return
public async Task<WorkItemDetail> GetWorkItemDetailAsync(int userNumber, int userNumberExternal, string applicationId, short computerNumber, DateTime wiDate, int wiSequence, int wiDetailSequence, bool includeImage)
{
using (HttpClient client = base.CreateHttpClient())
{
WorkItemDetail workitemdetail = new WorkItemDetail();
var service_result = await client.GetAsync(string.Format("api/work-item-detail?userNumber={0}&userNumberExternal={1}&applicationId={2}&computerNumber={3}&wiDate={4}&wiSequence={5}&wiDetailSequence={6}&includeImage={7}", userNumber, userNumberExternal, applicationId, computerNumber, wiDate, wiSequence, wiDetailSequence, includeImage));
await ValidateResponseAsync(service_result);
workitemdetail = await service_result.Content.ReadAsAsync<WorkItemDetail>();
return workitemdetail;
}
}

Why my ICollection is always empty?

I am trying to reach a foreach but my program never gets inside because my ICollection Coletores is always empty even if I put a lot of stuff in there.
The code where I want to get inside and it is always empty (I want to get inside the second foreach):
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (NavigationContext.QueryString.TryGetValue("email", out email))
{
//MessageBox.Show(email);
List<HyperlinkButton> listaLinks = new List<HyperlinkButton>();
AppDataContext db = new AppDataContext();
int i = 0;
HyperlinkButton aux = new HyperlinkButton();
foreach (Pessoa pessoa in db.Pessoas)
{
if (pessoa.Email == email)
{
foreach (Coletor coletor in pessoa.Coletores)
{
aux.Content = "Coletor " + (i + 1).ToString();
aux.FontSize = 24;
aux.NavigateUri = new Uri("/OcorrenciasPage.xaml?coletorId=" + coletor.Id.ToString(), UriKind.RelativeOrAbsolute);
listaLinks.Add(aux);
i++;
}
}
}
ListBox coletores = new ListBox();
coletores.ItemsSource = listaLinks;
stcList.Children.Add(coletores);
}
base.OnNavigatedTo(e);
}
Now the code that I am adding data:
if (txtLat.Text != "" && txtLong.Text != "" && rdNorte.IsChecked == true || rdSul.IsChecked == true && rdLeste.IsChecked == true || rdOeste.IsChecked == true)
{
foreach (var pessoa in db.Pessoas)
{
if (pessoa.Email == email)
{
pessoa.Coletores.Add(coletor);
}
}
db.Coletores.InsertOnSubmit(coletor);
db.SubmitChanges();
NavigationService.Navigate(new Uri("/ColetoresPage.xaml?email=" + email, UriKind.RelativeOrAbsolute));
}
Now, my Pessoa class:
public class Pessoa : INotifyPropertyChanged
{
private int _id;
[Column(IsDbGenerated = true, IsPrimaryKey = true)]
public int Id {
get { return _id;}
set { _id = value;
OnPropertyChanged("Id");
}
}
private string _nome;
[Column]
public string Nome
{
get { return _nome; }
set { _nome = value;
OnPropertyChanged("Nome");
}
}
private string _email;
[Column]
public string Email
{
get { return _email; }
set { _email = value;
OnPropertyChanged("Email");
}
}
private string _senha;
[Column]
public string Senha { get { return _senha; }
set { _senha = value;
OnPropertyChanged("Senha");
}
}
private string _profissao;
[Column]
public string Profissao { get { return _profissao; }
set { _profissao = value;
OnPropertyChanged("Profissao");
}
}
private int _idade;
[Column]
public int Idade { get { return _idade; }
set { _idade = value;
OnPropertyChanged("Idade");
}
}
private string _endereco;
[Column]
public string Endereco { get { return _endereco; }
set { _endereco = value;
OnPropertyChanged("Endereco");
}
}
private string _cidade;
[Column]
public string Cidade { get { return _cidade; }
set { _cidade = value;
OnPropertyChanged("Cidade");
}
}
private string _estado;
[Column]
public string Estado { get { return _estado; }
set { _estado = value;
OnPropertyChanged("Estado");
}
}
private EntitySet<Coletor> _coletores = new EntitySet<Coletor>();
[Association(Name = "FK_Coletores_PessoaColetores", Storage = "_coletores", ThisKey = "Id", OtherKey = "pessoaId")]
public ICollection<Coletor> Coletores
{
get { return _coletores; }
set { _coletores.Assign(value); }
}
private EntitySet<PessoaColetor> _pessoaColetores = new EntitySet<PessoaColetor>();
[Association(Name = "FK_PessoaColetores_Pessoas", Storage = "_pessoaColetores", OtherKey = "pessoaId", ThisKey = "Id")]
private ICollection<PessoaColetor> PessoaColetores
{
get { return _pessoaColetores; }
set { _pessoaColetores.Assign(value); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
The Coletores property on the Pessoa class looks alright. There is also a PessoaColetores property. Are you sure there has been no confusion between the two? Especially with intellisense one might dot or tab the wrong one.
Have you put a break point on the line that actually adds coletors (second code snippet)? Maybe stuff is added to the wrong collection.
Cheers, B.

Getting object reference not set to an instance of object for Business layer code attached

I have this Business Layer/ Contactentry.ascx page which calls a stored prcoedure to insert data into sql database and then the page below calls this business layer method. the issue is this method
aspdotnet.BusinessLogicLayer.ContactEntry AddEntry =
new ContactEntry(Convert.ToInt32(Session["ContactID"].ToString())
,Title,FirstName,MiddleName,LastName,JobTitle,Company,Website,OfficePhone
,HomePhone,Mobile,Fax,OEmail,PEmail,OAStreet,OACity,OAState,OACountry
,OAZipCode,PAStreet,PACity,PAState,PACountry,PAZipCode);
throws an error saying object refernece not set to an instance of an object although I have entered all values for the text fields.
using System;
using System.Data;
using System.Configuration;
using aspdotnet.DataAccessLayer;
namespace aspdotnet.BusinessLogicLayer
{
public class ContactEntry
{
private int _ContactID;
private string _Title;
private string _FirstName;
private string _MiddleName;
private string _LastName;
private string _JobTitle;
private string _Company;
private string _Website;
private string _OfficePhone;
private string _HomePhone;
private string _Mobile;
private string _Fax;
private string _OEmail;
private string _PEmail;
private string _OAStreet;
private string _OACity;
private string _OAState;
private string _OACountry;
private string _OAZipCode;
private string _PAStreet;
private string _PACity;
private string _PAState;
private string _PACountry;
private string _PAZipCode;
public int ContactID
{
get { return _ContactID; }
set { _ContactID = value; }
}
public string Title
{
get { return _Title; }
set { _Title = value; }
}
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string MiddleName
{
get { return _MiddleName; }
set { _MiddleName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
public string JobTitle
{
get { return _JobTitle; }
set { _JobTitle = value; }
}
public string Company
{
get { return _Company; }
set { _Company = value; }
}
public string Website
{
get { return _Website; }
set { _Website = value; }
}
public string OfficePhone
{
get { return _OfficePhone; }
set { _OfficePhone = value; }
}
public string HomePhone
{
get { return _HomePhone; }
set { _HomePhone = value; }
}
public string Mobile
{
get { return _Mobile; }
set { _Mobile = value; }
}
public string Fax
{
get { return _Fax; }
set { _Fax = value; }
}
public string OEmail
{
get { return _OEmail; }
set { _OEmail = value; }
}
public string PEmail
{
get { return _PEmail; }
set { _PEmail = value; }
}
public string OAStreet
{
get { return _OAStreet; }
set { _OAStreet = value; }
}
public string OACity
{
get { return _OACity; }
set { _OACity = value; }
}
public string OAState
{
get { return _OAState; }
set { _OAState = value; }
}
public string OACountry
{
get { return _OACountry; }
set { _OACountry = value; }
}
public string OAZipCode
{
get { return _OAZipCode; }
set { _OAZipCode = value; }
}
public string PAStreet
{
get { return _PAStreet; }
set { _PAStreet = value; }
}
public string PACity
{
get { return _PACity; }
set { _PACity = value; }
}
public string PAState
{
get { return _PAState; }
set { _PAState = value; }
}
public string PACountry
{
get { return _PACountry; }
set { _PACountry = value; }
}
public string PAZipCode
{
get { return _PAZipCode; }
set { _PAZipCode = value; }
}
public ContactEntry()
{
}
public ContactEntry(int ContactID, string Title, string FirstName, string MiddleName, string LastName, string JobTitle, string Company, string Website, string OfficePhone, string HomePhone, string Mobile, string Fax, string OEmail, string PEmail, string OAStreet, string OACity, string OAState, string OACountry, string OAZipCode, string PAStreet, string PACity, string PAState, string PACountry, string PAZipCode)
{
_ContactID=ContactID;
_Title=Title;
_FirstName = FirstName;
_MiddleName = MiddleName;
_LastName = LastName;
_JobTitle = JobTitle;
_Company = Company;
_Website = Website;
_OfficePhone = OfficePhone;
_HomePhone = HomePhone;
_Mobile = Mobile;
_Fax = Fax;
_OEmail=OEmail;
_PEmail=PEmail;
_OAStreet = OAStreet;
_OACity = OACity;
_OAState = OAState;
_OACountry =OACountry;
_OAZipCode = OAZipCode;
_PAStreet = PAStreet;
_PACity = PACity;
_PAState = PAState;
_PACountry = PACountry;
_PAZipCode = PAZipCode;
}
public bool Save()
{
if (_ContactID == 0)
return Insert();
else
return Update();
}
private bool Insert()
{
_ContactID = Convert.ToInt32(DBTask.ExecuteScalar(System.Configuration.ConfigurationManager.AppSettings[Web.Global.CfgKeyConnString], "ContactInfo_Insert", _Title, _FirstName, _MiddleName, _LastName, _JobTitle, _Company, _Website, _OfficePhone, _HomePhone, _Mobile, _Fax, _OEmail, _PEmail, _OAStreet, _OACity, _OAState, _OACountry, _OAZipCode, _PAStreet, _PACity, _PAState, _PACountry, _PAZipCode));
return (0 < _ContactID);
}
public static void Remove(int ContactID)
{
DBTask.ExecuteNonQuery(System.Configuration.ConfigurationManager.AppSettings[Web.Global.CfgKeyConnString], "ContactInfo_Delete", ContactID);
}
private bool Update()
{
try
{
DBTask.ExecuteNonQuery(System.Configuration.ConfigurationManager.AppSettings[Web.Global.CfgKeyConnString], "ContactInfo_Update", _ContactID, _Title, _FirstName, _MiddleName, _LastName, _JobTitle, _Company, _Website, _OfficePhone, _HomePhone, _Mobile, _Fax, _OEmail, _PEmail, _OAStreet, _OACity, _OAState, _OACountry, _OAZipCode, _PAStreet, _PACity, _PAState, _PACountry, _PAZipCode);
return true;
}
catch
{
return false;
}
}
public void LoadContact(int ContactID)
{
DataSet ds = DBTask.ExecuteDataset(System.Configuration.ConfigurationManager.AppSettings[Web.Global.CfgKeyConnString], "ContactInfo_GetContact", ContactID);
DataRow row = ds.Tables[0].Rows[0];
_ContactID=Convert.ToInt32(row["ContactID"].ToString());
_Title=row["Title"].ToString();
_FirstName = row["FirstName"].ToString();
_MiddleName = row["MiddleName"].ToString();
_LastName = row["LastName"].ToString();
_JobTitle = row["JobTitle"].ToString();
_Company = row["Company"].ToString();
_Website = row["Website"].ToString();
_OfficePhone = row["OfficePhone"].ToString();
_HomePhone = row["HomePhone"].ToString();
_Mobile = row["Mobile"].ToString();
_Fax = row["Fax"].ToString();
_OEmail=row["OfficialEmail"].ToString();
_PEmail=row["PersonalEmail"].ToString();
_OAStreet = row["OAStreet"].ToString();
_OACity = row["OACity"].ToString();
_OAState = row["OAState"].ToString();
_OACountry =row["OACountry"].ToString();
_OAZipCode = row["OAZip"].ToString();
_PAStreet = row["PAStreet"].ToString();
_PACity = row["PACity"].ToString();
_PAState = row["PAState"].ToString();
_PACountry = row["PACountry"].ToString();
_PAZipCode = row["PAZip"].ToString();
}
}
}
Insert form calling above function from Business Layer:
private void btnSave_Click(object sender, System.EventArgs e)
{
string Title = drplstTitle.SelectedItem.Text;
string FirstName = txtFirstName.Text;
string MiddleName = txtMiddleName.Text;
string LastName = txtLastName.Text;
string JobTitle = this.txtJobTitle.Text;
string Company = this.txtCompany.Text;
string Website = this.txtWebSite.Text;
string OfficePhone = this.txtOfficePhone.Text;
string HomePhone = this.txtHomePhone.Text;
string Mobile = this.txtMobile.Text;
string Fax = this.txtFax.Text;
string OEmail = this.txtOfficialEmail.Text;
string PEmail = this.txtPersonalEmail.Text;
string OAStreet = this.txtOAStreet.Text;
string OACity = this.txtOACity.Text ;
string OAState = this.txtOAState.Text;
string OACountry = this.txtOACountry.Text;
string OAZipCode = this.txtOAZipCode.Text;
string PAStreet = this.txtPAStreet.Text;
string PACity = this.txtPACity.Text;
string PAState = this.txtPAState.Text;
string PACountry = this.txtPACountry.Text;
string PAZipCode = this.txtPAZipCode.Text;
aspdotnet.BusinessLogicLayer.ContactEntry AddEntry =
new ContactEntry(Convert.ToInt32(Session["ContactID"].ToString()),Title,FirstName,MiddleName,LastName,JobTitle,Company,Website,OfficePhone,HomePhone,Mobile,Fax,OEmail,PEmail,OAStreet,OACity,OAState,OACountry,OAZipCode,PAStreet,PACity,PAState,PACountry,PAZipCode);
//AddEntry.Save();
}
I get object reference not set to an insance of object right after above method aspdotnet.BusinessLogicLayer.ContactEntry above. I see all values are being passed when I am debugging. I entered all values when entering values above but it still errors out. Not sure what I am missing. Please help , appreciate your time.
This line is suspicious:
Convert.ToInt32(Session["ContactID"].ToString())
Session["ContactID"] may return null and calling ToString() on null blows up. Convert.ToInt32(null) wouldn't throw an error - it would return 0, not NULL.
You to handle Session["ContactID"] for nulls and Empty before Converting it to Int32
Example :
ContactEntry cEntry = null;
if(Session["ContactID"] != null)
{
if(!String.IsNullOrEmpty(Session["ContactID"]))
{
cEntry = new ContactEntry(Convert.ToInt32(Session["ContactID"].ToString());
}
}
Check your Session["ContactID"].
Consider changing your code to something like this...
//...
string PAState = this.txtPAState.Text;
string PACountry = this.txtPACountry.Text;
string PAZipCode = this.txtPAZipCode.Text;
string contactIDstr = Session["ContactID"] as string;
int contactID = 0;
if(!String.IsNullOrEmpty(conactIDStr))
Int32.TryParse(contactIDStr, out contactID);
aspdotnet.BusinessLogicLayer.ContactEntry AddEntry = new ContactEntry(
contentID,
Title,
FirstName,MiddleName,LastName,JobTitle,Company,
Website,OfficePhone,HomePhone,Mobile,Fax,OEmail,PEmail,
OAStreet,OACity,OAState,OACountry,OAZipCode,PAStreet,PACity,PAState,PACountry,PAZipCode
);

Categories

Resources