Passing Parameter to Crystal Reports XI from Visual Studio 2015 - vb.net

I am running into problems with the passing of parameters to an externally created Crystal Reports XI report from the WinForms application I'm building in Visual Studio 2015 Community Edition. No matter what I try to do, the report doesn't seem to get the value unless I manually select it at the prompt (which shouldn't even be popping up) when the report is being displayed. I'm using the same code I've used in a previous application (although that one was built in VS2008), but I've tried a number of "alternate" versions of the code in my attempts to get this working. Here's the code that I'm currently using:
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Module modReports
Private WithEvents DocumentToPrint As New Printing.PrintDocument
Private Sub ShowReport(ByVal LID As Integer, ByVal InHouse As Boolean)
Dim Report As New ReportDocument
Dim ReportParameters As ParameterFieldDefinitions = Nothing
Dim Parameter As ParameterFieldDefinition = Nothing
Dim ApplicationValue As ParameterDiscreteValue = Nothing
Dim ReportValues As ParameterValues = Nothing
Dim ReportViewer As New frmReport
Dim Response As DialogResult = DialogResult.Cancel
PrintingReport = True
Report.Load(CRYSTAL_REPORT_FILE_PATH & "ExampleReport.rpt")
Report.Refresh()
Report.VerifyDatabase()
ReportParameters = Report.DataDefinition.ParameterFields
Parameter = ReportParameters.Item("PrintAll")
ReportValues = New ParameterValues
ApplicationValue = New ParameterDiscreteValue
'Parameter.CurrentValues.Clear()
'ReportValues.Clear()
ReportValues = Parameter.CurrentValues
If LID = 7777 Then
ApplicationValue.Value = True
Else
ApplicationValue.Value = False
End If
ReportValues.Add(ApplicationValue)
Parameter.ApplyCurrentValues(ReportValues)
Response = MessageBox.Show("Do you want to send this report directly to the printer?", "SEND TO PRINTER", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
If Response = DialogResult.No Then
With ReportViewer
.rptViewer.ReportSource = Nothing
.rptViewer.ReportSource = Report
.WindowState = FormWindowState.Maximized
.rptViewer.RefreshReport()
' Set zoom level: 1 = Page Width, 2 = Whole Page, 25-100 = zoom %
.rptViewer.Zoom(1)
.rptViewer.Show()
.ShowDialog()
End With
ElseIf Response = DialogResult.Yes Then
Dim SelectPrinter As New PrintDialog
Dim PrinterSelected As DialogResult = DialogResult.Cancel
With SelectPrinter
.Document = DocumentToPrint
.AllowPrintToFile = False
.AllowSelection = False
.AllowCurrentPage = False
.AllowSomePages = False
.PrintToFile = False
End With
PrinterSelected = SelectPrinter.ShowDialog
If PrinterSelected = DialogResult.OK Then
Dim Copies As Integer = DocumentToPrint.PrinterSettings.Copies
Dim PrinterName As String = DocumentToPrint.PrinterSettings.PrinterName
Dim LastPageNumber As Integer = 1
Dim PrintBuffer As String = String.Empty
LastPageNumber = Report.FormatEngine.GetLastPageNumber(New ReportPageRequestContext)
Report.PrintOptions.PrinterName = PrinterName
Report.PrintOptions.PrinterDuplex = DocumentToPrint.PrinterSettings.Duplex
Report.PrintToPrinter(Copies, True, 1, LastPageNumber)
If Copies = 1 Then
PrintBuffer = "Printed " & Copies & " copy of "
Else
PrintBuffer = "Printed " & Copies & " copies of "
End If
If LastPageNumber = 1 Then
PrintBuffer += LastPageNumber.ToString & " page."
Else
PrintBuffer += LastPageNumber.ToString & " pages."
End If
MessageBox.Show("The report was sent to the following printer:" & vbCrLf & " • " & PrinterName & vbCrLf & PrintBuffer, "REPORT PRINTED", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End If
PrintingReport = False
End Sub
End Module
The report itself is built to use an XML file as the data source, which is dynamically created by this application. All of that works normally, and oddly enough, if I send the report directly to the printer, it seems to print correctly without prompting me. It's only a problem when I try to display the report through the CrystalReportViewer object.
Some of the things I've tried without success:
I've tried with and without calling the Clear() methods on the
Parameter.CurrentValues and ReportValues objects.
I've tried moving all of the parameter setting logic to after I set the
ReportSource of the CrystalReportViewer control (rptViewer.ReportSource)
I've tried using alternate Crystal Reports objects (ParameterFields instead of ParameterFieldDefinitions and ParameterField instead of ParameterFieldDefinition).
I've tried removing all of the "complicated" code and just using the SetParameterValue method (i.e., Report.SetParameterValue("PrintAll", True)
I've even tried creating different types of parameter fields in the report itself (String, Boolean, Number) and passing appropriate values for those datatypes.
If I walk through the code, it doesn't appear to error out anywhere, and everything looks like it's working just great until I get to the .rptViewer.RefreshReport() line in the With ReportViewer block. I've verified that all of the parameters and values have only the value I am "selecting" via the application by checking them every step up to that point, and it all looks exactly as I expect it to look.
But the application (via Crystal Reports) continues to prompt me for the value I just passed in the code. If I select the value in that prompt, the report does generate correctly based on the value I select, but no matter what I "pass" in the programming, the prompt always defaults to True.
Does anyone have any suggestions that I may have overlooked for how to get this parameter to correctly pass to the CrystalReportViewer control? Please let me know if you need any additional information or have any questions about what I've set up so far here. Thank you in advance.

Okay, so based on the information I found over on http://www.it-sideways.com/2011/10/how-to-disable-parameter-prompt-for.html, it seems that the RefreshReport method for the CrystalReportViewer control basically wipes out any parameters and/or log on information:
1. ) Do not invoke CrystalReportViewer.RefreshReport Method
This method will refresh the data for the report currently displayed
in the CrystalReportViewer control. The report will prompt for
parameters or logon info is necessary.
So, this method is not needed unless the same
CrystalDecisions.CrystalReports.Engine.ReportDocument object is
reused.
By commenting out that line of the code, I was able to prevent the parameter prompt from being displayed. The only issue I have after making that change is that, even though the zoom level is being set to 1 (page width), and when I run the project the CrystalReportViewer control even shows that it's correctly set in the status bar ('Zoom Factor: Page Width' is displayed), the report itself is not actually zoomed in to the page width.
With the RefreshReport method uncommented, if I manually provided the value for my parameter, it would display the report properly zoomed. If I add the zoom button to the control (.rptViewer.ShowZoomButton = True), I can manually choose the Page Width option, which then correctly "re-zooms" the report to the desired level, but it won't immediately display that way if the RefreshReport method is not called.
Regardless, I can spend some time trying to fight that now, but I finally have it properly setting, passing and displaying the results of my parameter. I hope this helps someone else running into this issue.

Related

Crystal Report formula field index changing on each new build

I've got a Crystal Report which I made in CR2008, which I'm printing from my vb.net application. In this report, I have an image and a formula field.
The image formula (Under Format Graphic > Picture > Graphic Location is set to be the formula field called #imgLocation.
In my vb.net code, I have the following block to select the saved file path from the database, then fill #imgLocation with this value, to set the image that is being shown.
Try
Dim logoPath As String = ds.Tables(0).Rows(0).Item("reportLogoPath") & ""
If logoPath = "" Then
MessageBox.Show("No logo path has been defined in the System Settings. Please set " & _
"one and try again.", "Load Report Failed", MessageBoxButtons.OK)
Exit Sub
Else
cReport.DataDefinition.FormulaFields.Item(2).Text = Chr(34) & logoPath & Chr(34)
End If
Catch ex As Exception
errorLog(ex)
End Try
I've seen this working twice. The image I want replaced the placeholder image when I had FormulaFields.Item(2), but then I resized the image and it didn't work. I then changed the value of the index, and it worked with FormulaFields.Item(4), but again stopped working when I resized the image.
Why is the index changing, and what is the way around it?
I tried using the named parameter option, but FormulaFields.Item("#imgLocation") gave me an error of
Invalid Index
EDIT
As per #Bugs request, this is the report showing the correct string and image
Then, after deleting and re-saving the image (But in a slightly bigger size), the parameter was passed correctly still, but the placeholder image was shown instead.
This makes me think now that it's to do with image size, however, re-sizing it back to the original size still didn't show it again.
EDIT 2
Could it be do to with the fact that I'm loading a new form which contains the report viewer, rather than opening it from the same form?
cReport.RecordSelectionFormula = selectionFormula
Me.Cursor = Cursors.Default
Dim f As New frmReportViewer(con, cReport, 0)
f.Show()
Private Sub frmReportViewer_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
setFormSizes(Me, con)
Me.Location = New Point((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2), 10)
Me.Text = "Report Viewer"
Dim logOnInfo As New TableLogOnInfo()
Dim i As Integer
For i = 0 To cReport.Database.Tables.Count - 1
logOnInfo.ConnectionInfo.DatabaseName = "comm_db"
logOnInfo.ConnectionInfo.Password = "Acplus2016!"
cReport.Database.Tables.Item(i).ApplyLogOnInfo(logOnInfo)
Next i
cReport.VerifyDatabase()
crViewer.ReportSource = cReport
crViewer.ToolPanelView = CrystalDecisions.Windows.Forms.ToolPanelViewType.None
crViewer.Zoom(87)
Catch ex As Exception
errorLog(ex)
End Try
End Sub
Please note my answer is addressing the part regarding adding parameters. For the moment the no image available placeholder is proving difficult to resolve on my side.
To add a parameter please follow these steps:
Add a parameter within Crystal Reports called imageLocation:
After pressing OK you should have a parameter in your list like this:
The following code will pass a value to the parameter:
Dim cReport As New ReportDocument
cReport.Load("C:\Report.rpt")
If cReport.ParameterFields.Item("imageLocation") IsNot Nothing Then
cReport.SetParameterValue("imageLocation", "\\SAGE200FS\Sage\StockImages\sc002.jpg")
End If
reportViewer.ReportSource = cReport
This is the output (I have added the parameter onto the report):
Note that if you are passing parameters and they are shown on the report, make sure you don't have cReport.VerifyDatabase() in place. This often throws up a dialog box asking for the parameter values.
Screenshot of dialog box:
By not calling cReport.VerifyDatabase() this will stop the dialog box from showing.
Now through Crystal Reports you can set the Graphic Location using a parameter. To do this, add the parameter to the report and suppress the field (as you don't want to see it). Then you can add the Report Field as the location.
Add parameter to report and suppress:
Add Report Field as the Graphic Location for the OLE Object:~=
Run the report and input the parameter. This will change the image accordingly. See both screenshots:
SC001::
INT4303:
This however does not seem to work through VB. The ReportViewer does not handle the change of images. Instead you are left with the default image. I'm unsure why this is the case and I'm guessing it's a bug with Crystal. If anyone knows of why this happens, feel free to comment.
EDIT
After discussing the smaller points in chat, we seem to have worked out that the issue arose because of the file path. Saving it to the database as \\server\...\...\image.png was not displaying, but after changing it to Z:\...\...\image.png it has worked fine every time. It was because of the file path, all along.

Print report directly, without print dialogue box and report viewer

I need to print my reports directly to printer:
1) Without showing print dialogue box
2) Without showing the Reportviewer
I was suggested the following code:
Dim printerSettings As New PrinterSettings()
Dim printDialog As New PrintDialog()
printDialog.PrinterSettings = printerSettings
printDialog.AllowPrintToFile = False
printDialog.AllowSomePages = True
printDialog.UseEXDialog = True
Dim result As DialogResult = printDialog.ShowDialog()
If result = DialogResult.Cancel Then
Return
End If
Me.rptSalesReport.PrintOptions.PrinterName = printerSettings.PrinterName
Me.rptSalesReport.PrintToPrinter(printerSettings.Copies, False, 0, 0)
But I am receiving error on the last two lines, where I put the name of my reports,
rptSalesReport. It says:
rptSalesReport is not defined.
While the rptSalesReport is there in my project and I can view it through report viewer.
Please advise.
Thanks

VB.NET - Combobox goes blank when a button is clicked, databind doesn't update

Please forgive me, it has been some time since I've used VB.Net so this may be easy.
I have a simple login form with a text box, combobox and a button. The combobox is binded to a SQL database and displays the user names from Users table. The idea is that you select a name, type in a password, and you logon to a new form (This part works Great!). If you type a wrong password, the form pops up a message that says "invalid." For some reason at this stage, the combobox goes blank. The drop down now has empty spaces where names once were. Typing in a name with a password here results in object reference errors. I have tried everything to get the combo box to reset and searched the web but nothing works!!!
(I know this is not a secure login, this is just an easy example of binding data to a combo box and checking it against SQL table). Thanks for your help!
enter code here
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BTN_Logon.Click
Try
Dim STR_User As String = Users_nameComboBox.SelectedValue
Dim STR_Pwd As String = TB_Pwd.Text
STR_User = STR_User.Trim
'MessageBox.Show(STR_User & "|" & STR_Pwd)'Used to verify this stage works
Dim numRecords As Int16 = UsersTableAdapter.FillByLogin(Me.Login_testDataSet.users, STR_User, STR_Pwd)
'MessageBox.Show(numRecords) 'Used to verify this stage works
If (numRecords > 0) Then
Dim DB_User As String = Me.Login_testDataSet.users(0).users_name.Trim
Dim DB_Pwd As String = Me.Login_testDataSet.users(0).users_pwd.Trim
'MessageBox.Show(DB_User & "|" & DB_Pwd)'Used to verify this stage works
If DB_User.Equals(STR_User) And DB_Pwd.Equals(STR_Pwd) Then
'User is authenticated for application
'This section works (removed to cleanup code)
Else
MessageBox.Show("ERROR" & STR_User & "|" & STR_Pwd) 'Shows that this stage works
'Need to figure out why combobox doesn't refill, using restart for now
'Application.Restart()
End If
End If
MessageBox.Show("ERROR" & STR_User & "|" & STR_Pwd) 'Shows that this stage works
'Need to figure out why combobox doesn't refill, using restart for now
'Application.Restart()
Catch ex As Exception
MessageBox.Show(ex.Message)
'Need to figure out why combobox doesn't refill, using restart for now
'Application.Restart()
End Try
End Sub
InitializeComponent
'Users_nameComboBox
Me.Users_nameComboBox.DataBindings.Add(New System.Windows.Forms.Binding("Text",
Me.UsersBindingSource, "users_name", True))
Me.Users_nameComboBox.DataBindings.Add(New System.Windows.Forms.Binding("SelectedValue", Me.UsersBindingSource, "users_name", True))
Me.Users_nameComboBox.DataSource = Me.UsersBindingSource
Me.Users_nameComboBox.DisplayMember = "users_name"
Me.Users_nameComboBox.Name = "Users_nameComboBox"
Me.Users_nameComboBox.ValueMember = "users_name"

VB.Net: How To Display Previous Shadow Copy Versions of File Allowing User to Choose One

I'm writing an Excel file recovery program with VB.Net that tries to be a convenient place to gather and access Microsoft's recommended methods. If your interested in my probably kludgy, error filled, and lacking enough cleanup code it's here: http://pastebin.com/v4GgDteY. The basic functionality seems to work although I haven't tested graph macro table recovery yet.
It occurred to me that Vista and Windows 7 users could benefit from being offered a list of previous versions of the file within my application if the Shadow Copy Service is on and there are previous copies. How do I do this?
I looked at a lot of web pages but found no easy to crib code. One possibility I guess would be to use vssadmin via the shell but that is pretty cumbersome. I just want to display a dialogue box like the Previous Versions property sheet and allow users to pick one of the previous versions. I guess I could just display the previous version property sheet via the shell by programmatically invoking the context menu and the "Restore previous versions choice", however I also want to be able to offer the list for Vista Home Basic and Premium Users who don't have access to that tab even though apparently the previous versions still exist. Additionally if it possible I would like to offer XP users the same functionality although I'm pretty sure with XP only the System files are in the shadow copies.
I looked at MSDN on the Shadow Copy Service and went through all the pages, I also looked at AlphaVSS and AlphaFS and all the comments. I'm kind of guessing that I need to use AlphaVss and AlphFS and do the following?
Find out the list of snapshots/restore points that exist on the computer.
Mount those snapshots.
Navigate in the mounted volumes to the Excel file the user wants to recover and make a list of those paths.
With the list of paths handy, compare with some kind of diff program, the shadow copies of the files with the original.
Pull out the youngest or oldest version (I don't think it matters) of those shadow copies that differ from the recovery target.
List those versions of the files that are found to be different.
This seems cumbersome and slow, but maybe is the fastest way to do things. I just need some confirmation that is the way to go now.
I finally decided to go ahead and start coding. Please make suggestions for speeding up the code or what do with files that are found to be different from the recovery file target. Is there a simpler way to do this with AlphaVSS and AlphaFS?
Private Sub Button1_Click_2(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Find out the number of vss shadow snapshots (restore
'points). All shadows apparently have a linkable path
'\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy#,
'where # is a simple one, two or three digit integer.
Dim objProcess As New Process()
objProcess.StartInfo.UseShellExecute = False
objProcess.StartInfo.RedirectStandardOutput = True
objProcess.StartInfo.CreateNoWindow = True
objProcess.StartInfo.RedirectStandardError = True
objProcess.StartInfo.FileName() = "vssadmin"
objProcess.StartInfo.Arguments() = "List Shadows"
objProcess.Start()
Dim burp As String = objProcess.StandardOutput.ReadToEnd
Dim strError As String = objProcess.StandardError.ReadToEnd()
objProcess.WaitForExit()
Dim xnum As Integer = 0
Dim counterVariable As Integer = 1
' Call Regex.Matches method.
Dim matches As MatchCollection = Regex.Matches(burp, _
"HarddiskVolumeShadowCopy")
' Loop over matches.
For Each m As Match In matches
xnum = xnum + 1
'At the max xnum + 1 is the number of shadows that exist
Next
objProcess.Close()
Do
'Here we make symbolic links to all the shadows, one at a time
'and loop through until all shadows are exposed as folders in C:\.
Dim myProcess As New Process()
myProcess.StartInfo.FileName = "cmd.exe"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardInput = True
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
Dim myStreamWriter As StreamWriter = myProcess.StandardInput
myStreamWriter.WriteLine("mklink /d C:\shadow" & counterVariable _
& " \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy" _
& counterVariable & "\")
myStreamWriter.Close()
myProcess.WaitForExit()
myProcess.Close()
' Here I compare our recovery target file against the shadow copies
Dim sFile As String = PathTb.Text
Dim sFileShadowPath As String = "C:\shadow" & _
counterVariable & DelFromLeft("C:", sFile)
Dim jingle As New Process()
jingle.StartInfo.FileName = "cmd.exe"
jingle.StartInfo.UseShellExecute = False
jingle.StartInfo.RedirectStandardInput = True
jingle.StartInfo.RedirectStandardOutput = True
jingle.StartInfo.CreateNoWindow = True
jingle.Start()
Dim jingleWriter As StreamWriter = jingle.StandardInput
jingleWriter.WriteLine("fc """ & sFile & """ """ _
& sFileShadowPath & """")
jingleWriter.Close()
jingle.WaitForExit()
Dim jingleReader As StreamReader = jingle.StandardOutput
Dim JingleCompOut As String = jingleReader.ReadToEnd
jingleReader.Close()
jingle.WaitForExit()
jingle.Close()
Dim jingleBoolean As Boolean = JingleCompOut.Contains( _
"no differences encountered").ToString
If jingleBoolean = "True" Then
MsgBox(jingleBoolean)
Else
'I haven't decided what to do with the paths of
'files that are different from the recovery target.
MsgBox("No")
End If
counterVariable = counterVariable + 1
Loop Until counterVariable = xnum + 1
End Sub

Access forms in another project in VB.net 2010

I am using VB.net 2010 and I have two projects: SQLtesting and Controls. Their physical locations are:
C:\My Documents\Visual Studio 2010\Projects\SQLtesting\SQLtesting\ [forms reside here]
C:\My Documents\Visual Studio 2010\Projects\Controls\Controls\ [forms reside here]
The code shown below works fine. I run it from the project SQLtesting. It loads a listbox and a checkedlistbox with the controls found on a form. I can change the value of the ProjAndForm field to any form within the SQLtesting project and get the form's controls. The forms are not actually opened/shown and they are not suppose to be.
I would like to be able to access forms in other projects i.e.
*C:\My Documents\Visual Studio 2010\Projects\Controls\Controls*
while running the code from the SQLtesting project.
In actual use, (when this application is an .exe) the user (developer) will enter the Project Name, Form name and whatever else this requires and click on Button7. There cannot be any hardcoding as in my example code. This application will be installed on individual pc's or on a network so the code must work based on what the developer enters.
What I really need is a way to POINT to another project and form and still use my code.
I believe the statements needed would precede the following 3 statements I have.
ProjAndForm = "SQLtesting.Form1"
FormInstanceType = Type.GetType(ProjAndForm, True, True)
objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
Currently, if I change the value of ProjAndForm to "Controls.Form66" an exception is thrown on the FormInstanceType statement.
Could not load type 'Controls.Form66' from assembly 'SQLtesting,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
As I said above, the code works fine and provides exactly what I want as long as I
reference a form in the current project SQLtesting.
Can anyone help me with this?
Thank you.
Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button7.Click
Dim CtlType As Type
Dim FormInstanceType As Type
Dim index As Integer
Dim objForm As Form
Dim ProjAndForm As String
Dim TypeName1 As String
Dim TypeName2 As String
ListBox1.Sorted = True
ListBox1.Items.Clear()
CheckedListBox1.Sorted = True
CheckedListBox1.Items.Clear()
CheckedListBox1.CheckOnClick = True
ProjAndForm = "SQLtesting.Form1"
FormInstanceType = Type.GetType(ProjAndForm, True, True)
objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
For Each ctl As Control In objForm.Controls
CtlType = ctl.GetType
TypeName1 = CtlType.ToString.Substring(21) ' Remove system.windows.forms prefix
index = CheckedListBox1.FindStringExact(TypeName1)
If index = -1 Then
CheckedListBox1.Items.Add(TypeName1)
End If
TypeName1 = TypeName1 & ":" & ctl.Name & ":" & ctl.Text
ListBox1.Items.Add(TypeName1.ToString)
Next ctl
End Sub
What you are looking for is Assembly.LoadFrom. You will need the exe or dll for this.
Dim path As String = "youassemblywitpath.dll"
Dim ass As Assembly = Assembly.LoadFrom(path)
ProjAndForm = "SQLtesting.Form1"
FormInstanceType = ass.GetType(ProjAndForm)
objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
or you could use MEF.