Join two dynamic Linq in Asp.net - asp.net

I have used linq to store data, below is the code:
var result = (dynamic)null;
var serviceData = (dynamic)null;
var userData = (dynamic)null;
/****Linq 1*****/
serviceData= dtPasscode.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
/**Linq 2**/
userData = DisplyCustomerDetails(Convert.ToInt64(strSubAccountID));
result = serviceData.Concat(userData);
And another linq through function:
/**Function**/
System.Data.EnumerableRowCollection DisplyCustomerDetails(Int64 intAccountId)
{
var result = (dynamic)null;
/** Data Display if no service avaiable **/
IAccount_BL objAccount_BL = new Account_BL();
Customer objCustomer = new Customer();
DataTable dtCustomer = null;
int intErrorCount = 0;
objCustomer.Account_Id = Convert.ToInt64(intAccountId);
dtCustomer = objAccount_BL.GetCustomerDetails(objCustomer, ref intErrorCount);
objAccount_BL = null;
objCustomer = null;
if (intErrorCount == 0)
{
if (dtCustomer != null)
{
if (dtCustomer.Rows.Count > 0)
{
result = dtCustomer.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
}
}
}
return result;
}
I wanted to join both the result of Linq1 & Linq2, I tired Concat & Union, getting below error
'System.Data.EnumerableRowCollection<<>f__AnonymousTypea>' does not contain a definition for 'Concat'

To Concat both enumerables must of the same class; you cannot use anonymous classes. Define a class that has the two fields and change the code to Select them.
Also, don't use ... = (dynamic) null; just assign the variable directly
var serviceData= dtPasscode ...
var userData = DisplyCustomerDetails ...
var result = serviceData.Concat(userData);

Related

how to Add list of products from cart?

dears,
i have an API working with ASP.Net Core 3.1 posting orders
i want to post order head and get all items from another api in cart items and post it in order items my code as below
[HttpPost("addOrderHead")]
public async Task<ActionResult<OrderDto>> Posting(OrderDto dto)
{
try
{
if (dto == null)
{
return BadRequest(ModelState);
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var mappedEntities = _mapper.Map<Order>(dto);
_orderRepository.Add(mappedEntities);
if (await _orderRepository.Save())
{
int id = mappedEntities.OrderID;
var cartItems = await _cartItemRepository.GetCartItems(mappedEntities.ApplicationUserId);
var cartDto = new CartItemDto();
foreach(var item in cartItems)
{
cartDto.ItemID = item.ItemID;
cartDto.ItemLookupCode = item.ItemLookupCode;
cartDto.CategoryID = item.CategoryID;
cartDto.DepartmentID = item.DepartmentID;
cartDto.itemDescription = item.itemDescription;
cartDto.SubDescription3 = item.SubDescription3;
cartDto.Quantity = item.Quantity;
cartDto.Weight = item.Weight;
cartDto.SnapShotPrice = item.SnapShotPrice;
cartDto.StoreId = item.StoreId;
cartDto.barcode = item.barcode;
cartDto.Email = item.Email;
cartDto.ItemImage = item.ItemImage;
};
var items = new OrderItems()
{
OrderId = id,
ItemID = cartDto.ItemID,
ItemLookupCode = cartDto.ItemLookupCode,
CategoryID = cartDto.CategoryID,
DepartmentID = cartDto.DepartmentID,
itemDescription = cartDto.itemDescription,
SubDescription3 = cartDto.SubDescription3,
Quantity = cartDto.Quantity,
Weight = cartDto.Weight,
SnapShotPrice = cartDto.SnapShotPrice,
StoreId = cartDto.StoreId,
barcode = cartDto.barcode,
Email = cartDto.Email,
ItemImage = cartDto.ItemImage,
};
_orderItemsRepository.Add(items);
await _orderItemsRepository.Save();
return Ok(id);
}
return BadRequest(ModelState);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.InnerException.Message);
}
}
every time i run this api order header added successfully and order items add first item only
which cart items return with array of items ,
can any one help me in that ,
You need to put Add (and maybe .Save()) inside the foreach:
var cartItems = await _cartItemRepository.GetCartItems(mappedEntities.ApplicationUserId);
foreach(var item in cartItems)
{
var cartDto = new CartItemDto(); // inside foreach
cartDto.ItemID = item.ItemID;
....
var item = new OrderItems() // one item - not: items
{
OrderId = id,
ItemID = cartDto.ItemID,
...
ItemImage = cartDto.ItemImage,
};
_orderItemsRepository.Add(item); // add item before moving to next item.
}
await _orderItemsRepository.Save();
BTW. I'm not sure why you need cartDto; I think you can eliminate it:
var cartItems = await _cartItemRepository.GetCartItems(mappedEntities.ApplicationUserId);
foreach(var item in cartItems)
{
var item = new OrderItems() // one item - not: items
{
OrderId = id,
ItemID = item.ItemID,
...
ItemImage = item.ItemImage,
};
_orderItemsRepository.Add(item); // add item before moving to next item.
}
await _orderItemsRepository.Save();
The code is not correct.In the below line you it should be List instead of object
var cartItems = await _cartItemRepository.GetCartItems(mappedEntities.ApplicationUserId);
var cartDtoList = new List<CartItemDto>();
foreach(var item in cartItems)
{
carDto carDto= new CarDto();
cartDto.ItemID = item.ItemID;
cartDto.ItemLookupCode = item.ItemLookupCode;
cartDto.CategoryID = item.CategoryID;
cartDto.DepartmentID = item.DepartmentID;
cartDto.itemDescription = item.itemDescription;
cartDto.SubDescription3 = item.SubDescription3;
cartDto.Quantity = item.Quantity;
cartDto.Weight = item.Weight;
cartDto.SnapShotPrice = item.SnapShotPrice;
cartDto.StoreId = item.StoreId;
cartDto.barcode = item.barcode;
cartDto.Email = item.Email;
cartDto.ItemImage = item.ItemImage;
carDtoList.Add(carDto)
};
Similarly the orderItems will also be list.
The other simplest solution is to put all the things inside foreach loop like this
foreach(var item in cartItems)
{
cartDto.ItemID = item.ItemID;
cartDto.ItemLookupCode = item.ItemLookupCode;
cartDto.CategoryID = item.CategoryID;
cartDto.DepartmentID = item.DepartmentID;
cartDto.itemDescription = item.itemDescription;
cartDto.SubDescription3 = item.SubDescription3;
cartDto.Quantity = item.Quantity;
cartDto.Weight = item.Weight;
cartDto.SnapShotPrice = item.SnapShotPrice;
cartDto.StoreId = item.StoreId;
cartDto.barcode = item.barcode;
cartDto.Email = item.Email;
cartDto.ItemImage = item.ItemImage;
var items = new OrderItems()
{
OrderId = id,
ItemID = cartDto.ItemID,
ItemLookupCode = cartDto.ItemLookupCode,
CategoryID = cartDto.CategoryID,
DepartmentID = cartDto.DepartmentID,
itemDescription = cartDto.itemDescription,
SubDescription3 = cartDto.SubDescription3,
Quantity = cartDto.Quantity,
Weight = cartDto.Weight,
SnapShotPrice = cartDto.SnapShotPrice,
StoreId = cartDto.StoreId,
barcode = cartDto.barcode,
Email = cartDto.Email,
ItemImage = cartDto.ItemImage,
};
_orderItemsRepository.Add(items);
await _orderItemsRepository.Save();
return Ok(id);
}

Amazon DynamoDBv2 QueryOperationConfig SelectValues.Count not working

I have this piece of code like this:
var options = new DynamoDBOperationConfig
{
ConditionalOperator = ConditionalOperatorValues.Or,
OverrideTableName = nameTable,
ConsistentRead = true
};
new QueryOperationConfig()
{
IndexName = indexName,
Filter = queryFilter,
Select = SelectValues.Count
};
result = context.FromQueryAsync<TEntity>(queryConfig, options).GetRemainingAsync().Result;
as per the documentation, it should return just the count of values that match the filter, at least, the piece of code in the SelectValues class says that
//
// Summary:
// An enumeration of all supported Select values for Query and Scan. Value of Count
// will force service to return the number of items, not the items themselves.
but result is always an empty list; how can i make the count work ?
If you are still looking for the answer, this is the solution:
new QueryOperationConfig()
{
IndexName = indexName,
Filter = queryFilter,
Select = SelectValues.Count,
ConsistentRead = true
};
var table = context.GetTargetTable<TEntity>();
var search = table.Query(queryConfig);
result = search.Count;
Having ConsistentRead set to true will cause it to give you real time updates when the table is updated.
It's not working on Document level...
You can try to do this in low level model.
int count = 0;
Dictionary<string, AttributeValue> lastKey = null;
do
{
var request = new QueryRequest
{
TableName = "tableNmae",
IndexName = "indexName",
KeyConditionExpression = "ID= :v_ID",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{
":v_ID",
new AttributeValue
{
N = "1"
}
}
},
ConsistentRead = false,
Select = Select.COUNT,
ExclusiveStartKey = lastKey
};
var respone = await tableClient.QueryAsync(request);
count += respone.Count;
lastKey = respone.LastEvaluatedKey;
} while (lastKey != null && lastKey.Count != 0);

Datatables Object Reference not set to instance of an object for one variable

This is my datatables serverside implementation. FilterInput contains 5 variables:
Level <- string
Message <- string
Exception <-string
StartDate <- DateTime
EndDate <- DateTime
For some reason when I run this code as it is, I will always get this error:
{System.NullReferenceException: Object reference not set to an
instance of an object.
This is referring to this line:
data = data.Where(
u => u.Level.ToString().ToLower().Contains(FilterInput.Level.ToLower()) &&
u.Message.ToString().ToLower().Contains(FilterInput.Message.ToLower()) &&
u.Exception.ToString().ToLower().Contains(FilterInput.Exception.ToLower())
).ToList();
However, if I remove the search for FilterInput.Exception, everything runs fine again. I have tested it with input ("abc") or without input ("") and the results are the same. The other FilterInputs don't have the same error.
public JsonResult Search(SearchViewModels Input, EventLogsSearchViewModel FilterInput)
{
JsonResult result = new JsonResult(null);
try
{
var data = dbContext.EventLogs.ToList();
int totalRecords = data.Count;
var modelStructure = new Dictionary<int, string>();
modelStructure.Add(1, "Level");
modelStructure.Add(2, "TimeStamp");
modelStructure.Add(3, "LogEvent");
modelStructure.Add(4, "Message");
modelStructure.Add(5, "MessageTemplate");
modelStructure.Add(6, "Exception");
modelStructure.Add(7, "Properties");
var StartDate = FilterInput.StartDate != default(DateTime);
var EndDate = FilterInput.EndDate != default(DateTime);
if ((!string.IsNullOrEmpty(FilterInput.Level) && !string.IsNullOrWhiteSpace(FilterInput.Level)) ||
(!string.IsNullOrEmpty(FilterInput.Message) && !string.IsNullOrWhiteSpace(FilterInput.Message)) ||
(!string.IsNullOrEmpty(FilterInput.Exception) && !string.IsNullOrWhiteSpace(FilterInput.Exception)) ||
(StartDate && EndDate))
{
data = data.Where(
u => u.Level.ToString().ToLower().Contains(FilterInput.Level.ToLower()) &&
u.Message.ToString().ToLower().Contains(FilterInput.Message.ToLower()) &&
u.Exception.ToString().ToLower().Contains(FilterInput.Exception.ToLower())
).ToList();
data = data.Where(u => u.TimeStamp >= FilterInput.StartDate && u.TimeStamp <= FilterInput.EndDate).ToList();
}
if (!(string.IsNullOrEmpty(Input.Order) && string.IsNullOrEmpty(Input.OrderDir)))
{
var columnName = modelStructure.FirstOrDefault(f => f.Key == Convert.ToInt32(Input.Order));
data = data.AsQueryable().OrderBy(columnName.Value + " " + Input.OrderDir).ToList();
}
int recFilter = data.Count;
data = data.Skip(Input.StartRec).Take(Input.PageSize).ToList();
var modifiedData = data.Select(u => new EventLogsListViewModel
{
Id = u.Id,
Message = u.Message,
MessageTemplate = u.MessageTemplate,
Level = u.Level,
TimeStamp = u.TimeStamp,
Exception = u.Exception,
Properties = u.Properties,
LogEvent = u.LogEvent
});
result = this.Json(new
{
draw = Convert.ToInt32(Input.Draw),
recordsTotal = totalRecords,
recordsFiltered = recFilter,
data = modifiedData,
order = Input.Order,
orderdir = Input.OrderDir
});
}
catch (Exception e)
{
logger.LogError(e, LoggingGlobals.LoadingException);
}
return result;
}
EDIT: The exception still happens even when FilterInput.Exception is not null

Conditional to limit .Net webservice results

I'm not sure if this is the right way but I have a web service that returns json. Now I wanted to set a conditional to omit rows returned that have a value of false in cell appearInShowcase. Most of the code is pretty straight forward what it does but the cell that has a true false value is appearInShowcase which is in a table photo. In the ms sql database the appearInShowcase is of type ntext.
public List<wsGalleryPhotos> GetGalleryPhotos(int collectionID)
{
photoDataContext dc = new photoDataContext();
List<wsGalleryPhotos> results = new List<wsGalleryPhotos>();
System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.GetCultureInfo("en-US");
foreach (photo photo in dc.photos.Where(s => s.collectionID == collectionID))
{
if(photo.appearInShowcase == "true")
{
results.Add(new wsGalleryPhotos()
{
photoID = photo.photoID,
collectionID = Convert.ToInt32(photo.collectionID),
name = photo.name,
description = photo.description,
filepath = photo.filepath,
thumbnail = photo.thumbnail
});
}
}
return results;
}
if you want to add a condition, you should do it like this:
public List<wsGalleryPhotos> GetGalleryPhotos(int collectionID)
{
photoDataContext dc = new photoDataContext();
List<wsGalleryPhotos> results = new List<wsGalleryPhotos>();
System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.GetCultureInfo("en-US");
results = dc.photos.Where(s => s.collectionID == collectionID && s.appearInShowcase == "true")
.Select(s => new wsGalleryPhotos
{
photoID = s.photoID,
collectionID = collectionID,
name = s.name,
description = s.description,
filepath = s.filepath,
thumbnail = s.thumbnail
}).ToList();
return results;
}

Add parent row and add child for that new parent row

i am creating new record in 'Timecard' table and at the same time i want to create one record in 'TimecardStatusTrack' table using entity framework. i am able to create parent record but while adding child record i am getting exception. the code i have written is like
var fEmpManager = DependencyContainer.GetInstance<IBusinessService<FacilityEmployee>>();
int timecardStatusDidNotWork =
Convert.ToInt32(GeneralCodeId.TimeCardStatusDidNotWork, CultureInfo.InvariantCulture);
Timecard timecard = new Timecard();
TimecardStatusTrack timecardStatus = new TimecardStatusTrack();
try
{
var fEmp = fEmpManager.Where(w => w.JobId == jobId && w.AgencyBiddingProfile.AgencyCandidateId == agencyCandidateId).FirstOrDefault();
timecard.JobId = jobId;
timecard.AgencyCandidateId = agencyCandidateId;
timecard.WeekStartDate = Convert.ToDateTime(weekStartDate, CultureInfo.InvariantCulture);
timecard.WeekEndDate = Convert.ToDateTime(weekEndDate, CultureInfo.InvariantCulture);
timecard.FacilityEmployeeId = fEmp.Id;
timecard.FacilityId = fEmp.FacilityId;
timecard.TimecardStatusGCId = timecardStatusDidNotWork;
timecard.AddUser = SessionManager.AuthorizedInfo.UserId;
timecard.AddDate = DateTime.Now;
timecardStatus.TimecardStatusGCId = timecardStatusDidNotWork;
timecardStatus.AddUser = SessionManager.AuthorizedInfo.UserId;
timecardStatus.AddDate = DateTime.Now;
timecardStatus.UpdatedBy = SessionManager.AuthorizedInfo.UserId;
timecardStatus.Comments = string.Empty;
_ViewTimeCardBusibessService.Create(timecard);
timecard.TimecardStatusTracks.Add(timecardStatus);
_ViewTimeCardBusibessService.Update(timecard);
}
catch (Exception ex)
{
HandleValidationErrors(ex);
}
finally
{
DependencyContainer.ReleaseInstance(fEmpManager);
}

Resources