Fill dropdownlist when there is no data in database - c#

I have a dropdownlist that are filled with age ranging from 0-100. This the user can then choose and the selected value gets inserted into a database via linq. The user doesn't have an age value in the database but this is something that he will add later on the edit page. The problem is that there is an error when loading the "edit profile page" if there is no a NULL value on age in the database.
Error message:
System.NullReferenceException: Object reference not set to an instance of an object. at DatingSite.Members.Redigera.getData(Guid user) in c:\DatingSite\DatingSite\Members\Redigera.aspx.cs:line 43
Code for dropdownlist:
public void addAge()
{
dropAge.Items.Insert(0, "Välj ålder");
int index = 1;
for (int i = 0; i <= 100; i++)
{
ListItem li = new ListItem(i.ToString(), i.ToString());
dropAge.Items.Insert(index, li);
index++;
}
}
Code for getting the users information:
private void getData(Guid user)
{
var repository = new DAL.Repository.UpdateRepository();
currentProfilbild.ImageUrl = "~/" + repository.getAvatar(user);
Fnamn.Text = repository.getName(user);
Enamn.Text = repository.getEnamn(user);
tbxPresText.Text = repository.getPresText(user);
var gender = repository.getGender(user);
try
{
var age = repository.getAge(user).Trim();
if (string.IsNullOrEmpty(age))
{
addAge();
}
else
{
dropAge.SelectedValue = repository.getAge(user).Trim();
}
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
}
}
Linq-code:
public string getAge(Guid uID)
{
using (var context = new dbEntities())
{
var user = context.UserInformation.First(c => c.UserId == uID);
return user.Ålder;
}
}

The error could be here:
public string getAge(Guid uID)
{
using (var context = new dbEntities())
{
var user = context.UserInformation.First(c => c.UserId == uID);
if(user != null && !String.IsNullOrEmpty(user.Ålder))
return user.Ålder;
else
return string.empty;
}
}

My guess is the exception is here, since the age is null and you're trying to do a Trim operation.
var age = repository.getAge(user).Trim();
May be you can do this.
var age = repository.getAge(user);
if(!string.IsNullOrEmpty(age))
{
age = age.Trim();
}
BTW, you might considering bringing all the data in one call rather than calling multiple times for firstname, lastname, age, etc.

Related

The name does not exist in the current context, ApiController, asp.net core, IEnumerable

I'm making a service that return a list IEnumerable, the trouble is that when return the element IEnumerable appear this error: The name 'ActivitiesList' does not exist in the current context
I share you my code, the error appear in the last line: return ActivitiesList;
[HttpPost]
[Route("user/get-user-activities")]
public IEnumerable<ActivitiesClass> GetUserActivities()
{
string email = User.FindFirstValue(ClaimTypes.Email);
try
{
if (!String.IsNullOrEmpty(email))
{
using (SecondAppContext db = new SecondAppContext())
{
using (var transaccion = new TransactionScope())
{
User UserModel = db.User
.Where(b => b.Email == email)
.First();
var IdUser = UserModel.Id;
IEnumerable<ActivitiesClass> ActivitiesList =
(
from activity in db.Activities
where activity.IdUser == IdUser &&
activity.DateCreated > DateTime.Now.AddDays(-3)
select new ActivitiesClass
{
dataCreated = activity.DateCreated,
description = activity.Description,
category = activity.Category,
gender = activity.Gender,
ageMin = (int)activity.AgeMin,
ageMax = (int)activity.AgeMax
}).ToList();
transaccion.Complete();
}
}
}
}
catch (Exception ex)
{
Error(ex.ToString());
}
return ActivitiesList;
}
You need to be mindful of scopes..
Yuo need to be thinking about returning an error code if something isn't as expect
You should be using the async and await pattern.
There is no need for a transaction here
Also you should use standard casing and naming conventions e.g User userModel
Untested Example
public async Task<IEnumerable<ActivitiesClass>> GetUserActivities()
{
string email = User.FindFirstValue(ClaimTypes.Email);
if (string.IsNullOrEmpty(email))
return null; // you should think about this
try
{
await using var db = new SecondAppContext();
// what are yu going to if the user is not found?
var userModel = await db.User
.Where(b => b.Email == email)
.FirstOrDefaultAsync();
if (userModel == null)
return null; // you should think about this
return await (
from activity in db.Activities
where activity.IdUser == userModel.Id && activity.DateCreated > DateTime.Now.AddDays(-3)
select new ActivitiesClass
{
dataCreated = activity.DateCreated,
description = activity.Description,
category = activity.Category,
gender = activity.Gender,
ageMin = (int) activity.AgeMin,
ageMax = (int) activity.AgeMax
}).ToListAsync();
}
catch (Exception ex)
{
Error(ex.ToString());
}
return null; // you should think about this
}
the name 'ActivitiesList' does not exist in the current context
The issue relates that you are defining the ActivitiesList in the if statement, so it will show the above error. Besides, since the IEnumerable<T> is an interface, I suggest you could define a List<ActivitiesClass> instance to store the return data.
Try to modify your code as below:
[HttpPost]
[Route("user/get-user-activities")]
public IEnumerable<ActivitiesClass> GetUserActivities()
{
string email = User.FindFirstValue(ClaimTypes.Email);
//define a List<ActivitiesClass> to store the return data.
List<ActivitiesClass> ActivitiesList = new List<ActivitiesClass>();
try
{
if (!String.IsNullOrEmpty(email))
{
using (SecondAppContext db = new SecondAppContext())
{
using (var transaccion = new TransactionScope())
{
User UserModel = db.User
.Where(b => b.Email == email)
.First();
var IdUser = UserModel.Id;
//set values for the ActivitiesList
ActivitiesList =
(
from activity in db.Activities
where activity.IdUser == IdUser &&
activity.DateCreated > DateTime.Now.AddDays(-3)
select new ActivitiesClass
{
dataCreated = activity.DateCreated,
description = activity.Description,
category = activity.Category,
gender = activity.Gender,
ageMin = (int)activity.AgeMin,
ageMax = (int)activity.AgeMax
}).ToList();
transaccion.Complete();
}
}
}
}
catch (Exception ex)
{
Error(ex.ToString());
}
return ActivitiesList; //Call the `.AsEnumerable()` method, if you want to convert the List to the IEnumerable<>.
}
After calling this method, if the IEnumerable result doesn't contain records, it means not matched data.

Trying to Add to Database: Collection was modified; enumeration operation may not execute?

Below is my controller That I am calling from a href button and passing an id. The href button is a duplicate button which is meant to create a copy of the selected module and add it to the database and then return it.
public ActionResult dupe(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
MODULE Modules = db.MODULE.Find(id);
if (Modules == null)
{
return HttpNotFound();
}
else
{
MODULE newMOd = new MODULE();
newMOd.APPLY__FINISH = Modules.APPLY__FINISH;
newMOd.CREATED_BY = Modules.CREATED_BY;
newMOd.CREATED_DATE = Modules.CREATED_DATE;
newMOd.MODULE_DESC = "Duplicate-"+Modules.MODULE_DESC;
newMOd.MODULE_TYPE = Modules.MODULE_TYPE;
newMOd.MODULE_TYPE1 = Modules.MODULE_TYPE1;
newMOd.PRODUCT_LINE = Modules.PRODUCT_LINE;
newMOd.MODULE_NAME = "Duplicate-" + Modules.MODULE_NAME;
foreach (MODULE_PARTS mp in Modules.MODULE_PARTS)
{
newMOd.MODULE_PARTS.Add(mp);
}
foreach (MODULE_OPTION mo in Modules.MODULE_OPTION)
{
MODULE_OPTION m = new MODULE_OPTION();
m.OPTION_NAME = mo.OPTION_NAME;
m.OPTION_TYPE = mo.OPTION_TYPE;
m.PRODUCT_LINE = mo.PRODUCT_LINE;
m.ADDED_BY = mo.ADDED_BY;
m.ADDED_ON = mo.ADDED_ON;
m.DEFAULT_FACTOR = mo.DEFAULT_FACTOR;
foreach (OPTION_PARTS op in mo.OPTION_PARTS)
{
m.OPTION_PARTS.Add(op);
}
newMOd.MODULE_OPTION.Add(mo);
}
newMOd.MODULE_PARTS = Modules.MODULE_PARTS;
newMOd.MODULE_OPTION = Modules.MODULE_OPTION;
db.MODULE.Add(newMOd);
db.SaveChanges();
}
return View(Modules);
}
This is my controller method, and when I try to add this module to database I get collection modified error. I'm not sure how or where?
enter image description here
The exception message in this case is quite clear... you cannot modify a member of a collection you are currently iterating over. It's that simple.

How to update AmountDue value by InvoiceId in XERO API using C#

I am getting the list of Invoice details by Invoice Id.
Now i want to update AmountDue by respective Invoice Id.
i tried by below code:
ByInvoiceId.AmountDue = Convert.ToDecimal(100.00);
public_app_api.Invoices.Update(ByInvoiceId);
but..Error as
"A validation exception occurred"
What's the reason behind and How to solve this?
There are a number of ways to change the amount due on an invoice, however changing the value of the property directly is not one of them.
The amount due on an invoice is driven by the totals of the line items on the invoice minus the total of payments and allocated credit. One way to change the amount due is to change the values of your line items or add/remove some line items. You won't be able to change the invoice if it has been paid/partially paid.
Another way you could change the amount due on an invoice is to add a payment against the invoice or allocate credit from a credit note, prepayment, or overpayment to the invoice
In addition to MJMortimer's answer.
You can't change the line amounts on an AUTHORISED invoice via the c# API. You have to VOID the invoice and create a new one. You can however update DRAFT and SUBMITTED ones by updating the line items.
EDIT: Here is some code to help you. This is create invoice code, but amending one is essentially the same.
public XeroTransferResult CreateInvoices(IEnumerable<InvoiceModel> invoices, string user, string status)
{
_user = XeroApiHelper.User(user);
var invoicestatus = InvoiceStatus.Draft;
if (status == "SUBMITTED")
{
invoicestatus = InvoiceStatus.Submitted;
}
else if (status == "AUTHORISED")
{
invoicestatus = InvoiceStatus.Authorised;
}
var api = XeroApiHelper.CoreApi();
var xinvs = new List<Invoice>();
foreach (var inv in invoices)
{
var items = new List<LineItem>();
foreach (var line in inv.Lines)
{
decimal discount = 0;
if (line.PriceBeforeDiscount != line.Price)
{
discount = (decimal)(1 - line.Price / line.PriceBeforeDiscount) * 100;
}
items.Add(new LineItem
{
AccountCode = line.AccountCode,
Description = line.PublicationName != "N/A" ? line.PublicationName + " - " + line.Description : line.Description,
TaxAmount = (decimal)line.TaxAmount,
Quantity = 1,
UnitAmount = (decimal)line.PriceBeforeDiscount,
DiscountRate = discount,
TaxType = line.XeroCode,
ItemCode = line.ItemCode
});
}
var person = inv.Company.People.FirstOrDefault(p => p.IsAccountContact);
if (person == null)
{
person = inv.Company.People.FirstOrDefault(p => p.IsPrimaryContact);
}
var ninv = new Invoice
{
Number = inv.ClientInvoiceId,
Type = InvoiceType.AccountsReceivable,
Status = invoicestatus,
Reference = inv.Reference,
Contact = new Contact
{
Name = inv.Company.OrganisationName,
//ContactNumber = "MM" + inv.Company.CompanyId.ToString(),
FirstName = person.FirstName,
LastName = person.LastName,
EmailAddress = person.Email,
Phones = new List<Phone>()
{
new Phone {PhoneNumber = person.Telephone, PhoneType = PhoneType.Default},
new Phone {PhoneNumber = person.Mobile, PhoneType = PhoneType.Mobile}
},
Addresses = new List<Address>
{ new Address
{
//AttentionTo = inv.Company.People.FirstOrDefault(p => p.IsAccountContact) == null
//? inv.Company.People.FirstOrDefault(p=> p.IsPrimaryContact).FullName
//: inv.Company.People.FirstOrDefault(p => p.IsAccountContact).FullName,
//AddressLine1 = inv.Company.OrganisationName,
AddressLine1 = inv.Company.Address.Address1,
AddressLine2 = inv.Company.Address.Address2 ?? "",
AddressLine3 = inv.Company.Address.Address3 ?? "",
Region = inv.Company.Address.CountyState,
City = inv.Company.Address.TownCity,
PostalCode = inv.Company.Address.PostCode,
}
}
},
AmountDue = (decimal)inv.TotalAmount,
Date = inv.InvoiceDate,
DueDate = inv.DueDate,
LineItems = items,
LineAmountTypes = LineAmountType.Exclusive
};
if (SessionContext.TransferContactDetailsToXero == false)
{
ninv.Contact = new Contact
{
Id = inv.Company.XeroId ?? Guid.Empty,
Name = inv.Company.OrganisationName
};
}
xinvs.Add(ninv);
}
var success = true;
var xinvresult = new List<Invoice>();
try
{
api.SummarizeErrors(false);
xinvresult = api.Invoices.Create(xinvs).ToList();
}
catch (ValidationException ex)
{
// Something's gone wrong
}
foreach (var inv in xinvresult)
{
var mminvoice = invoices.FirstOrDefault(i => i.ClientInvoiceId == inv.Number);
if (inv.Errors != null && inv.Errors.Count > 0)
{
success = false;
if (mminvoice != null)
{
var errors = new List<XeroError>();
foreach (var err in inv.Errors)
{
errors.Add(new XeroError { ErrorDescription = err.Message });
}
mminvoice.XeroErrors = errors;
}
}
else
{
mminvoice.XeroTransferDate = DateTime.Now;
mminvoice.XeroId = inv.Id;
mminvoice.XeroErrors = new List<XeroError>();
}
}
return new XeroTransferResult
{
Invoices = invoices,
Success = success
};
}

Get ID value from combo box with entity framework

With ADO.net, if I want to retrieve the ID from combobox I just do such like this :
int idToGet = int.parse(tbCategory.SelectedValue.ToString());
Then done,
But when I bind the combobox with EF, it will show error Input string was not in a correct format. So the current value show { id = 7, category = TESTING } and not as usual.
Here a my code snippet :
public void loadCategory()
{
tbCategory.DataSource = null;
var listCategoryObj = new malsic_inventoryEntities();
var query = from cat in listCategoryObj.Category
//join cat in listItmObj.Category on n.id_category equals cat.id
select new { cat.id,cat.category };
if (query.Count() > 0)
{
tbCategory.DataSource = query.ToList();
tbCategory.DisplayMember = "category";
tbCategory.ValueMember = "id";
tbCategory.Invalidate();
}
else
{
tbSubCategory.Enabled = false;
}
}
public void loadSubcategory()
{
tbSubCategory.DataSource = null;
int id_category_current = int.Parse(tbCategory.SelectedItem.Value.ToString());
var listSubCategoryObj = new malsic_inventoryEntities();
var query = from SubCat in listSubCategoryObj.SubCategories
where SubCat.id_category == id_category_current
select new { SubCat.id, SubCat.subcategory };
if (query.Count() > 0)
{
groupBox1.Enabled = true;
tbSubCategory.DataSource = query.ToList();
tbSubCategory.DisplayMember = "subcategory";
tbSubCategory.ValueMember = "id";
tbSubCategory.Invalidate();
}
else
{
groupBox1.Enabled = false;
}
}
I do something wrong?
I don't think your problem is anything to with ADO.NET or Entity Framework. I think your problem is on the line with int.Parse. Try setting id_category_current this way instead of how you do it now:
int id_category_current;
if(!int.TryParse(tbCategory.SelectedItem.Value.ToString(), out id_category_current))
{
groupBox1.Enabled = false;
return;
}

List(T) from sql db table

I want to create List(T) from sql db table
let's say i have one table
ID Name
1 xyz
2 efd
3 abc
4 pqr
i want to some code in C# who will read this db table data and write
following lines in my c# class or / notepad or whatever...
List<ItemViewModel> Items= new List<ItemViewModel>();
Items.Add(new ItemViewModel() { id= 1, name= "xyz"}
Items.Add(new ItemViewModel() { id= 2, name= "efd"}
Items.Add(new ItemViewModel() { id= 3, name= "abc"}
Items.Add(new ItemViewModel() { id= 4, name= "pqr"}
thanks in advance
Add "dapper" to your project (available on NuGet), then:
var list = connection.Query<YourType>("select * from TableName").ToList();
Or for a parameterless query:
var region = "South";
var list = connection.Query<YourType>(
"select * from TableName where Region=#region", new { region });
Here one of best code that you can got, the following method can deal with any data classes and system defined types :
public List<T> ExecuteQuery<T>(string s, SqlConnection condb, params SqlParameter[] Params)
{
List<T> res = new List<T>();
string er = "";
SqlDataReader r = null;
try {
if (condb == null)
throw new Exception("Connection is NULL");
if (string.IsNullOrEmpty(s))
throw new Exception("The query string is empty");
using (SqlCommand cm = new SqlCommand(s, condb)) {
if (Params.Length > 0) {
cm.Parameters.AddRange(Params);
}
if (cm.Connection.State != ConnectionState.Open)
cm.Connection.Open();
r = cm.ExecuteReader;
object prps = typeof(T).GetProperties;
object prpNames = prps.Select((System.Object f) => f.Name).ToList;
if (r.HasRows) {
while (r.Read) {
if (typeof(T).FullName.Contains("System.")) {
res.Add(r(0));
// Classes
} else {
object c = Activator.CreateInstance(typeof(T));
for (j = 0; j <= r.FieldCount - 1; j++) {
object jj = j;
//er = dt.Rows(jj)("ColumnName").ToLower
object fname = r.GetName(j).ToString;
er = fname;
object fType = r.GetProviderSpecificFieldType(j).ToString.ToLower;
object p = prps.Where((System.Object f) => f.Name.Trim.ToLower == fname.ToLower).ToList;
if (p.Count > 0) {
//Date or DateTime
if (fType.Contains("date")) {
if (!p(0).PropertyType.FullName.ToLower.Contains("system.nullable") && (r(fname) == null || r(fname).Equals(System.DBNull.Value))) {
p(0).SetValue(c, Now, null);
} else {
if (!(p(0).PropertyType.FullName.ToLower.Contains("system.nullable") && (r(fname) == null || r(fname).Equals(System.DBNull.Value)))) {
p(0).SetValue(c, r(fname), null);
}
}
//String
} else if (fType.Contains("string")) {
if (r(fname) == null || r(fname).Equals(System.DBNull.Value)) {
p(0).SetValue(c, "", null);
} else {
p(0).SetValue(c, r(fname), null);
}
} else {
if (!(p(0).PropertyType.FullName.ToLower.Contains("system.nullable") && (r(fname) == null || r(fname).Equals(System.DBNull.Value)))) {
p(0).SetValue(c, r(fname), null);
}
}
}
}
res.Add(c);
}
}
}
r.Close();
}
//If cm IsNot Nothing Then
// 'cm.Connection.Close()
// cm.Dispose()
//End If
} catch (Exception ex) {
if (r != null && r.IsClosed == false)
r.Close();
throw ex;
}
return res;
}
Usage :
var data = ExecuteQuery<ItemViewModel>("SELECT [ID], [Name] FROM [ItemViewTable]",
new SqlConnection("SomeConnectionString"));
If you just want a list populated with whatever data is currently in the database table, you can just do a simple query. You don't have to involve code generation.
Using linq-to-sql to read the contents of the table and create an ItemViewModel for each entry:
using(var context = new MyLinqDbContext())
{
var items = (from i in context.MyTable
select new ItemViewModel { id = ID, name = Name })
.ToList();
}
If you want C# code generated which is being created from database values and compiled into your solution, you want to use Microsofts text templating engine (T4). To get a hold of this technique, you can read up on it in detail in this blog entry.
If you understand the basics of T4, you can read up this blog, there's an example of how to dynamically create Enum classes for static lookup tables which are stored in a database. Starting from this code, you can write your own code generation template which creates the classes you need.

Categories