mongodb query to find field - vb.net - vb.net

How would I structure a query for mongodB to make a 'stored procedure' or make the request to select an id which is marked active and then delete that field immediately or mark it as inactive; whichever one has the better performance. Here is the collection structure:
db = server.GetDatabase("test")
siteCollection = db("test")
collection = db.GetCollection(Of BsonDocument)("siteids")
Dim book As BsonDocument = New BsonDocument() _
.Add("siteid", BsonValue.Create(BsonType.String)) _
.Add("active", BsonValue.Create(BsonType.String))
collection.Insert(book)
I found the java version and not sure if this will work and what is .net syntax
db.things.find( { x : 4 } , { j : 1 } )
This apparantly finds records where x = 4 but only return where j = 1 so I want one siteid where active = 'N'
Thanks; here is what I have come up with thus far:
' Dim squery = Query.EQ("active", "Y")
Dim squery = Query.EQ("active", "Y")
Dim ssort = SortBy.Null
Dim uupdate = Update.[Set]("active", "N")
Dim result = collection.FindAndModify(squery, ssort, uupdate)
' Dim dresult = collection.FindAs(Of BsonDocument)(squery)
Dim newSiteId As String = dresult.Count
As you can see the first line commented out I thought a simple select would be implemented but that comes back null. Then with the second last statement commented out that too returned value Null.

Related

How to update a single column in single row in a datatable using LinQ

I'm working on a project that uses a Master database (a datatable) to drive downloading of files from an FTP server. During the process, I create a local database (another datatable) for each client in the master database. Here is the code that I use to create a client database:
Console.WriteLine(" Building Client Database")
Clientdatabase = New DataTable
Clientdatabase = DataBaseTable.Clone
Dim RowList = (From row In DataBaseTable.AsEnumerable() Where (row.Field(Of String)("co") = CompanyID))
For Each RowItem In RowList
Clientdatabase.ImportRow(RowItem)
Next
This code is working as expected; the Clientdatabase is accurate in what it contains. My problem is updating a field in the Clientdatabase. From within a loop, I'm getting each record that contains the full path and file name of the target file on the FTP server, then I attempt to update the clientdatabase with the local path and I can't get it to work. From within the loop this code is performing the logic and downloading the file:
Dim FileList = (From row In DataBaseTable.AsEnumerable().Select(Function(x) New With {
Key .co = x.Field(Of String)("co"),
Key .path = x.Field(Of String)("path"),
Key .OriginalFileName = x.Field(Of String)("OriginalFileName"),
Key .DocumentID = x.Field(Of String)("DocumentID")
}).Where(Function(s) s.co = CompanyID).ToList)
Console.Write(" Downloading Files : ")
Dim CursorArray() As String = Split("\,|,/,-", ",")
Dim FileCounter As Integer = 1
For Each CompanyFile In FileList
Dim ThisFile As String = CompanyFile.path.Replace("\", "/")
Dim Results As TransferOperationResult = DownloadFromPath(ThisFile, DestinPath)
Dim TmpParts() As String = Split(ThisFile, "/")
Dim LocalName As String = TmpParts(UBound(TmpParts))
If Results.IsSuccess Then
UpdateCDBPath(CompanyID, CompanyFile.DocumentID, LocalName)
ReportData &= CompanyID & ",Success," & CompanyFile.OriginalFileName & "," & ThisFile & vbCrLf
Else
ReportData &= CompanyID & ",Failed," & CompanyFile.OriginalFileName & "," & ThisFile & vbCrLf
End If
FileCounter += 1
Console.Write(CursorArray(FileCounter Mod 4) & Chr(8))
Next
The call to update (UpdateCDBPath) contains the following code:
Sub UpdateCDBPath(ByVal CompanyID As String, ByVal DocumentID As String, TargetValue As String)
Dim result = (From row In Clientdatabase.AsEnumerable().Select(Function(x) New With {
Key .DocumentID = x.Field(Of String)("DocumentID"),
Key .Co = x.Field(Of String)("co")
}).Where(Function(s) s.DocumentID = DocumentID And s.Co = CompanyID ) Select Clientdatabase)
For Each ItemRow In result
ItemRow.Rows(0).Item("Path") = TargetValue
Next
End Sub
The problem is within this code block. DocumentID is a GUID that is unique within the client that uniquely identifies the document, TargetValue is the replacement path (local path to the file). If I'm understanding the Linq correctly (and I'm not), it should only return the rows I'm interested in (1), thus how I'm setting the new path. I've tried countless examples from various examples and can't make it work. When I check the Clientdatabase, none of the path fields are updated. I've also confirmed that after saving the Clientdatabase locally, the fields are still the same. Can some one please point me in the right direction, tell me where I went wrong or something so I can solve this. I eventually will need to update other fields in the clientdatabase; this is the first one. Thanks in advance for any and all help that might come my way!
The linq for result is returning a EnumerableRowCollection(Of System.Data.DataTable), meaning that it contains a list of rows that are the entire Clientdatabase.
As each row contains the entire DataRowCollection, ItemRow.Rows(0).Item("Path") = TargetValue will update only the first row in Clientdatabase as many times as there are records in results.
Changing the query to return an EnumerableRowCollection(Of System.Data.DataRow) allows each row to be accessed directly in a loop:
Sub UpdateCDBPath(ByVal CompanyID As String, ByVal DocumentID As String, TargetValue As String)
Dim result = From row In Clientdatabase.AsEnumerable()
Where row.Field(Of String)("DocumentID") = DocumentID AndAlso
row.Field(Of String)("co") = CompanyID
Select row
For Each ItemRow In result
ItemRow.Item("Path") = TargetValue
Next
End Sub

How can I merge 2 DataView built in 2 different way?

I am not a c# developer and I found myself at work working with a huge C# application...hug..
Now I am trying to populate an existing DataGrid with some more data which has been 'created' in a different way...let me show you what I mean.
This is how the existing DataView is generated:
Dim lDataSet As System.Data.DataSet
Dim lSqlCommand As New System.Data.SqlClient.SqlCommand
Dim lConvert As New PeoplePlanner.Common.Data.Convert
lSqlCommand.CommandType = CommandType.StoredProcedure
lsqlCommand.CommandText = "AccessIntegrationEmployeeInboundSearch"
lDataSet = objDatabase.GetDataSet(lSqlCommand)
If Not IsNothing(lDataSet) Then
objDataView = lDataSet.Tables(0).DefaultView
End If
There is probably be stuff missing in that code but hopefully it is enough to get an overview. It uses Stored Procedure (SP) to get some data from the DB and it returns the result inside 'lDataSet' and then we do 'objDataView = lDataSet.Tables(0).DefaultView'.
Now the new data which I want to 'merge in' it has the same fields but it is not the response of a SP but of an operation I have created which returns back a List of OnBoardingEmployee(let's call it like that) and if I want to correctly show ONLY the data inside that list this is what I do:
Dim lDataView As System.Data.DataView
Dim op = CoreInjector.Inject(Of IGetAllDataHubIncomingMessagesToBeProcess).Execute()
lDataView = Common.Detail.DataGridOperationHelper.ConvertToDataTable(op.OnBoardingEmployee).DefaultView
objDataView = lDataView
Where:
op contains a list of OnBoardingEmployee which has the same fields as the existing table
lDataView basically is the same as objDataView that's why as last step I assign objDataView = lDataView
Now I would basically like to merge, join, add, whatever
The objDataView created for the first table:
objDataView = lDataSet.Tables(0).DefaultView
with the one I have created afterwards:
lDataView = Common.Detail.DataGridOperationHelper.ConvertToDataTable(x.OnBoardingEmployee).DefaultView
How do I do that? :'(
They have the same data structure or better say they use the same view.
Thanks for the help :)
I have got it working :) this is my implementation:
Dim employeeJSONTable As DataTable
Dim employeeExistingTable As DataTable
Dim myDataRow As DataRow
Dim employeeID As Integer
if Request.QueryString.Get("Function") = "HubInbound" then
Dim employeeJSONList = CoreInjector.Inject(Of IGetAllDataHubIncomingMessagesToBeProcess).Execute()
employeeJSONTable = Common.Detail.DataGridOperationHelper.ConvertToDataTable(employeeJSONList.OnBoardingEmployee)
employeeJSONTable.PrimaryKey = New DataColumn(){ employeeJSONTable.Columns("EmployeeID")}
End If
lDataSet = objDatabase.GetDataSet(lSqlCommand)
employeeExistingTable = lDataSet.Tables(0)
For Each row As DataRow In employeeExistingTable.Rows
employeeID = row.Item("EmployeeID")
myDataRow = employeeJSONTable.Rows.Find(employeeID)
if (myDataRow Is Nothing) then
employeeJSONTable.ImportRow(row)
End If
Next row
If Not IsNothing(employeeJSONTable.DefaultView) And Request.QueryString.Get("Function") = "HubInbound" Then
objDataView = employeeJSONTable.DefaultView
Elseif Not IsNothing(lDataSet) Then
objDataView = lDataSet.Tables(0).DefaultView
End if

Submitchanges after a loop - only last record saved

The following code works, but it only saves the last record in the loop, and I can't figure out why. I think the Submitchanges() is in the right place, at the end of the loop. Can someone please show me what's wrong? Thanks.
Sub POPULATE_CHAIN()
Dim newChain As New CHAIN
Dim dpSTRIKE As Integer
'get list of Options Contracts
Dim lstOPT = From Z In DATA.OPTIONs, X In DATA.UDLies
Where X.UDLY_SYM = Z.UDLY_SYM
Select Z.CONTRACT, Z.STRIKE_GAP, X.UDLY_LAST
Dim dctOPT = lstOPT.ToDictionary(Function(Z) Z.CONTRACT)
For Each key In dctOPT.Keys
For COUNT = 1 To 5
dpSTRIKE = 1850 + 5 * COUNT
Dim lkup = From Z In DATA.CHAINs
Select Z
Dim RCD_EXISTS As Boolean = lkup.Any(Function(Z) Z.CONTRACT = dctOPT(key).CONTRACT And Z.P_C = "C" And Z.STRIKE = dpSTRIKE)
If RCD_EXISTS = False Then
newChain.CONTRACT = dctOPT(key).CONTRACT
newChain.P_C = "C"
newChain.STRIKE = dpSTRIKE
DATA.CHAINs.InsertOnSubmit(newChain)
Else
newChain.CONTRACT = dctOPT(key).CONTRACT
newChain.P_C = "C"
newChain.STRIKE = dpSTRIKE
End If
Next
Next
DATA.SubmitChanges()
End Sub
Dim newChain As New CHAIN
should be inside Fore Each, exactly inside second for.
Since it is declared outside the loop, it will be detached from table and attached again to table. So it will be inserted only in last row.

Linq Entity compare 3 fields with wildcard vb.net

Im sure this code was working but cannot rememeber what i did to make it work.
I want to match fields first middle and last with wildcard in between to string user
Return (From q In context.users
Where (Join( {q.user_first, q.user_middle, q.user_last}, "%"))
.ToLower.Contains(user.ToLower)
Select q).ToList
The error message is:
LINQ to Entities does not recognize the method 'System.String
Join(System.String[], System.String)' method, and this method cannot
be translated into a store expression.
Hope someone finds this useful.
I created a computed column in user table called user_fullname:
(rtrim((coalesce([user_first]+' ','')+coalesce([user_middle]+' ',''))+coalesce([user_last]+' ','')))
The code below, splits the name into an array to work out what to search for.
Dim names As String() = user.Trim.Split(" ")
If names.Count = 2 Then
Dim fname As String = names(0)
Dim lname As String = " " & names(1)
Return (From q In context.users Where (q.user_fullname.StartsWith(fname) And q.user_fullname.Contains(lname)) Select q).AsQueryable
ElseIf names.Count = 1 Then
Return (From q In context.users Where (q.user_fullname.StartsWith(user) Or q.user_last.StartsWith(user)) Select q).AsQueryable
ElseIf names.Count = 3 Then
Dim fname As String = names(0)
Dim lname As String = names(2)
Dim mname As String = names(1)
Return (From q In context.users Where (q.user_first.StartsWith(fname) And q.user_middle.StartsWith(mname) And q.user_last.StartsWith(lname)) Select q).AsQueryable
Else
Return Nothing

Insert a Date as a String to Access using a DAO Recordset

I am using some code I found in an old C# post to run a DAO insert into Access with VB.net. I ran the code to insert numbers and it ran fine. However When i try to insert a date as a string between hashes I get a Data type conversion error. I have had a look and I can't see how to change the data type of the recordset field to accept a string/date.
Here is the code:
Dim dbEngine As New dao.DBEngine
Dim db As dao.Database = dbEngine.OpenDatabase(DataDirectoryName & DatabaseName)
Dim rs As dao.Recordset = db.OpenRecordset(TableName)
Dim myFields As dao.Field() = New dao.Field(FieldNames.Count - 1) {}
For k As Integer = 0 To FieldNames.Count - 1
myFields(k) = rs.Fields(FieldNames(k))
Next
dbEngine.BeginTrans()
For i As Double = 0 To Data.Rows - 1
rs.AddNew()
For k As Integer = 0 To FieldNames.Count - 1
rs.Fields(k).Value = Data.Value(k, i)
rs.Fields(FieldNames(k)).Value = Data.Value(k, i)
myFields(k).Value = Data.Value(k, i)
Next
rs.Update()
Next
dbEngine.CommitTrans()
rs.Close()
db.Close()
Here is one row of data:
(0) = "74"
(1) = "#01 February 2012 00:02:00#"
(2) = "40"
(3) = "130"
(4) = "60"
'Data' is a custom class that is a list (of list (of string)).
While VBA will accept date delimiters on your string, eg #11 February 2013 20:23:11# it seems that VB.Net will not, however, it does accept for an MS Access update.
rs.Fields("adate").Value = CDate("11 February 2013 20:23:11")