SSRS - Custom Code - ssrs-2008

I'm trying to access a REST service from a function written in the custom code of a report. I don't want to move that code into a separate assembly so the problem is around the custom code, please don't send me to custom assemblies.
Here's the code:
Public Shared Function GetData(ByVal id As String) As String
Dim strURL As String = ("http://..." & id)
Dim webRequest As System.Net.HttpWebRequest = DirectCast(System.Net.WebRequest.Create(strURL), System.Net.HttpWebRequest)
webRequest.Method = "Get"
Dim webResponse As System.Net.HttpWebResponse = DirectCast(webRequest.GetResponse, System.Net.HttpWebResponse)
Dim rdr As New System.IO.StreamReader(webResponse.GetResponseStream)
Return rdr.ReadToEnd
End Function
When I'm using it i receive the error:
System.Security.SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessPermission.Demand()
at System.Net.HttpWebRequest..ctor(Uri uri, ServicePoint servicePoint)
at System.Net.HttpRequestCreator.Create(Uri Uri)
at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase)
at System.Net.WebRequest.Create(String requestUriString)
at ReportExprHostImpl.CustomCodeProxy.GetData(String what, String id, String defaultValue)
The action that failed was:
Demand
The type of the first permission that failed was:
System.Net.WebPermission
The Zone of the assembly that failed was:
MyComputer
And I suppose that I may have future problems with System.IO too.
I had a look on CAS and I'm totally blurred, I don't know what policy file I have to change, what code group I have to change and how.
My understanding is that this is the code group used for custom code (in rssrvpolicy.config):
<CodeGroup
class="UnionCodeGroup"
version="1"
PermissionSetName="Execute"
Name="Report_Expressions_Default_Permissions"
Description="This code group grants default permissions for code in report expressions and Code element.>
<IMembershipCondition
class="StrongNameMembershipCondition"
version="1"
PublicKeyBlob="002400...CAEDDA2"
/>
</CodeGroup>
but simply setting the PermissionSetName to Fulltrust doesn't make any change.

For anyone experiencing this issue (a year and a half after the fact), if you are receiving this exception when trying to view the report from BIDS, then you need to update the RSPreviewPolicy.config file in your Visual Studio's PrivateAssemblies directory.
There are three security policy files that need to be modified for uses like this (custom code in expression or custom assemblies.) Detailed notes (including a seriously crucial one on where to place new CodeGroup elements!!) can be found on the MSDN page titled (as of today) "Using Reporting Services Security Policy Files". The security config files are the report server config (rssrvpolicy.config), the report manager config (rsmgrpolicy.config) and the report designer config (RSPreviewPolicy.config).
A great test for this is to update one at a time and test all three after each update (after deploying a report to your report server instance of course : ).

You should try PermissionSetName="FULLTRUST" in the codegroup.

Related

Get triggered rule names which is executing on decision server from client side (Redhat Decision Manager)

I am using the REST api for executing rules on Decision Server (Redhat Decision Manager 7.2) using a stateless kie session. I'm currently getting the number of triggered rules, but I also want to get the names of those rules. Is this possible?
KieServicesConfiguration conf = KieServicesFactory.newRestConfiguration(URL, USER, PASSWORD);
List<GenericCommand<?>> commands = new ArrayList<GenericCommand<?>>();
commands.add((GenericCommand<?>)
KieServices.Factory.get().getCommands().newInsert(applicant, "applicant"));
commands.add((GenericCommand<?>)
KieServices.Factory.get().getCommands().newInsert(loan, "loan"));
commands.add((GenericCommand<?>)KieServices.Factory.get().getCommands().newFireAllRules("numberOfFiredRules"));
KieCommands kieCommands = KieServices.Factory.get().getCommands();
BatchExecutionCommand batchCommand = kieCommands.newBatchExecution(commands, "default-stateless-ksession");
ServiceResponse<ExecutionResults> executeResponse = ruleServicesClient
.executeCommandsWithResults("loan-application_1.2.0", batchCommand);
System.out.println("Number of fired rules:" executeResponse.getResult().getValue("numberOfFiredRules"));
You have to use an AgendaEventListener to keep track of rules exectioned. By implemnting org.kie.api.event.rule.AgendaEventListener interface you can capture these detials.
To know which rules are triggered I added an action column with custom code (Action BRL fragment) that writes the rule name in one of the field of my fact. You can get it from rule.name.
Example:myFact.logMyRuleName(rule.name)

how to get dictionary value from webrequest using sharepoint designer

I am trying to retrieve a value from a HTTP web service call in sharepoint designer. This should be simple. the Rest query is simple, and always returns only a single value:
https://Site.sharepoint.com/sites/aSiteName/_api/web/lists/getByTitle('MyListTitle')/items/?$select=Title&$top=1
In the Sharepoint Designer workflow, I'm setting the required Accept and Content-type header to the value of "application/json;odata=verbose
I am unable to get the value of the "Title" field that is returned by the call.
when I execute the REST query in the browser, I get the following data returned:
{"d":{"results":[{"__metadata":{"id":"af9697fe-9340-4bb5-9c75-e43e1fe20d30","uri":"https://site.sharepoint.com/sites/aSiteName/_api/Web/Lists(guid'6228d484-4250-455c-904d-6b7096fee573')/Items(5)","etag":"\"1\"","type":"SP.Data.MyListName"},"Title":"John Doe"}]}}
I've tried dozens of variations of the dictionary 'query', but they always return blank.
I'm using the 'get an item from a dictionary' action in SP Designer, using item name or path values like:
d/results(0)/Title
d/Title
d/results/Title
and literally dozens of other variations - but it always returns blank.
I'm writing the raw response from the webRequest to the list for debugging, and it shows the value like this:
{"odata.metadata":"https:\/\/site.sharepoint.com\/sites\/aSiteName\/_api\/$metadata#SP.ListData.MyListTitle&$select=Title","value":[{"odata.type":"SP.Data.MyListTitle","odata.id":"616ed0ed-ef1d-405b-8ea5-2682d9662b0a","odata.etag":"\"1\"","odata.editLink":"Web\/Lists(guid'6228d484-4250-455c-904d-6b7096fee573')\/Items(5)","Title":"John Doe"}]}
I must be doing something simple that is wrong?
Using "d/results(0)/Title" is right. Check the steps in article below to create a workflow.
CALLING THE SHAREPOINT 2013 REST API FROM A SHAREPOINT DESIGNER WORKFLOW
It working fine in my test workflow.
I faced the exact same issue. In my case the reason was that in the API call, the header was not set properly.
As you would have noticed many times, that if you type the variables inline when creating the "Call Http Web service" action, those might not get set properly. The surest way is to open the properties and set from there. In my case when i opened the properties i found that RequestHeaders was not set. Once i set it from there, i got the desired results.
Hope this helps to someone in future, this question being unanswered till now!!
tried dump those json called from sharepoint workflow into a list. Sometimes you'll get a different format than when you called that from browser. I experienced this issue when calling API projectserver (project online). When I called it using servistate (chrome extension) it returns d/results, but when I dump the value into the list I got value and yet I used same request header value.

How to use xml data source on jasper server

I would like to use xml data source in jasper server (5.0.0). Xml files are created "on the fly" while application is running so different reports will have different xml data sources. I know that jasper server does not have XML data source defined but I found out that creating report without data source and then passing parameter XML_FILE - java.io.File will do the work. I managed to do this in java servlet:
jasperReport = JasperCompileManager.compileReport("path to jrxml");
HashMap map = new HashMap();
map.put("XML_FILE", new File(xmlSourceFile));
jasperPrint = JasperFillManager.fillReport(jasperReport,map);
byte [] o = JasperExportManager.exportReportToPdf(jasperPrint);
but unfortunately failed to do it on jasper server. I am using rest services to run report so I can use only String parameters. I've tried to write a scriptlet that converts String parameter with xml url to java.io.File
public class XmlScriplet extends JRDefaultScriptlet{
#Override
public void beforeReportInit(){
try {
String param = (String)this.getParameterValue("fileName");
HashMap map = new HashMap();
map.put("XML_FILE", new File(param));
this.parametersMap.putAll(map);
} ...
but this gives me an empty report.
Thank you in advance.
You can also pass any XML resource (be an static XML or even a REST service) by passing by simply "net.sf.jasperreports.xml.source" parameter to your report, if you are using Jasperreports Server 5.5, and assuming your report unit is named "report" and your xml data resource is in http://(host):(port)/resource.xml path, you might want to call the report using Jasper's REST v2 API like this:
http://(host):(port)/jasperserver/rest_v2/reports/path/to/your/report/unit/report.html?net.sf.jasperreports.xml.source=http://(host):(port)/resource.xml
In order to have a default "net.sf.jasperreports.xml.source" value in your report, You should also add the following in the "parameters" section in your report source jrxml
<parameter name="net.sf.jasperreports.xml.source" class="java.lang.String">
<defaultValueExpression><![CDATA["http://(host):(port)/resource.xml"]]> </defaultValueExpression>
</parameter>
Do not forget to add xpath2 query support to jasperreports server by appending:
# addition for xpath2 queries
net.sf.jasperreports.query.executer.factory.xpath2 = net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory
to /WEB-INF/classes/jasperreports.properties inside the deployed dir in the appserver
For more info about which parameters xml data source allows, you could also take a look at the official documentation
The JasperSoft Community wiki has two articles that will help explain some of the details.
Remote XML Datasource
Using XML Datasource in JasperReports server
You may need experiment with the XML_URL parameter to get your XML into the report.

How to make Rest service with JSONP capability to be run in Sharepoint 2007 (MOSS)?

We need to access a sharepoint 2007 site from javascript. Basically we need to use the search.asmx service but since that does not support rest nor jsonp it can't be used directly.
The original plan was to make custom wcf service with support for rest and jsonp. This was a small undertaking but when I gave the service to the Sharepoint guys none of them could package it to a wsp package for installation in sharepoint 2007 and get it working.
According to this question Rest Webservices for Sharepoint 2007 this might not be so easy and a httpmodule is required for rest-typed urls. The other idea about running it as a standalone app might not be enough since I think that the service needs access to SPContext.
Would it be possible to just create an Application Page and there in the code behind override Render, clear the output buffer, change mime type and render the json-serialized data? So the url would be http://spsite/mycustomquery.aspx?q=mysearchtext&start=0&count=200&callback=mycallbackfunction.
An application page would at least support Get but does it have access to SPContext?
Here is the wcf service I started with.
Contract
[ServiceContract]
public interface IRestSPQuery
{
[OperationContract]
[WebGet(UriTemplate = "query/{queryText}/{startAt}/{count}?callback={callback}", ResponseFormat = WebMessageFormat.Json)]
[JSONPBehavior(callback = "callback")]
ResultTable Query(string queryText, string startAt, string count, string callback);
}
Implementation
public ResultTable Query(string queryText, string startAt, string count, string callback)
{
//http://sharepointsite/_vit_bin/CustomQuery/RestSPQuery.svc/Query/searchtext/0/200?callback=myfunction
KeywordQuery keywordQuery = new KeywordQuery(SPContext.Current.Site);
keywordQuery.StartRow = startAt;
keywordQuery.RowLimit = count;
keywordQuery.SortList.Add("Rank", SortDirection.Descending);
keywordQuery.QueryText = queryText;
ResultTableCollection searchResults = keywordQuery.Execute();
ResultTable relevantResultsTable = searchResults[ResultType.RelevantResults];
return relevantResultsTable;
}
You could try adding an ".ashx" file to your solution that implements IHttpHandler. According to this blog article you can do it by adding an Application Page to your solution but save it as a ".ashx" extension. The article is written for SharePoint 2010 but you will have to check if it works for 2007. Following the rest of the article you should be able to set it up for REST/JSONP.
I ended up creating a custom aspx page and override the Render method and there output json/jsonp and also change the content type to application/json.
The solution and a ready to deploy wsp-file can be found here http://www.filedropper.com/restqueryservice.

EntityFramework, AppHarbor and configuration variables

I'm having some trouble with EntityFramework (database first) and AppHarbor.
I'm trying to use the configuration string as inserted into the web.config by AppHarbor (I've added the metadata into the Sequelizer config option on the website), and I'm trying to add some additional values using code provided.
Currently I'm being a very bad person and embedding the string directly into my apps configuration provider - not good if the hosting provider switch DBs on us, so I'm looking to do it the proper way and use the values AppHarbor supply via the web.config.
This is the string as per provided by AppHarbor (passwords and server details removed):
metadata='res://*/MyDataEntities.csdl|res://*/MyDataEntities.ssdl|res://*/MyDataEntities.msl;';provider=System.Data.SqlClient;provider connection string='Server=servername.sequelizer.com;Database=databasename;User ID=username;Password=<snip>;'
If used "as is", that generates the following error:
The specified metadata path is not valid. A valid path must be either an existing directory, an existing file with extension '.csdl', '.ssdl', or '.msl', or a URI that identifies an embedded resource.
I then use the following code (purloined off of one of the AppHarbor support discussions) to append the required extra things EF needs...
if (String.IsNullOrWhiteSpace(ProductionDatabaseConnectionString))
{
// Get it on first read and cache it
var configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
var connectionString = configuration.ConnectionStrings.ConnectionStrings["SQLAppHarbor001"].ConnectionString;
// Add the required extra metadata for EF4.x
if (!connectionString.Contains("MultipleActiveResultSets=True;"))
connectionString += "MultipleActiveResultSets=True;";
if (!connectionString.Contains("App=EntityFramework;"))
connectionString += "App=EntityFramework;";
configuration.ConnectionStrings.ConnectionStrings["SQLAppHarbor001"].ConnectionString = connectionString;
configuration.Save();
ProductionDatabaseConnectionString = connectionString;
}
return ProductionDatabaseConnectionString;
That produces the connection string as follows:
metadata='res://*/MyDataEntities.csdl|res://*/MyDataEntities.ssdl|res://*/MyDataEntities.msl;';provider=System.Data.SqlClient;provider connection string='Server=servername.sequelizer.com;Database=databasename;User ID=username;Password=<snip>;'MultipleActiveResultSets=True;App=EntityFramework;
But that produces the error:
Format of the initialization string does not conform to specification starting at index 165.
Index 165 being the start of "provider connection string".
The working connection string I use embedded, which currently works without issue, is:
metadata='res://*/MyDataEntities.csdl|res://*/MyDataEntities.ssdl|res://*/MyDataEntities.msl;';provider=System.Data.SqlClient;provider connection string='Server=servername.sequelizer.com;Database=databasename;User ID=username;Password=<snip>;multipleactiveresultsets=True;App=EntityFramework'
The only real differences being that the "multipleactiveresultsets=True;App=EntityFramework" entries are inside the "provider connection string" string rather than outside.
Other people seem to be using EntityFramework on AppHarbor using the supplied configuration variables fine, so what an I doing wrong?
Update: Multiple Active Result Sets (MARS) can now be enabled for the injected connection string by using the Sequelizer admin panel. This is the recommended approach since the web.config no longer needs to be modified, which causes an AppDomain reload during startup
I came up against this today! I did the following:
var configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
var connectionString = configuration.ConnectionStrings.ConnectionStrings["ConnStringAlias"].ConnectionString;
if (!connectionString.Contains("multipleactiveresultsets=True;"))
{
connectionString = connectionString.TrimEnd('\'');
connectionString = connectionString += "multipleactiveresultsets=True;\'";
configuration.ConnectionStrings.ConnectionStrings["ConnStringAlias"].ConnectionString = connectionString;
configuration.Save();
}
The MultipleActiveResultSets property must be inside the provider connection string, which is why you received an error regarding the format of your connection string.
I seen a few 'solutions' around but none seemed to work for me, including the solution at the bottom of a support page of how to do exactly this on AppHarbor's site. The solution provided even sends the application into an infinite loop as the application will restart every time the web.config file is saved, which is every time in the example.