I am trying to search for data in my datagrid using the code sample below. I have had it working with the code looking a bit different, but I am now going to use async in my coding and I have tried to do so with the sample below, but have no idea how to change the code to work correctly.
private async Task btnSearchSysproStock_Click(object sender, RoutedEventArgs e)
{
using (DataEntities DE = new DataEntities())
{
List<SSData> stockSearch = await (from a in DE.tblSysproStocks where
(a => txtSearchSysproStock.Text == string.Empty || a.StockCode.Contains(txtSearchSysproStock.Text)) //The error is in this line
select new SSData
{
SID = a.StockID,
SCode = a.StockCode,
SDescription = a.StockDescription,
SConvFactAltUom = (float)a.ConvFactAltUom,
...
}).ToListAsync();
dgSysproStock.ItemsSource = stockSearch;
}
}
I am getting the following error:
Cannot convert lamba expression to type 'bool' because it is not a delegate type
Can anyone please help me to get this code that I am using to work. Thanks in advance! :)
LINQ where clause expects bool expression, you don't need lambda here :
from a in ...
where txtSearchSysproStock.Text == string.Empty ||
a.StockCode.Contains(txtSearchSysproStock.Text)
select ...
Related
i am trying to get data from database passing a string value. but get null value instead of the data.
i have tried the following code
order getCustomerOrder(string or_n)
{
using (foodorderingEntities db = new foodorderingEntities ())
{
var result = db.orders.Where(or => or.order_no == or_n).FirstOrDefault();
return result;
}
}
please some one guide me to solve this problem.
Please paste your order object, so we know if its reference object/primitive etc, you can use this to understand the two ways to retrieve orders.
I would recommend you read this answer & this MSDN string compare, if your default culture is causing an issue in the comparison, it will help you understand whats going on
Options 1:
// Query syntax
IEnumerable<CustomerOrder> queryResultsCustomerOrder =
from order in orders
where order.number == myOrderNumber
select order;
Options 2:
// Method-based syntax
IEnumerable<CustomerOrder> queryResultsCustomerOrder2 = orders.Where(order => order.Number == myOrderNumber);
using the above, now you can get however many orders the customer has. I am assuming your order is a number, but you can change it to whatever like a string.
Int based order comparison sample
IEnumerable<CustomerOrder> getCustomerOrder(int myOrderNumber)
{
if(myOrderNumber <1) return null;
using (foodorderingEntities dbContextOrderSet = new foodorderingEntities())
{
IEnumerable<CustomerOrder> resultsOneOrManyOrders = orders.Where(order => order.Number == myOrderNumber);
return resultsOneOrManyOrders ;
}
}
string based order comparison
IEnumerable<CustomerOrder> getCustomerOrder(string myOrderNumber)
{
//no orders
if(String.IsNullOrEmpty(myOrderNumber)) return null;
using (foodorderingEntities dbContextOrderSet = new foodorderingEntities())
{
IEnumerable<CustomerOrder> resultsOneOrManyOrders = orders.Where(order => order.Number == myOrderNumber);
// you can replace the *** comparison with .string.Compare and try inside the block
return resultsOneOrManyOrders ;
}
}
I am using the except keyword in c# for the first time and I have been struggling a lot with this. If possible could you please have a look into my function and let me know where I am wrong.
I need to return the string of arrays. indivEmails1 and indivEmails2 contains an array of email id's. I need to return an email id's which are not in indivEmails2 but not in indivEmails1. But it has to be string of array.
public string[] getNewCCEmailsIDs(WorkOrderModel model)
{
string[] emailids = null;
var result = _db.WorkOrders
.Where(w => w.idWorkOrder == model.idWorkOrder && w.idCompany == model.idCompany)
.Select(w => new {w.Status, w.ExternalEmails});
if (dbItem.Status == (int) WorkOrderStatus.Approved )
{
string NewCCEmail = "";
var comEmails1 = dbItem.ExternalEmails.Trim(';');
string[] indivEmails1 = comEmails1.Split(';');
string comEmails2 = model.ExternalEmails.Trim(';');
string[] indivEmails2 = comEmails2.Split(';');
IEnumerable<string> emailsToAdd = indivEmails2.Except(indivEmails1);
//NewCCEmail = emailsToAdd;
}
if (NewCCEmail != "") // when client delete an email id from CC and press save.
emailids = NewCCEmail.Split(';');
}
return emailids;
}
I am getting below error. I have looked eveywhere but no luck.
Error 54 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<string>' to 'string[]'. An explicit conversion exists (are you missing a cast?) C:\Users\Bakul\Documents\GitHub\Maxpanda\Maxpanda\Controllers\WorkOrderController.cs 930 25 Maxpanda
Any help will be very much appreciated.
Thanks.
Use ToList()
List<string> emailsToAdd = indivEmails2.Except(indivEmails1).ToList();
Thank you every one. Changed code to below and it worked.
string[] emailsToAdd = indivEmails2.Except(indivEmails1).ToArray();
I am using C# and have a login session.
The site will only view the news (nyhet) that the journalist have written. (It's a site where the journalist can edit the news)
protected void FyllNyhetDropDownList()
{
using (NyhetAdminDataContext dbKobling = new NyhetAdminDataContext())
{
Journalist brukernavn = (from journalist in dbKobling.Journalists
where journalist.JournalistId = Convert.ToInt16(Session["bruker"].ToString())
select journalist).SingleOrDefault();
List<Nyhet> nyhetliste = (from nyhet in dbKobling.Nyhets
select nyhet).ToList();
if (nyhetliste.Count() > 0)
{
NyhetDropDowwnList.DataTextField = "Tittel";
NyhetDropDowwnList.DataValueField = "NyhetId";
NyhetDropDowwnList.DataSource = nyhetliste;
NyhetDropDowwnList.DataBind();
}
}
}
It's here all go wrong. Can anyone help?
where journalist.JournalistId = Convert.ToInt16(Session["bruker"].ToString())
I get the error message
Cannot implicitly convert type 'int' to 'bool'
Thanks for any help!
Shouldn't you be using ==?
where journalist.JournalistId == Convert.ToInt16(Session["bruker"].ToString())
try below
Journalist brukernavn = dbKobling.Journalists.SingleOrDefault(x => x.JournalistId ==
Convert.Int16(Session["bruker"].ToString()));
I am trying to create a method that converts a regular sql statement to c# objects, So i decided to use Irony to parse the sql statement then i return the statement as an Action that contains the type of the statement and the values of it depending on the type
Here is my non completed code [ Because i got frustrated as i don't know what to do then ]
private List<Action> ParseStatement(string statement)
{
var parser = new Parser(new SqlGrammar());
var parsed = parser.Parse(statement);
var status = parsed.Status;
while (parsed.Status == ParseTreeStatus.Parsing)
{
Task.Yield();
}
if (status == ParseTreeStatus.Error)
throw new ArgumentException("The statement cannot be parsed.");
ParseTreeNode parsedStmt = parsed.Root.ChildNodes[0];
switch (parsedStmt.Term.Name)
{
case "insertStmt":
var table = parsedStmt.ChildNodes.Find(x => x.Term.Name == "Id").ChildNodes[0].Token.ValueString;
var valuesCount =
parsedStmt.ChildNodes.Find(x => x.Term.Name == "insertData").ChildNodes.Find(
x => x.Term.Name == "exprList").ChildNodes.Count;
var values = parsedStmt.ChildNodes.Find(x => x.Term.Name == "insertData").ChildNodes.Find(
x => x.Term.Name == "exprList").ChildNodes;
foreach (var value in values)
{
string type = value.Token.Terminal.Name;
}
break;
}
return null;
}
private Type ParseType(string type)
{
switch (type)
{
case "number":
return typeof (int);
case "string":
return typeof (string);
}
return null;
}
So the Question Here is : How could i make use of Irony to convert a string SQL Statement to a c# objects ?
Here is an example of what i want to achieve :
INSERT INTO Persons VALUES (4,'Nilsen', 'Johan', 'Bakken 2',
'Stavanger')
And get it converted to
return new Action<string type, string table, int val1, string val2, string val3, string val4, string val5>;
Dynamically depending on what the method have read from the statement.
I hope i have well explained my idea so you can help me guys, And if there is something unclear please tell me and i will try to explain it.
I was trying to parse SQL with Irony as well. I gave up because the sample SQL parser in Irony don't handle: CTEs, Order by column number, half the special statements like
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
While I had a great time learning about Irony, I don't have the coding chops to implement all the aforementioned parts correctly.
I ended up using the Microsoft-provided SQL parsing library. Sample code for LINQPad 5 below:
// Add a reference to
// C:\Program Files (x86)\Microsoft SQL Server\130\SDK\Assemblies\
// Microsoft.SqlServer.TransactSql.ScriptDom.dll
//
// https://blogs.msdn.microsoft.com/gertd/2008/08/21/getting-to-the-crown-jewels/
public void Main()
{
var sqlFilePath = #"C:\Users\Colin\Documents\Vonigo\database-scripts\Client\Estimate\spClient_EstimateAddNew.sql";
bool fQuotedIdenfifiers = false;
var parser = new TSql100Parser(fQuotedIdenfifiers);
string inputScript = File.ReadAllText(sqlFilePath);
IList<ParseError> errors;
using (StringReader sr = new StringReader(inputScript))
{
var fragment = parser.Parse(sr, out errors);
fragment.Dump();
}
}
If you are not doing this as a fun exercise I would recommend using Linq to SQL to generate your stub classes or Entity Framework as Drunken Code Monkey mentioned in the comments.
Here's a good article to get you started: Generating EF code from existing DB
I have the following code:
var data = (sender as Button).DataContext as Web.Booking;
EntityQuery<Web.Ticket> ticketQuery =
from t in _ticketContext.GetTicketsQuery()
where t.ticketId == data.ticketId
select t;
LoadOperation<Web.Ticket> loadTicket = this._ticketContext.Load(ticketQuery);
loadTicket.Completed += (s, args) => { MessageBox.Show("Loaded Tickets!"); };
ticketDomainDataSource.DataContext = loadTicket.AllEntities;
var ticketData = ticketDomainDataSource.DataContext as Web.Ticket;
string ticketName = ticketData.ticketName;
The main code that I'm having trouble with is the:
var ticketData = ticketDomainDataSource.DataContext as Web.Ticket;
string ticketName = ticketData.ticketName;
It returns an error:
Object reference not set to an
instance of an object.
Can anyone help me out on what I'm doing wrong here, I can't figure out what's null and how I can return proper data.
Thanks
Your issue is likely that DataContext cannot be cast to Web.Ticket. If you look at the documentation for C# -- as returns a null on a conversion failure. See - http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx
If you change your line of code to
var ticketData = (Web.Ticket) ticketDomainDataSource.DataContext;
you should get a better cast error.