Dynamic variables in linq select statement - vb.net

I have a listbox that is dynamically filled by certain values depending on what table has been selected from another list box. Once a value is selected, it is being graphed vs a date & time range. With my ignorance of linq: depending on what value is selected, the linq to sql statement I need to create to grab data from my database is different as I can't use an index on an anonymous type.
result = From t In db.APS _
Where t.DateTime >= startDate And _
t.DateTime <= finishDate And t.Weight = weight _
Select t.DateTime, t.TotalConcentration
t.TotalConcentration should be selected if my listbox value is "Total Concentration", but if it's something else, like "Temperature" or "Flow Rate" (connected to appropreate database columns) - this method obviously isn't going to work. I need to be able to dynamically select a specific column from the anonymous type list, or use some other method I'm unaware of to do this. I'm using VB, but if you have a solution in C# it would also be appreciated.

Have a look at Dynamic Linq. Dynamic Linq allows you to specify field and table names in your Linq statements as strings, so you should be able to pass it a string from your listbox to specify the field you want to Select.
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Related

SQL Injection from a textbox

I'm new to MS Access.
So, I wrote a SQL query(query name = qryEmployeeInfo) which shows employee information. The query outputs two columns. The employee ID(header name = employee_ID) and the corresponding employee address(header name = employee_address).
My Access form has a text box(text box name = txtEmployeeID) that I want the user to be able to enter the employee_ID into and have it output the corresponding employee_address into another text box (text box name = txtEmployeeAddress). I also want the employee_address to be in the format of a string variable so I can perform other VBA checks on it later(for example - if LIKE "California" THEN...something).
I want to write what (I think) is called an injection SQL query so that I can pull the address data from the query for that specific employee_ID. I believe the format should look like this:
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("select employee_address from qryEmployeeInfo where employee_ID = "' & txtEmployeeID & "'", dbOpenDynaset)
Do I have this written correctly?
If so, then how do I get that output into a string variable format(variable name = strEmployeeAddress)?
After I get the employee address into a string variable format I want to simply use txtEmployeeAddress.value = strEmployeeAddress to populate the employee address text box. Again, I also want the employee_address to be in the format of a string variable so I can perform other VBA checks on it later(for example - if LIKE "California" THEN...something).
Any help you could provide would be greatly appreciated.
If employee_ID is a number field, remove apostrophe delimiters.
If employee_ID is a text field, move first apostrophe so it is within quote marks.
"select employee_address from qryEmployeeInfo where employee_ID = '" & txtEmployeeID & "'"
Then txtEmployeeAddress = rs!employee_address
However, instead of opening a recordset object, could just use DLookup.
txtEmployeeAddress = DLookup("employee_address", "qryEmployeeInfo", "employee_ID =" & txtEmployeeID)
Or even better, eliminate the VBA. The DLookup() expression can be in textbox ControlSource property, just precede with = sign.
However, domain aggregate functions can perform slowly. So instead of textbox, use a combobox for selecting employee. Include employee information in combobox RowSource. Expression in textbox references column of combobox: =combobox.Column(1). Issue is combobox has limit on how many characters can be pulled into column so if field is memo (long text) type, this approach is not feasible and should use DLookup.
The address will be available in textbox for use as long as this form is open. If you want the address to be available to other procedures even after form is closed, then need to set a global or public variable. Such variable must be declared in a module header to make it available to multiple procedures. TempVars are another way to hold values for future use. I have never used them.

Sorting Data on Form in Access 2010 by VBA

I have the following setup:
Table "Mitarbeiter" (Users) with fields: "UNummer" / "Sortierung" /....
Table "Mo01" (a sheet for every month) with fields: "UNummer" / "01" / "02" / ....
The Field UNummer in Table Mo01 is a combination field that gets Mitarbeiter.UNummer and saves it as text
I call a Form "Monatsblatt" that is based on the table Mo01.
In that Form I have a Field "fldSort" that is calling "Sortierung" from table "Mitarbeiter". The Data in that field is based on "=DomWert("Sortierung";"Mitarbeiter";"UNummer = '" & [ID] & "'")"
This works and looks like this:
I am trying to sort the form by that "fldSort" in Form "Monatsblatt" by using this code:
Form_Monatsblatt.OrderBy = "fldSort"
Form_Monatsblatt.OrderByOn = True
When I start the form with that code running, Access asks for parameters:
I tried a lot of different ways of writing the code, referencing to the field in different ways. I do NOT want to base the form on anything other then the table.
Why not ask the wide world watch "Why Access asking me for Parameter"? That would have brought you to the clue I think. Debug.Print or MsgBox your .OrderBy and you see it's "fldSort", not a valid sort. Access is assuming you want to use a parameter called fldSort, but you want the string in the variable fldSort, but it's not recognized, because of the double quotes surrounding it. Everything between 2 double quotes is interpreted as a string, even it's a var name.
Delete the quotes and everything will work fine (if your sort string is sufficent)!
Form_Monatsblatt.OrderBy = fldSort
[Update]
Late, but now I see the clue. You added a calculated field to the form, but you can't sort or filter them.
Instead of appending this field to the table, create a query and add it there, then you bind the form to the query and add the field to the form. Now you can filter and sort as you like!
The query looks like this:
SELECT *,
Dlookup("Sortierung","Mitarbeiter","UNummer = '" & [ID] & "'") AS ldSort
FROM Mo01;
Or with a join:
SELECT
Mo01.*,
Mitarbeiter.Sortierung AS fldSort
FROM
Mo01
LEFT JOIN
Mitarbeiter
ON
Mo01.ID = Mitarbeiter.UNummer;
Now you can use
Form_Monatsblatt.OrderBy = "fldSort"
Form_Monatsblatt.OrderByOn = True
because you have a bound control called fldSort.
[/Update]

Use an Access Forms Unbound text box as a Field filter in a table

Access 2013 - Reference an Unbound text box on a Form
I am currently trying to use an unbound text box [Text161] on a Form name [DCM_Gap_Servers] to sort information through a table. I want the query that I created to be able to take the users input from [DCM_Gap_Servers]![Text161] as the field that is being sorted from the table names 'Server'.
This is the SQL I am using right now in the query:
SELECT * FROM Servers WHERE "Forms![DCM_Gap_Servers]![Text161]" IS NULL
** I have already Tried:
"Forms![DCM_Gap_Servers]![Text161]" ; (Forms![DCM_Gap_Servers]![Text161]); Forms.[DCM_Gap_Servers]![Text161]
This will work at any time if I replace the Text Box reference with the actual Field name I am using, but since there are hundreds of combinations of fields, I need the reference to work.
I have looked all over, and I can't seem to find the correct answer. I am willing to do it in VBA if needed, whatever it takes to get the filtering done correctly.
Thank You.
It is:
SELECT * FROM Servers WHERE Forms.[DCM_Gap_Servers].[Text161] IS NULL
but that will just select all records whenever your textbox is Null.
So it rather is:
SELECT * FROM Servers WHERE SomeField = Forms.[DCM_Gap_Servers].[Text161]
To use the form value as a field name, you must use concatenated SQL:
strSQL = "SELECT * FROM Servers WHERE " & Forms![DCM_Gap_Servers]![Text161].Value & " IS NULL"
This you might pass to the SQL property of an existing query object:
MyQueryDef.SQL = strSQL
Or:
Constant SQL As String = "SELECT * FROM Servers WHERE {0} IS NULL"
FieldName = Forms![DCM_Gap_Servers]![Text161].Value
MyQueryDef.SQL = Replace(strSQL, "{0}", FieldName)
Of course, take care the the field name isn't a zero length string.

Can we allow user to only select one parameter at a time in SSRS

I have three date columns. My report has 6 parameters: start and end date range for all three columns. Currently user has to select all date range but what if I want to allow user to only select one date range at a time. I cannot do "allow NULL values" option in the parameter because that see it as a field containing null value. I don't think it's possible to allow user to select only one parameter at a time so I'm trying an approach where there will be three parameters: one will consists of date field names. And rest two are based on date range of the field that is select from previous parameter. For example user selects a date field name from first and then date parameters will be cascaded and grab a value of date field based on the date field name that is selected in previous parameter. But I'm not sure exactly how to approach this. Any ideas?
I do that in some of my reports. The first parameter is "Does the range apply to A, B, or C" and the second and third parameters are the start and end data respectively. Well, I use integers, but dates should work the same as long as you format them.
The way it works, is you set the query in your dataset to be a function, and build it as mostly a quote but with the parameter values substituted in. A typical one might be
= "SELECT * FROM dbo.Trips WHERE " + Parameters!WhatField.Value + " between '" + FormatDateTime(Parameters!StartDate.Value, dateformat.shortdate) + "' and '" + FormatDateTime(Parameters!EndDate.Value, dateformat.shortdate) + "'"
Your parameter "WhatField" is a drop down list with 3 permitted values, make the value be the field name and the display be what your user wants to see as a description of the field.
I think you have to set the query for delayed evaluation somewhere (but I can't spot where right now, so maybe I'm mis-remembering), and you should set default values for your parameters that don't crash your report, but other than that it's fairly straightforward.
Oh, and to make the query a function it's just like a text query but hit the button to the right of the text box - it has a "fx" on it
If you need an even more complex query, you can put the whole query text in code (off the report properties) and call that function from the "fx" button to generate your query string.

Why doesn't my query use my criteria?

I have a db in Access and I'm trying to get a textbox to run my query and pass an other bounded textbox's value in as the criteria in DLookUp. I have the query running in design view and when I enter the criteria directly it returns the correct results. When I open the report it gives me the sum of all the possible rows. In other words it doesn't filter the rows.
I haven't used Access in about twelve years, thankfully, and everything I've done up to this point has been tutorial/example patchwork, but here it is...
SQL Query:
SELECT Sum(IIf(Attended=-1,1,0)) AS attendance
FROM Students_Classes_Attendance
WHERE (((CStr([Students_Classes_Attendance].[Class_Id]))=[classId]));
DLookUp as Control Source:
=DLookUp("[Total Attendance by Class]![attendance]",
"[Total Attendance by Class]",
"[Class_Id] =" & [Class_Id])
I'm lost at the moment. I'm guessing that the value isn't there before the query fires and since the criteria is an optional parameter that it's being passed null, but I would hope you'd get an error from that. Not that #Error is very meaningful anyway.
Does anyone know for certain the problem and the best way to correct it? Thanks.
Edit:
I did the changes recommended in the answer so now my DLookUp looks like...
=DLookUp("[attendance]",
"[Total Attendance by Class]",
"[Class_Id] =" & [Class_Id])
...still returns the total for all rows. Removing the criteria completely makes no difference either, which returns me to thinking it has something to do with the bound textbox not having a value.
DLookup uses the following syntax:
Syntax for numerical values:
DLookup("FieldName" , "TableName" , "Criteria = n")
Syntax for strings: (note the single apostrophe before and after the string value)
DLookup("FieldName" , "TableName" , "Criteria= 'string'")
Syntax for dates: (note the # before and after the date value)
DLookup("FieldName" , "TableName" , "Criteria= #date#")
I believe you just need to remove the table name from the first parameter. Try this:
=DLookUp("[attendance]", "[Total Attendance by Class]", "[Class_Id] = " & [Class_Id])
Keep in mind that if Class_Id is a Text Field, you need to surround it by single quotes:
=DLookUp("[attendance]", "[Total Attendance by Class]", "[Class_Id] = '" & [Class_Id] & "'")