I have a EDM (phoneDB) that models a back-end MSSQL database. I've developed a ASP.NET (VB) application that allows one to edit the information in this database. When someone edits a record entry I'd like to record this action.
Right now, I'm doing the following:
For Each..Next that checks whether entry is an object that has had its entitystate modified.
And If Not..End If that ensures we aren't dealing with a relationship entity or a null entity.
Now this is where it gets fuzzy. What I want to do is grab the information from these modified objects and record them into the database. Now I have something like this:
Dim audit as History
audit.action = "Changed information in " & propName & " to " & entry.CurrentValues(propName) & " from " & entry.OriginalValues(propName)
audit.action_by = this_user
audit.action_date = Date.Now
audit.extension_id =
I'm not sure, however, how to tell it to pull a specific property from entry. For example, I need to get (pseudo-code) something like:
audit.extension_id = entry.OriginalValues(extension_id)
I don't understand what do you mean by "pulling a specific property from an entry"? The (pseudo) code you wrote is not telling much, what is an extesion_id in your case? If extension_id is a property name of an entity, then you obtain it's original value by calling entry.OriginalValues("extension_id"), but I'm fairly sure you knew that.
Btw, you can do intricate history recording in the DB itself using triggers without the data layer even knowing it. It's a fairly old trick and works fast, see this
Here is how I accomplished it in the end:
Private Shared Sub context_SavingChanges(ByVal sender As Object, ByVal e As EventArgs)
' This allows us to record a history of the changes made by the user to the database. The record is created automatically by EF, but we need to save it to the database
' for permanent retention.
For Each entry As ObjectStateEntry In DirectCast(sender, ObjectContext).ObjectStateManager.GetObjectStateEntries(EntityState.Modified)
If Not entry.IsRelationship And entry.Entity IsNot Nothing Then
For Each propName As String In entry.GetModifiedProperties()
Dim context As New AppsEntities()
Dim audit As New History
audit.action_note = "Changed information in " & propName & " to " & entry.CurrentValues(propName) & " from " & entry.OriginalValues(propName)
audit.action_by = CStr(HttpContext.Current.Session("person_name"))
audit.action_date = Date.Now
audit.extension_id = entry.CurrentValues.GetValue(0)
context.AddToHistories(audit)
context.SaveChanges()
Next
End If
Next
End Sub
Related
I have a query called qryAlloc_Source that has two paramaters under one criteria:
>=[forms]![frmReportingMain]![txtAllocStart] And <=[forms]![frmReportingMain]![txtAllocEnd])
A have a separate query that ultimately references qryAlloc_Source (there are a couple queries in between), and that query runs fine when I double click it in the UI, but if I try to open it in VBA, I get an error. My code is:
Dim rst As Recordset
Set rst = CurrentDb.OpenRecordset("qryAlloc_Debits")
I am getting run-time error 3061, Too few parameters. Expected 2. I've read that I may need to build out the SQL in VBA using the form parameters, but it would be pretty complex SQL given that there are a few queries in the chain.
Any suggestions as to a workaround? I considered using VBA to create a table from the query and then just referencing that table--I hate to make extra steps though.
The reason you get the error when you just try to open the recordset is that your form is not open and when you try to access [forms]![frmReportingMain] it's null then you try to get a property on that null reference and things blow up. The OpenRecordset function has no way of poping up a dialog box to prompt for user inputs like the UI does if it gets this error.
You can change your query to use parameters that are not bound to a form
yourTableAllocStart >= pAllocStart
and yourTableAllocEnd <= pAllocEnd
Then you can use this function to get the recordset of that query.
Function GetQryAllocDebits(pAllocStart As String, pAllocEnd As String) As DAO.Recordset
Dim db As DAO.Database
Dim qdef As DAO.QueryDef
Set db = CurrentDb
Set qdef = db.QueryDefs("qryAlloc_Debits")
qdef.Parameters.Refresh
qdef.Parameters("pAllocStart").Value = pAllocStart
qdef.Parameters("pAllocEnd").Value = pAllocEnd
Set GetQryAllocDebits = qdef.OpenRecordset
End Function
The disadvantage to this is that when you call this now on a form that is bound to it it doesn't dynamically 'fill in the blanks' for you.
In that case you can bind forms qryAlloc_debts and have no where clause on the saved query, then use the forms Filter to make your where clause. In that instance you can use your where clause exactly how you have it written.
Then if you want to still open a recordset you can do it like this
Function GetQryAllocDebits(pAllocStart As String, pAllocEnd As String) As DAO.Recordset
Dim qdef As DAO.QueryDef
Set qdef = New DAO.QueryDef
qdef.SQL = "Select * from qryAlloc_Debits where AllocStart >= pAllocStart and pAllocEnd <= pAllocEnd"
qdef.Parameters.Refresh
qdef.Parameters("pAllocStart").Value = pAllocStart
qdef.Parameters("pAllocEnd").Value = pAllocEnd
Set GetQryAllocDebits = qdef.OpenRecordset
End Function
While a [Forms]!... reference does default to a form reference when a QueryDef is run from the GUI, it is actually just another Parameter in the query in VBA. The upshot is you don't have to recode your query/create a new one at all. Also, as #Brad mentioned, whether a parameter is in the final query of a chain of queries or not, you are able to refer to the parameter as if it is in the collection of the final query. That being the case, you should be able to use code similar to this:
Sub GetQryAllocDebits(dteAllocStart As Date, dteAllocEnd as Date)
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
Set db = CurrentDb()
Set qdf = db.QueryDefs("qryAlloc_Debit")
If CurrentProject.AllForms("frmReportingMain").IsLoaded Then
qdf.Parameters("[forms]![frmReportingMain]![txtAllocStart]") = [forms]![frmReportingMain]![txtAllocStart]
qdf.Parameters("[forms]![frmReportingMain]![txtAllocEnd]") = [forms]![frmReportingMain]![txtAllocEnd]
Else
qdf.Parameters("[forms]![frmReportingMain]![txtAllocStart]") = CStr(dteAllocStart)
qdf.Parameters("[forms]![frmReportingMain]![txtAllocEnd]") = CStr(dteAllocEnd)
End If
Set rst = qdf.OpenRecordset
Do Until rst.EOF
'...do stuff here.
Loop
Set rst = Nothing
Set qdf = Nothing
Set db = Nothing
End Function
If the referenced form is open, the code is smart enough to use the referenced controls on the form. If not, it will use the dates supplied to the subroutine as parameters. A gotcha here is that the parameters did not like when I set them as date types (#xx/xx/xx#), even if the field were dates. It only seemed to work properly if I set the params as strings. It didn't seem to be an issue when pulling the values straight out of the controls on the forms, though.
I know it's been a while since this was posted, but I'd like to throw in my tuppence worth as I'm always searching this problem:
A stored query can be resolved:
Set db = CurrentDb
Set qdf = db.QueryDefs(sQueryName)
For Each prm In qdf.Parameters
prm.Value = Eval(prm.Name)
Next prm
Set rst = qdf.OpenRecordset
For SQL:
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", "SELECT * FROM MyTable " & _
"WHERE ID = " & Me.lstID & _
" AND dWeekCommencing = " & CDbl(Me.frm_SomeForm.Controls("txtWkCommencing")) & _
" AND DB_Status = 'Used'")
For Each prm In qdf.Parameters
prm.Value = Eval(prm.Name)
Next prm
Set rst = qdf.OpenRecordset
This assumes that all parameter values are accessible - i.e. forms are open and controls have values.
'I have two parameters in my recordset and I was getting the "Too few parameters. Expected 2" 'error when using an OpenRecordset in MS Access vba, and this is how I got around it and IT WORKS! see the below sub routine:
'Private Sub DisplayID_Click()
'1. I created variables for my two parameter fields xEventID and xExID as seen below:
Dim db As Database
Dim rst As Recordset
Dim xEventID As Integer
Dim xExId As Integer
'2. Sets the variables to the parameter fields as seen below:
Set db = CurrentDb
xEventID = Forms!frmExhibitorEntry!txtEventID
xExId = Forms!frmExhibitorEntry!subExhibitors!ExID
'3. Set the rst to OpenRecordSet and assign the Set the variables to the WHERE clause. Be sure to include all quotations, ampersand, and spaces exactly the way it is displayed. Otherwise the code will break!exactly as it is seen below:
Set rst = db.OpenRecordset("SELECT tblInfo_Exhibitor.EventID,tblInfo_Display.ExID, tblMstr_DisplayItems.Display " _
& "FROM tblInfo_Exhibitor INNER JOIN (tblMstr_DisplayItems INNER JOIN tblInfo_Display ON tblMstr_DisplayItems.DisplayID = tblInfo_Display.DisplayID) ON tblInfo_Exhibitor.ExID = tblInfo_Display.ExID " _
& "WHERE (((tblInfo_Exhibitor.EventID) =" & xEventID & " ) and ((tblInfo_Exhibitor.ExID) =" & xExId & " ));")
rst.Close
Set rst = Nothing
db.Close
'End Sub
I have a database connected to my vb program. One of the forms in the project edits the information in the database. The Form works by searching for a student first, showing the student at the top of the database and then edits the information. the problem is when the information is edited, it edits the first row in the database, not the one chosen (it kind of replaces it). So how do i code it so it can edit only that particular row and not the first one from the database? The Code:
Private Sub cmdEdit_Click()
With frmStudents.Adodc1.Recordset
.Fields(1) = txtFirstName.Text
.Fields(2) = txtLastName.Text
.Fields(3) = txtMarks(0).Text
.Fields(4) = txtMarks(1).Text
.Fields(5) = txtMarks(2).Text
.Update
frmStudents.StudentTable.Refresh '.DataSource = frmStudents.Adodc1
End With
MsgBox "Student Updated Successfully", vbInformation, "Success"
End If
End Sub
I am a complete beginner at ASP.net(and this forum) i am using Visual studio 2013 and have created created another table in the created database using the package manager console.
How do i go about placing the information into this new table? (I am looking to store firstname and last name in a separate table)
The create account button is below:
Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
Dim userName As String = UserNameCtrl.Text
Dim Firstnane As String = firstnamectrl.Text
Dim manager = New UserManager
Dim User = New ApplicationUser() With {.UserName = userName}
Dim result = manager.Create(User, Password.Text)
If result.Succeeded Then
IdentityHelper.SignIn(manager, User, isPersistent:=False)
IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
Else
ErrorMessage.Text = result.Errors.FirstOrDefault()
End If
End Sub
Any pointers in the right direction, hints or suggested reading would be very helpful.
If I understand correctly, this link may be of some help:
http://www.codeguru.com/vb/gen/vb_database/adonet/article.php/c15033/A-Basic-VBNET-ADONET-Tutorial-Adding-Deleting-and-Updating.htm
It is for a windows form application, but it should translate pretty well if you're using web forms. Basically, you just want to make a connection to the database during the button click event (the simplest way I know of to make this connection is using ADO.NET), and pass the values of the first and last name in a SQL query to the sql server.
You would be building the sql query as a string, and concatenating your vb variables into that string. Something like; "Insert into table xxx(firstname, LastName) values " & Firstname & ", " & Lastname...
I have looked at a previous example of yours detailed below. However I have a problem:
Heres my code it runs off a button on a form called Reports:
Dim dbs As Database
Dim qdf As QueryDef
Dim varitem As Variant
Set dbs = CurrentDb()
Set qdf = dbs.QueryDefs("Qry_rpt_cr")
qdf.Parameters(0) = Forms!frm_reports.rmselectfilter.Column(1, varitem)
qdf.Parameters(4) = Forms!frm_reports.rmselectperiod.Column(0, 0)
qdf.Parameters(3) = Forms!frm_reports.rmselectperiod.Column(0, 1)
qdf.Parameters(2) = Forms!frm_reports.rmselectperiod.Column(0, 2)
qdf.Parameters(1) = Forms!frm_reports.rmselectperiod.Column(0, 3)
Set grst = CurrentDb.OpenRecordset("Select * from Qry_rpt_cr")
DoCmd.OpenReport "rpt_cr_test", acPreview
grst.Close
Set grst = Nothing
End Sub
The question is the query needs five parameters to be passed to it and then open the recordset using the defined parameters and then open the report. But the code does not open. Its says an error on this line Set grst = CurrentDb.OpenRecordset("Select * from Qry_rpt_cr") asking for 5 parameters but I have passed them earlier in the code. Any suggestions would be welcomed. HAppy to make a donation for a correct answer. ED
Example from your archives
From Access Web you can use the "name" property of a recordset. You resulting code would look something like this:
In the report
Private Sub Report_Open(Cancel As Integer)
Me.RecordSource = gMyRecordSet.Name
End Sub
In the calling object (module, form, etc.)
Public gMyRecordSet As Recordset
'...
Public Sub callMyReport()
'...
Set gMyRecordSet = CurrentDb.OpenRecordset("Select * " & _
"from foo " & _
"where bar='yaddah'")
DoCmd.OpenReport "myReport", acViewPreview
'...
gMyRecordSet.Close
Set gMyRecordSet = Nothing
'...
End Sub
I've not used Access for a while , but i think you are setting the params for a query, and then running a different query. Access is asking for params to be provided for the query you are asking ("select * from ..."), not the (named) query that your query references, if that makes sense.
This should be easily fixed, just run OpenRecordset from the QueryDef:
Set grst = qdf.OpenRecordSet
and then Access will include the query's params correctly.
Edit: Thx Remou
Working on a Online Test.
I have 3 tables
Questions
Subject
Topic
I have made a stored procedure which returns 25 random records. I want to store it in-memory and then display 1 question at a time with AJAX. I don't want to hit database 25 times as there are many users, I tried and store the result in viewstate but then I am not able to cast it back. if I use
Dim qus = from viewstate("questions")
it works, but it doesn't work when I retrieve 1 record at a time.
Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
ViewState.Add("QuestionNo", 0)
Dim qus = From q In PML.PM_SelectRandomQuestionFM Select q
viewstate.add("questions",qus)
LoadQuestion(0)
End If
End Sub
Private Sub LoadQuestion(ByVal i As Integer)
Dim QuestionNo As Integer = CType(ViewState("QuestionNo"), Integer) + 1
Try
If QuestionNo <= 25 Then
Dim qus = viewstate("questions")
Me._subjectTopic.Text = String.Format("<b>Subject:</b> {0} -- <b>Topic:</b> {1}", qus(i).subjectName, qus(i).TopicName)
Me._question.Text = " " & qus(i).Question
Me._answer1.Text = " " & qus(i).Answer1
Me._answer2.Text = " " & qus(i).Answer2
Me._answer3.Text = " " & qus(i).Answer3
Me._answer4.Text = " " & qus(i).Answer4
Me._questionNo.Text = String.Format("Question No. {0} / 25", QuestionNo)
ViewState.Add("QuestionNo", QuestionNo)
Else
Server.Transfer("freeMemberResult.aspx")
End If
Catch ex As Exception
Throw New System.Exception(ex.ToString)
End Try
End Sub
I tried casting the object to
Dim qus = CType(ViewState("questions"), IQueryable(Of PM_SelectRandomQuestionFMResult))
but then I get this error
System.Linq.Enumerable+WhereSelectEnumerableIterator`2
Please HELP or if there is any other method to do it, if my method of doing online test is wrong.
Regards
IMO, you're over-engineering this. Why screw around trying to hold the data in memory? Why not write each question to a div, and then hide all of the question divs except for the "current question".
Much easier to implement and you're not hitting the server with several AJAX calls, This also make saving state (previously answered questions, etc) much, much easier.
Have you tried just using Session to maintain state? Is there a requirement that prohibits you from doing this?
Dim qus = CType(Me.Session("questions"), IQueryable(Of PM_SelectRandomQuestionFMResult))