how to find the max id from a generic list - asp.net

i m getting a collection of data in list's object. And from this list i want to get the maximum id.`
Dim objinfo As List(Of AlbumInfo) = objPhotos.GetPhotos_Alb_ID(Me.ModuleId, hdd_AlbID.Value)
Dim Photo_Image As String = ""
Dim str As String = Photo_Image & fu_Photo.PostedFile.FileName.Substring(fu_Photo.PostedFile.FileName.LastIndexOf("."))
If objinfo.Count >= 1 Then
Photo_Image = Convert.ToString(hdd_AlbID.Value) + "_" + Convert.ToString(objinfo.Item("0").Photo_Id + 1)
Else
Photo_Image = Convert.ToString(hdd_AlbID.Value) + "_" + Convert.ToString("1")
End If
this returns the "0"th positions id from Convert.ToString(objinfo.Item("0").Photo_Id + 1)
but i want to get the last item's id.

Well, you specify max in the title, and last in the question, so here's both:
Max:
Photo_Image = hdd_AlbID.Value.ToString() & "_" & _
objinfo.Max(Function(o) o.Photo_Id) _
.Photo_Id.ToString()
Last:
Photo_Image = hdd_AlbID.Value.ToString() & "_" & _
objinfo.Last().Photo_Id.ToString()

Use Max extension method. For example,
...
maxPhotoId = objInfo.Max(Function(photo) photo.Photo_Id).Photo_Id
...

Related

What's the best way to parse an SQL fragment string into a List(of string) for a Listbox control?

I'm trying to take this string:
(("DISPLAY_NAME" like N'sadf%') And ("ID" = 2) And ("IsCRITERION" = null))
and parse it into a List(of string) so that it can be displayed like:
(
(
"DISPLAY_NAME" like N'sadf%'
)
And
(
"ID" = 2
)
Or
(
"IsCRITERION" = null
)
)
I'm close but don't quite have it. My code currently looks like:
Dim filterlist As New List(Of String)
Dim temp As String = String.Empty
Dim lvl As Integer = 0
Dim pad As String = String.Empty
For Each chr As Char In originalString '--- filter is the string i posted above
Select Case chr.ToString.ToLower()
Case "("
filterlist.Add(pad.PadLeft(lvl * 5) & chr)
lvl += 1
Case ")"
filterlist.Add(pad.PadLeft(lvl * 5) & temp)
If lvl > 0 Then lvl -= 1
filterlist.Add(pad.PadLeft(lvl * 5) & chr)
'If lvl > 0 Then lvl -= 1
temp = String.Empty
Case Else
temp &= chr
End Select
Next
'--- Removes the empty line produced by generating the List(of String)
filterlist = filterlist.Where(Function(s) Not String.IsNullOrWhiteSpace(s)).ToList()
listSelectedCriteria.DataSource = filterlist
listSelectedCriteria.DataBind()
Unfortunately, the above code produces something close to what I desire but the "And"s and "Or"s are not in the right places:
(
(
"DISPLAY_NAME" like N'sadf%'
)
(
And "ID" = 2
)
(
Or "IsCRITERION" = null
)
)
Would using regular expressions be better? Thanks for the help
Probably the "best" way (although that's getting into "primarily opinion-based" territory) would be to use a parser, but assuming that your input is limited to similar looking strings, here's what I came up with:
Dim originalString = "((""DISPLAY_NAME"" like N'sadf%') And (""ID"" = 2) And (""IsCRITERION"" = null))"
Dim filterlist = New List(Of String)()
Dim temp = New StringBuilder()
Dim lvl = 0
Dim addLine =
Sub(x As String)
filterlist.Add(New String(" ", lvl * 4) & x.Trim())
End Sub
For Each c In originalString
Select Case c
Case "("
If temp.Length > 0 Then
addLine(temp.ToString())
temp.Clear()
End If
addLine("(")
lvl += 1
Case ")"
If temp.Length > 0 Then
addLine(temp.ToString())
temp.Clear()
End If
lvl -= 1
addLine(")")
Case Else
temp.Append(c)
End Select
Next
If temp.Length > 0 Then
addLine(temp.ToString())
temp.Clear()
End If
filterlist.Dump() ' LINQPad ONLY
This results in:
(
(
"DISPLAY_NAME" like N'sadf%'
)
And
(
"ID" = 2
)
And
(
"IsCRITERION" = null
)
)
However, you will probably end up having to add code as you find different inputs that don't quite work how you want.
Instead of looking at each characters, I would start be doing a split. And then add/remove padding depending on what character is at the start.
Dim tempString As String = "((""DISPLAY_NAME"" like N'sadf%') And (""ID"" = 2) And (""IsCRITERION"" = null))"
Dim curPadding As String = ""
Const padding As String = " "
Dim result As New List(Of String)
For Each s As String In Text.RegularExpressions.Regex.Split(tempString, "(?=[\(\)])")
If s <> "" Then
If s.StartsWith("(") Then
result.Add(curPadding & "(")
curPadding &= padding
result.Add(curPadding & s.Substring(1).Trim())
ElseIf s.StartsWith(")") Then
curPadding = curPadding.Substring(padding.Length)
result.Add(curPadding & ")")
result.Add(curPadding & s.Substring(1).Trim())
Else
result.Add(curPadding & s)
End If
End If
Next

SQL error in Access 2010

I have created a Form in MSAccess 2010 and when running I am getting following error :
The select statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect.
The name of my Database is Accessexp
Here is my code:
Private Sub SearchButton_Click()
Dim dbs As Database
Dim rs As Recordset
Dim qdf As QueryDef
Dim productName As String
Dim lastNQuarters As String
Dim strSql As String
Dim columns As String
Dim compstr As String
Dim curstr As String
Dim timestr As String
Dim tablestr As String
Dim sumstr As String
Dim varItem As Variant
Dim compcount As Integer
Dim colcount As Integer
Dim errorcount As Integer
Dim Monthvalue As String
Set dbs = CurrentDb()
errorcount = 0
colcount = 0
lastNQuarters = Me!quarterbox.Value
tablestr = ""
timestr = Me!Monthbox.Value
MsgBox (timestr)
tablestr = "Q" & lastNQuarters
For Each varItem In Me!columnlist.ItemsSelected
If Me!columnlist.ItemData(varItem) <> "---" Then
columns = columns & "," & Chr(34) & Me!columnlist.ItemData(varItem) & Chr(34)
colcount = colcount + 1
End If
Next varItem
compcount = 0
For Each varItem In Me!practicelist.ItemsSelected
compstr = compstr & "," & Chr(34) & Me!practicelist.ItemData(varItem) & Chr(34)
compcount = compcount + 1
Next varItem
If compcount = 0 Then MsgBox ("Warning: No Practice Selected"): errorcount = errorcount + 1
If colcount = 0 Then MsgBox ("Warning: No Practice Selected"): errorcount = errorcount + 1
If errorcount = 0 Then
lastNQuarters = Me!quarterbox.Value
strSql = "Select " & columns & ", " & tablestr & " from Accessexp where Accessexp.[Quarter] = " & tablestr & " and Accessexp.[Month] = " & timestr & ";"
MsgBox (strSql)
Set rs = dbs.OpenRecordset(strSql, dbOpenSnapshot)
With dbs
Set qdf = .CreateQueryDef("QueryOutput", strSql)
DoCmd.OpenQuery "QueryOutput"
.QueryDefs.Delete "QueryOutput"
End With
dbs.Close
qdf.Close
End If
End Sub
My query is coming like this :
Select ,"Revenue Blended","Revenue Direct" Q4
from Accessexp
where Accessexp.[Quarter] = Q4 and Accessexp.[Month] = April;
Is there any other way to seperate values with commas and not putting in begining
After you've built your string with the leading comma just use
columns = Mid(columns, 2)
to trim off the first character.
Other notes:
Wrap your column names in square brackets, not double quotes
String literals need to be enclosed in quotes.
Your resulting query string should look more like this:
Select [Revenue Blended],[Revenue Direct]
from Accessexp
where Accessexp.[Quarter] = 'Q4' and Accessexp.[Month] = 'April';
Try this updated Code.
Private Sub SearchButton_Click()
Dim dbs As Database, rs As Recordset
Dim qdf As QueryDef
Dim productName As String, lastNQuarters As String
Dim strSql As String, columns As String, compstr As String
Dim curstr As String, timestr As String, tablestr As String
Dim sumstr As String, varItem As Variant
Dim compcount As Integer, colcount As Integer, errorcount As Integer
Dim Monthvalue As String
Set dbs = CurrentDb()
errorcount = 0
colcount = 0
lastNQuarters = Me!quarterbox.Value
tablestr = ""
timestr = Me!Monthbox.Value
MsgBox timestr
tablestr = "Q" & lastNQuarters
For Each varItem In Me!columnlist.ItemsSelected
If Me!columnlist.ItemData(varItem) <> "---" Then
columns = columns & "[" & Me!columnlist.ItemData(varItem) & "],"
colcount = colcount + 1
End If
Next
compcount = 0
For Each varItem In Me!practicelist.ItemsSelected
compstr = compstr & "[" & Me!practicelist.ItemData(varItem) & "],"
compcount = compcount + 1
Next
If compcount = 0 Then
MsgBox ("Warning: No Practice Selected")
errorcount = errorcount + 1
Else
compstr = Left(compstr, Len(compstr)-1)
End If
If colcount = 0 Then
MsgBox ("Warning: No Practice Selected")
errorcount = errorcount + 1
Else
columns = Left(columns, Len(columns)-1)
End If
If errorcount = 0 Then
lastNQuarters = Me!quarterbox.Value
strSql = "SELECT " & columns & " FROM Accessexp WHERE Accessexp.[Quarter] = '" & tablestr & "'" & _
" AND Accessexp.[Month] = '" & timestr & "';"
MsgBox (strSql)
Set rs = dbs.OpenRecordset(strSql, dbOpenSnapshot)
With dbs
Set qdf = .CreateQueryDef("QueryOutput", strSql)
DoCmd.OpenQuery "QueryOutput"
'.QueryDefs.Delete "QueryOutput"
End With
dbs.Close
qdf.Close
End If
End Sub

Index was out of range. Must be non-negative and less than the size of the collection - chart databind

I'm trying to build a datatable and then bind it to a gridview and chart object. The gridview appears fine but when I build the x,y array and bind them to the chart object I get the error above.
I've read many forums to understand that the index is looking at a field that is out of range but I've queried in the immediate window all the fields and the are clearly values there. There error occurs as soon as I bind it to the chart object and I don't know why the chart object doesn't just display properly.
This is my aspx codebehind:
Dim dt As DataTable = New DataTable()
dt.Columns.Add("CompanyName")
dt.Columns.Add("Amount")
dt.Columns.Add("Proportion")
Using DBContext As New fundmatrixEntities
Dim queryUnits = (From c In DBContext.Units Where c.SavingApplicationId = savAppId Select New With {.LoanAppId = c.LoanApplicationId}).Distinct().ToList()
Dim companyName As String = ""
Dim savingsAmount As String = ""
Dim totalProportion As String = ""
Dim totalSavingsAmount As String = ""
For Each loan In queryUnits
If Not loan.LoanAppId Is Nothing Then
companyName = classSQLDirect.ExecQuery("SELECT companyname FROM companyprofile where loanapplicationid='" & loan.LoanAppId.ToString & "'")
savingsAmount = classSQLDirect.ExecQuery("SELECT SUM(Amount) from unit where SavingApplicationId='" & savAppId.ToString & "' and LoanApplicationId='" & loan.LoanAppId.ToString & "'")
totalSavingsAmount = classSQLDirect.ExecQuery("SELECT amount FROM SavingApplication WHERE SavingApplicationId='" & savAppId.ToString & "'")
totalProportion = ((savingsAmount / totalSavingsAmount) * 100) & "%"
dt.Rows.Add(companyName, savingsAmount, totalProportion)
End If
Next
gvwBusinesses.DataSource = dt
gvwBusinesses.DataBind()
End Using
Dim x As String() = New String(dt.Rows.Count - 1) {}
Dim y As String() = New String(dt.Rows.Count - 1) {}
For i As Integer = 0 To dt.Rows.Count - 1
x(i) = dt.Rows(i)(0).ToString()
y(i) = dt.Rows(i)(2).ToString()
Next
chart1.Series(0).Points.DataBindXY(x, y)
chart1.Series(0).ChartType = SeriesChartType.Pie
The code errors on the line
chart1.Series(0).Points.DataBindXY(x, y)

Creating SQL query in VB.net from a Checkboxlist

I have a checkboxlist and I populate it dynamically from a database. For example after i populate the checkboxlist is like that:
Los Angeles
New York
London
Berlin
Amsterdam
I want to create a SQL query according to the checkboxes are checked. If i want to choose only one city (e.g. only New York) i want the result to be:
(City = 2)
Thats works properly but when i have multiple cities (e.g. New York, London and Amsterdam) i want the result to be for example:
(City = 2) OR (City = 3) OR (City = 5)
Or if i choose Los Angeles and Berlin I want the result to be like this:
(City = 1) OR (City = 4)
How can i achieve this? That's my code below but I am stacked. Any ideas?
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim var As String = ""
Dim counter As Integer = 0
Dim myList As New List(Of String)()
For i As Integer = 0 To CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
myList.Add(i + 1)
counter = counter + 1
If counter = 1 Then
var = "(City =" & i + 1 & ")"
Else
Console.WriteLine(myList(1))
Dim myArray As String() = myList.ToArray()
For j As Integer = 1 To myArray.Length
Dim var2 As String = " OR (City =" & counter & ")"
var = "(City =" & myArray(0) & ")" & var2
Next
End If
End If
Next
SQL = "SELECT * FROM Data1 WHERE (" & var & ") ORDER BY [ID]"
Session("Search") = SQL
Server.Transfer("Data_Form.aspx")
End Sub
What I recommend most strongly is to look into Table-value Parameters:
http://msdn.microsoft.com/en-us/library/bb675163(v=vs.110).aspx
This will fix your issue and help you avoid sql injection vulnerabilities.
But if you really insist on using string concatenation, try using an IN() condition, where you end up with something more like CITY IN (1,2) instead of (City = 1 OR City = 2). You can make this a bit easier to write by leading with an unused ID, like so:
Dim cityClause As String = " CITY IN (-1{0})" 'start with a valid clause
Dim cityIDs As String = ""
For Each box As ListItem In CheckBoxList1.Items.Where(Function(b) b.Selected)
'Try storing the ID for each city in the value part of each listitem,
' rather than using the index order
cityIDs = cityIDs & "," & box.Value
Next box
cityClause = string.Format(cityClause, cityIDs)
You can use City IN(2,3,5) instead of (City = 2) OR (City = 3) OR (City = 5):
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim condition As String = ""
For i As Integer = 0 To CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
condition = condition & "," & (i + 1)
End If
Next
SQL = "SELECT * FROM Data1 WHERE (" & condition.SubString(1) & ") ORDER BY [ID]"
Session("Search") = SQL
Server.Transfer("Data_Form.aspx")
End Sub

ASP.Net String Split not working

Here's my code
Dim RefsUpdate As String() = Session("Refs").Split("-"C)
Dim PaymentsPassedUpdate As String() = Session("PaymentsPassed").Split("-"C)
Dim x as Integer
For x = 1 to RefsUpdate.Length - 1
Dim LogData2 As sterm.markdata = New sterm.markdata()
Dim queryUpdatePaymentFlags as String = ("UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''"+ RefsUpdate(x) +"'' AND bookno = ''"+ Session("number") +"'' ') SET alpaid = '"+PaymentsPassedUpdate(x) +"', paidfl = 'Y', amountdue = '0' ")
Dim drSetUpdatePaymentFlags As DataSet = Data.Blah(queryUpdatePaymentFlags)
Next
I don't get any errors for this but it doesn't seem to working as it should
I'm passing a bookingref like this AA123456 - BB123456 - CC123456 - etc and payment like this 50000 - 10000 - 30000 -
I basically need to update the db with the ref AA123456 so the alpaid field has 50000 in it.
Can't seem to get it to work
Any ideas?
Thanks
Jamie
I'm not sure what isn't working, but I can tell you that you are not going to process the last entry in your arrays. You are going from 1 to Length - 1, which is one short of the last index. Therefore, unless your input strings end with "-", you will miss the last one.
Your indexing problem mentioned by Mark is only one item, but it will cause an issue. I'd say looking at the base your problem stems from not having trimmed the strings. Your data base probably doesn't have spaces leading or trailing your data so you'll need to do something like:
Dim refsUpdateString as string = RefsUpdate(x).Trim()
Dim paymentsPassedUpdateString as string = PaymentsPassedUpdate(x).Trim()
...
Dim queryUpdatePaymentFlags as String = ("UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''" & refsUpdateString & "'' AND bookno = ''" & Session("number") & "'' ') SET alpaid = '" & paymentsPassedUpdateString & "', paidfl = 'Y', amountdue = '0' ")
Also, I would recommend keeping with the VB way of concatenation and use the & character to do it.

Resources