CrystalReports DataTable Error VB.NET - windows

I'm trying to pass all data from a DB to a report: but I get an error (The report has no tables)
Dim sqlConn As String = "SELECT (SUM(item_selldetail * item_quantity )/ 100 * 12) AS isv_report," & _
" (SUM( item_selldetail * item_quantity ) - (SUM(item_selldetail * item_quantity )/ 100 * 12)) " & _
" AS capital_report,SUM( item_selldetail * item_quantity ) AS total_report FROM qa_items;"
Dim objDataAdapter As New MySqlDataAdapter(sqlConn, objConn)
' DataSet
Dim ds As New DataSet
' llenar el DataSet
objDataAdapter.Fill(ds)
Dim mireporte As New ReportDocument()
mireporte.Load("C:\Users\Jonathan\Desktop\Proyectos\Quickadmon\Quickadmon\Reportes\report_capital_rpt.rpt")
mireporte.SetDataSource(ds)
Me.capitalreport_viewer_capital_report.ReportSource = mireporte
Anyone have any idea what I can do?

Sample code here , try to dolike this
sql = "SELECT Product_id,Product_name,Product_price FROM Product"
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet1
dscmd.Fill(ds, "Product")
cnn.Close()
Dim objRpt As New CrystalReport1
objRpt.SetDataSource(ds.Tables(1))
CrystalReportViewer1.ReportSource = objRpt
CrystalReportViewer1.Refresh()
If you need full source code :
http://vb.net-informations.com/crystal-report/crystal_report_from_sql_query_string.htm
merca.

Here's what I've done in the past.
1.) Create an ADO.NET (XML) Connection in Crystal. You will need to provide a path to an XML file to do this, the XML file will include the DataTable (or DataReader's) schema. It would look something like this (the x0020 represents a space in a field if you have one, see http://www.blakepell.com/Blog/?p=14 for more details on that):
<?xml version="1.0" encoding="utf-8" ?>
<people>
<first_x0020_name>
<last_x0020_name>
<phone>
</people>
2.) Set your data source like you did, in my wrapper code I had something like this where I was setting it from properties on the wrapper:
If _dataReader IsNot Nothing Then
report.SetDataSource(_dataReader)
End If
If _dataTable IsNot Nothing Then
report.SetDataSource(_dataTable)
End If
3.) Put it in your viewer control (or export it which is usually what I do since I'm generating the PDF output from it).
report.Export()
If this doesn't work for you, then post the specific stack trace and exception that you receive whenever you do this so we can troubleshoot it better. ;)

Related

VB Script for Automating File Creation (On-Demand Opportunity!)

I'm a Financial person and not quite the VB scripting guru, but I'm wondering if someone could create a sample vb script based on my requirements.
Whoever provides the solution first and the solution works on my end will have an opportunity (paid of course) to create more of these custom solutions where I work at. It wouldn't be full-time position, but more of an On-Demand opportunity.
Requirements:
To be able to read a text file that is delimited by comma and has various entries
For example, in text file...
SEC_E_All_Entities,HSII,SL_DIMENSION,READWRITE,#IDESCENDANTS,N
SEC_E_ENT_Americas,Americas,SL_DIMENSION,READ,MEMBER,N
And perform the following...
Create an XML file per entry, based on the first value
For example:
Create SEC_E_All_Entities.XML and SEC_E_ENT_Americas.XML
Within each file, write the contents where you can see how the values match each tag.
For example:
In the SEC_E_All_Entities.XML file, write...
<?xml version="1.0" encoding="UTF-8" ?>
<acls>
<acl>
<name>SEC_E_All_Entities</name>
<objectName>HSII</objectName>
<objectType>SL_DIMENSION</objectType>
<accessMode>READWRITE</accessMode>
<flag>#IDESCENDANTS</flag>
<isUser>N</isUser>
</acl>
</acls>
In the SEC_E_All_Americas.XML file, write...
<?xml version="1.0" encoding="UTF-8" ?>
<acls>
<acl>
<name>SEC_E_ENT_Americas</name>
<objectName>Americas</objectName>
<objectType>SL_DIMENSION</objectType>
<accessMode>READ</accessMode>
<flag>MEMBER</flag>
<isUser>N</isUser>
</acl>
</acls>
Regards,
Judy
Sample script
'Step 1 - Read the file and store the content in memory (an array)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\pankaj.jaju\Desktop\StackOverflow\acls.txt", 1)
arrFile = Split(objFile.ReadAll, vbCrLf) 'will store one line in each array index
objFile.Close
'Step 2 - Load the XML template in memory
Set xmlTemplate = CreateObject("MSXML2.DOMDocument.6.0")
With xmlTemplate
.ValidateOnParse = True
.Async = False
.LoadXML "<?xml version=""1.0"" encoding=""UTF-8"" ?>" & _
"<acls>" & _
"<acl>" & _
"<name></name>" & _
"<objectName></objectName>" & _
"<objectType></objectType>" & _
"<accessMode></accessMode>" & _
"<flag></flag>" & _
"<isUser></isUser>" & _
"</acl>" & _
"</acls>"
End With
'Step 3 - Load the relevant fields for which the data is to be set from csv file
Set nodeFields = xmlTemplate.DocumentElement.SelectNodes("/acls/acl/*")
'Step 4 - Read each line of text and create XML
For i = LBound(arrFile) To UBound(arrFile)
arrLine = Split(arrFile(i), ",") 'will split the line into various fields (to be used to create the xml)
For j = LBound(arrLine) To UBound(arrLine) 'set values for each field
nodeFields(j).Text = arrLine(j)
Next
Set xmlNew = xmlTemplate
xmlNew.Save objFSO.BuildPath("C:\Users\pankaj.jaju\Desktop\StackOverflow\", nodeFields(0).Text & ".xml") 'copy modified template as new xml file
Set xmlNew = Nothing
Next

Access 2010 - Run-time error 3022

I'm trying to add records to an exisiting table called "Topics" (section as of "For Each SelectedTopic In SelectedTopicsCtl.ItemsSelected" in the code below).
When executing the code i always get "Run-time error '3022': The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. So it goes wrong at the creation of the Autonumber in the field "ID" (= the only field that is indexed - no duplicates).
When debugging, line "TopicRecord.Update" in the code below is highlighted.
I have read several posts on this topic on this forum and on other forums but still cannot get this to work - i must be overlooking something....
Private Sub Copy_Click()
Dim JournalEntrySourceRecord, JournalEntryDestinationRecord, TopicRecord As Recordset
Dim JournalEntryToCopyFromCtl, JournalEntryToCopyToCtl, JournalEntryDateCreatedCtl, SelectedTopicsCtl As Control
Dim Counter, intI As Integer
Dim SelectedTopic, varItm As Variant
Set JournalEntryToCopyFromCtl = Forms![Copy Journal Entry]!JournalEntryToCopyFrom
Set JournalEntryToCopyToCtl = Forms![Copy Journal Entry]!JournalEntryToCopyTo
Set JournalEntryDateCreatedCtl = Forms![Copy Journal Entry]!JournalEntryDateCreated
Set JournalEntrySourceRecord = CurrentDb.OpenRecordset("Select * from JournalEntries where ID=" & JournalEntryToCopyFromCtl.Value)
Set JournalEntryDestinationRecord = CurrentDb.OpenRecordset("Select * from JournalEntries where ID=" & JournalEntryToCopyToCtl.Value)
Set SelectedTopicsCtl = Forms![Copy Journal Entry]!TopicsToCopy
Set TopicRecord = CurrentDb.OpenRecordset("Topics", dbOpenDynaset, dbSeeChanges)
With JournalEntryDestinationRecord
.Edit
.Fields("InitiativeID") = JournalEntrySourceRecord.Fields("InitiativeID")
.Fields("DateCreated") = JournalEntryDateCreatedCtl.Value
.Fields("Comment") = JournalEntrySourceRecord.Fields("Comment")
.Fields("Active") = "True"
.Fields("InternalOnly") = JournalEntrySourceRecord.Fields("InternalOnly")
.Fields("Confidential") = JournalEntrySourceRecord.Fields("Confidential")
.Update
.Close
End With
JournalEntrySourceRecord.Close
Set JournalEntrySourceRecord = Nothing
Set JournalEntryDestinationRecord = Nothing
For Each SelectedTopic In SelectedTopicsCtl.ItemsSelected
TopicRecord.AddNew
For Counter = 3 To SelectedTopicsCtl.ColumnCount - 1
TopicRecord.Fields(Counter) = SelectedTopicsCtl.Column(Counter, SelectedTopic)
Next Counter
TopicRecord.Fields("JournalEntryID") = JournalEntryToCopyToCtl.Value
TopicRecord.Fields("DateCreated") = JournalEntryDateCreatedCtl.Value
TopicRecord.Update
Next SelectedTopic
TopicRecord.Close
Set TopicRecord = Nothing
End Sub
First, your Dims won't work as you expect. Use:
Dim JournalEntrySourceRecord As Recordset
Dim JournalEntryDestinationRecord As Recordset
Dim TopicRecord As Recordset
Second, it looks like you get your ID included here:
TopicRecord.Fields(Counter)
or Topic is a query that includes it somehow. Try to specify the fields specifically and/or debug like this:
For Counter = 3 To SelectedTopicsCtl.ColumnCount - 1
TopicRecord.Fields(Counter).Value = SelectedTopicsCtl.Column(Counter, SelectedTopic)
Debug.Print Counter, TopicRecord.Fields(Counter).Name
Next Counter

Reduced performance when creating object in classic asp

Trying to measure a website performance I created a simple logging sub to see what parts are slow during the execution of a classic asp page.
sub log(logText)
dim fs, f
set fs = Server.CreateObject("Scripting.FileSystemObject")
set f = fs.OpenTextFile("log.txt", 8, true)
f.WriteLine(now() & " - " & logText)
f.Close
set f = Nothing
set fs = Nothing
end sub
log "Loading client countries"
set myR = Server.CreateObject("ADODB.RecordSet")
myR.ActiveConnection = aConnection
myR.CursorLocation=2
myR.CursorType=3
myR.LockType=2
myR.Source = "SELECT * FROM CC ORDER BY ccName ASC"
log "Opening db connection"
myR.open()
log "Opened db connection"
Here are the results (only showing the time part):
...
11:13:01 - Loading client countries
11:13:06 - Opening db connection
11:13:06 - Opened db connection
...
Creating the ADODBRecordSet and setting a few properties takes about 5 seconds. This does not always happen, sometimes the code is executed fast, but usually when I reload the page
after a few minutes the loading times are more or less the same as the example's. Could this really be a server/resources issue or should I consider rewriting the code? (My best option would be to write this in C#, but I have to study this code first before moving forward anyway).
Update: I added more code after receiving 1st comment to present a few more code. Explanation: The code creates a combobox (selection menu) with the retrieved countries (it continues where the previous piece of code stopped).
if not myR.eof then
clientCountries = myR.getrows
send("<option value='0'>Select country</option>")
log "Creating combobox options"
for i = 0 to ubound(clientCountries, 2)
if cstr(session("clientCountry")) <> "" then
if cstr(clientCountries(1, i)) = cstr(session("clientCountry")) then
isSelected = "selected" else isSelected = ""
end if
end if
if cstr(session("clientCountry")) = "" then
if cstr(clientCountries(1, i)) = "23" then
isSelected = "selected"
else
isSelected = ""
end if
end if
optionString = ""
optionString = clientCountries(2, i)
send("<option value='" & clientCountries(1, i) & "' " & isSelected & ">" & convertToProperCase(optionString) & "</option>")
next
log "Created combobox options"
end if
myR.Close
myR.ActiveConnection.close
myR.ActiveConnection = nothing
set myR = nothing
log "Loaded client countries"
The next two log entries are as follows:
11:13:06 - Creating combobox options
11:13:06 - Created combobox options
...
So far, the SELECT query as the rest of the page (2 or 3 queries more) is executed within the next second more or less. The only part slowing the page down is what you can see in the first part of the log. I'm not sure if I can profile the SQLServer, because I only have cPanel access. This is the only way I know of, unless there's something else I could have a look at.
First, Check your connection string, I've experienced slower times with certain providers. The best provider I've found for classic asp is sqloledb
Second, I would close my SQL object before I did the For statement on the GetRows() array. You don't want to keep that open if you don't need to.
Third, I'd use stored procedures. You'll get a performance improvement by saving on compile time.
Fourth, I would avoid doing a SELECT * statement at all cost, instead I would return ONLY the columns I need. (Your code looks like it only needs 2 columns)
Fifth, I would build indexes on the tables taking longer than expected.
If this doesn't resolve the issue, I would consider other languages/solutions. Not sure what the dataset looks like, so can't say if a flat-file database should be considered or not.
Also, try this for a recordset instead and see what happens:
Set myR = Server.CreateObject("Adodb.Recordset")
myR.Open "SELECT * FROM CC ORDER BY ccName ASC", aConnection
If myR.RecordCount > 0 Then clientCountries = myR.GetRows()
myR.Close
Set myR = Nothing
If IsArray(myR) Then
For ....

CurrentRegion.Select and Table format in VBS

I'm very new (1 week) to visual basic and basically I'm trying to automate some repetitive work, now to the point , within a number of files produced with varying data I need to format the selected range as a table (medium 9) but i'm in a block at the moment and need some help and would really appreciate it, here is what i have so far>>>>
Option Explicit
Dim strDate, strRepDate, strPath, strPathRaw , strDate2
dim dteTemp, dteDay, dteMth, dteYear, newDate, myDate
myDate = Date()
dteTemp = DateAdd("D", -1, myDate)
dteDay = DatePart("D", dteTemp)
dteMth = DatePart("M", dteTemp)
dteYear = DatePart("YYYY", dteTemp)
If (Len(dteDay) = 1) Then dteDay = "0" & dteDay
If (Len(dteMth) = 1) Then dteMth = "0" & dteMth
strDate = dteYear&"-"&dteMth&"-"&dteDay
strDate2 = dteYear&""&dteMth&""&dteDay
Dim objXLApp, objXLWb, objXLWs
Set objXLApp = CreateObject("Excel.Application")
Set objXLWb = objXLApp.Workbooks.Open("C:\Users\CuRrY\Desktop\"&strDate2&"\Agent Daily Disposition "&strDate2&".xls")
objXLApp.Application.Visible = True
'start excell
Set objXLWs = objXLWb.Sheets(1)
'objXLWs.Cells(Row, Column ).Value
With objXLWs
objXLWs.Cells(3, 1).Value = "Agent Name"
'objXLWs.Range("A3").Select
objXLWs.Range("A3").CurrentRegion.Select
'End With
as you can see i reached as far as CurrentRegion.Select but how to format selected cells into (medium 9) i've tried so much and failed
Thanks for any help
You can configure the CurrentRegion(which represents a Range object) through the SpecialCells Submethod. Although your conditions are specific to your xls sheet, you will still have to follow the formatting available through the specialcells() method properties. Also, by utilizing the currentregion property, the page assumes you have a xls header. So it is important to verify your table structure before trying to incorporate this property.
For instance:
Sub FillIn()
Range("A1").CurrentRegion.SpecialCells(xlCellTypeBlanks).FormulaR1C1 _
= "=R[-1]C"
Range("A1").CurrentRegion.Value = Range("A1").CurrentRegion.Value
End Sub
View the available properties that can be applied to CurrentRegion -> Here
And the MSDN Article -> Here

Copy one Recordset to another

Since I received so nice and fast solution to my problem, I will try again to get some help from you:
I opened two Recordsets.
Set cmd1.ActiveConnection = cn1
cmd1.CommandText = "SELECT * FROM mov Where [Date] >= #" & DateA & "#;"
Set RSold = cmd1.Execute
Set cmd2.ActiveConnection = cn2
cmd2.CommandText = "SELECT * FROM mov"
Set RSnew = cmd2.Execute
(I want to save only selected records of a file.)
I know how to copy record by record, but is there a 'Short Cut' to do it faster ?
Thanks
try this:
Dim i As Long
Do While Not RSold.EOF
' You can place if condition here
RSNew.AddNew
For i = 0 To RSold.Fields.Count - 1
RSNew.Fields(RSold.Fields(i).Name) = RSold.Fields(i).Value
Next i
RSNew.Update
RSold.MoveNext
Loop
This will copy records from RSold to RSnew recordset
You Can use code :
Set RSNew = RSOld.Clone
#user1838163 :Saving the second Recordset as a file
Dim RFileNm As String
Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")
RFileNm = "c:\temp\" & Trim(RFileNm) & ".adt"
fs.DeleteFile (RFileNm)
RSNew .Save RFileNm, adPersistADTG
RSNew .Close
RSNew .Open RFileNm, , , , adCmdFile
I think this will do what you want by doing it all at once.
Dim objPB As New PropertyBag
objPB.WriteProperty "rs", RSOld
Set RSNew = objPB.ReadProperty("rs")
Set objPB = Nothing
I don't think CLONE is going to do what you want. It just gives you another view of the same recordset you already have. This allows you to use multiple bookmarks and so forth, but the recordset is still attached to the same database the original was. I also need a way to copy the recordset and save it to a new database in a new format.

Resources