Paging in SharePoint with SPSiteDataQuery - vb.net

I'm attempting to write a WebPart for SharePoint that will display a list of the most recent uploads and modifications to the Site (including all Document Lists)
To that end I have created an SPGridView and I am using an SPSiteDataQuery to populate that with my (customisable) selected Lists. I'm aware that SPQuery has the ListItemCollectionPosition, but as far as I know this will not work for multiple lists, and doing one at a time ruins sorting/paging.
This is a snippet of what I have:
Dim query As New SPQuery()
Dim lists As String = "<Lists ServerTemplate='101'>"
For Each li As Guid In SelectedLists ' Personalisable Property
lists &= "<List ID='" & li.ToString & "' />"
Next
lists &= "</Lists>"
query.Lists = lists
query.RowLimit = 30 ' This will be the page size and is temporarily hardcoded
' These Id's are all SPBuildInFieldId's converted ToString
query.ViewFields = "<FieldRef ID'" & _filenameId & "' />" &
"<FieldRef ID='" & _modifiedId & "' />" &
"<FieldRef ID='" & _modifiedById & "' />" &
"<FieldRef ID='" & _versionId & "' />" &
"<FieldRef ID='" & _checkedOutToId & "' />" &
"<FieldRef ID='" & _fileSizeId & "' />" &
"<FieldRef ID='" & _createdId & "' />" &
"<FieldRef ID='" & _createdById & "' />"
query.Webs = "<Webs Scope='Recursive' />"
query.Query = "<OrderBy><FieldRef ID='" & _modifiedId & "' Ascending='FALSE' /></OrderBy>"
Dim temp as DataTable = objWeb.GetSiteData(query)
For Each row As DataRow In temp.Rows
Dim aRow = dtTable.Rows.Add()
' Get List Information
Dim listId As Guid = New Guid(row.Item("ListId").ToString)
Dim thisList As SPList = objWeb.Lists(listId)
Dim fileName As String = row.Item(_filenameId).ToString
aRow.Item("DocIcon") = "/_layouts/15/images/" & Utilities.SPUtility.MapToIcon(objWeb, fileName, "")
aRow.Item("FileName") = fileName
aRow.Item("FileLink") = objWeb.Url & "/" & thisList.Title & "/" & fileName
aRow.Item("ListName") = thisList.Title
aRow.Item("ListLink") = objWeb.Url & "/" & thisList.Title
aRow.Item("Modified") = row.Item(_modifiedId).ToString
aRow.Item("ModifiedBy") = New SPFieldLookupValue(row.Item(_modifiedById).ToString).LookupValue
aRow.Item("Version") = row.Item(_versionId).ToString
aRow.Item("CheckedOutTo") = New SPFieldLookupValue(row.Item(_checkedOutId).ToString).LookupValue
aRow.Item("FileSize") = row.Item(_fileSizeId).ToString
aRow.Item("Created") = row.Item(_createdId).ToString
aRow.Item("Author") = New SPFieldLookupValue(row.Item(_createdById).ToString).LookupValue
Next
This DataTable is set to the source of my SPGridView, and that allows paging (I am currently using an SPGridViewPager), but it will always return the full collection of documents from the query, which is going to cause some overhead once there are a lot of documents.
What I'd like is to be able to paginate in the query itself so that it only returns correct documents for the current page (~30 at a time), but I'm hitting a wall trying to achieve this.
Is there a solution I'm missing that will allow me to both query a predetermined set of lists in modified order, and also paginate at query time?
Thanks in advance and apologies for any bad wording/formatting, this is my first question on this site.

There is a workaround for this case, while it may not 'best choice' if you have huge data volume.
"Imagine If we want to display 25 records in a page & the user wants to navigate to page no 2.
uint recordsPerPage = 25;
uint pageNumber = 2;
So the rowLimit property of our query should be 25 * 2 = 50."
https://nivas07.wordpress.com/2010/06/15/paging-using-spsitedataquery/

Related

Append string to record

Environement : Oracle 11gR2 , ASP .Net, VB
Aim: need to append text string to an existing record.
Problem: When using the following
strSQL += "Update table_name SET "
strSQL += " JOB = '" & Trim(Me.txtjob.Text) & "',"
strSQL += " NAME = '" & Trim(Me.txtname.Text) & "',"
strSQL += " REMARK = REMARK || ' " & Trim(Me.txtremark.Text) & "'"
It appends the already existing data along with the new data to the new data.
Example:
Contents before SQL Execution: ABC
Contents to append: DEF
Result after execution : ABCABCDEF
expected result: ABCDEF
I tried to use a few permutations to get the right result but to no avail.
Any suggestions/resolution will be appreciated.
Okay, it seems that this was a rather straight forward solution which i ended up over complicating.
IN my case:
I was reading the record and displaying it in a text box.
What i ended up doing was :
just update the entire contents of the text box again to the record.
Thus overwriting the already existing contents along with the modified contents of the textbox.
strSQL += " DOC_LOCATION = '" & System.Web.HttpUtility.HtmlEncode(Trim(Me.txtremark.Text)) & (" Last Edit: ") & temp & " " & DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") & "'"
Since this was a rather simple application, this solution worked for me.

entity to linq where clause

I am using entity to linq
Please find my linq query -
Using lcntxRT60Entities As New RT60Entities(EntityConnection)
Dim lstrDocumentWhereClause As String
lstrDocumentWhereClause = astrDocumentWhereClause & " AND it.TransactionType = " + aintTransactionType.ToString + " AND it.VoidIndicator = 0"
lstrDocumentWhereClause = lstrDocumentWhereClause & " AND it.RtRouteDetails.RouteNumber = " + aintRouteNumber.ToString
If adatFromDate.ToString IsNot Nothing And adatToDate.ToString IsNot Nothing Then
adatToDate = adatToDate.AddHours(23).AddMinutes(59).AddSeconds(59)
lstrDocumentWhereClause = lstrDocumentWhereClause & " AND (it.TransactionDateTime BETWEEN DATETIME'" & Convert.ToDateTime(adatFromDate).ToString("yyyy-MM-dd HH:mm") & "' AND DATETIME'" & Convert.ToDateTime(adatToDate).ToString("yyyy-MM-dd HH:mm:ss") & "')"
End If
Dim Documents = From CTH In lcntxRT60Entities.RtCstTrnHeader.Where(lstrDocumentWhereClause) _
Join C In lcntxRT60Entities.RtCustomer.Where(astrCustomerWhereClause) On CTH.RtCustomer.CustomerID Equals C.CustomerID _
Select CTH, C _
Order By CTH.RouteKey, CTH.VisitKey, CTH.TransactionKey
Dim DocumentDetails = From Document In Documents.ToList _
Select Document.CTH
Return DocumentDetails.Skip(aintStartRow).Take(aintPageSize).ToList
i have problem with my where clause -
lstrFilterCriteria = "it.DocumentPrefix + it.DocumentNumber LIKE '" & lstrValue.ToString().Trim() & "'"
this throw conversion error .
If i use this
lstrFilterCriteria = "it.DocumentPrefix+SqlFunctions.StringConvert((integer)it.DocumentNumber) LIKE '" & lstrValue.ToString().Trim() & "'"
its throw syntax error .
how to convert concatenate this two column .
Document prefix is string and document number is integer .
Please suggest .
Thnaks
Using lcntxRT60Entities As New RT60Entities(EntityConnection)
Dim query=lcntxRT60Entities.RtCstTrnHeader
.Where(t=>t.TransactionType==aintTransactionType)
.Where(t=>t.VoidIndicator==0)
If adatFromDate.ToString IsNot Nothing And adatToDate.ToString IsNot Nothing Then
adatToDate = adatToDate.AddHours(23).AddMinutes(59).AddSeconds(59)
query=query.Where(t=>t.TransactionDateTime>adatFromDate && t.TransactionDateTime<adatToDate);
End If
query=query
.OrderBy(t=>t.RouteKey)
.ThenBy(t=>t.Visitkey)
.ThenBy(t=>t.TransactionKey)
Return query.Skip(aintStartRow).ToList
You will have to add in your own parameters for whatever astrDocumentWhereClause and astrCustomerWhereClause may contain before this as you didn't supply it in your example code.

items in listview load not showing

i have a problem in viewing items in listview
this is my code
rs.Open("select tableStudentRecords.*, tableTransaction.*, tablePayments.* from tableStudentRecords, tableTransaction , tablePayments" & _
" where tableStudentRecords.studnum = tableTransaction.studnum and tablePayments.psitscode = tableTransaction.psitscode", con, 3, 3)
Dim i As Integer = 0
With lvPaymentRecords
Do Until rec.EOF
.Items.Add(rec("tableTransaction.studnum").Value)
x = rec("sname").Value & ", " & rec("fname").Value & " " & rec("mi").Value & " " & rec("ext").Value
.Items(i).SubItems.Add(x)
lvPaymentRecords.Items(i).SubItems.Add(rec("sem").Value)
.Items(i).SubItems.Add(rec("sy").Value)
.Items(i).SubItems.Add(rec("total").Value)
i = i + 1
rec.MoveNext()
Loop
End With
rec.Close()
con.Close()
the thing is, items wont appear in listview, i dont know what is the cause,
tableStudentRecords and tablePayments are both PRIMARY keys,
here is the database relationships
(im sorry i cant post the image due to less reputation)
tableStudentRecords _____ tableTransaction _____ tablePAyments
-studnum _____________ -psitscode _____________-psitscode
-sname _______________ -studnum ____________-sem
-fname ________________ -sy __________________-payname
-gndr __________________-total _______________-amount
i only need to view the sem from tablePayments in listview load,
You must declare a ListViewItem variable. The codes should be
Dim lpRec As ListViewItem
With lvPaymentRecords
Do Until rec.EOF
lpRec=.Items.Add(rec("tableTransaction.studnum").Value)
x = rec("sname").Value & ", " & rec("fname").Value & " " & rec("mi").Value & " " & rec("ext").Value
lpRec.SubItems.Add(x)
lpRec.SubItems.Add(rec("sem").Value)
lpRec.Items(i).SubItems.Add(rec("sy").Value)
lpRec.Items(i).SubItems.Add(rec("total").Value)
i = i + 1
rec.MoveNext()
Loop
End With
rec.Close()
con.Close()
Hope it can help you.

How to split double quotation from string in VB.net

I have problem with inserting text from txt file into SQl Compact edition database.
the line in text file is like bellow:
item_code,Loc,cost_price,run_spr,recd_dt,disp_flag,R_qty,s_qty,a_qty,stk_qty,O_qty,
"017245588","I01","0.000","0.000","261013","N","0.000000","-2.000000","0.000000","-2.000000","0.000000"
it has 11 field
when I using this insert statement bellow:
Dim sqlstr As String
Dim sr As StreamReader = New StreamReader("C:\SKORPIO\pdt_item.txt")
Dim line As String = sr.ReadLine()
While Not (sr.EndOfStream)
line = sr.ReadLine()
Dim fields() As String = line.Split(",")
sqlstr = "INSERT INTO pdt_item (item_code,loc,cost_price,run_spr,recd_dt,disp_flag,R_qty,s_qty,a_qty,stk_qty,O_qty) VALUES( '" & fields(0) & "' ,'" & fields(1) & "','" & fields(2) & "','" & fields(3) & "','" & fields(4) & "','" & fields(5) & "','" & fields(6) & "','" & fields(7) & "','" & fields(8) & "','" & fields(9) & "','" & fields(10) & "' )"
Dim obj As SqlCeCommand = New SqlCeCommand(sqlstr, conn)
obj.ExecuteNonQuery()
the insert statement been like this
INSERT INTO pdt_item (item_code,loc,cost_price,run_spr,recd_dt,disp_flag,R_qty,s_qty,a_qty,stk_qty,O_qty) VALUES( '"017245588"' ,'"I01"','"0.000"','"0.000"','"261013"','"N"','"0.000000"','"-2.000000"','"0.000000"','"-2.000000"','"0.000000"' )
so because of two double quotations its give error
note that i did test manually without double quotations like in statement bellow its working normally.
INSERT INTO pdt_item (item_code,loc,cost_price,run_spr,recd_dt,disp_flag,R_qty,s_qty,a_qty,stk_qty,O_qty) VALUES( '017245588' ,'I01','0.000','0.000','261013','N','0.000000','-2.000000','0.000000','-2.000000','0.000000' )
So please how I can write code in VB to do this
The correct approach to this operations is through a parameterized query.
The matter is further complicated from the presence of double quotes around the field values that, I suppose, need to be removed before storing the value in the database
However, this could be the correct code....
Dim fields() As String = line.Split(",")
sqlstr = "INSERT INTO pdt_item " & _
"(item_code,loc,cost_price,run_spr,recd_dt,disp_flag," & _
"R_qty,s_qty,a_qty,stk_qty,O_qty) VALUES " & _
"( #p1, #p2, #o3, #p4, #p5, #p6, #p7, #p8, #p9, #p10, #p11)"
Dim obj As SqlCeCommand = New SqlCeCommand(sqlstr, conn)
obj.Parameters.AddWithValue("#p1", fields(0).Trim(""""c))
obj.Parameters.AddWithValue("#p2", fields(1).Trim(""""c))
obj.Parameters.AddWithValue("#p3", fields(2).Trim(""""c))
obj.Parameters.AddWithValue("#p4", fields(3).Trim(""""c))
obj.Parameters.AddWithValue("#p5", fields(4).Trim(""""c))
obj.Parameters.AddWithValue("#p6", fields(5).Trim(""""c))
obj.Parameters.AddWithValue("#p7", fields(6).Trim(""""c))
obj.Parameters.AddWithValue("#p8", fields(7).Trim(""""c))
obj.Parameters.AddWithValue("#p9", fields(8).Trim(""""c))
obj.Parameters.AddWithValue("#p10", fields(9).Trim(""""c))
obj.Parameters.AddWithValue("#p11", fields(10).Trim(""""c))
obj.ExecuteNonQuery()
There is still a problem related to the datatype of the columns in the datatable. This code assumes that every column is of type text and so every parameter value is passed as a string. If this is not the case a conversion (and a check if the value could be effectively converted) is needed when adding the parameter value.
EDIT Looking at your comment below it is clear that the simple split operation is not enough to handle correctly the file data. You need to use an instance of a TextFieldParser class. It has a property named: HasFieldEnclosedInQuotes that, when set to true, allows to ignore the field separator (the comma) when it appears inside the double quotes
So your loop could be replaced by: (Warning NOT TESTED)
Using sr As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\SKORPIO\pdt_item.txt")
sr.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
sr.Delimiters = New String() {","}
sr.HasFieldEnclosedInQuotes = True
Dim fields As String() = sr.ReadFields()
While Not sr.EndOfData
fields = sr.ReadFields()
......
What about removing the quotes first?
Instead of :
line.Split(",")
line.Replace( """", "" ).Split(",")
NOTE: this isn't good if you actually have any data with quotes in it that where you want quotes written to your database
Please use string as
"INSERT INTO pdt_item (item_code,loc,cost_price,run_spr,
recd_dt,disp_flag,R_qty, qty,a_qty,stk_qty,O_qty)
VALUES( '" + fields(0) + "' ,'" + fields(1) + "','" + fields(2) + "','" + fields(3) +
"','" + fields(4) + "','" + fields(5) + "','" +
fields(6) + "','" + fields(7) + "','" + fields(8) + "','" +
fields(9) + "','" + fields(10) + "' )";

SQL command will not insert into database

I'm trying to use a VB button to insert data into a database, but it keeps bringing up the error message I have in place for exceptions.
Can anyone help me with why this does not update the database?
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sql As String
Dim adapter As New SqlDataAdapter
Dim Customer As String = TextBox1.Text
Dim Product As String = TextBox2.Text
Dim Location As String = TextBox3.Text
Dim Details As String = TextBox4.Text
Dim Owners As String = DropDownList1.Text
Dim Urgency As String = DropDownList2.Text
connetionString = "Data Source=ZUK55APP02;Initial Catalog=BugFixPortal;User ID=SLC***;Password=rep***"
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand
adapter.UpdateCommand.CommandText = sql
adapter.UpdateCommand.ExecuteNonQuery()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
End Sub
I would not go down this road as your code is weak against SQL Injection
you should use parameters instead.Something like the below
c.Open();
string insertString = #"insert into YourTable(name, street, city,....) values(#par1, #par2, #parN,....)"
SqlCommand cmd = new SqlCeCommand(insertString, c);
cmd.Parameters.Add("#par1", SqlDbType.VarChar).Value = "MyName";
//etc
cmd.ExecuteNonQuery();
c.Close();
You are incorrectly quoting your values.
This string has an opening and closing single quote around ALL the values, which is incorrect.
VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
Instead, put single quotes around character data, eg., if Product is a varchar, it would look like this:
VALUES (" & Owners & ", " & Customer & ", '" & Product & "', " & Location & ", " & Urgency & ", " & Details & ")"
The real problem, though, is that you should be using parameterized queries instead. This code is prone to SQL injection attacks.
Change this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
to Something like this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!" & ex.Message)
It will give you more details on the exception, however at a quick glance I can see a problem, the values you are trying to insert are strings, you've enclosed all your values in a single set of ' characters, rather than enclosing each string parameter in a pair of ' values, i.e.
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & "', '" & Customer & "', '" & Product & "',' " & Location & "', '" & Urgency & "', '" & Details & "')"
You really should look at parameterizing your queries as you're wide open to SQL injection attacks. See HERE
In terms of your code itself, your SQL syntax is wrong as you need to put apostrophes around each value. Try this:
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('" & Owners & "', '" & Customer & "', '" & Product &
"', '" & Location & "', '" & Urgency & "', '" & Details & "')"
Here's an example using Parameters
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('#Owners', '#Customer', '#Product', '#Location', '#Urgency', '#Details')"
Then add parameters like so:
command.Parameters.AddWithValue("#Owners", Owners)
command.Parameters.AddWithValue("#Customer", Customer)
command.Parameters.AddWithValue("#Product", Product)
command.Parameters.AddWithValue("#Location", Location)
command.Parameters.AddWithValue("#Urgency", Urgency)
command.Parameters.AddWithValue("#Details", Details)
I think you want to use adapter.InsertCommand instead of adapter.UpdateCommand
in
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand //(adapter.InsertCommand)
adapter.UpdateCommand.CommandText = sql //(adapter.InsertCommand)
adapter.UpdateCommand.ExecuteNonQuery() //(adapter.InsertCommand)
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
and agree with parametrized sql query
see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx for more infos