I have a situation here where I have a deployed rdl file in the reporting server. The rdl file in question has a parameter.
I am using the rs.exec component to execute the report; whenever I remove the parameter from the rdl file, I successfully run the report from the stored procedure. When I add the parameter, all I keep getting is
\\server\R\subfolder\working\inputfile\example.batK00WE is not recognized as an internal or external operable program or batch file.
Here is what I did: I created a .rss file in VB (Please see code below)
Public Sub Main()
TRY
DIM historyID as string = Nothing
DIM deviceInfo as string = Nothing
DIM extension as string = Nothing
DIM encoding as string
DIM mimeType as string = "application/Excel"
DIM warnings() AS Warning = Nothing
DIM streamIDs() as string = Nothing
DIM results() as Byte
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
rs.LoadReport(REPORTSERVER_FOLDER, historyID)
results = rs.Render(FORMAT, deviceInfo, extension, mimeType, encoding, warnings, streamIDs)
DIM stream As FileStream = File.OpenWrite(FILENAME)
stream.Write(results, 0, results.Length)
stream.Close()
Catch e As IOException
Console.WriteLine(e.Message)
End Try
End Sub
Afterwards... I wrote batch file that utilizes the rs.exec. Please see below:
"\\server\R\subfolder\working\app\rs.exe" -i \\server\R\subfolder\working\inputfile\coo.rss -s "http://server/ReportServer_MSSQLSERVER2" -v FILENAME="\\server\R\subfolder\working\inputfile\file.csv" -v REPORTSERVER_FOLDER="/FILE_REPORT/FILE" -t -v FORMAT="EXCEL" -e Exec2005
If you see the above script the rs.exec utilizes the path of the report server etc.
Finally I created a stored procedure that will run the report on the server and pass into the server the parameter value.
CREATE PROCEDURE [dbo].[test_sproc]
#ProcessID varchar(50)
AS
DECLARE #cmdsql varchar(1000)
Declare #id varchar(50)
Set #id=#SID
Set #cmdsql= '"\\server\R\subfolder\working\inputfile\example.bat"' + #id
exec master..xp_CMDShell #cmdsql
So here is my question is: How do I pass the parameter value from stored procedure to the report server? Where did I go wrong with my code?
Related
I have a program which exports a System.Data.DataTable to an XLSX / OpenXml Spreadsheet. Finally have it mostly working. However when opening the Spreadsheet in Excel, Excel complains about the file being invalid, and needing repair, giving this message...
We found a problem with some content in . Do you want us to
try to recover as much as we can? If you trust the source of the
workbook, clik Yes.
If I click Yes, it comes back with this message...
Clicking the log file and opening that, just shows this...
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<logFileName>error268360_01.xml</logFileName>
<summary>Errors were detected in file 'C:\Users\aabdi\AppData\Local\Temp\data.20190814.152538.xlsx'</summary>
<repairedRecords>
<repairedRecord>Repaired Records: Cell information from /xl/worksheets/sheet1.xml part</repairedRecord>
</repairedRecords>
</recoveryLog>
Obviously, we don't want to deploy this into a production environment like this. So I've been trying to figure out how to fix this. I threw together a quick little sample to validate the XML and show the errors, based on this link from MSDN. But when I run the program and load the exact same XLSX document that Excel complains about, the Validator comes back saying that the file is perfectly Valid. So I'm not sure where else to go from there.
Any better tools for trying to validate my XLSX XML? Following is the complete code I'm using to generate the XLSX file. (Yes, it's in VB.NET, it's a legacy app.)
If I comment out the line in the For Each dr As DataRow loop, then the XLSX file opens fine in Excel, (just without any data). So it's something with the individual cells, but I'm not really DOING much with them. Setting a value and data type, and that's it.
I also tried replacing the For Each loop in ConstructDataRow with the following, but it still outputs the same "bad" XML...
rv.Append(
(From dc In dr.Table.Columns
Select ConstructCell(
NVL(dr(dc.Ordinal), String.Empty),
MapSystemTypeToCellType(dc.DataType)
)
).ToArray()
)
Also tried replacing the call to Append with AppendChild for each cell too, but that didn't help either.
The zipped up XLSX file (erroring, with dummy data) is available here:
https://drive.google.com/open?id=1KVVWEqH7VHMxwbRA-Pn807SXHZ32oJWR
Full DataTable to Excel XLSX Code
#Region " ToExcel "
<Extension>
Public Function ToExcel(ByVal target As DataTable) As Attachment
Dim filename = Path.GetTempFileName()
Using doc As SpreadsheetDocument = SpreadsheetDocument.Create(filename, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook)
Dim data = New SheetData()
Dim wbp = doc.AddWorkbookPart()
wbp.Workbook = New Workbook()
Dim wsp = wbp.AddNewPart(Of WorksheetPart)()
wsp.Worksheet = New Worksheet(data)
Dim sheets = wbp.Workbook.AppendChild(New Sheets())
Dim sheet = New Sheet() With {.Id = wbp.GetIdOfPart(wsp), .SheetId = 1, .Name = "Data"}
sheets.Append(sheet)
data.AppendChild(ConstructHeaderRow(target))
For Each dr As DataRow In target.Rows
data.AppendChild(ConstructDataRow(dr)) '// THIS LINE YIELDS THE BAD PARTS
Next
wbp.Workbook.Save()
End Using
Dim attachmentname As String = Path.Combine(Path.GetDirectoryName(filename), $"data.{Now.ToString("yyyyMMdd.HHmmss")}.xlsx")
File.Move(filename, attachmentname)
Return New Attachment(attachmentname, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
End Function
Private Function ConstructHeaderRow(dt As DataTable) As Row
Dim rv = New Row()
For Each dc As DataColumn In dt.Columns
rv.Append(ConstructCell(dc.ColumnName, CellValues.String))
Next
Return rv
End Function
Private Function ConstructDataRow(dr As DataRow) As Row
Dim rv = New Row()
For Each dc As DataColumn In dr.Table.Columns
rv.Append(ConstructCell(NVL(dr(dc.Ordinal), String.Empty), MapSystemTypeToCellType(dc.DataType)))
Next
Return rv
End Function
Private Function ConstructCell(value As String, datatype As CellValues) As Cell
Return New Cell() With {
.CellValue = New CellValue(value),
.DataType = datatype
}
End Function
Private Function MapSystemTypeToCellType(t As System.Type) As CellValues
Dim rv As CellValues
Select Case True
Case t Is GetType(String)
rv = CellValues.String
Case t Is GetType(Date)
rv = CellValues.Date
Case t Is GetType(Boolean)
rv = CellValues.Boolean
Case IsNumericType(t)
rv = CellValues.Number
Case Else
rv = CellValues.String
End Select
Return rv
End Function
#End Region
For anyone else coming in and finding this, I finally tracked this down to the Cell.DataType
Setting a value of CellValues.Date will cause Excel to want to "fix" the document.
(apparently for dates, the DataType should be NULL, and Date was only used in Office 2010).
Also, if you specify a DataType of CellValues.Boolean, then the CellValue needs to be either 0 or 1. "true" / "false" will also cause Excel to want to "fix" your spreadsheet.
Also, Microsoft has a better validator tool already built for download here:
https://www.microsoft.com/en-us/download/details.aspx?id=30425
I have this code set in access, but no email is sending upon clicking the button on the form. I have outlook open. When i click the button on the form, i can't see anything that actually happens. I want the email address to be equal to the value in [text1], and I am trying to make the subject include a fixed message plus the input from [text2]. Even without these variables, I can't get this to work
Public Sub Command495_Click()
Dim mailto As String
Dim ccto As String
Dim bccto As String
mailto = [text1]
ccto = ""
bccto = ""
emailmsg = "trial"
mailsub = [text2] & ", Does this work?"
On Error Resume Next
DoCmd.SendObject acSendNoObjectType, , acFormattxt, mailto, ccto, bccto, mailsubj, emailmsg, True
End Sub
I have checked to make sure the onclick property shows event procedure. I am stuck, please help!
Here are a few suggestions and a modified version of your code.
ALWAYS use Option Explicit and compile your module before testing. You had a number of variables that were not defined and incorrect spelling of some options.
NEVER bypass errors when testing (get rid of your "On Error Resume Next") That's why you never saw an error.
Look for every place I entered ">>>" and address that issue.
Always explicitly define your variables and use the proper Type. Removes all doubt of what/where something is.
Option Compare Database
Option Explicit
Public Sub Command495_Click()
Dim mailto As String
Dim ccto As String
Dim bccto As String
Dim emailmsg As String
Dim mailsub As String
mailto = [Text1] ' >>> Where is [Text1]?? Remove for testing
ccto = ""
bccto = ""
emailmsg = "trial"
mailsub = [Text2] & ", Does this work?" ' >>> Where is [Text2]?? Remove for testing
' >>> Bad idea to ignore errors when testing!!
On Error Resume Next
'>>> Following line had: (1) 'acSendNoObjectType' which is incorrect; (2) mailsubj, which is undefined
DoCmd.SendObject acSendNoObject, , acFormatTXT, mailto, ccto, bccto, mailsub, emailmsg, True
End Sub
i have a code like this for passing parameter filed value into crystal report.
Dim projectreportds As New ProjectRptnew -**this s dataset name**
If ds.Tables.Count > 0 Then
projectreportds.Tables(0).Merge(ds.Tables(0))
Dim rpt As New ProjectReportNew-**this s report name**
rpt.SetParameterValue("ExhbitionName", cmbExhibition.Text)
Dim objrpt As New frmrptengine(AppPath & "\reports\ProjectReportNew.rpt", projectreportds)
objrpt.ShowDialog()
End If
but if am running this code am asking parameter value.what changes i have to make in my code..
Try this:
Set App = CreateObject("CrystalRuntime.Application")
report= "c:\report.rpt"
Set rep = app.OpenReport(report)
For i = 1 To rpt.Database.Tables.Count
Print rpt.Database.Tables(i).name
If rpt.Database.Tables(i).name = "YOUR_TABLE_NAME" Then
//first table login
rpt.Database.Tables(i).SetLogonInfo "YOUR_SERVER_NAME","YOUR_DATABASE_PATH",Username.Abbreviated,Password
Else
//second table login
rpt.Database.Tables(i).SetLogonInfo "YOUR_SERVER_NAME","YOUR_DATABASE_PATH",Username.Abbreviated,Password
End If
Next
YOUR_TABLE_NAME= name of the table, you can find it under "Database" menĂ¹, "Database Expert" ->"Selected Tables"
YOUR_SERVER_NAME= the server name of source database
YOUR_DATABASE_PATH= the complete path of the source database
Username.Abbreviated= the username to access database
Password= password of "Username.Abbreviated" to access database
and to pass parameter field:
rpt.ParameterFields(1).AddCurrentValue (num)
num is my parameter field
i am new to run SQL Scripts using sqlcmd in C#. i saw some code in Internet but i am not understanding how it Works.
string path = string.Empty;
OpenFileDialog opd = new OpenFileDialog();
opd.Filter = "sql files|*.sql";
if (opd.ShowDialog() == DialogResult.OK)
{
path = opd.FileName;//Here i am taking Database sqlScript
}
string tmpFile = Path.GetTempFileName();
SqlConnectionStringBuilder connection=new SqlConnectionStringBuilder(#"Data Source=LPTP2\LPTP2;Initial Catalog=Database;Integrated Security=True");
string argument = string.Format(#" -S {0} -d {1} -i ""{2}"" -o ""{3}""",
#".\SQLEXPRESS", "Database", path, tmpFile);
// append user/password if not use integrated security
if (!connection.IntegratedSecurity)
argument += string.Format(" -U {0} -P {1}", "sa", "abc#123");
var process = Process.Start("sqlcmd.exe", argument);
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
while (true)
{
// wait for the process exits. The WaitForExit() method doesn't work
if (process.HasExited)
break;
Thread.Sleep(500);
}
i am not understanding how these three lines are working
string tmpFile = Path.GetTempFileName();
SqlConnectionStringBuilder connection=new SqlConnectionStringBuilder(#"Data Source=LPTP2\LPTP2;Initial Catalog=HemoTrace;Integrated Security=True");
string argument = string.Format(#" -S {0} -d {1} -i ""{2}"" -o ""{3}""",
#".\SQLEXPRESS", "HemoTrace", path, tmpFile);
// append user/password if not use integrated security
if (!connection.IntegratedSecurity)
argument += string.Format(" -U {0} -P {1}", "sa", "abc#123");
Why i am doing this means i want to run a SQL SCRIPT the script which execute to create a database. but i want to do using sqlcmd. In Client Place if i execute my .exe file it finish my work(to attach database to Server).
Please help me regarding this.
string tmpFile = Path.GetTempFileName();
Declare a string variable called tmpFile and use Path.GetTempFileName() to generate a unique temp file name and store it in the variable
SqlConnectionStringBuilder connection=new
SqlConnectionStringBuilder(#"Data Source=LPTP2\LPTP2;Initial Catalog=HemoTrace;
Integrated Security=True");
Use the SqlConnectionStringBuilder class to build a SQL Server connection string. This doesn't actually connect to anything, it just generates a connection string.
string argument = string.Format(#" -S {0} -d {1} -i ""{2}"" -o ""{3}""",
#".\SQLEXPRESS", "HemoTrace", path, tmpFile);
declare a string called argument and set it to a a bunch of characters, including the path to the temp file that was generated earlier. This bunch of characters is suitable to use as arguments to the SQLCMD command line.
// append user/password if not use integrated security
if (!connection.IntegratedSecurity)
argument += string.Format(" -U {0} -P {1}", "sa", "abc#123");
Use a property of the SqlConnectionStringBuilder class to work out if we should add the command line switch to indicate trusted security.
After all of this you run:
var process = Process.Start("sqlcmd.exe", argument);
If you dump this fill string out you'll find something that can be run on the command line.
SQLCMD is a command line program, which incidentally needs to be installed on your client machine.
The command line program takes a bunch of arguments which you have built in previous lines of your code.
There are some issues in this code:
You need to have SQLCMD.EXE istalled for it to work.
You hard code trusted security in a string, load this into a special class then use that class to work out if you're using trusted security... you've already hard coded it!
You also hard code a certain server in the connection string but then hard code a different server in the arguments for SQLCMD
It appears the connection string (the middle line) is totally redundant in this case.
We are trying to build an EntityConnection dynamically so that different users are connecting to differnet databases determined at run-time. In order to do this we are testing the code found here: http://msdn.microsoft.com/en-us/library/bb738533.aspx. We have implemented this below:
' Specify the provider name, server and database.
Dim providerName As String = "System.Data.SqlClient"
Dim serverName As String = "OurDBServerName"
Dim databaseName As String = "OurDBName"
' Initialize the connection string builder for the
' underlying provider.
Dim sqlBuilder As New SqlConnectionStringBuilder
' Set the properties for the data source.
sqlBuilder.DataSource = serverName
sqlBuilder.InitialCatalog = databaseName
sqlBuilder.IntegratedSecurity = False
sqlBuilder.UserID = "OurAppUserName"
sqlBuilder.Password = "OurPassword"
' Build the SqlConnection connection string.
Dim providerString As String = sqlBuilder.ToString
' Initialize the EntityConnectionStringBuilder.
Dim entityBuilder As New EntityConnectionStringBuilder
'Set the provider name.
entityBuilder.Provider = providerName
' Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString
' Set the Metadata location to the current directory.
entityBuilder.Metadata = "res://*/NotaModel.csdl|" & _
"res://*/NotaModel.ssdl|" & _
"res://*/NotaModel.msl"
Console.WriteLine(entityBuilder.ToString)
Using conn As EntityConnection = New EntityConnection(entityBuilder.ToString)
conn.Open()
Console.WriteLine("Just testing the connection.")
conn.Close()
End Using
When the conn.Open() is run an error is thrown: "Unable to load the specified metadata resource." It seems to indicate that one or more of the "res://*..." references is wrong. I have confirmed that the project does indeed contain these files (under the bin/debug folder). What are we missing here - any ideas?
Thanks
Yes, the res:// part is wrong. Look at the resource names in Reflector (inside the assembly), not on your local filesystem, to see what they should be.