Tài liệu Sams Microsoft SQL Server 2008- P11 ppt

50 594 0
Tài liệu Sams Microsoft SQL Server 2008- P11 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

ptg 481 Using Reporting Services Web Services static string GetReportXML_VS2008(string ReportPath) { //creates a new web service (proxy) and sets its credentials ReportExecutionServiceSoapClient rs = new ReportExecutionServiceSoapClient(); //Windows authentication rs.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; // Setup Render() call byte[] result = null; string encoding, mimeType, extension, DeviceInfo=null; Warning[] warnings = null; string[] streamIDs = null; try { string historyID = null; ExecutionInfo ExecInfo; ExecutionHeader ExecHeader; ServerInfoHeader SvrInfoHeader; //Note: set TrustedUserHeader = null, this is undocumented structure ExecHeader = rs.LoadReport(null, ReportPath, historyID, out SvrInfoHeader, out ExecInfo); rs.Render(ExecHeader, null, “XML”, DeviceInfo, out result, out extension, out mimeType, out encoding, out warnings, out streamIDs); //Gets a byte stream with Comma Separated Value (XML) layout return System.Text.Encoding.ASCII.GetString(result); } catch (SoapException e) { //Return exception message, if exception occurred return e.Message; } } Before we can use the preceding code, we must sort out security. Notice the following lines in the code: 28 From the Library of STEPHEN EISEMAN Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 482 CHAPTER 28 Using Reporting Services Web Services rs.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; It is a request to WCF to impersonate the user. In addition to the code, we need to prop- erly configure security in the app.config file. You can find the app.config file in your project’s folder. Double-click it to edit, and ensure that it has the following in the security section. (Note that most of the security section is already set and you just need to fill missing items, such as clientCredentialType .) <security mode=”TransportCredentialOnly”> <transport clientCredentialType=”Windows” proxyCredentialType=”None” realm=”” /> <message clientCredentialType=”UserName” algorithmSuite=”Default” /> </security> Note that Windows in the preceding code sample is case sensitive. You may see the following exception if security is improperly configured: Message=”The HTTP request is unauthorized with client authentication scheme ‘Anonymous’. The authentication header received from the server was ‘Negotiate,NTLM’.” You may see this exception if you do not have sufficient privileges to access: An unhandled exception of type ‘System.Net.WebException’ occurred in system.web.services.dll. Additional information: The request failed with HTTP status 401: Unauthorized. The following is an exception if you do not request to impersonate a user: Message=”The HTTP request is unauthorized with client authentication scheme ‘Ntlm’. The authentication header received from the server was ‘NTLM’.” Also notice: <client> <endpoint address=http://127.0.0.1:80/ReportServer/ReportExecution2005.asmx . This is an address of the ReportExecution2005 services end. In the preceding example, it is pointing to the localhost (127.0.0.1) port 80 . If you need to configure your applica- tion to use another SSRS, you can just modify the endpoint address. A call to GetReportXML _ VS2008 as shown here demonstrates an assignment of the /Samples/DemoList report in the XML form to a text box textBoxResult : textBoxResult.Text = GetReportXML_VS2008(“/Samples/DemoList”); From the Library of STEPHEN EISEMAN Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 483 Using Reporting Services Web Services NOTE If you want to incorporate the results of Render() in the web application, you can pass device information settings to retrieve an HTML fragment that does not contain a Body element (for example, DeviceInfo=”<DeviceInfo><HTMLFragment>True </HTMLFragment></DeviceInfo>” ). Do not forget to change the format string to HTML if you need to get HTML output for the application. Most parameters in the Render() function are optional and accept null values. Warning[] warnings; contains an array of objects with information about errors and warnings for which SSRS did not generate exceptions. In production code, you need to make sure to incorporate handling for warnings. The example uses part of the information available in SoapException . SoapException has four properties: . Actor: The code that caused the exception. . Detail: The XML describing application-specific error information. Detail is an XMLNode object, and inner text from Detail can be accessed for the flow control (for example, if(ex.Detail[“ErrorCode”].InnerXml == “rsItemNotFound”) {/*handle the error*/} ). . HelpLink: A link to a Help file associated with the error. . Messsage: A message describing the error. The Report Execution web service is very sensitive to the report’s path, requires the path to start from / (slash), and does not accept URL-encoded strings. If the path is incorrect, the web service returns an ItemNotFoundException or InvalidItemPathException excep- tion. For example, for a report with the name My DemoList (note the space after the word My) located in the Samples directory, the URL-encoded path /Samples/My%20DemoList is not acceptable. It would cause an error with an exception similar to the following: System.Web.Services.Protocols.SoapException: The item ‘/ReportProject/Top%20SalesPeople’ cannot be found. —-> Microsoft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item ‘/ReportProject/Top%20SalesPeople’ cannot be found. If SSRS is configured in native mode and the path does not start with a slash, SSRS gener- ates InvalidItemPathException : System.Web.Services.Protocols.SoapException: The path of the item 28 From the Library of STEPHEN EISEMAN Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 484 CHAPTER 28 Using Reporting Services Web Services ’ReportProject/TopSalesPeople’ is not valid. The full path must be less than 260 characters long; other restrictions apply. If the report server is in native mode, the path must start with slash. ---> Microsoft.ReportingServices.Diagnostics.Utilities.InvalidItemPathException : The path of the item ‘ReportProject/TopSalesPeople’ is not valid. The full path must be less than 260 characters long; other restrictions apply. If the report server is in native mode, the path must start with slash. The proper way to enter this path is /Samples/My Demolist (prefixed with slash when SSRS is in the native mode and without URL encoding). Actions in GetReportXML_VS2008 () should produce the same result as http://localhost/ReportServer/ReportExecution2005.asmx?/Samples/DemoList&rs: Command=Render&rs:Format=XML . The difference is that the web service call is not interac- tive, but the web service call allows an application to receive and process a report’s XML internally. System.Text.Encoding.ASCII.GetString is used to convert a byte[] array that Render() returns to a string. Note that ASCII is an option suitable for text-based formats, such as XML and CSV. Other converters (such as Unicode) are available in the System.Text.Encoding namespace. As a comparison, to use .NET 2.0 web services style code, you follow steps 1 through 4 above to access the Add Service Reference dialog box and then complete the following steps: 1. Access the Add Web Reference dialog box by clicking the Advanced button on the Add Service Reference dialog box. 2. Enter http://<server>/ReportServer/ReportExecution2005.asmx in the URL field. 3. Click Go. 4. Set Web Reference Name to ReportExecution2005_VS2005 (see Figure 28.3). 5. Click Add Reference. Under the project folder, note the Web References folder. 6. Add web references: using EmbeddedReport.ReportExecution2005_VS2005; using System.Web.Services.Protocols; 7. And add the following code: From the Library of STEPHEN EISEMAN Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 485 Using Reporting Services Web Services static string GetReportXML2005(string ReportPath) { //creates a new web service (proxy) and set its credentials ReportExecutionService rs = new ReportExecutionService(); //windows authentication rs.Credentials = System.Net.CredentialCache.DefaultCredentials; //Assign web service URL. This is optional operation. Default URL 28 //is assigned during the creation of a proxy. //Typically http://<<server name>>/ReportServer/ReportExecution2005.asmx //rs.Url = ReportingServicesURL; // Setup Render() call byte[] result = null; string encoding, mimeType, extension; Warning[] warnings = null; string[] streamIDs = null; try { //Should be called prior to Render() to set report’s path FIGURE 28.3 Add Web Reference dialog box. From the Library of STEPHEN EISEMAN Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 486 rs.LoadReport(ReportPath, null); //Gets a byte stream with Comma Separated Value (XML) layout result = rs.Render(“XML”, null, out extension, out encoding, out mimeType, out warnings, out streamIDs); return System.Text.Encoding.ASCII.GetString(result); } catch (SoapException e) { //Return exception message, if exception occurred return e.Message; } } The line rs.Credentials = System.Net.CredentialCache.DefaultCredentials; is very important. An application must supply credentials to the SSRS web service before the application can access a report. DefaultCredentials is the Windows authentication for the user. Report Management Web Service (ReportService 2005.asmx) Previously in this chapter, you saw an example of the Report Execution web service ( ReportExecution2005.asmx ). Most of the report-execution functionality is available using URL access. In contrast, only a few URL access methods (such as ListChildren() ) are available from the Report Management web service ( ReportService2005.asmx ). Thus, the Report Management web service is often used in combination with the Report Execution web service, and sometimes in combination with URL access. The combination of various access methods provides the most comprehensive access to SSRS. NOTE The following examples use Visual Studio 2005 .NET 2.0 style. We explained the differ- ence between Visual Studio 2008 .NET 3.5 WCF-style samples and Visual Studio 2005 .NET-2.0 style samples previously in this chapter. To access the Report Management web service, you can follow the same steps used earlier to access the Report Execution web service: 1. Add a web reference to the Report Management web service ( ReportService2005.asmx ). 2. Name the proxy ReportService2005 . CHAPTER 28 Using Reporting Services Web Services From the Library of STEPHEN EISEMAN Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 487 Report Management Web Service ( ReportService2005.asmx ) 28 3. Add a reference to the proxy in the code (using EmbeddedReport.Report Execution2005; ). 4. Call Report Management web service methods. The following is an example of a console application returning items stored on SSRS start- ing from the root / folder: using System; using System.Collections.Generic; using System.Linq; using System.Text; using ConsoleApplication1.ReportService2005; using System.Web.Services.Protocols; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //creates new Web service (proxy) and set its credentials ReportingService2005 rs = new ReportingService2005(); rs.Credentials = System.Net.CredentialCache.DefaultCredentials; try { CatalogItem[] items = rs.ListChildren(“/”, true); Console.Write(“Item Path, Item Name, Item Type, MimeType”); foreach (CatalogItem ci in items) { Console.Write(ci.Path + “,” + ci.Name + “,” + ci.Type + “,” + ci.MimeType + “\n”); } return; } catch (SoapException e) { Console.Write(e.Message); } } } } From the Library of STEPHEN EISEMAN Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 488 Valid items include DataSources , Folders , LinkedReports , Reports , Resources , and Unknown items. How to Script Reporting Services (Using the RS Utility) The RS utility is a scripting utility that enables access to Reporting Services functionality using Visual Basic .NET scripts. In scripts, you can define classes and use other object- oriented functionality of Visual Basic .NET. By default, the RS utility is installed in the C:\Program Files\Microsoft SQL Server\100\Tools\Binn directory. SSRS no longer comes with sample scripts, but you can download samples from the online community www.codeplex.com/MSFTRSProdSamples/ Release/ProjectReleases.aspx?ReleaseId=16045. You can dissect and modify sample scripts to fit scenarios at hand. Scripting is a convenient way to automate repetitive administrative tasks or tasks that apply to a group of items. Executing the rs /? command yields the following usage direction: Microsoft (R) Reporting Services RS Version 10.0.1600.22 ((SQL_PreRelease).080709-1414 ) x86 Executes script file contents against the specified Report Server. RS -i inputfile -s serverURL [-u username] [-p password] [-l timeout] [-b] [-e endpoint] [-v var=value] [-t] -i inputfile Script file to execute -s serverURL URL (including server and vroot) to execute script against. -u username User name used to log in to the server. -p password Password used to log in to the server. -e endpoint Web service endpoint to use with the script. Options are: Exec2005 - The ReportExecution2005 endpoint Mgmt2005 - The ReportService2005 endpoint -l timeout Number of seconds before the connection to the server times out. Default is 60 seconds and 0 is infinite time out. -b Run as a batch and rollback if commands fail -v var=value Variables and values to pass to the script -t trace Include trace information in error message The following sample script gets a list of extensions registered with Reporting Services and, as a bonus, outputs the Report Server version and edition. For the purpose of an example, you can add the following code to the RsUtilTest.rss file: CHAPTER 28 Using Reporting Services Web Services From the Library of STEPHEN EISEMAN Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 489 Working with Report Parameters 28 Public Sub Main() Dim Extensions As Extension() = rs.ListExtensions(ExtensionTypeEnum.All) Console.WriteLine(“Report Server Version Number:” & rs.ServerInfoHeaderValue.ReportServerVersionNumber) Console.WriteLine(“Report Server Edition:” & rs.ServerInfoHeaderValue.ReportServerEdition) Dim Ext As Extension Dim Type As String Console.WriteLine(“Type Name”) For Each Ext In Extensions Select Ext.ExtensionType Case ExtensionTypeEnum.Delivery Type = “Delivery” Case ExtensionTypeEnum.Render Type = “Render “ Case ExtensionTypeEnum.Data Type = “Data “ Case Else Type = “Other “ End Select Console.WriteLine(Type + “ “ + Ext.Name) Next End Sub ReportServerVersionNumber and ReportServerEdition are properties of Reporting Services. You need to call Reporting Services before the properties are set. If you place this call after you access Reporting Services properties, those properties will be empty. This is what we are doing in the following line: Extension()=rs.ListExtensions(ExtensionTypeEnum.All) The scripting utility provides an internal reference to Reporting Services through the rs object, which is ready to be used in scripts without an explicit instance creation. The command to execute the script might look like the following: rs -iRsUtilTest.rss -shttp://localhost/ReportServer Working with Report Parameters Report parameters are encapsulated by two classes: The ParameterValue class enables developers to set and retrieve report parameter values, and the ReportParameter class is used to get and set properties of a parameter. Both ParameterValue and ReportParameter are necessary to get complete information about a parameter. However, the ParameterValue class is sufficient to set and retrieve values of a parameter. The following From the Library of STEPHEN EISEMAN Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 490 code snippet shows how to pass parameters to render a function. You can incorporate this code into the GetReportXML2005() function written earlier in this chapter by adding the following code inside of the try block after LoadReport and through the call to the func- tion Render , replacing the original Render call (Visual Studio 2005, .NET 2.0 style): ParameterValue[] parameters = new ParameterValue[1]; parameters[0] = new ParameterValue(); parameters[0].Name = “SalesOrderNumber”; parameters[0].Value = “SO43659”; rs.SetExecutionParameters(parameters, “en-us”); result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); Or the following code for Visual Studio 2008, .NET 3.5, WCF style. Note that the main differences between WCF and .NET 2.0 style, in this case, are in the SetExecutionParameters and Render function signatures: ExecutionInfo ExecInfo; ExecutionHeader ExecHeader; ParameterValue[] parameters = new ParameterValue[1]; parameters[0] = new ParameterValue(); parameters[0].Name = “SalesOrderNumber”; parameters[0].Value = “SO43659”; rs.SetExecutionParameters(ExecHeader, null, parameters, “en-us”, out ExecInfo); rs.Render(ExecHeader, null, “XML”, DeviceInfo, out result, out extension, out mimeType, out encoding, out warnings, out streamIDs); In the previous examples, you can see two out of three string properties of the ParameterValue class: Name and Value . The third property is a Label and is used as an alternate name for a parameter. Note the usage of the SetExecutionParameters() function that assigns the parameter and parameter’s language (because this is optional, you can pass null ) to the current execution of a report. ReportParameter is used in conjunction with GetReportParameters() and SetReportParameters() . GetReportParameters() retrieves a report’s parameters’ properties ( ReportParameter class) and can validate whether an array of ParameterValue values passed to this function are acceptable for a report. SetReportParameters() sets properties of parameters. Table 28.2 outlines commonly used public properties of the ReportParameter class. CHAPTER 28 Using Reporting Services Web Services From the Library of STEPHEN EISEMAN Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... directories The default Report Server binary directory is C:\Program Files \Microsoft SQL Server\ MSRS10.MSSQLSERVER\Reporting Services\ReportServer\bin The default Report Designer binary directory is C:\Program Files \Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies The default Report Manager binary directory is C:\Program Files \Microsoft SQL Server\ MSRS10.MSSQLSERVER\Reporting Services\ReportManager\bin... Files \Microsoft SQL Server\ MSRS10.MSSQLSERVER\ Reporting Services\ReportServer\bin \Microsoft. Samples.ReportingServices ➥PrinterDeliverySample.dll” /> Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark From the Library of STEPHEN EISEMAN Common Considerations for Custom Reporting Services Extensions 507 NOTE Server\ MSRS10.MSSQLSERVER\Reporting Services\ReportServer\bin\... Manager uses RSReportServer.config configuration instead {SecConfig}: To abbreviate security configuration files The default location for the Report Server security configuration file is C:\Program Files \Microsoft SQL Server\ MSRS10.MSSQLSERVER\Reporting Services\ReportServer\RsSrvPolicy config The default location for the Report Designer security configuration file is C:\Program Files \Microsoft Visual... abbreviate configuration files (note the default file path) The default location for the Report Server configuration file is C:\Program Files \Microsoft SQL Server\ MSRS10.MSSQLSERVER\Reporting Services\ ReportServer\RSReportServer.config The default location for the Report Designer configuration file is C:\Program Files \Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\RSReportDesigner.config A separate... subscription in the Report Server database and returns a SubscriptionID string to a user For each subscription, there is either a shared or dedicated schedule in a form of the SQL Server Agent job that inserts an event in the Report Server database Event table NOTE When working with delivery extensions, always ensure that SQL Server Agent is running Some error messages related to a stopped SQL Server Agent could... Visual Studio to generate an RDCE implementation DLL: 1 Copy your implementation (for example, RdceImpl.dll) to the following: %ProgramFiles% \Microsoft SQL Server\ MSSQL.\ReportingServices\Report Server\ bin 2 Register your extension in the Report Server reportserver.config file: True 5 Enable the RDCE property on desired reports 6 Even though after the first three steps the Report Server is configured to use the RDCE extension, the extension is not used by default Developers/IT have... explained later in this chapter Interactions Between User, SSRS, and a Delivery Extension Custom Report Items Typical extensions installed with SSRS are as follows: Data processing: Microsoft SQL Server, Microsoft SQL Server Analysis Services, Oracle, SAP NetWeaver BI, Hyperion Essbase, Teradata, OLE DB, ODBC, XML, SAP BW, Essbase, and Teradata Delivery: File share, email, document library, null Note... SetProps.Value = “RdceImpl” props(0) = SetProps rs.SetProperties(“//”, props) 29 End Sub 7 Run the script to enable RDCE on the report: %ProgramFiles% \Microsoft SQL Server\ MSSQL.\Tools\Binn\RS.exe -s -i .rss This needs to be done for each report that you want to be run via the RDCE extension Keep in mind that there are feature limitations on reports . extensions installed with SSRS are as follows: . Data processing: Microsoft SQL Server, Microsoft SQL Server Analysis Services, Oracle, SAP NetWeaver BI, Hyperion. Console.WriteLine(“Report Server Version Number:” & rs.ServerInfoHeaderValue.ReportServerVersionNumber) Console.WriteLine(“Report Server Edition:” & rs.ServerInfoHeaderValue.ReportServerEdition)

Ngày đăng: 14/12/2013, 16:15

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan