Cannot read account number from list - c#

I am trying to read AccountNumber from a text file, but it does not seem to be reading the AccountNumber from the text file, and I can confirm that the text file location string is correct. Also, note that currently the user is only set to access BasicAccountTestRepository class, but I am trying to get the LoadAccounts method to be able to call GetAccounts() from FileAccountRepository.cs. According to my instructions, I should be able to read from the text file in this class. I am getting a NullReferenceException on LoadAccounts method, says "Object reference not set to an instance of an object."
Accounts.txt
AccountNumber,Name,Balance,Type
10001,Free Account,100,F
20002,Basic Account,500,B
30003,Premium Account,1000,P
FileAccountRepository.cs
public class FileAccountRepository : IAccountRepository
{
List<Account> accounts = new List<Account>();
public Account _account = new Account();
public void GetUsers() {
string path = #".\Accounts.txt";
string[] rows = File.ReadAllLines(path);
for (int i = 1; i < rows.Length; i++)
{
string[] columns = rows[i].Split(',');
//Account account = new Account();
_account.AccountNumber = columns[0];
_account.Name = columns[1];
_account.Balance = Decimal.Parse(columns[2]);
if (columns[3] == "F")
{
_account.Type = AccountType.Free;
}
else if (columns[3] == "B")
{
_account.Type = AccountType.Basic;
}
else if (columns[3] == "P")
{
_account.Type = AccountType.Premium;
}
accounts.Add(_account);
}
}
public Account LoadAccount(string AccountNumber)
{
if (accounts.Any(x => x.AccountNumber == AccountNumber))
{
return _account;
}
return null;
}
public void SaveAccount(Account account)
{
_account = account;
}
}
AccountManager.cs
...
public AccountLookupResponse LookupAccount(string accountNumber)
{
AccountLookupResponse response = new AccountLookupResponse();
FileAccountRepository fileAccount = new FileAccountRepository(); //NullReferenceException
fileAccount.GetUsers();
response.Account = _accountRepository.LoadAccount(accountNumber);
if(response.Account == null)
{
response.Success = false;
response.Message = $"{accountNumber} is not a valid account.";
}
else
{
response.Success = true;
}
return response;
}
...

You need to fix the code in your GetUsers. This code is wrong because is adding the same instance to your list. This will end with many entries in your list but for the same Account instance and all of these entries show the same data. The data assigned to the variable _account in the last loop.
You need to have a variable of type Account declared and initialized inside the loop. In this way every entry in the list is a different instance with different data
public class FileAccountRepository : IAccountRepository
{
List<Account> accounts = new List<Account>();
public void GetUsers() {
string path = #".\Accounts.txt";
string[] rows = File.ReadAllLines(path);
for (int i = 1; i < rows.Length; i++)
{
Account data = new Account();
string[] columns = rows[i].Split(',');
data.AccountNumber = columns[0];
data.Name = columns[1];
data.Balance = Decimal.Parse(columns[2]);
if (columns[3] == "F")
{
data.Type = AccountType.Free;
}
else if (columns[3] == "B")
{
data.Type = AccountType.Basic;
}
else if (columns[3] == "P")
{
data.Type = AccountType.Premium;
}
accounts.Add(data);
}
}
Now when you need to find an account by AccountNumber you call the method LoadAccount searching the Account from the list
public Account LoadAccount(string AccountNumber)
{
return accounts.FirstOrDefault(x => x.AccountNumber == AccountNumber);
}
FirstOrDefault will search your list for a matching value according to your lambda expression and return the account found or null.

Related

Count doesn't consider the newly inserted record

After inserting the first record, the count shows 0 even after the insert. I can see the the record inserted as soon as SaveContext()
is executed. So looks like userChangeRequestApprovalRepository isnt refreshed with the newly inserted data.
Is it appropriate to do count + 1 like the statement below instead
userChangeRequestApprovalRepository.Where(x => x.UserChangeRequestId == userChangeRequest.Id).Count() + 1;
Code
InsertUserChangeRequestApproval(userChangeRequest);
SaveContext();
var numberOfAprovals = userChangeRequestApprovalRepository.Where(x => x.UserChangeRequestId == userChangeRequest.Id).Count();
insert method
private void InsertUserChangeRequestApproval(UserChangeRequest userChangeRequest)
{
UserChangeRequestApproval userChangeRequestApproval = new UserChangeRequestApproval()
{
UserChangeRequestId = userChangeRequest.Id,
ApprovedByAuthUserId = userChangeRequest.ChangedByAuthUserId,
ApprovedDateTime = DateTime.Now,
IsActive = true
};
UserChangeRequestApprovalRepository.Insert(userChangeRequestApproval);
}
public virtual void Insert(TEntity entity)
{
_dbSet.Add(entity);
}
SaveContext method
public int SaveContext()
{
return _context.SaveChanges();
}
The code for the whole method
public IdentityResult ApproveUserChangeRequest(UserChangeRequest userChangeRequest, int approvedByAuthUserId, string authApplicationName)
{
var userChangeRequestRepository = UserChangeRequestRepository.GetAllAsList();
var userChangeRequestApprovalRepository = UserChangeRequestApprovalRepository.GetAllAsList();
var appSettingRepository = AppSettingRepository.GetAllAsList();
var clientCompanyContactRepository = ClientCompanyContactRepository.GetAllAsList();
var applicationUserRepo = ApplicationUserRepo.GetAllAsList();
// int approvedByAuthUserID = GetApprovedByUserId(authApplicationName, approvedByAuthUserName);
// Check if UserChangeRequest is still Pending
bool isUserChangeRequestPending = userChangeRequestRepository.Any(x => x.Id == userChangeRequest.Id && x.ChangeStatus == "Pending");
if (isUserChangeRequestPending && approvedByAuthUserId > 0)
{
// Inserting record in the UserChangeRequestApproval table
InsertUserChangeRequestApproval(userChangeRequest);
SaveContext();
using (var userTransaction = Context.Database.BeginTransaction())
{
using (var securityTransaction = _securityContext.Database.BeginTransaction())
{
try
{
//Get the Number of approval required for Internal and External Users
int? internalApprovalsRequired = GetApprovals("InternalUserChangeRequestApprovalsRequired", appSettingRepository);
int? externalApprovalsRequired = GetApprovals("ExternalUserChangeRequestApprovalsRequired", appSettingRepository);
//Get the name of the application the auth user belongs to
var authUserApplicationName = GetApplicationName(userChangeRequest.AuthUserId);
//Get the Number of approvals for the request
var numberOfAprovals = userChangeRequestApprovalRepository.Where(x => x.UserChangeRequestId == userChangeRequest.Id).Count();
//If the number of approvals is equal or greater than the Approvals required then Update AppUser or Contact details
if ((authUserApplicationName == "ArgentexTrader" && numberOfAprovals >= internalApprovalsRequired) || (authUserApplicationName == "ArgentexClient" && numberOfAprovals >= externalApprovalsRequired))
{
//Updating the clientcontact table
UpdateClientContact(userChangeRequest, clientCompanyContactRepository);
//Updating the auth user table
UpdateAuthUser(userChangeRequest);
//Updating the IdentityDB user table
UpdateIdentityDBUser(userChangeRequest, applicationUserRepo);
//Updating the UserChangeRequest table
userChangeRequest.ChangeStatus = "Approved";
UserChangeRequestRepository.Update(userChangeRequest);
SaveContext();
userTransaction.Commit();
securityTransaction.Commit();
return IdentityResult.Success;
}
}
catch (Exception ex)
{
userTransaction.Rollback();
securityTransaction.Rollback();
_logger.Error(ex);
return IdentityResult.Failed(new IdentityError { Description = ex.Message });
}
}
}
}
return null;
}

How to store multiple xml data into single list using IEnumerable<SyncEntity> in c#

I have to store multiple xml files data into a single list of IEnumerable<SyncEntity>, but I don't get exact result as expected. Below is my sample code.
public IEnumerable<SyncEntity> GetUpdatedItemsOfType(DateTime? fromDate, string entityName, List<string> fieldsToRetrieve)
{
ConnLogger.WriteInfo("Dooors SyncConnector", "Run DOORS DXL for List of Getupdateditems of type ");
try
{
var dxlInput = $"{TmpRootFolder};{entityName};{fromDate.ToString()};{string.Join(",", fieldsToRetrieve)};{fieldsToRetrieve.Count.ToString()}";
string dxlPath = GetDxl("GetUpdatedItemsOfType.dxl");
//ActivateAsync(() =>
//{
// DoorsHandle.result = dxlInput;
// DoorsHandle.runFile(dxlPath);
//});
_doorsHandle.result = dxlInput;
_doorsHandle.runFile(dxlPath);
return GetUpdatedItemsOfTypePagination(TmpRootFolder);
}
catch (Exception ex)
{
ConnLogger.WriteException("Doors SyncConnector", ex, "Failed to get list of updateditems of type");
throw;
}
}
The above GetUpdatedItemsOfType(DateTime? fromDate, string entityName, List<string> fieldsToRetrieve) method is where I start one process of doors.
private IEnumerable<SyncEntity> GetUpdatedItemsOfTypePagination(string folderPath)
{
int currentPage = 1;
string finishFilePath = Path.Combine(folderPath, "GetUpdateItemsOfType_Finish.xml");
while (true)
{
string xmlFileFullPath = Path.Combine(folderPath, $"GetUpdateItemsOfType{currentPage}.xml");
bool pageReadCompleted = false;
for (int i = 0; i < 1000; i++) //wait max time of 1,000*0.1 = 100 seconds
{
if (!File.Exists(xmlFileFullPath))
{
if (File.Exists(finishFilePath))
{
yield break;
}
Thread.Sleep(TimeSpan.FromSeconds(0.1));
continue;
}
List<SyncEntity> pageItems = GetUpdatedItemsPage(xmlFileFullPath);
pageReadCompleted = true;
foreach (var syncEntity in pageItems)
{
yield return syncEntity;
}
break;
}
if (!pageReadCompleted)
{
throw new ApplicationException("Timeout reached for GetUpdatedItems method...");
}
currentPage++;
}
}
The above GetUpdatedItemsOfTypePagination(string folderPath) method checks the xml files in given folder.
private List<SyncEntity> GetUpdatedItemsPage(string xmlFilePath)
{
List<FileAttachment> fileAttachment=new List<FileAttachment>();
var xmlData = GenericSerializer.XmlDeSerialize<UpdatedItemsResult>(File.ReadAllText(xmlFilePath));
return xmlData.Items.Select(field => new SyncEntity
{
Name = field.ObjectName,
Id = field.Id,
Modified = Convert.ToDateTime(field.LastModifiedOn),
Fields = field.Attributes.Select(filed => new EntityField
{
Name = filed.Name,
Type = MetadataManager.FromDoorsDataType(filed.Type),
Value = fileAttachment
}).ToList()
}).ToList();
//copy here relevant code from the Execute method
}
The above GetUpdatedItemsPage(string xmlFilePath) method is the relevant code to deserialize the xml data.

Foreach is not checking properly in mvc when doing a workflow

Am doing a workflow cheching in which i have 2 values and the when the foreach condition is checked only one time it enters the loop and exits out without going to the next one.
public CustomBusinessServices InvokeWorkFlowPermissionBusinessRule(dynamic workFlowImplemented, out string serviceName, out int permissionId)
{
try
{
List<WorkflowEligibilityMapping> workFlowPermissionService = new List<WorkflowEligibilityMapping>();// to handle null values
int current_ControllerId = Convert.ToInt32(workFlowImplemented); //ControllerId
using (var db = new AdminDb())
{
//to select services against this controller
workFlowPermissionService = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId)
select new WorkflowEligibilityMapping
{
Service = permission.Service,
WorkFlowPermissionId = permission.WorkFlowPermissionId
}).ToList();
}
int[] workFlowServiceDetails = workFlowPermissionService.Select(x => x.WorkFlowPermissionId).ToArray();
//to Login userId
var userId = Assyst.PanERP.Common.AppSession.Common.UserID;
/*******************Issue in foreach i think**************************************/
foreach (int workFlowServiceDetail in workFlowServiceDetails)
/*******workFlowServiceDetails have 2 valus********/
{
using (var db = new AdminDb())
{
string workFlowServiceDtl = (from perm in db.WorkFlowPermission.AsNoTracking()
where perm.WorkFlowPermissionId == workFlowServiceDetail
select perm.Service).FirstOrDefault();
//to select eligibility rules against this service
string eligibility = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId) && permission.WorkFlowPermissionId == workFlowServiceDetail
select permission.EligibilityRule).FirstOrDefault();
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
string[] strTxt = workFlowServiceDtl.Split(';'); //split the service name by ';' and strore it in an array
string serviceUrl = string.Empty;
string workFlowServiceName = string.Empty;
string classpath = string.Empty;
workFlowServiceName = strTxt[0].ToString();
workFlowServiceName = workFlowServiceName.Replace(" ", "");//get the service name by removing empty blank space for the word
classpath = strTxt[1].ToString();
//Invoke REST based service (like Node.Js service)
if (strTxt.Length == 4)
{
serviceUrl = strTxt[3].ToString();
}
//Invoke c# based service
else
{
serviceUrl = string.Empty;
}
var userLists = PermissionCallMethod(classpath, workFlowServiceName, new[] { workFlowImplemented, eligibility }, serviceUrl);
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Assyst.PanERP.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
}
}
serviceName = string.Empty;
permissionId = 0;
return null;
}
catch (Exception ex)
{
throw ex;
return null;
}
}
workFlowServiceDetails have 2 values and the workFlowServiceDetail takes the first one and checks for it.goes through the loop and mapes the role for the first one to the user list at the end and the without checking the for the second vale it moves out of the loop. Please help me to make the loop work for 2 values.Is it some problem in the return part...?
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Assyst.PanERP.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
If any of the above if statements evaluates to true, your loop will exit without looping through the second item in your array. The reason for this is that you are in your first conditional check do the following:
return new CustomBusinessServices() { strMessage = validationMessage };
And in your second:
return userLists;
The return statement will exit your method, and therefore terminate the foreach as well.
Try building your object first, and after your loop has walked through each item, do a return statement returning your object.

Update not reflected in table

This is my action method has been defined in Home controller for updating row
[HttpPost]
public ActionResult UpdateISRCEntry(ABC.Models.tbl1 z, List<string> verticall,string Album, string Song)
{
if (Session["user"] != null)
{
if (verticall != null)
{
foreach (string s1 in verticall)
{
if (s1 == "Radio")
{ z.Radio = "Radio"; }
if (s1 == "Online")
{ z.Online = "Online"; }
if (s1 == "Mobile")
{ z.Mobile = "Mobile"; }
}
}
tbl1.Service.Class1.updatetbl1(z, Album, Song);
return RedirectToAction("Home");
}
else
{
return RedirectToAction("Index");
}
}
and below is my method has been implemented in class1 to implement updatable row
public static bool updatetbl1(tbl1 obj, string Album, string Song)
{
ABC.Models.tbl1 objmain = new Models.mainISRC();
using (ABCManagementDBEntities1 dbcontect = new ABCManagementDBEntities1())
{
var zz = (from z in dbcontect.tbl1
where z.Album == Album && z.Song == Song select z
).SingleOrDefault();
objmain.Mood = obj.Mood;
objmain.Online = obj.Online;
objmain.Radio = obj.Radio;
dbcontect.SaveChanges();
return true;
}
return false;
}
All these codes are running successfully but the update is not reflected in my table for that row. However, during running my code no any kind of error is arise. Please help someone.
Add this before dbcontect.SaveChanges();
dbcontect.Entry(objmain).State = EntityState.Modified;
dbcontect.SaveChanges();
or I think just this will do
this.UpdateModel(objmain);
dbcontect.SaveChanges();
You should update entity before SaveChanges()
Why are you pulling the zz object and never use it? The way your wrote your "updatetbl1" method, you are inserting a new object (objmain) to the database instead of updating the zz object. Am I assuming correct here?
I think it should be like this:
public static bool updatetbl1(tbl1 obj, string Album, string Song)
{
ABC.Models.tbl1 objmain = new Models.mainISRC();
using (ABCManagementDBEntities1 dbcontect = new ABCManagementDBEntities1())
{
var zz = (from z in dbcontect.tbl1
where z.Album == Album && z.Song == Song select z
).SingleOrDefault();
zz.Mood = obj.Mood;
zz.Online = obj.Online;
zz.Radio = obj.Radio;
dbcontect.Entry(zz).State = EntityState.Modified;
dbcontect.SaveChanges();
return true;
}
return false;
}

Either an issue with my linq statement or with my GetCollection<T>()

Here is my code:
This is the function being called by fiddler using:
http://localhost:3334/Service/Login/?json={'username':'cara','password':'password'}
public ActionResult Login(JObject JSON)
{
var response = JsonResponse.OKResponse();
var username = JSON["username"].ToString();
var password = JSON["password"].ToString();
var helper = new MemberHelper();
//goes into here and never returns
if (helper.ValidateUser(username, password))
{
MongoCollection<User> users = db.GetCollection<User>();
var usr = users.FindAll().FirstOrDefault(u => u.UserName.Equals(username));
response.data.Add(usr);
}
else
{
return Json(JsonResponse.ErrorResponse("Invalid username or password provided!"), JsonRequestBehavior.AllowGet);
}
return Json(response, JsonRequestBehavior.AllowGet);
}
And the validateUser method within MemberHelper:
public override bool ValidateUser(string username, string password)
{
var hash = Encoding.ASCII.GetBytes(password);
var provider = new SHA256CryptoServiceProvider();
for (int i = 0; i < 1024; i++) // 1024 round SHA256 is decent
hash = provider.ComputeHash(hash);
var pass = Convert.ToBase64String(hash);
MongoCollection<User> users = db.GetCollection<User>();
//***The following statement is where the program just stops***
var usr = users.FindAll().FirstOrDefault(u => u.UserName.Equals(username) && u.Password.Equals(pass));
...
}
And getCollection....
public MongoCollection<T> GetCollection<T>(string name = null)
{
string collectionName = name;
if (collectionName == null) {
collectionName = typeof(T).Name;
}
return Database.GetCollection<T>(collectionName);
}
I really don't know what is going wrong. I am new to linq so I am not sure if there is some golden rule that I am breaking. Please help! Let me know if there is anything else I need to add.
You can also change it to something like
var usr = users.AsQueryable().Where(u => u.UserName.Equals(username)).FirstOrDefault();
The problem was indeed within the method GetCollection<>() once I replaced it with the following code, it worked just fine:
public MongoCollection<T> GetCollection<T>(string name = null)
{
string collectionName = name;
if (collectionName == null)
collectionName = typeof(T).Name;
if (Database.CollectionExists(collectionName) == false)
Database.CreateCollection(collectionName);
return Database.GetCollection<T>(collectionName);
}

Categories

Resources