linq check if matches null or selected item - c#

I am checking to see if items already match whats in my MSSQL DB. I am using LINQ to update records. I would like to know how i can check if an item is equal to d_0_2 or if its equal to null/empty. How would i go about doing this?
below is my existing code, which partially works. but is failing due to the null/Empty
if (updateProduct.studioId == Convert.ToInt32(d_0_2.SelectedValue)) { }
else { updateProduct.studioId = Convert.ToInt32(d_0_2.SelectedValue);}
Thanks in advance.

I'm not sure if I understood you question correctly, but you want to check if item is null or if not is it studioId equal to d_0_2.SelectedValue
if (updateProduct == null)
{
//create new update product
}
else if (updateProduct.studioId != Convert.ToInt32(d_0_2.SelectedValue))
{
updateProduct.studioId = Convert.ToInt32(d_0_2.SelectedValue);
}

string value = d_0_2.SelectedValue.ToString();
// what if SelectedValue is empty or null?
if (!string.IsNullOrEmpty(value))
return;
// what if product is null?
if (updateProduct != null)
return;
if (updateProduct.studioId != null &&
updateProduct.studioId == Convert.ToInt32(value))
{
// you have product and its id equal to d_0_2.SelectedValue
}
else
{
// studioId not equal to to d_0_2.SelectedValue
updateProduct.studioId = Convert.ToInt32(value);
}

Related

Make null columns invisible in DataGridView

I have a datagridview in WinForm C# application called custFleetDataGrid
I've tried to create a method which will set each column to invisible if all the rows are null or ""
The code does not work as expected, columns with blank data remain in the grid view.
I'm calling Code like this
custFleetDataGrid.RemoveEmptyColumns();
Method I'm using to remove NullColumns
public static class ExtensionGridView
{
public static DataGridView RemoveEmptyColumns(this DataGridView grdView)
{
foreach (DataGridViewColumn clm in grdView.Columns)
{
bool notAvailable = true;
foreach (DataGridViewRow row in grdView.Rows)
{
if (row.Cells[clm.Index].Value == null || row.Cells[clm.Index].Value.ToString() != "")
{
notAvailable = false;
break;
}
}
if (notAvailable)
{
grdView.Columns[clm.Index].Visible = false;
}
}
return grdView;
}
}
could this be because the compiler is trying to convert a null value to a string?
Correct, that's the exact case. Just it's not the compiler, but the code you have written.
I would suggest you encapsulating the empty cell logic into separate extension method inside the ExtensionGridView class:
public static bool IsEmpty(this DataGridViewCell cell)
{
var value = cell.Value;
return value == null || value == DBNull.Value || (value as string) == string.Empty;
}
Then you can use simple LINQ to determine the empty columns:
public static IEnumerable<DataGridViewColumn> EmptyColumns(this DataGridView gridView)
{
return gridView.Columns.Cast<DataGridViewColumn>()
.Where(c => gridView.Rows.Cast<DataGridViewRow>().All(r => r.Cells[c.Index].IsEmpty()));
}
Then your method could be simply like this:
public static DataGridView RemoveEmptyColumns(this DataGridView gridView)
{
foreach (var column in gridView.EmptyColumns())
column.Visible = false;
return gridView;
}
If Value is null, you'll get a NullReferenceException if using ToString() on it. So you have to null-check the value before using ToString().
Go like this:
// IF (Value is empty => use "").ToString() <-- IsNullOrEmpty
if (!string.IsNullOrEmpty(row.Cells[clm.Index].Value ?? "").ToString())
{
notAvailable = false;
break;
}
Check the details about ?? here.
Its the same as:
// If not null
if(row.Cells[clm.Index].Value != null)
{
// If string of value is empty
if(row.Cells[clm.Index].Value.ToString() != "")
{
notAvailable = false;
break;
}
}
Away from your problem here's a short version of everything:
public static DataGridView RemoveEmptyColumns(this DataGridView grdView)
{
for (int i = 0; i < grdView.ColumnCount; i++)
{
// On each iteration get all values of a column
IEnumerable<string> column = grdView.Rows.Cast<DataGridViewRow>().Select(row => (string)row.Cells[i].Value);
// If there is no value with length > 0 => visible = false
if (!column.Any(x => x.Length > 0)) { grdView.Columns[i].Visible = false; }
}
return grdView;
}
Instead of iterating trough each row i'd let my select statement do it like so:
SELECT some columns FROM yourtable WHERE thecolumn IS NOT NULL
Your problem is that you are checking if row.value.toString() is null or empty. If valueis null, when it tries to get the toString() to check if its null or empty it can't.
Change your if statement to:
if (row.Cells[clm.Index].Value != null || row.Cells[clm.Index].Value.toString()!="")
{
//Code
}
Important note:
In C# (and most modern languages) you have two opetaors for OR (| and ||) and two for AND(& &&). If its just one (&/|) it will check both sides but if it have two (&&/||) if the first condetin determines eveirthing (a true for OR or a false for AND) it will not check the second one.
This gives you more rendiment but also is usefull for not having nullpointerexeptions. If it's null, it will not check the second part and it will not explote. If you just put one it will say "Yes, is null, lets check if the string is also "" and will throw a NulPointerExeption.

C# NetSuite WebServices: Get value from custom field in saved search (ItemSearchAdvanced)

I'm using C# MVC to connect to NetSuite using their WebServices API. I have some current code that calls a saved search of inventory items. Here is the current code that is working perfectly:
ItemSearchAdvanced searchItems = new ItemSearchAdvanced();
searchItems.savedSearchId = "128";
SearchResult result = netSuiteSvc.search(searchItems);
int totalRecords = 0;
int processedRecords = 0;
UpdateNetsuitePriceListModel returnObj = new UpdateNetsuitePriceListModel();
returnObj.NewPriceList = new List<NetSuitePriceListRecord>();
if (result.status.isSuccess)
{
SearchRow[] searchRows = result.searchRowList;
if (searchRows != null && searchRows.Length >= 1)
{
for (int i = 0; i < searchRows.Length - 1; i++)
{
ItemSearchRow itemRow = (ItemSearchRow)searchRows[i];
if (itemRow.basic.itemId != null && itemRow.basic.mpn != null && itemRow.basic.basePrice != null && itemRow.basic.salesDescription != null)
{
returnObj.NewPriceList.Add(new NetSuitePriceListRecord()
{
ItemId = itemRow.basic.itemId[0].searchValue,
ManufacturerPartNumber = itemRow.basic.mpn[0].searchValue,
ContractPrice = Convert.ToDecimal(itemRow.basic.basePrice[0].searchValue),
Cost = CalculateProductCostForIngram(Convert.ToDecimal(itemRow.basic.basePrice[0].searchValue)),
Description = itemRow.basic.salesDescription[0].searchValue
});
processedRecords++;
}
totalRecords++;
}
}
else
{
throw new Exception("NetSuite Part List Blank");
}
}
else
{
throw new Exception("NetSuite Part List Search Failure");
}
Now I have need to pull the itemId from a custom added field rather than the default itemId field.
Obviously since this is a custom field it isn't a property of ItemSearchRowBasic. It looks like instead of the property I can choose "customFieldList" which is an array of "SearchColumnCustomField". If I choose an index for the array I can see that SearchColumnCustomField contains:
customLabel
internalId
scriptId
I imagine I should be able to get the internalId of the SearchColumnCustomField and somehow use that to get the search value for that custom column but I've had some trouble finding any examples that fit so far.
This custom field is a free form text field added to all inventory items.
Try setting scriptId with the ID of the field ("custitem_xyz"). That should work.
Before 2013 one would use internalId, but since then it changed to scriptId.
You would need to loop over the CustomRecord items in the customFieldList. I then usually check for a specific type so I can cast to the correct object, but with some reflection you could probably avoid that.
foreach (Record r in mySearchResponse.recordList){
foreach (CustomFieldRef cr in ((CustomRecord)r).customFieldList){
if (cr.GetType().Name == "SelectCustomFieldRef"){
if (((SelectCustomFieldRef)cr).scriptId == "my_custom_field"){
internalID = ((CustomRecord)r).internalId;
}
}
}
}

Does EntityFramework Monitor variables prior to it's declaration and use?

I couldn't understand what was happening when I use Linq.Any() method to check if object contains a specific value, the code throws a NullReferenceException on variable with data prior it's use.
The code below:
public ML.Order FetchOrder(ML.MLDBContext db, long OrderID)
{
if (db == null)
db = new ML.MLDBContext();
//avoided code to fetch the Order details from another system via API
Order apiOrder = api.OrdersGet(OrderID);
//avoided code to test null results
bool isNew = false; //to check if fetched order is new or must be updated on DB
//load from DB
ML.Order dbOrder = db.Orders.Where(o => o.OrderID == apiOrder.id).FirstOrDefault();
if (dbOrder == null)
{
isNew = true;
//avoided code to fill dbOrder with apiOrder data
//Below code check if user bought the same product before
//the error is thrown here but it's not null
string ListingID = apiOrder.order_items.First().item.id;
var previousOrders = db.Orders.Where(order => order.OrderID != apiOrder.id && order.CustomerID == apiOrder.buyer.id && order.SellerID == apiOrder.seller.id).ToList();
foreach (ML.Order prevOrder in previousOrders)
{
if (prevOrder.OrderedItems.Any(i => i.ListingID == ListingID)) //Line who causes the error
{
//code to mask as reordered item
}
}
Some points:
I'm sure "apiOrder.order_items.First().item.id" always have any value.
I'm sure the Order contains the item I'm looking for and the field isn't nullable.
When I comment the line who causes the error, the debug will pass through without errors
To solve this problem, I had to replace Linq.Any() by foreach
foreach (ML.Order prevOrder in previousOrders)
{
foreach (ML.OrderedItem item in prevOrder.OrderedItems)
{
if (item.ListingID == ListingID)
{
//code to mask as reordered item
}
}
}
My doubt is:
Does Linq.Any() or EntityFramework Monitor variables prior to it's declaration and use?
Why the NullreferenceException was trowed on variable prior it usage?
What's the problem using the Linq.Any() method to check the existence of a value inside EF object?

Add to exisiting Database instance from MVC Controller

Private BookingDB db = new BookingDB();
Private MonthDb mdb = new MonthDB();
if (ModelState.IsValid)
{
String date = (booking.Start_Date).ToString();
var check = from b in mdb.months
where b.BookedDays.Contains(date)
select b;
if (check != null)
{
return View(booking);
}
else
{
booking.Reservation_Owner = User.Identity.Name;
//Add booking.Start_Date to mdb.Entry(check).BookedDays
mdb.SaveChanges();
db.bookings.Add(booking);
db.SaveChanges();
return RedirectToAction("Index");
}
}
I've got this code that on creation of a new booking, will check that no exisiting bookings have already been made on or around that specific day.
if the day to be booked is not already been booked (ie exists under BookedDays in mdb.months) then i wish to add the Start_Date of the booking, to the BookedDays string in the mdb.months database (the mdb.month database is just a list of the 12 months)
at first i tried using mdb.Entry() to add to that specific month instance, however i cannot get it to work.
the error is:
the model does not have a definition for BookedDays
what do?
Your checking that check is null
if (check != null)
{
return View(booking);
}
else
{
and then using check anyway:
check.BookedDays
check is null and therefore does not contain any BookedDays. I'm guessing your null check is the wrong way around and should be
if (check == null)
{
return View(booking);
}
else
{
That said your problem is not well explained so I'm not sure.

How to get specific information from a session List

(List<Fruit>)Session["listSession"]
the session list is created in my home page.
and i would like to access information on another page
I would like to loop throw
if ((List<Fruit>)Session["listSession"].name == "apple ")
{
item.(access a method in my fruit class)
}else {
// do something else
}
\
List<Fruit> fruits = Session["listSession"] as List<Fruit>;
if(fruits != null)
{
foreach(Fruit fruit in fruits)
{
if(fruit.name=="apple")
fruit.Method();
else
//do something else
}
}
A couple of points here: you can just grab the instance from the session as a list and keep a reference to it, then you can check it is something (not null) and that it contains something which is also something (if nullable), before grabbing a reference of that and performing desired actions:
var fruitList = Session["listSession"] as List<Fruit>;
if (fruitList != null && fruitList.Count > 0)
{
var fruit = fruitList[0];
if (fruit != null && fruit.name == "apple ")
{
fruit.Consume();
}
}
That ought to help, though I'm sure you'll need to build on it to further your purpose.

Categories

Resources