vb.net linq update Data - vb.net

Hi Guys thanks for all the help on things. Im using linq and im able get get data ouf of it realy easy. but i seem to not be able to update the data. the program does not error on it and it looks likes it has updated but it does not save te changes.
Public Function UpdateAlarmsbyKey(ByVal objKey As Integer, ByVal IdNumber As String) As Boolean
Dim lqAlarms As New linqAlarmDumpDataContext
Dim GetAlrms = From r In lqAlarms.AlarmDrops _
Where r.Key = objKey _
Select r
For Each Calls In GetAlrms
If Calls.AlarmsHandled = "" Then
Calls.AlarmsHandled = IdNumber
Return True
Else
Calls.AlarmsHandled = Calls.AlarmsHandled & ":" & IdNumber
Return True
End If
Next
Return False
End Function

Try calling -
lqAlarms.SubmitChanges()
after you've updated the Calls.AlarmsHandled property. Also, your code is looping round a result set but will only change the first record it finds, is that the behaviour you wanted?

Related

Is it possible to create an extension method that can be used in an sql query?

I have an application that draws elements from a database when a search button is clicked. I need to update it so that I can find elements that have a specific Substring exactly 6 places into the string. For example, I need to find 111-2233-44-555 by looking for 33 at the 6th and 7th places. My first instinct was to create an extension method for the string class so that I could say something like this:
Dim example As String = "111-2233-44-555"
If example.HasYear(33) Then
'Do Something'
End If
And this worked perfectly. Here's the method I made:
Public Module StringExtensionMethods
''' <summary>
''' Finds the year in a competition number of format XXX-XXXX-XX-XXX
''' </summary>
''' <param name="pstrCompNum">The competition number to find the year in</param>
<Extension()>
Public Function HasYear(ByVal pstrCompNum As String, ByVal pstrCompYear As String) As Boolean
Try
Dim testString As String = pstrCompNum
Debug.Print(testString)
Dim testSubstring As String = testString.Substring(6, 2)
If testSubstring.Equals(pstrCompYear) Then
Return True
End If
Return False
Catch ex As Exception
Throw ex
End Try
End Function
End Module
But a problem arises when I try to use this method in an SQL query. Rightfully so, since HasYear() isn't related to SQL in any way whatsoever. Here's the query I want to execute:
Dim o = From c In myContext.Competitions.Include("CodeJusticeBranches").Include("CodeJusticeLocations").Include("CodeCompetitionTypes").Include("CodePositionTypes").Include("CompetitionPositions") _
Where (pstrCompNum Is Nothing OrElse c.comp_number = pstrCompNum) _
And (pstrCompYear Is Nothing OrElse c.comp_number.HasYear(strYear) = True) _
And (pstrCompTypeId Is Nothing OrElse c.CodeCompetitionTypes.code_ct_id = CInt(pstrCompTypeId)) _
And (pstrBranchId Is Nothing OrElse c.CodeJusticeBranches.code_branch_id = CInt(pstrBranchId)) _
And (pstrPosTypeId Is Nothing OrElse c.CodePositionTypes.code_pos_type_id = CInt(pstrPosTypeId)) _
Order By c.comp_number _
Select c
I get the error LINQ to Entities does not recognize the method 'Boolean HasYear (System.String, System.String)' method, and this method cannot be translated into a store expression.
So what I'm looking for is essentially a way to make an extension method that can be used in an SQL query. Any ideas?
Don't include custom functions in your LINQ. It must be convertable to SQL so your extension method doesn't qualify. Just execute your query with supported where clauses, then tack on your custom queries after.
Dim o = (
From c In myContext.Competitions.Include("CodeJusticeBranches").Include("CodeJusticeLocations").Include("CodeCompetitionTypes").Include("CodePositionTypes").Include("CompetitionPositions")
Where (pstrCompNum Is Nothing OrElse c.comp_number = pstrCompNum) _
And (pstrCompTypeId Is Nothing OrElse c.CodeCompetitionTypes.code_ct_id = CInt(pstrCompTypeId)) _
And (pstrBranchId Is Nothing OrElse c.CodeJusticeBranches.code_branch_id = CInt(pstrBranchId)) _
And (pstrPosTypeId Is Nothing OrElse c.CodePositionTypes.code_pos_type_id = CInt(pstrPosTypeId))
Order By c.comp_number Select c).ToList().
Where(Function(c) c.pstrCompYear Is Nothing OrElse c.comp_number.HasYear(strYear))
I like what #djv posted, but I've decided to try out Andrew Morton's suggestion, to just omit the HasYear() altogether. I ended up using this:
Dim k = From c In myContext.Competitions.Include("CodeJusticeBranches").Include("CodeJusticeLocations").Include("CodeCompetitionTypes").Include("CodePositionTypes").Include("CompetitionPositions") _
Where (pstrCompNum Is Nothing OrElse c.comp_number = pstrCompNum) _
And (pstrCompYear Is Nothing OrElse c.comp_number.Substring(6, 2) = pstrCompYear) _
And (pstrCompTypeId Is Nothing OrElse c.CodeCompetitionTypes.code_ct_id = CInt(pstrCompTypeId)) _
And (pstrBranchId Is Nothing OrElse c.CodeJusticeBranches.code_branch_id = CInt(pstrBranchId)) _
And (pstrPosTypeId Is Nothing OrElse c.CodePositionTypes.code_pos_type_id = CInt(pstrPosTypeId)) _
Order By c.comp_number _
Select c
Notice the line And (pstrCompYear Is Nothing OrElse c.comp_number.Substring(6, 2) = pstrCompYear)
This solved my problem very simply.

Insert number of record based on checkboxlist selected value in vb.net

I have this skill checkboxlist which contains skills that can be selected by the user. If the user select two skills,two records will be inserted to the table.
I tried this one:
Dim varSkillID As Integer()
varSkillID = split(skills, ",")
If varSkillID(0).value > 0 Then
Dim sql As String = Nothing
For I = 0 To varSkillID()
sql = "INSERT INTO tblConstituentSkills (skillID) VALUES ( " & varSkillID.Value & ")"
Next I
end if
but its not working. Thanks!
I also tried this code.
Dim varSkillID() As String = Split(skillID, ",")
For i As Integer = 0 To varSkillID.Length - 1
If varSkillID(i) <> "" Then
Using sql As New SqlProcedure("spInsertSkill")
sql.AddParameter("#ConstituentIdNo", constituentIdNo)
sql.AddParameter("#skillID", varSkillID(i))
sql.ExecuteNonQuery()
End Using
End If
Next i
It works when I only select single skill. But if I select two or more skills this error appears "Nullable object must have a value."
please use the editor help to design your request. It is very hard to read.
What does the errormessage say?
There is an End If missing
Where does constituentIdNo.Value is coming from?
To call the Sub:
Call r101("123456", "1,2,3,4")
the Sub:
Public Sub r101(ByVal constituentIdNo As String, ByVal skills As String)
Dim varSkillID() As String = Split(skills, ",")
Dim sql As String = Nothing
For i As Integer = 0 To varSkillID.Length - 1
If varSkillID(i) <> "" Then sql = "INSERT INTO tblConstituentSkills (ConstituentIdNo, skillID) VALUES (" & constituentIdNo & ", " & varSkillID(i) & ")"
Next i
End Sub
This is not the cleanest code, but the best I could create from your given feedback.
I don't see why to convert skills to integer.
I just read this and saved me.separate comma separated values and store in table in sql server
Thanks stackoverflow!you're a savior!

for each loop using a datagridview

I trying to perform a calculation on some values within a DGV that has been imported from data within an xls file. but I cant get the loop to work. what I need it to do is read the value of the cells in column 2 and column 3 of each row, put them in to a text box and then output the result of the calculation to column 4 of the DVG. I would post the code but frankly I haven't got anything real to go on. am I correct in thinking I need to be using a For each loop???
Any help or guidance is greatly appreciated.
Thanks in advance
I find it Little hard understanding your request... But how about this?
For Each Row As DataGridViewRow In DataGridView1.Rows
Dim CellValues As New List(Of String)
Dim Failed As Boolean = False
For x = 1 To 2 'This is right. It's NOT supposed to be 2 To 3.
If Row.Cells(x).Value <> Nothing Then
CellValues.Add(Row.Cells(x).Value.ToString())
ElseIf Row.Cells(x).Value = Nothing Then
Failed = True
End If
Next
If Failed = True Then
Continue For
End If
TextBox1.AppendText(CellValues(0) & " + " & CellValues(1) & Environment.NewLine)
Row.Cells(3).Value = CInt(CellValues(0)) + CInt(CellValues(1))
Next

Run-time error "13": in my VBA excel code

I'm writing a script that will count a numbers of days between few separate dates. I have a data in cell like:
1-In Progress#02-ASSIGNED TO TEAM#22/01/2013 14:54:23,4-On
Hold#02-ASSIGNED TO TEAM#18/01/2013 16:02:03,1-In Progress#02-ASSIGNED
TO TEAM#18/01/2013 16:02:03
That's the info about my transaction status. I want to count the numbers of days that this transaction was in "4-On Hold". So in this example it will be between 18/01/2013 and 22/01/2013.
I wrote something like this(sorry for ma native language words in text)
Sub Aktywnywiersz()
Dim wiersz, i, licz As Integer
Dim tekstwsadowy As String
Dim koniectekstu As String
Dim pozostalytekst As String
Dim dataztekstu As Date
Dim status4jest As Boolean
Dim status4byl As Boolean
Dim datarozpoczecia4 As Date
Dim datazakonczenia4 As Date
Dim dniw4 As Long
wiersz = 2 'I start my scrypt from second row of excel
Do Until IsEmpty(Cells(wiersz, "A")) 'this should work until there is any text in a row
status4jest = False 'is status 4-On Hold is now in a Loop
status4byl = False 'is status 4-On Hold was in las loop
dniw4 = 0 ' numbers od days in 4-On Hold status
tekstwsadowy = Cells(wiersz, "H").Value2 'grabing text
tekstwsadowy = dodanieprzecinka(tekstwsadowy) 'in some examples I had to add a coma at the end of text
For i = 1 To Len(tekstwsadowy)
If Right(Left(tekstwsadowy, i), 1) = "," Then licz = licz + 1 'count the number of comas in text that separates the changes in status
Next
For j = 1 To licz
koniectekstu = funkcjaliczeniadni(tekstwsadowy) 'take last record after coma
Cells(wiersz, "k") = koniectekstu
dataztekstu = funkcjadataztekstu(koniectekstu) 'take the date from this record
Cells(wiersz, "m") = dataztekstu
status4jest = funkcjaokreslenia4(koniectekstu) 'check if there is 4-On Hold in record
Cells(wiersz, "n") = status4jest
If (status4byl = False And staus4jest = True) Then
datarozpoczecia4 = dataztekstu
status4byl = True
ElseIf (status4byl = True And staus4jest = False) Then
datazakonczenia4 = dataztekstu
status4byl = False 'if elseif funkcion to check information about 4-On Hold
dniw4 = funkcjaobliczeniadniw4(dniw4, datazakonczenia4, datarozpoczecia4) 'count days in 4-On Hold
Else
'Else not needed...
End If
tekstwsadowy = resztatekstu(tekstwsadowy, koniectekstu) 'remove last record from main text
Next
Cells(wiersz, "L") = dniw4 ' show number of days in 4-On Hold status
wiersz = wiersz + 1
Loop
End Sub
Function funkcjaliczeniadni(tekstwsadowy As String)
Dim a, dl As Integer
dl = Len(tekstwsadowy)
a = 0
On Error GoTo errhandler:
Do Until a > dl
a = Application.WorksheetFunction.Find(",", tekstwsadowy, a + 1)
Loop
funkcjaliczeniadni = tekstwsadowy
Exit Function
errhandler:
funkcjaliczeniadni = Right(tekstwsadowy, dl - a)
End Function
Function dodanieprzecinka(tekstwsadowy As String)
If Right(tekstwsadowy, 1) = "," Then
dodanieprzecinka = Left(tekstwsadowy, Len(tekstwsadowy) - 1)
Else
dodanieprzecinka = tekstwsadowy
End If
End Function
Function resztatekstu(tekstwsadowy, koniectekstu As String)
resztatekstu = Left(tekstwsadowy, Len(tekstwsadowy) - Len(koniectekstu))
End Function
Function funkcjadataztekstu(koniectekstu As String)
funkcjadataztekstu = Right(koniectekstu, 19)
funkcjadataztekstu = Left(funkcjadataztekstu, 10)
End Function
Function funkcjaobliczeniadniw4(dniw4 As Long, datazakonczenia4 As Date, datarozpoczecia4 As Date)
Dim liczbadni As Integer
liczbadni = DateDiff(d, datarozpoczecia4, datazakonczenia4)
funkcjaobliczaniadniw4 = dniw4 + liczbadni
End Function
Function funkcjaokreslenia4(koniectekstu As String)
Dim pierwszyznak As String
pierwszyznak = "4"
If pierszyznak Like Left(koniectekstu, 1) Then
funkcjaokreslenia4 = True
Else
funkcjaokreslenia4 = False
End If
End Function
And for now I get
Run-time error "13"
in
dataztekstu = funkcjadataztekstu(koniectekstu) 'take the date from this record
I would be very grateful for any help.
You are getting that error because of Type Mismatch. dataztekstu is declared as a date and most probably the expression which is being returned by the function funkcjadataztekstu is not a date. You will have to step through it to find what value you are getting in return.
Here is a simple example to replicate that problem
This will give you that error
Option Explicit
Sub Sample()
Dim dt As String
Dim D As Date
dt = "Blah Blah"
D = getdate(dt)
Debug.Print D
End Sub
Function getdate(dd As String)
getdate = dd
End Function
This won't
Option Explicit
Sub Sample()
Dim dt As String
Dim D As Date
dt = "12/12/2014"
D = getdate(dt)
Debug.Print D
End Sub
Function getdate(dd As String)
getdate = dd
End Function
If you change your function to this
Function funkcjadataztekstu(koniectekstu As String)
Dim temp As String
temp = Right(koniectekstu, 19)
temp = Left(temp, 10)
MsgBox temp '<~~ This will tell you if you are getting a valid date in return
funkcjadataztekstu = temp
End Function
Then you can see what that function is returning.
I tried running your code, but it is a little difficult to understand just what it is that you want to do. Part of it is the code in your language, but the code is also hard to read beacuse of the lack of indentation etc. :)
Also, I do not understand how the data in the worksheet looks. I did get it running by guessing, though, and when I did I got the same error you are describing on the second run of the For loop - that was because the koniectekstu string was empty. Not sure if this is your problem, so my solution is a very general.
In order to solve this type of problem:
Use Option Explicit at the top of your code module. This will make you have to declare all variables used in the module, and you will remove many of the problems you have before you run the code. Eg you are declaring a variable status4jest but using a different variable called staus4jest and Excel will not complain unless you use Option Explicit.
Declare return types for your functions.
Format your code so it will be easier to read. Use space before and after statements. Comment everything! You have done some, but make sure a beginner can understand. I will edit you code as an example of indentation.
Debug! Step through your code using F8 and make sure all variables contain what you think they do. You will most likely solve your problem by debugging the code this way.
Ask for help here on specific problems you run into or how to solve specific problems, do not send all the code and ask why it is not working. If you break down your problems into parts and ask separately, you will learn VBA yourself a lot faster.
A specific tip regarding your code: look up the Split function. It can take a string and make an array based on a delimiter - Example: Split(tekstwsadowy, ",") will give you an array of strings, with the text between the commas.
Did I mention Option Explicit? ;)
Anyway, I hope this helps, even if I did not solve the exact error you are getting.

Combining VBA and formulas to check for unique output

Ok, I've got this formula which generates usernames based on a list of first and last names. Now, while this works, I want the cells to refer to my own VBA function instead. But, I still want to use the original formula because of much less code.
I've got this formula:
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(LOWER(LEFT(table[[#This Row];[Firstname:]])&table[[#This Row];[Lastname:]]);"æ";"a");"ø";"o");"å";"a")
This basically generates the username. But, I want to run this through a separate function, to find out if the username is already taken. And if it is, it should generate a slightly different user name.
I was thinking something along these lines:
Public Function genUserName(ByVal strFirstName, strLastName As String)
Dim strUsername As String
Set objDomain = GetObject("WinNT://grunnarbeid2.local")
objDomain.Filter = Array("User")
'FormulaR1C1 = "=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(LOWER(LEFT(tableFaste[[#This Row];[Fornavn:]])&tableFaste[[#This Row];[Etternavn:]]);""æ"";""a"");""ø"";""o"");""å"";""a"")"
'strUsername = ActiveCell.FormulaR1C1
blnFound = False
For Each objUser In objDomain
If objUser.Name = strUsername Then
blnFound = True
Exit For
End If
Next
genUserName = strUsername
End Function
So, how do I combine these?
I would suggest limiting the functionality of genUserName to just checking uniqueness, and pass the result of your existing formual into it:
Public Function genUserName(ByVal strUsername As String)
Set objDomain = GetObject("WinNT://grunnarbeid2.local")
objDomain.Filter = Array("User")
blnFound = False
For Each objUser In objDomain
If objUser.Name = strUsername Then
blnFound = True
Exit For
End If
Next
genUserName = strUsername
End Function
then call it from a cell like
=genUserName(SUBSTITUTE( ... ))