Get report parameters as URL string - javascript
I have an application that serves SSRS reports. A given report is accessed in the following way:
https://reportserver.com/reportname
Upon clicking View Report, a postback is submitted to the report server with the user-defined parameters. I need to grab these user-defined parameters and parse them as a URL string.
Desired result: https://reportserver.com/reportname?param1=foo¶m2=bar
I found this doc that gets me close to what I need. This method should allow me to grab all visible parameters and parse them myself, but I need hidden parameters as well.
How can I build this parameter string? We're using JavaScript/jQuery in the front end so it may be possible to grab this client-side before the POST, but I haven't found a way of doing this either.
I got it working. Fair warning: I'm new to ASP.NET so this is likely not an ideal solution.
I added an event handler to the report viewer control's code behind. This queries the execution log, grabbing the parameters selected most recently by the user. It is meant to be triggered when a button called "Save Report" is clicked. If you try to handle this with a Load or PreRender event handler it will fire before the row has a chance to insert into the database, giving you the result of the user's second most recent execution parameters.
Define the Button (.ascx file)
<asp:LinkButton ID="SaveReportButton" runat="server" title="Save this Report"></asp:LinkButton>
Add event handler to code behind (.ascx.vb file)
Protected Sub SaveReportButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveReportButton.Click
Dim conn As New SqlConnection(<connection string here>)
Dim cmd As New SqlCommand("SELECT TOP 1 Parameters FROM [ReportServer].[dbo].[ExecutionLogStorage] WHERE <qualify on user, timestamp, etc. here>", conn)
cmd.Parameters.AddWithValue(<query parameter here>)
conn.Open()
Dim result = cmd.ExecuteScalar()
' Prevents NullReferenceException from result.ToString() in case no result is found
If (result IsNot Nothing)
' Redirect based on parameter string retrieved from log
Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri & "?" & result.ToString())
End If
conn.Close()
End Sub
Call postback from JavaScript on button click
<li>
<a href=\'javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(<reference SaveReportButton with appropriate arguments>)\' id="SaveReportButton" title="Save Report">
Save Report
</a>
</li>
Documentation on WebForm_DoPostBackWithOptions() and WebForm_PostBackOptions() is sparse, but a colleague has already done it this way so I followed suit for consistency's sake because it works.
I've created URLs for reports with parameters 3 different ways. A combination of the the first two may get you closer to solving your problem.
Use custom code in the report properties.
Public Function ShowParameterValues(ByVal parameter As Parameter) As String
Dim s as String = String.Empty
Try
If parameter.IsMultiValue then
s = "Multivalue: "
For i as integer = 0 to parameter.Count-1
s = s + CStr(parameter.Value(i)) + " "
Next
Else
s = "Single value: " + CStr(parameter.Value)
End If
Return s
Catch ex As Exception
Return "error"
End Try
End Function
OR
Use a hyperlink in the report.
=Globals!ReportServerUrl + "/ReportServer?"
+ Replace(Globals!ReportFolder, " ", "+") + "%2f"
+ Replace(Globals!ReportName, " ", "+") + "&rs:Command=Render"
+ "&boolean_value=" + CStr(Parameters!boolean_value.Value)
+ "&single_value_parameter=" + Parameters!single_value_parameter.Value
+ "&multi_value_parameter=" + Join(Parameters!multi_value_parameter.Value, "&multi_value_parameter=")
+ IIf(IsNothing(Parameters!week_date_start.Value), "&week_date_start:isnull=True", "&week_date_start=" & Format(Parameters!week_date_start.Value, Variables!FormatDate.Value))
+ IIf(IsNothing(Parameters!week_date_end.Value), "&week_date_end:isnull=True", "&week_date_end=" & Format(Parameters!week_date_end.Value, Variables!FormatDate.Value))
Also, I usually add this as a report variable and then you can have a standard textbox for the footer that doesn't have to change.
=Variables!UrlReportWithParameters.Value
OR
Use the execution log. Check out the column URL_Report_Filtered
--Purpose: to search the reporting services execution log
DECLARE #all_value AS VARCHAR(10) = '<ALL>';
DECLARE #LogStatus AS VARCHAR(50) = '<ALL>';
DECLARE #ReportFolder AS VARCHAR(450) = 'Testing';
DECLARE #ReportName AS VARCHAR(450) = '<ALL>';
DECLARE #UserName AS VARCHAR(260) = '<ALL>';
DECLARE #GroupByColumn AS VARCHAR(50) = 'Report Folder';
DECLARE #StartDate AS DATETIME = NULL;
DECLARE #EndDate AS DATETIME = NULL;
WITH
report_users
AS
(
SELECT
[UserID]
, [UserName]
, [SimpleUserName] = UPPER(RIGHT([UserName], (LEN([UserName])-CHARINDEX('\',[UserName]))))
FROM
[dbo].[Users]
)
,
report_catalog
AS
(
SELECT
rpt.[ItemID]
, rpt.[CreatedById]
, rpt.[ModifiedById]
, rpt.[Type]
, rpt.[Name]
, [ReportName] = rpt.[Name]
, rpt.[Description]
, rpt.[Parameter]
, [CreationDate] = CONVERT(DATETIME, CONVERT(VARCHAR(11), rpt.[CreationDate], 13))
, [ModifiedDate] = CONVERT(DATETIME, CONVERT(VARCHAR(11), rpt.[ModifiedDate], 13))
, [ReportFolder] = SUBSTRING(rpt.[Path], 2, LEN(rpt.[Path])-LEN(rpt.[Name])-2)
, rpt.[Path]
, [URL_ReportFolder] = 'http://' + Host_Name() + '/Reports/Pages/Report.aspx?ItemPath=%2f' + SUBSTRING(rpt.[Path], 2, LEN(rpt.[Path])-LEN(rpt.[Name])-2) + '&ViewMode=List'
, [URL_Report] = 'http://' + Host_Name() + '/Reports/Pages/Report.aspx?ItemPath=%2f' + SUBSTRING(rpt.[Path], 2, LEN(rpt.[Path])-LEN(rpt.[Name])-2) + '%2f' + rpt.[Name]
, [ReportDefinition] = CONVERT(VARCHAR(MAX), CONVERT(VARBINARY(MAX), rpt.[Content]))
, [HostName] = Host_Name()
FROM
[dbo].[Catalog] AS rpt
WHERE
1=1
AND rpt.[Type] = 2
)
SELECT
[GroupBy1] =
CASE
WHEN #GroupByColumn = 'Report Name' THEN rpt.[ReportName]
WHEN #GroupByColumn = 'Report Folder' THEN rpt.[ReportFolder]
WHEN #GroupByColumn = 'User Id' THEN usr.[SimpleUserName]
ELSE '<N/A>'
END
, rpt.[Path]
, rpt.[ReportFolder]
, rpt.[Name]
, rpt.[URL_ReportFolder]
, rpt.[URL_Report]
, [URL_Report_Filtered] = rpt.[URL_Report] + '&rs:Command=Render&' + CONVERT(VARCHAR(max), el.[Parameters])
, [UserName] = usr.[SimpleUserName]
, el.[Status]
, el.[TimeStart]
, el.[RowCount]
, el.[ByteCount]
, el.[Format]
, el.[Parameters]
, [TotalSeconds] = CONVERT(CHAR(8),DATEADD(ms,(el.[TimeDataRetrieval] + el.[TimeProcessing] + el.[TimeRendering]),0),108)
, [TimeDataRetrieval] = CONVERT(CHAR(8),DATEADD(ms,el.[TimeDataRetrieval],0),108)
, [TimeProcessing] = CONVERT(CHAR(8),DATEADD(ms,el.[TimeProcessing],0),108)
, [TimeRendering] = CONVERT(CHAR(8),DATEADD(ms,el.[TimeRendering],0),108)
, [OrderbyDate] = CAST([TimeStart] AS DATETIME)
FROM
report_catalog AS rpt
LEFT JOIN [dbo].[ExecutionLog] AS el ON el.[ReportID] = rpt.[ItemID]
LEFT JOIN report_users AS usr ON el.[UserName] = usr.[UserName]
WHERE
1=1
AND (#all_value IN(#LogStatus) OR el.[Status] IN(#LogStatus))
AND (#all_value IN (#ReportFolder) OR rpt.[ReportFolder] IN(#ReportFolder))
AND (#all_value IN(#ReportName) OR rpt.[ReportName] IN(#ReportName))
AND (#all_value IN(#UserName) OR usr.[SimpleUserName] IN(#UserName))
AND (#StartDate IS NULL OR CONVERT(DATETIME, CONVERT(VARCHAR(11), el.[TimeStart], 13)) >= #StartDate)
AND (#EndDate IS NULL OR CONVERT(DATETIME, CONVERT(VARCHAR(11), el.[TimeStart], 13)) <= #EndDate)
Related
loading saving and showing json results in javascript
I have a php file called rows2.php that shows results like so after entering new fields in a database. It is simply showing the new id of the field :- {'new_id':'92'} I want to load this with javascript and add the new_id to existing list with : either side of the number and display it but I seem to be struggling? Many thanks. The javascript to load the page and get the result is : $.getJSON("rows2.php", function(result) { var new_id=console.log(result[0].new_id); document.getElementById('vehicle_list').value = '' + document.getElementById('vehicle_list').value + 'new_id' + ':'; })
You should use document.getElementById('vehicle_list').innerHTML = ''+document.getElementById('vehicle_list').innerHTML+'new_id'+':'; instead of document.getElementById('vehicle_list').value = ''+document.getElementById('vehicle_list').value+'new_id'+':'; .value is used only in case of input elements otherwise you must use .innerHTML
Don't put the variable name (new_id) in quotes. document.getElementById('vehicle_list').value = '' + document.getElementById('vehicle_list').value + new_id + ':';
Display thumbnailPhoto from Active Directory using Javascript only - Base64 encoding issue
Here's what I'm trying to do: From an html page using only Javascript I'm trying to query the Active Directory and retrieve some user's attributes. Which I succeded to do (thanks to some helpful code found around that I just cleaned up a bit). I can for example display on my html page the "displayName" of the user I provided the "samAccountName" in my code, which is great. But I also wanted to display the "thumbnailPhoto" and here I'm getting some issues... I know that the AD provide the "thumbnailPhoto" as a byte array and that I should be able to display it in a tag as follow: <img src="data:image/jpeg;base64," /> including base64 encoded byte array at the end of the src attribute. But I cannot manage to encode it at all. I tried to use the following library for base64 encoding: https://github.com/beatgammit/base64-js But was unsuccesful, it's acting like nothing is returned for that AD attribute, but the photo is really there I can see it over Outlook or Lync. Also when I directly put that returned value in the console I can see some weird charaters so I guess there's something but not sure how it should be handled. Tried a typeof to find out what the variable type is but it's returning "undefined". I'm adding here the code I use: var ADConnection = new ActiveXObject( "ADODB.connection" ); var ADCommand = new ActiveXObject( "ADODB.Command" ); ADConnection.Open( "Data Source=Active Directory Provider;Provider=ADsDSOObject" ); ADCommand.ActiveConnection = ADConnection; var ou = "DC=XX,DC=XXXX,DC=XXX"; var where = "objectCategory = 'user' AND objectClass='user' AND samaccountname='XXXXXXXX'"; var orderby = "samaccountname ASC"; var fields = "displayName,thumbnailPhoto"; var queryType = fields.match( /,(memberof|member),/ig ) ? "LDAP" : "GC"; var path = queryType + "://" + ou; ADCommand.CommandText = "select '" + fields + "' from '" + path + "' WHERE " + where + " ORDER BY " + orderby; var recordSet = ADCommand.Execute; fields = fields.split( "," ); var data = []; while(!recordSet.EOF) { var rowResult = { "length" : fields.length }; var i = fields.length; while(i--) { var fieldName = fields[i]; if(fieldName == "directReports" && recordSet.Fields(fieldName).value != null) { rowResult[fieldName] = true; } else { rowResult[fieldName] = recordSet.Fields(fieldName).value; } } data.push(rowResult); recordSet.MoveNext; } recordSet.Close(); console.log(rowResult["displayName"]); console.log(rowResult["thumbnailPhoto"]); (I replaced db information by Xs) (There's only one entry returned that's why I'm using the rowResult in the console instead of data) And here's what the console returns: LOG: Lastname, Firstname LOG: က䙊䙉Āā怀怀 (same here Lastname & Firstname returned are the correct value expected) This is all running on IE9 and unfortunetly have to make this compatible with IE9 :/ Summary: I need to find a solution in Javascript only I know it should be returning a byte array and I need to base64 encode it, but all my attempts failed and I'm a bit clueless on the reason why I'm not sure if the picture is getting returned at all here, the thing in the console seems pretty small... or if I'm nothing doing the encoding correctly If someone could help me out with this it would be awesome, I'm struggling with this for so long now :/ Thanks!
jQuery Ajax + Classic ASP return error 'unexpected end of input'
I have two problems on this combination. After Ajax always return error (unexpected end of input),In localhost it still can save date successfully, seems not a big problem. The code works in my localhost but does not work in 1App Server(http://www.1apps.net/), I had tried to submit a technique question and them had a response quickly with this way http://www.mikesdotnetting.com/article/98/ajax-with-classic-asp-using-jquery However, I think the way in that article should be working but I am confused why my code is only work in localhost and other web server but not 1App. The following is my code: ASP: if request.QueryString("action")="CostUpdate" then Response.ContentType = "application/json" a = request.form("GI") b = request.form("GP") c = request.form("NA") Set rs = Server.CreateObject("ADODB.Recordset") sql = "Select * From Cost where CostDate = #" & date() & "# and CostItem ='" & a & "'" rs.open sql,conn,1,3 if rs.eof then Set rs = Server.CreateObject("ADODB.Recordset") sql = "Select * From Cost" rs.open sql,conn,1,3 rs.addnew rs("CostDate")=date() rs("CostItem")=a rs("CostAmount")=c rs("CostNumber")= b * c rs.update else Set rs = Server.CreateObject("ADODB.Recordset") sql = "Select * From images where CostDate =#" & adid & "# and CostItem = " & a rs.open sql,conn,1,3 rs("CostAmount")=c rs("CostNumber")=b * c rs.update end if end if JS var $GoodsId = $("#costtable tbody").find("tr").eq(c).find("input").eq(1).val(); var $GoodsPrice = $("#costtable tbody").find("tr").eq(c).find("input").eq(2).val(); var $NewAmount = $("#costtable tbody").find("tr").eq(c).find("input").eq(3).val(); $.ajax({ url: 'work.asp?action=CostUpdate', type: "POST", data: { GI: $GoodsId,GP: $GoodsPrice,NA: $NewAmount }, dataType: "json", error: function (xhr, status, error) { console.info("CallAjax"); console.info('An error occured.. ' + xhr.responseText + '..' + error); }, success: function () { console.info("Sucess"); } });
there are several problems in asp code: Don't open new sql command when rs is still open. So I created a new recordset (rs2) to use inside the if block. You don't need to recreate rs for every action. so i deleted repeating createobject. There is no need to set contentType to Json because no data is generated. You are only updating database. Use rs.open sql,objcon,2,2 when you want to use sql update command. use rs.close and also set rs=nothing to free server memory. there is no definition for parameter adid. do you defined it somewhere else? You are posting data to asp page not getting. So you have to use request.form in first line and also send parameter "action" within posted data. is this entire asp codes? where do you define conn? Besides the error "unexpected end of input" is not an ASP error. You may forgot } inside JavaScript codes. the presented code is OK, check entire your code. if request.form("action")="CostUpdate" then a = request.form("GI") b = request.form("GP") c = request.form("NA") Set rs = Server.CreateObject("ADODB.Recordset") Set rs2 = Server.CreateObject("ADODB.Recordset") sql = "Select * From Cost where CostDate = #" & date() & "# and CostItem ='" & a & "'" rs.open sql,conn,1,3 if rs.eof then sql = "Select * From Cost" rs2.open sql,conn,2,2 rs2.addnew rs2("CostDate")=date() rs2("CostItem")=a rs2("CostAmount")=c rs2("CostNumber")= b * c rs2.update rs2.close else sql = "Select * From images where CostDate =#" & adid & "# and CostItem = " & a rs2.open sql,conn,2,2 rs2("CostAmount")=c rs2("CostNumber")=b * c rs2.update rs2.close end if rs.close end if set rs=nothing set rs2=nothing
Javascript (and JSP) won't create table properly with if statement
So i'm using multiple if statements to draw data from a database based on the users search criteria. What i'm struggling with is if(request.getParameter("searchProperty")!= ""){ SearchStatement = "town_city = '" + request.getParameter("searchProperty") + "'"; if(request.getParameter("bedrooms") != "0"){ SearchStatement += " AND bedrooms = '" + request.getParameter("bedrooms") + "'"; } } with the idea that this concatenates a string to use as a query in the database, and bring back the results the user is searching for (this is a property searching website). I thought i'd done the if statement correctly. From what i understand, from what i've put, if the user were to select 0 in bedrooms it should return ALL results, but instead it returns NONE (who wants a house without a bedroom..) Can somebody explain what's going wrong please? here's where the SQL statement is built and input MyProperties = bookSQL.executeQuery("SELECT * FROM PROPERTIES WHERE " + SearchStatement); with the expected outcome being, for example SELECT * FROM PROPERTIES WHERE Location = 'input' AND Bedrooms = 'value' unless value = 0 where it should just be SELECT * FROM PROPERTIES WHERE Location = 'input'
i think the problem is with this statement, request.getParameter("bedrooms") != "0" should be something like this , (!request.getParameter("bedrooms").isEmpty()) Remember you are comparing the strings so if is "0" if(request.getParameter("bedrooms").equals("0")){ return SearchStatement ; } else { SearchStatement += " AND bedrooms = '" + request.getParameter("bedrooms") + "'" } Hope this helps!!
On Click event not firing from code behind
In my code below , my ("OnClick") is not firing. Does anyone know why? e.Row.Cells(1).Attributes("OnClick") = "window.location.href='MachineSweepLite.aspx?AreaID='" _ + GridView1.DataKeys(e.Row.RowIndex).Values("ID").ToString() Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then e.Row.Cells(1).Attributes("onmouseover") = "this.style.cursor='hand';this.style.textDecoration='underline';" e.Row.Cells(1).Attributes("onmouseout") = "this.style.textDecoration='none';" Dim Index As Integer = e.Row.RowIndex e.Row.Cells(1).Attributes("OnClick") = "window.location.href='MachineSweepLite.aspx?AreaID='" + GridView1.DataKeys(e.Row.RowIndex).Values("ID").ToString End If End Sub Edit above.
You have a error in your attribute, as you are adding the value of the ID after the closing single quote... For example, if the ID was 12, you're sending this to the browser... window.location.href='MachineSweepLite.aspx?AreaID='12 Note that the 12 is not part of the URL. You should have the following instead... e.Row.Cells(1).Attributes("onclick") = string.Format("window.location.href='MachineSweepLite.aspx?AreaID={0}';", GridView1.DataKeys(e.Row.RowIndex).Values("ID").ToString()) Also note, as of .NET 4.0 it is unnecessary to have the _ character when spanning over multiple lines.
e.Row.Attributes("onClick") = "CallFunction('" & Convert.ToString(GridView1.DataKeys(e.Row.RowIndex).Values("ID")) & "');" JS code: function CallFunction(val) { // do your login here }