Inserting Query Each Single Query Results as Contents to a Combo Box - c#

I have this query where I am expecting a lot of results.
private void addContentInCmbPhy() {
DbClassesDataContext myDb = new DbClassesDataContext(dbPath);
var match = from phy in myDb.Physicians
select phy.Phy_FName;
for(IQueryable<string> phy in match){
cmbPhysicians.Items.Add(phy);
}
}
In my query above it will return several results, and I want those name results to be inserted as Items in my comboBox, how would I add it? it gives me this following errors
Error 7 Only assignment, call, increment, decrement, and new object expressions can be used as a statement C:\Users\John\documents\visual studio 2010\Projects\PatientAdministration\PatientAdministration\Pat_Demog.cs 415 43 PatientAdministration
Error 8 ; expected C:\Users\John\documents\visual studio 2010\Projects\PatientAdministration\PatientAdministration\Pat_Demog.cs 415 40 PatientAdministration
Error 9 ; expected C:\Users\John\documents\visual studio 2010\Projects\PatientAdministration\PatientAdministration\Pat_Demog.cs 415 43 PatientAdministration

Aren't you using the wrong looping statement? It should be foreach instead of for. If you are using a for loop then you need to have an incrementer.

It is god if you have you datacontext inside of a using statement. Becuase then you just have the connection as long as you need. And you are disposing it directly after. I would probably do it something like this:
private void addContentInCmbPhy()
{
List<string> match;
using (var myDb = new DbClassesDataContext(dbPath))
{
match = (from phy in myDb.Physicians
select phy.Phy_FName).ToList();
}
foreach(var phy in match){
cmbPhysicians.Items.Add(phy);
}
}

private void addContentInCmbPhy()
{
List<string> match;
using (var myDb = new DbClassesDataContext(dbPath))
{
cmbPhysicians.Items.AddRange((from phy in myDb.Physicians
select phy.Phy_FName).ToArray());
}
// foreach(var phy in match){
// cmbPhysicians.Items.Add(phy);
// }
}

Related

Using Dapper and Npgsql unable to select from a list of Guids

Taking an example from a previous post; I am unable to query using IN and a list of Guids; I get different errors depending on what I have tried...
public class DataAccess
{
string _connectionString = "{your connection string}";
public async Task<IEnumerable<CustomerDto>> GetListAsync(List<Guid> customers)
{
const string query = #"
SELECT Id,
Name
FROM Customers
WHERE Id IN #CustomerIdList
";
using (var c = new SqlConnection(_connectionString))
{
return await c.QueryAsync<CustomerDto>(query, new { CustomerIdList = customers.ToArray() });
}
}
}
The above fails with 42601: syntax error at or near "$1"
I have tried various things like the below which also fails with 42601: syntax error at or near "$1":
return await c.QueryAsync<CustomerDto>(query, new { CustomerIdList = new[] { customers[ 0 ], customers[ 1 ], customers[ 2 ], customers[ 3 ] } } );
Can anyone help, what am I doing wrong?
EDIT: Fixed query due to copying example code example from another question
Found out that you have to use a different clause as IN does not work with an array of parameters in Postgresql which sounds like a bit of a flaw to me:
WHERE Id = ANY(#CustomerIdList)

How to fix "Incorrect syntax near ')'". when there is no ) in the query

I am attempting to run a query against my database using Dapper, however, an exception is being thrown. The message of the exception is
Incorrect syntax near ')'
The part of this that is confusing to me is that I have no right parens in my entire query. It used to have some, but I have been simplifying it until I got to this:
select i.id as EmployeeReviewId
from #ReviewIds i
Which still causes the error.
#ReviewIds is a table-valued-parameter that only has one column, an int column named id.
I am calling the function like this:
await connection.QueryAsync<FooInfo>(sql, new { reviewIds });
where FooInfo is an object that has an EmployeeReviewId property, and reviewIds is an enumerable of int.
I have to assume that this is something to do with how I am using Dapper.
Would anyone know how to fix this issue?
You are probably passing user defined table parameter incorrectly. You have to pass it as DataTable, not as a simple array. A minimal working example is
public class FooInfo
{
public int EmployeeReviewId { get; set; }
}
class Program
{
static async Task Main(string[] args)
{
using (var connection =
new SqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=YOUR_DB_NAME;Server=."))
{
var result = await connection.QueryAsync<FooInfo>("select i.id as EmployeeReviewId from #ReviewIds i", new
{
ReviewIds = CreateTableType(new[] {1, 2, 3})
});
Console.WriteLine(result);
}
}
private static DataTable CreateTableType(IEnumerable<int> nums)
{
var t = new DataTable();
t.SetTypeName("dbo.ArrayOfInt");
t.Columns.Add("id");
foreach (var num in nums)
{
t.Rows.Add(num);
}
return t;
}
}
Where dbo.ArrayOfInt is
CREATE TYPE dbo.ArrayOfInt AS TABLE
(
id int NOT NULL
)

Index was outside the bounds of the array while using Lucene.NET

I am using Lucene.net version 3 library to index the data and search on them but for some reason, sometimes it throws a weird error message internally and I can not even understand why this happens. Below is my code when I try to search on the index:
using (var analyzer = new StandardAnalyzer(Version.LUCENE_30))
{
using (var reader = IndexReader.Open(directory, true))
{
using (var searcher = new IndexSearcher(reader))
{
term = QueryParser.Escape(term);
var parsedQuery =
new MultiFieldQueryParser(Version.LUCENE_30, includedFields, analyzer)
.Parse(term);
var result = searcher.Search(parsedQuery, reader.MaxDoc); //Here happens the error
totalCount = result.TotalHits;
var matches = result.ScoreDocs.OrderByDescending(x => x.Score).ToPaginated(page, size);
foreach (var match in matches)
{
int docId = match.Doc;
var document = searcher.Doc(docId);
var item = //...
list.Add(item);
}
}
}
}
This error message does not always happen, it only happens when some random text string are being set as a searching term, so sometimes it works well and sometimes crashes.
I am trying to escape the term but still no luck. Does anybody have any idea what I might be doing wrong in here ?
Here is the error message:
at Lucene.Net.Search.TermScorer.Score() in d:\Lucene.Net\FullRepo\trunk\src\core\Search\TermScorer.cs:line 136 at Lucene.Net.Search.DisjunctionSumScorer.AdvanceAfterCurrent() in d:\Lucene.Net\FullRepo\trunk\src\core\Search\DisjunctionSumScorer.cs:line 187 at Lucene.Net.Search.DisjunctionSumScorer.NextDoc() in d:\Lucene.Net\FullRepo\trunk\src\core\Search\DisjunctionSumScorer.cs:line 155 at Lucene.Net.Search.BooleanScorer2.NextDoc() in d:\Lucene.Net\FullRepo\trunk\src\core\Search\BooleanScorer2.cs:line 397 at Lucene.Net.Search.BooleanScorer.NextDoc() in d:\Lucene.Net\FullRepo\trunk\src\core\Search\BooleanScorer.cs:line 369 at Lucene.Net.Search.BooleanScorer.Score(Collector collector) in d:\Lucene.Net\FullRepo\trunk\src\core\Search\BooleanScorer.cs:line 389 at Lucene.Net.Search.IndexSearcher.Search(Weight weight, Filter filter, Collector collector) in d:\Lucene.Net\FullRepo\trunk\src\core\Search\IndexSearcher.cs:line 221 at Lucene.Net.Search.IndexSearcher.Search(Weight weight, Filter filter, Int32 nDocs) in d:\Lucene.Net\FullRepo\trunk\src\core\Search\IndexSearcher.cs:line 188 at Blog.Services.SearchService.<>c__DisplayClass3_0.b__0() in E:\Blog\Blog\Blog.Services\SearchService.cs:line 98 at
Here is a random string which makes it crash: 212 i think webapp using ef db first i am trying to use lazy. The string does not have any meaning but still strange to me why it should make lucene crash...

C# IEnumerable to List error?

I got a simple IEnumerable with some data in my debugging session for StockSearchList. How do I convert to a List but ToList is not accespted.
public IEnumerable<StockSearchItemViewModel> StockSearchList
{
get
{
if (string.IsNullOrEmpty(_stockSearchFilter))
return _stockSearchList;
var filterLower = _stockSearchFilter.ToLower();
return _stockSearchList.Where(x => { var symbolLower = x.Symbol.ToLower(); return (symbolLower.StartsWith(filterLower) || symbolLower.StartsWith(filterLower)); });
}
}
In another method i got:
List<StockTickerData> ssl = new List<StockTickerData>();
ssl = StockSearchList<StockTickerData>.ToList();
But I get build error of:
Error 4 The property 'xxxx.StockViewModel.StockSearchList' cannot be used with type arguments .... stockviewmodel.cs 838 19
How do I convert ssl to a be list from the values in StockTickerData
Thanks
It is just a simple syntax error, the right code:
List<StockTickerData> ssl = StockSearchList.ToList();

Parsing SQL Statement With Irony

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

Categories