Serving Business Graphics from a Web Service

Serving Business Graphics from a Web Service

ost graphics packages require you to format your XML data to a specific standard before they can output any charts, a method which robs you of the flexibility that makes XML valuable in the first place. This loss is unnecessary, since it’s relatively easy to create a data agnostic charting application in which the data comes from any http source as XML, as demonstrated in my last article. In this article, I’ll show you how to take full advantage of XML’s flexibility. Using the same concepts and code, you’ll use SOAP to expand the chart server’s functionality to consume Web Services.

This article will walk you through the process. First, you will create a Web service that exposes SQL Server data from a sample NorthWind database via a Web service. Next, using the Microsoft SOAP Toolkit, you’ll enhance your charting server to consume the data and chart it. Lastly, you’ll build a sample bar chart showing all of the products in stock from the NorthWind database.

Preparation
To attach your application to a Web service in Visual Studio.NET, use the ‘Add Web Reference’ functionality within the project explorer window. This generates classes that implicitly handle the SOAP messaging between your application and the target Web service. This form of binding is very useful?but is limited. The software designer has to explicitly declare at design time the connection to the Web service.

For the chart server to be as flexible as the URL based one from the earlier article, the facility to discover and consume SOAP based Web services has to be done at run time. Visual Studio.NET is limited in how it can achieve this, but can be expanded on by downloading and installing the Microsoft SOAP toolkit. The toolkit supports the extended functionalities. I will walk you through this process later in the article.

If you haven’t done so already, you also need to install the SQL Server desktop engine included with Visual Studio.NET. Note that if you select the desktop engine as part of the Visual Studio installation, the engine will not install. You still need to run its installation file. This file (Setup.exe) is located in the Setup/MSDE directory in the Visual Studio.NET installation folder. This installs a SQL Server with the instance name YOURMACHINEVSDOTNET. Reboot after installing.

Next, install the Northwind and Pubs databases by opening a DOS box and running the following osql commands:

osql E S COMPUTERNAMEVSDOTNET i "C:PROGRAM FILESMICROSOFT VISUALSTUDIO .NETFRAMEWORKSDKSAMPLESSETUPinstpubs.sql"

and

osql E S COMPUTERNAMEVSDOTNET i "C:PROGRAM FILESMICROSOFT VISUALSTUDIO .NETFRAMEWORKSDKSAMPLESSETUPinstnwnd.sql"

Replace COMPUTERNAME with the name of your computer, and keep the quotes. Note that there is a space between the ‘Studio’ and the ‘.NET’.

The SQL Server service manager will start by default, however it will not start the SQL Service itself by default. To configure the SQL Server Service Manager to automatically start when Windows starts up, open the service manager from your taskbar or from the startup folder within the start menu. Select ‘SQL Server’ from the ‘Services’ drop-down list and check the ‘Auto-start service when OS starts’ checkbox.

Reboot and you are ready to build a Web service that exposes this data.

Building the Web Service
Open Visual Studio.Net and select to create a new C# ASP.NET Web service. Name the service NWind.

Make sure that the Service1.asmx.cs[Design] window is selected. Open the ‘Server Explorer’ window, and browse to the SQL Servers node. Open the SQL Server that corresponds to COMPUTERNAMEVSDOTNET. Open the ‘Tables’ node and drag the ‘Products’ table onto the design window. Two objects should be present on the form, SqlConnection1 and SqlDataAdapter1.

Go to the ‘Data’ menu, and select ‘Generate Dataset.’ Select ‘New’ and call your dataset ‘DataSet1’. Make sure that ‘Add this dataset to the designer’ is selected. Click OK.

This creates a dataset schema called DataSet1 and a dataset object called dataSet11.

Adding the following Web method exposes the contents of a dataset as an XML document:

	[WebMethod]	public System.Xml.XmlDocument GetProductsData()	{		sqlDataAdapter1.Fill(dataSet11.Products);		System.IO.StringWriter sw = new System.IO.StringWriter();		dataSet11.Namespace = "";		dataSet11.WriteXml(sw);		System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();		xDoc.LoadXml(sw.ToString());		return xDoc;

You now have a Web service called NWind that exposes the Products table of the Northwind database as a Web service. It is relatively simple to expand this Web service to allow different tables, views, or stored procedures to be exposed or parameterized. For the sake of simplicity and demonstration, I am exposing the entire products table in this article.

Expand the Chart Server to Consume SOAP Web Services
Before you can expand the functionality of the chart server, there are three preparatory tasks:

  1. You need to change the structure of the chart server’s configuration file. The chart server is taken from a configuration file called charts.xml. This file always assumes that a straight http call is being made to an XML data source. To allow the file to determine whether the call is a straight http call or a SOAP call, use the code example shown below. This new configuration structure allows dynamic Web service end points:
    http://localhost/nwind/service1.asmx/GetProductsData?  http://localhost/dfconfig2.xml  //ProductsDataSet/Products[UnitPrice>40]/./UnitsInStock//ProductsDataSet/Products[UnitPrice>40]/./ProductName  600  400  http://localhost/Nwind/Service1.asmx?WSDL  http://localhost/dfconfig2.xml  //UnitPrice   //ProductName  600  400  http://tempuri.org/GetProductsData  GetProductsData

    Notice that a new attribute, called ‘type’ is added to the chart node, and in the case of type=’soap’, two new nodes ‘soapaction’ and ‘function’ are required. These are explained in more detail below.

  2. Download and install the SOAP toolkit. The chart server uses the SOAP toolkit to connect to and consume Web services.

    Once the toolkit is installed, load the chart server you created in the previous article. In it, add a reference to the MS SOAP toolkit by selecting ‘References’ in the solution explorer and then selecting ‘Add Reference’. On the ensuing dialog box, select the COM tab. Double click the ‘Microsoft SOAP Type Library v3.0’ and click ‘OK’.

  3. Update the chart server source code to use the SOAP library and to understand the new XML format from Step 1. The source code for this article contains updated code for the following functions:
    • Page_Load: This function now contains additions for processing the configuration file, reading in the extra nodes (‘soapaction’ and ‘function’ listed above), and reading the call type parameter.
    • CallCharter: This function has been amended to allow extra parameters to be passed. In addition, depending on the call type, it calls a new function ‘xmlSoapLoad’. This function consumes the Web service and returns an XML document to the charter.
    • The SOAP Load Function
      A new function has been added to the chart server since the previous article’s publication. This function uses the parameters defined in the charts.xml file above to discover and call the Web service using SOAP.

      It needs to be as generic as possible so you can pass in the specifics for its location, namespace, and required functions. As such, the SOAP load function takes the following parameters:

      strLocation

      Specifies the WSDL file containing the description of the web service.

      strSoapAction

      Specifies the namespace and method for the action that we will be performing.

      strSoapFunction

      Specifies the fully qualified SOAP Method that will be used within the SOAP envelope.

      strWrapperNameSpace

      Specifies the namespace to use.

      Table 1: Parameters that are passed to the SOAP Load function and their description.

      First, the function creates a Http connection object and points it at the WSDL for the Web service, which was automatically generated by Visual Studio.NET when you built the Web service. When consuming any Web service, you need to view the WSDL. To view the WSDL when a Web service is generated using Microsoft Visual Studio.Net, run the Web service, and get the standard Microsoft service front-end. At the top of the screen, there is a hyperlink to the ‘Service Description’. This takes you to the WSDL for your Web service.

      Note: When configuring a chart to consume a Web service, the setting must point to the WSDL file for the Web service. This allows the charter to automatically generate soap messages of the required structure.

      In addition the function needs to specify the SOAP Action, which is the method that defines the function that you are going to call. In the WSDL file, find a node called:

      	Within this node, there's a childnode called :	 

      ‘GetProductsData’ is the name of a public function defined within your Web service. Within this childnode, the SOAP action is specified. If you use the default settings when creating the Nwind Web service (above), the SOAP action for this function is defined as ‘http://tempuri.org/GetProductsData’. The connector object uses this value in its ‘SoapAction’ property. You configure this value in the the node in the charts.xml file.

      The following code shows how these properties are used to specify the SOAP connector to the desired Web service using VB.NET.

              Dim connector As New MSSOAPLib30.HttpConnector30Class()        connector.Property("EndPointURL") = strLocation        connector.Property("SoapAction") = strSoapAction

      Next you set up a SOAP Serializer object, which creates a SOAP command envelope. In this case, you’re calling a simple function on the Web service which takes no parameters. The chart server is easily expanded to tokenize parameters within the charts.xml file and pass them into this function. The serializer object allows you to add these parameters as elements to pass to the Web service.

       
      Figure 1: This is a sample of the data charted from the Northwind data source.

      The most important part of the SOAP Load function is the ‘StartElement’ property setting. This setting passes the other configurable parameters. If you go back to the WSDL file again, and look at the binding node for the SOAP messages on this service, you will see that the node containing the soap action was called ‘operation’.

      The contents of this node should be set in the charts.xml file in the node. In addition, you need to specify the the wrapper namespace. Use the ‘targetNameSpace’ value specified in the WSDL with the name of the Web service and the message type appended. For example, you are using a SOAP message, so the wrapper name space would be ‘http://tempuri.org/nwind/message’. This code shows how to create a serializer object that contains the SOAP message:

              Dim serializer As New MSSOAPLib30.SoapSerializer30Class()        serializer.Init(connector.InputStream)        serializer.StartEnvelope("", "", "")        serializer.StartBody("STANDARD")        serializer.StartElement(strSoapFunction, strWRAPPERNAMESPACE, "", "")        serializer.EndElement()        serializer.EndBody()        serializer.EndEnvelope()        serializer.Finished()

      Next, the function reads the response from the service using a SOAP reader class, and loads the contents of the response into an XML Document:

              Dim reader As New MSSOAPLib30.SoapReader30Class()        reader.Load(connector.OutputStream, "")        Dim strTest As String        strTest = reader.BodyEntries(0).xml        Dim xDoc As New System.Xml.XmlDocument()        xDoc.LoadXml(strTest)        Return xDoc

      Expanded Functionalities
      Figure 1 shows the result of charting the Products table from the Northwind database, with the data exposed as a Web service, and an XPath variable specifying the UnitsInStock for all items whose unit price is greater than $40.

      This shows the power and extensibility of the charting server. Given a URL or a WSDL file, the charter will consume the data and produce a chart according to your requirements.

devx-admin

devx-admin

Share the Post:
Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time

Semiconductor Stock Plummet

Dramatic Downturn in Semiconductor Stocks Looms

Recent events show that the S&P Semiconductors Select Industry Index seems to be experiencing a downturn, which could result in a decline in semiconductor stocks. Known as a key indicator

Anthropic Investment

Amazon’s Bold Anthropic Investment

On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This decision demonstrates Amazon’s commitment to

AI Experts Get Hired

Tech Industry Rehiring Wave: AI Experts Wanted

A few months ago, Big Tech companies were downsizing their workforce, but currently, many are considering rehiring some of these employees, especially in popular fields such as artificial intelligence. The

Lagos Migration

Middle-Class Migration: Undermining Democracy?

As the middle class in Lagos, Nigeria, increasingly migrates to private communities, a PhD scholar from a leading technology institute has been investigating the impact of this development on democratic

AI Software Development

ChatGPT is Now Making Video Games

Pietro Schirano’s foray into using ChatGPT, an AI tool for programming, has opened up new vistas in game and software development. As design lead at business finance firm Brex, Schirano

Llama Codebot

Developers! Here’s Your Chatbot

Meta Platforms has recently unveiled Code Llama, a free chatbot designed to aid developers in crafting coding scripts. This large language model (LLM), developed using Meta’s Llama 2 model, serves

Tech Layoffs

Unraveling the Tech Sector’s Historic Job Losses

Throughout 2023, the tech sector has experienced a record-breaking number of job losses, impacting tens of thousands of workers across various companies, including well-established corporations and emerging startups in areas

Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G technology by local network providers

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to transform the way modern warfare

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI detection software, such as Turnitin’s

US Commitment

US Approves Sustainable Battery Research

The US Department of Energy has revealed a $325 million commitment in the research of innovative battery types, designed to enable solar and wind power as continuous, 24-hour energy sources.

Netanyahu Musk AI

Netanyahu and Musk Discuss AI Future

On September 22, 2023, Israeli Prime Minister Benjamin Netanyahu met with entrepreneur Elon Musk in San Francisco prior to attending the United Nations. In a live-streamed discussion, Netanyahu lauded Musk

Urban Gardening

Creating Thriving Cities Through Urban Gardening

The rising popularity of urban gardening is receiving increased recognition for its numerous advantages, as demonstrated in a recent study featured in the Environmental Research Letters journal. Carried out by