How to force DbEntityValidationException? - entity-framework

I need to do some testing, and I need to force the DbEntityValidationException. I'm trying with these lines of code, trying to save with invalid id, trying to add instead of numeric value, a string value, but I keep getting DBUpdateException, and I need the DbEntityValidationException. Can you please help with an idea what I need to insert in order to get this exception? Thanks!
Dim lRndvrq = New RndvRq
Dim lRndvrqAc = New RndvRqAc
lRndvrq.RQ = 663
lRndvrq.RT_CL = "RQ"
lRndvrqAc.UP = 1
lRndvrqAc.RQ = 0 'lRndvrq.RQ
lRndvrqAc.AR = RnD.Common.Enums.AccessRight.Read
lRndvrq.RndvRqAc.Add(lRndvrqAc)
Context.RndvRq.Add(lRndvrq)
Context.SaveChanges()

Related

VB Script in Access Variable not found

So I was advised that I could create some copy replace functionality to this form.
Here is my coding attempt in VB:
First I connect to DB using DAO. Then I use a SELECT statement that has been verified to pull the last record inserted into the DB. Then I try to refill the controls with the values from the query but I am getting reference errors.
Private Sub AutoFill_Click()
Dim db As DAO.Database, rs As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb()
strSQL = "SELECT DISTINCTROW TOP 1 CPOrders.Cust, Customer.NAME, CPOrders.CP_Ref, CPOrders.Slsman, CPOrders.Date_opn, CPOrders.CPSmall, CPOrders.InvIssu, CPOrders.InvNo, CPOrders.InvDate, CPOrders.DueDate, CPOrders.ETADate, CPOrders.Closed, CPOrders.BuyerRef, CPOrders.ToCity, CPOrders.ToState, CPOrders.ToCtry, CPOrders.ToPort, CPOrders.Supplier, CPOrders.Origin, CPOrders.Product, CPOrders.GradeType, CPOrders.NoUnits, CPOrders.Pkg, CPOrders.Qty, CPOrders.TotSale, CPOrders.TotCost, CPOrders.GrMargin, CPOrders.[Sale$/Unit], CPOrders.[Cost$/Unit], CPOrders.OceanCost, CPOrders.OceanNotes, CPOrders.BLadingDate, CPOrders.USAPort, CPOrders.FOBCost, CPOrders.FASExportVal, CPOrders.InlandFrt, CPOrders.CommodCode, CPOrders.Notes FROM Customer INNER JOIN CPOrders ON Customer.[CUST_#] = CPOrders.Cust ORDER BY CPOrders.CP_Ref desc;"
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset, dbReadOnly)
rs.MoveFirst
CP_Ref.ControlSource = rs!CP_Ref
Slsman.ControlSource = rs!Slsman
CPSmall.ControlSource = rs!CPSmall
InvIssu.ControlSource = rs!InvIssu
InvDate.ControlSource = rs!InvDate
DueDate.ControlSource = rs!DueDate
Closed.ControlSource = rs!Closed
rs.Close
db.Close
The control source reference picks up and autocompletes the word.
I would think that as it stands. although i'm not filling all the values with records from my SELECT statement that it would populate but instead i get things like #NAME? where the values should be. I also get a break in my code and it says "Invalid use of null"
Why? I appreciate your guys input and I can provider screenshots if necessary. I think this is involving the reference tie, but I'm not sure. Any help is much appreciated.
You are using the field names from the SELECT statement as if they were variables.
CP_Ref.ControlSource = rs("CP_Ref")
Slsman.ControlSource = rs("Slsman")
CPSmall.ControlSource = rs("CPSmall")
InvIssu.ControlSource = rs("InvIssu")
InvDate.ControlSource = rs("InvDate")
DueDate.ControlSource = rs("DueDate")
Closed.ControlSource = rs("Closed")
When you have that worked out, tackle the "Invalid use of null" problem by first identifying any fields that could potentially be NULL and using something like
SELECT Iif(IsNull([InvDate]), '', [InvDate]) As [InvDate], ...
in the SELECT statement to pass across a minimum of an empty string rather than a NULL value.

Access VBA visible control form from another form

I have a table and form setup to control another form in my database.
I'm wanting to make a code that will take the title from my field and add it to my code as a variable to change the visibility options of my other form.
my form is set with all the of the names to all objects on the form I want to control.
LSE_FORM_ADMIN = The table with all the LSE_FORM_ALL names in it.
Table is setup with 3 columns key, names and a checkbox which I put into a form to make a continuous list.
here is my code on the form, but I keep getting and runtime 424: object required error:
Private Sub Form_Current()
Dim VARSET As Object
Dim VAR As String
VARSET = DLookup("TITLE", Table!LSE_FORM_ADMIN, "") 'keep getting error here
VAR = VARSET
If Me!CB = "-1" Then
Form_LSE_FORM_ALL!VAR.Visible = True
Else
Form_LSE_FORM_ALL!VAR.Visible = False
End If
End Sub
can someone help me fix this code so that it will grab the title field data and make it a variable to add to the rest of the code?
It's difficult to see exactly what you are trying to achieve, but your problems stem from using the variant variable type when you should be using an explicit Form or Control type. Using your last example.
RSTT.Visible = True 'getting Run-time error '424': object required
This is because you have declared RSTT as a variant. The line
RSTT = "Form_LSE_FORM_ALL" & "!" & (RST)
results in the variable RSTT containing a string, which does not have a property ".Visible"
Set DB = CurrentDb
Set RS = DB.OpenRecordset("LSE_FORM_ADMIN")
These lines are redundant as you have the values that you need available on the form fields which are already bound to the table LSE_FORM_ADMIN.
As far as I understand, you have a continuous form (ADMIN?) bound to the table LSE_FORM_Admin. As you step through the records on this form, you want code to be fired which takes the value of the TITLE field/control and use it to set a control with the same name, on a separate form, Form_LSE_FORM_ALL, to be (in)visible, dependent on the value of the checkbox control name CB on the ADMIN form?
If you want the ADMIN form to make the changes "live" to the ALL form, you should consider using an event of the CB checkbox control. Using the current event of the form means that the changes you make will not be reflected in the ALL form until you step out of the record you have just edited, then back in, to fire the form's Current event on that record.
Example using AfterUpdate event of CB checkbox
Private Sub CB_AfterUpdate()
Dim strRST As String
Dim frmTarget as Form
Dim ctlRSTT As Control
Set strRST = Me!TITLE
Set frmTarget = Forms("Form_LSE_FORM_ALL")
Set ctlRSTT = frmTarget.Controls(strRST)
ctlRSTT.Visible = Me!CB 'getting Run-time error '424': object required
End Sub
really not sure how to do the syntax when doing a recordset to a table from the form, need some help with that.
here is my code and attempt at the record set:
Private Sub Form_Current()
Dim DB As Database
Dim RS As Recordset
Dim RST As String
Set DB = CurrentDb
Set RS = DB.OpenRecordset("LSE_FORM_ADMIN")
Set RST = RS 'GETTING OBJECT REQUIRED ERROR ON "RST ="
Do Until RS.EOF
RST = Me!TITLE
RS.MoveNext
Loop
If Me!CB = "-1" Then
Form_LSE_FORM_ALL!RS.Visible = True
Else
Form_LSE_FORM_ALL!RS.Visible = False
End If
End Sub
I think I know what you are trying to do, but your descriptions / references are not matching up. Please look at the following comments and clarify:
1. You say "...make a code that will take the title from my field and ..." but your code is taking "Me.Title", "ME" is a reference to the Form - not a field.
2. Your code is in the "Form_Current" event, which means it will fire for every record you process. That will work, but I think you want to do this code only once to be more efficient.
3. You have no provision for processing more than one field. I think you need to loop through all fields in your table, setting visible to true or false.
The following is my suggestion, but I will update once you clarify the issues.
Option Compare Database
Option Explicit
Dim DB As DAO.Database
Dim RS As DAO.Recordset
'Dim RST As Variant
'Dim RSTT As Variant
Public Sub FORM_CURRENT()
Set DB = CurrentDb
Set RS = DB.OpenRecordset("LSE_FORM_ADMIN")
Do While Not RS.EOF ' Loop thru all field names for the form
If RS!HideYN = True Then ' Desire to hide the field?
Me(RS!ctlname).Visible = False ' Yes, hide the field.
Else
Me(RS!ctlname).Visible = True ' No, show the field
End If
RS.MoveNext ' Get next field name
Loop
RS.Close
Set RS = Nothing
Set DB = Nothing
'Set RST = Me!Title
'RSTT = "Form_LSE_FORM_ALL" & "!" & (RST)
'If Me!CB = "-1" Then
' RSTT.Visible = True 'getting Run-time error '424': object required
'Else
' RSTT.Visible = False
'End If
End Sub
Final code, thanks to Cheesenbranston.
Private Sub Form_AfterUpdate()
Dim strRST As String
Dim frmTarget As Form
Dim ctlRSTT As Control
strRST = Me!TITLE
Set frmTarget = Forms("LSE_FORM_ALL")
Set ctlRSTT = frmTarget.Controls(strRST)
If Me!CB = "-1" Then
ctlRSTT.Visible = True
Else
ctlRSTT.Visible = False
End If
End Sub
#Cheesenbranston: Your original code was more like a toggle of on and off so if my object was not visible then my trigger checkbox would make it visible when checked, more of a quality of life for my own needs, none the less worked. Also strRST doesn't need SET since its just a String. Thanks again =D very happy day!

iDB2Commands in Visual Studio 2010

These are the basic things I know about iDB2Commands to be used in Visual Studio 2010. Could you please help me how could I extract data from DB2? I know INSERT, DELETE and Record Count. But SELECT or Extract Data and UPDATE I don't know.
Imports IBM.Data.DB2
Imports IBM.Data.DB2.iSeries
Public conn As New iDB2Connection
Public str As String = "Datasource=10.0.1.11;UserID=edith;password=edith;DefaultCollection=impexplib"
Dim cmdUpdate As New iDB2Command
Dim sqlUpdate As String
conn = New iDB2Connection(str)
conn.Open()
'*****Delete Records and working fine
sqlUpdate = "DELETE FROM expusers WHERE username<>#username"
cmdUpdate.Parameters.Add("username", iDB2DbType.iDB2Date)
cmdUpdate.Parameters("username").Value = ""
'*****Insert Records and working fine
sqlUpdate = "INSERT INTO expusers (username, password, fullname) VALUES (#username, #password, #fullname)"
cmdUpdate.Parameters.Add("username", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters.Add("password", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters.Add("fullname", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters("username").Value = txtUsername.Text
cmdUpdate.Parameters("password").Value = txtPassword.Text
cmdUpdate.Parameters("fullname").Value = "Editha D. Gacusana"
'*****Count Total Records and working fine
Dim sqlCount As String
Dim cmd As New iDB2Command
sqlCount = "SELECT COUNT(*) AS count FROM import"
cmd = New iDB2Command(Sql, conn)
Dim count As Integer
count = Convert.ToInt32(cmd.ExecuteScalar)
'*****Update Records and IT IS NOT WORKING AT ALL
sqlUpdate = "UPDATE expusers SET password = #password WHERE RECNO = #recno"
cmdUpdate.Parameters.Add("recno", iDB2DbType.iDB2Integer)
cmdUpdate.Parameters.Add("password", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters("recno").Value = 61
cmdUpdate.Parameters("password").Value = txtPassword.Text
cmdUpdate.Connection = conn
cmdUpdate.CommandText = sqlUpdate
cmdUpdate.ExecuteNonQuery()
conn.Close()
Please help me how to code the SELECT query wherein I could extract/fetch data from DB2 Database. Also, how could i update the records in the database.
Thanks!
Instead of ExecuteNonQuery(), look at ExecuteReader(). I don't have VS2010 installed, but try something like this:
iDB2Command cmdSelect = new iDB2Command("SELECT username, password, fullname FROM expusers", conn);
cmdSelect.CommandTimeout = 0;
iDB2DataAdapter da = new iDB2DataAdapter(cmdSelect);
DataSet ds = new DataSet();
da.Fill(ds, "item_master");
GridView1.DataSource = ds.Tables["expusers"];
GridView1.DataBind();
Session["TaskTable"] = ds.Tables["expusers"];
da.Dispose();
cmdSelect.Dispose();
cn.Close();
See: http://gugiaji.wordpress.com/2011/12/29/connect-asp-net-to-db2-udb-for-iseries/
If you aren't trying to bind to a grid, look at iDB2Command.ExecuteReader() and iDB2DataReader()
The DELETE is working fine? The code has the parameter type for "username" set to iDB2Date. The INSERT has "username" set to iDB2VarChar. How is the column defined in the table? Char, Varchar or Date?
On the UPDATE, you reference RECNO, but that does not seem to be a column in the table. Updating a relational database table by row number is a bad idea - the row numbers are not guaranteed to stay constant. If you are just testing, as I think you are, don't use RECNO, use RRN(). The DB2 for i syntax is WHERE rrn(expusers) = #recno
To help your testing, do a SELECT without a WHERE clause and list out all the rows. Make sure the name stored in the username column matches the name you are trying to update. Pay particular attention to the case of the data. If the name in expusers looks like "EDITHA D. GACUSANA", and #username is "Editha D. Gacusana" then it will not match on the WHERE clause.

Trying to Insert QBO Credit Memo with IPP.NET

I am using IPP.Net to attempt to insert a single CreditMemo into Quickbooks Online. I have been successful inserting an invoice with similar code. My code for inserting the CreditMemo is as follows:
Try
Dim qboCreditMemo As New Intuit.Ipp.Data.Qbo.CreditMemo
Dim qboCreditMemoHdr As New Intuit.Ipp.Data.Qbo.CreditMemoHeader
Dim qboCreditMemoLine As Intuit.Ipp.Data.Qbo.CreditMemoLine
Dim CreditMemoLines As New List(Of Intuit.Ipp.Data.Qbo.CreditMemoLine)
Dim CreditMemoItemAttributes As Qbo.ItemChoiceType2()
Dim CreditMemoItemValues As Object()
For Each row In tblTrans.Rows
If bFirstRow Then
'Set CreditMemo header
qboCreditMemoHdr.DocNumber = "SMA" & CStr(row("batch_id"))
qboCreditMemoHdr.TxnDate = Format(row("acct_date"), "yyyy-MM-dd")
qboCreditMemoHdr.Msg = row("batch_descr")
qboCreditMemoHdr.CustomerId = New Intuit.Ipp.Data.Qbo.IdType
qboCreditMemoHdr.CustomerId.Value = row("iface_owner_id")
qboCreditMemo.Header = qboCreditMemoHdr
bFirstRow = False 'only do this once
End If
'Lines
qboCreditMemoLine = New Qbo.CreditMemoLine
qboCreditMemoLine.Desc = row("descr")
qboCreditMemoLine.Amount = row("amount_owner")
qboCreditMemoLine.AmountSpecified = True
CreditMemoItemAttributes = {Qbo.ItemsChoiceType2.ItemId, Qbo.ItemsChoiceType2.UnitPrice, Qbo.ItemsChoiceType2.Qty}
CreditMemoItemValues = {New Qbo.IdType With {.idDomain = Qbo.idDomainEnum.QBO, .Value = row("iface_item_id")}, row("unitPrice"), row("quantity")}
qboCreditMemoLine.ItemsElementName = CreditMemoItemAttributes
qboCreditMemoLine.Items = CreditMemoItemValues
qboCreditMemoLine.ClassId = New Intuit.Ipp.Data.Qbo.IdType
qboCreditMemoLine.ClassId.Value = row("iface_class_id")
CreditMemoLines.Add(qboCreditMemoLine) 'Add line to list of lines
Next row
qboCreditMemo.Line = CreditMemoLines.ToArray 'Add CreditMemo lines to CreditMemo lines property
resultCreditMemo = commonService.Add(qboCreditMemo) 'Add CreditMemo to request
Return "OK"
'Catch exID As Intuit.Ipp.Exception.IdsException
'Return exID.Message
Catch ex As Exception
Return ex.Message
End Try
I got an error with message 'Internal Server Error'. It seems to be an IdsException. As indicated in my other article, I was able to get detailed information for a BatchRequest through the Fault and Error objects. However, I do not understand how to get the details on this error for a single invoice using Dataservices.
I think I may need better error handling, assuming there is more information available for this error. And, I need help figuring out why the same properties that I set for an invoice would not work for a CreditMemo. Unfortunately the documentation in the Intuit website where the required properties are listed does not include a CreditMemo (though it includes an Invoice).
CreditMemo is not supported in QBO:
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0400_QuickBooks_Online/0500_Supported_Entities_and_Operations
I had almost the same issue, and the problem was that the qty and amount should not be negative. I changed it on my creditmemoLine and it worked

How to INSERT into table using Entity Data Model (EDMX)

I am trying to write a button handler in VB.NET that will read rows from a gridview and write them to a DB if a checkbox is checked.
I setup this application to use EntityDataSource and added my .edmx file to a DAL folder. I have the button method written but I do not know enough about EF to know how to handle the data the data from the gridview. Here is my btn_click method:
Private Sub btnGetChecks_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetChecks.Click
'********************************************
'* gets status of checkbox and writes to db *
'********************************************
Dim row As GridViewRow
Label6.Text = ""
For Each row In DvsGridView.Rows
Dim RowCheckBox As CheckBox = CType(row.FindControl("chkStatus"), CheckBox)
If RowCheckBox.Checked Then
Label6.Text += row.Cells(5).Text & " Checked "
' Need to write checked data to the db
' ******* WHAT GOES HERE? *******
Else
Label6.Text += row.Cells(5).Text & " Unchecked "
End If
Next
End Sub
I am fairly new to EDMX but understand VB.net. Any direction would be greatly appreciated.
Check this sample code and modify this to match your entities and objects
Using db As New DBEntities()
'set values here
Dim x As New TableNameE()
x.col1 = "value1"
x.col2 = "value2"
db.AddToTableNameE(x)
db.SaveChanges()
End Using
Thanks to #rs., I was able to figure out my issues. Referring to the accepted answer, for those wondering what .AddToTableNameE() should be in your proj, it's just going to be .Add(x). It's also somewhat a performance hit using .SaveChanges() for every row, you should create a Dim List(Of TableNameE()) and add the "x" to the list, then use .AddRange() like this:
//creating a data access class is one way to connect to your db by passing in db path
Dim context As New Namespace.YourContext(New DataAccessClass() With {.Path = aBrowsedForSDFFileTextBoxMaybe.Text})
Dim listOfTableObjects As List(Of Namespace.TableObject) = New List(Of Namespace.TableObject)
For n = 1 To SomethingRelatedToRows
Dim tableObject As New Namespace.TableObject() With {
.entityProp1 = TableObject(n).entityProp1,
.entityProp2 = TableObject(n).entityProp2,
.entityProp3 = TableObject(n).entityProp3,
.entityProp4 = TableObject(n).entityProp4,
.entityProp5 = TableObject(n).entityProp5,
.entityProp6 = TableObject(n).entityProp6
}
listOfTableObjects.Add(tableObject)
Next n
//.TableObjects being the DbSet from the ...Context.vb file
context.TableObjects.AddRange(listOfTableObjects)
context.SaveChanges()