Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

How to use Microsoft Microsoft Azure platform AppFabric Service Bus and Microsoft WCF Data Services to expose on-premises database to the internet


View products that this article applies to.

INTRODUCTION

This article describes an All-In-One Code Framework sample that is available for download.

When you want to expose local database to internet you may consider a lot of things, including:
  • How to expose your database. If you directly allow TCP connections to local SQL Server it involves a lot of security problems.
  • How to scale the entire system. 
This sample code demonstrates how to use Microsoft Azure platform AppFabric to resolveboth of above issues, and use the following techniques/products:
  • Service Bus in Microsoft Azure platform AppFabric
  • WCF Data Services (formerly named ADO.NET Data Services)
  • Microsoft SQL Server
     
 

Difficulty level

Download information

To download this code sample, click the following link:

 

Technical overview

Service Bus in Microsoft Azure platform AppFabric provides the flexibility and the scalability of the entire solution.

Note You can refer to the LoadBalance sample in AppFabric SDK to learn details about how to use Service Bus to load balance for your service. This article does not describe the details for the simplicity purpose.

Service Bus also allows you to expose the local data to the internet. Therefore, you can consume the data in your cloud applications. WCF Data Services works as an intermediate node that can provide additional access control and other business logic to meet your needs.The implementation of the solution is similar as the implementation of a self-hosted WCF Data Service. The difference is the binding mode in the implementation of the solution needs to be changed to WebHttpRelayBinding binding mode to use Microsoft Azure platform AppFabric Service Bus. With the binding, you can control the authentication by setting a property of the binding to a RelayClientAuthenticationType.None value or a RelayClientAuthenticationType.RelayAccessToken value. If you set the RelayClientAuthenticationType.RelayAccessToken value,Access Control Service will be involved to an issue access token to your client application. Then, your client application uses this access token to request sending information on Service Bus. Service Bus validates the token, and if the token is valid then the client application will be allowed to communicate with the on-premises WCF Data Services. Thus you have additional access control via the help of Service Bus.

You can run the following code to get an access token from Access Control Service:
 
private static string GetTokenFromACS()
        {
            string s = string.Empty;
            try
            {
                // Request a token from ACS
                WebClient client = new WebClient();
                client.BaseAddress = string.Format("https://{0}-sb.accesscontrol.windows.net", _servicenamespace);
 
                NameValueCollection values = new NameValueCollection();
                values.Add("wrap_name", "owner");
                values.Add("wrap_password", _issuerkey);
                values.Add("wrap_scope", _scope);
 
                byte[] responseBytes = client.UploadValues("WRAPv0.9", "POST", values);
                string response = Encoding.UTF8.GetString(responseBytes);
                Console.WriteLine("\nreceived token from ACS: {0}\n", response);
 
                return response
                    .Split('&')
                    .Single(value => value.StartsWith("wrap_access_token=", StringComparison.OrdinalIgnoreCase))
                    .Split('=')[1];
            }
            catch (WebException ex)
            {
                // You can set a breakpoint here to check detailed exception from detailedexception
                StreamReader sr = new StreamReader(ex.Response.GetResponseStream());
                var detailedexception = sr.ReadToEnd();
            }
            return s;
 
 
        }
 




A custom IDispatchMessageInspector object is used to resolve a potential issue that causes by the existence of Service Bus. By default, Service Bus alters the message. Therefore the message cannot be correctly recognized by the WCF Data Services. To work around this issue, you can run the following code to add the custom IDispatchMessageInspector.
class MyInspector : IDispatchMessageInspector 
        {
 
 
            #region IDispatchMessageInspector Members
 
            public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel, InstanceContext instanceContext)
            {
                // Workaround for Service Bus scenario for PUT&POST
                MessageBuffer buffer = request.CreateBufferedCopy(int.MaxValue);
                Message copy = buffer.CreateMessage();
                MemoryStream ms = new MemoryStream();
                Encoding encoding = Encoding.UTF8;
                XmlWriterSettings writerSettings = new XmlWriterSettings { Encoding = encoding };
                XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(ms));
                copy.WriteBodyContents(writer);
                writer.Flush();
                string messageBodyString = encoding.GetString(ms.ToArray());
                messageBodyString = @"<?xml version=""1.0"" encoding=""utf-8""?><Binary>" + 
                    Convert.ToBase64String(Encoding.UTF8.GetBytes(messageBodyString)) + "</Binary>";
                ms = new MemoryStream(encoding.GetBytes(messageBodyString));
                XmlReader bodyReader = XmlReader.Create(ms);
                Message originalMessage = request;
                request = Message.CreateMessage(originalMessage.Version, null, bodyReader);
                request.Headers.CopyHeadersFrom(originalMessage);
             
                if (!request.Properties.ContainsKey(WebBodyFormatMessageProperty.Name))
                {
                    request.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
                }
 
                return null;
                
            }
 
            public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
                
            }
 
            #endregion
        }
         



 

Technology category

  • Microsoft Azure platform AppFabric
  • WCF Data Services

Languages

This code sample contains the following programming languages:
 
Language Project Name
Visual C# CSAzureServiceBusWCFDS
Visual Basic.NET VBAzureServiceBusWCFDS

Prerequisites

  • This sample application was created by using Microsoft Visual Studio 2008 with Service Pack 1 installed.
  • This sample application was created by using Microsoft Microsoft Azure AppFabric SDK V1.0 installed.

Tags
 

  • WCF Data Services
  • Microsoft Azure
  • AppFabric
  • Service Bus

↑ Back to the top


More Information

What is All-In-One Code Framework?

All-In-One Code Framework shows most Microsoft development techniques by using code samples in different programming languages. Each example is carefully selected, composed, and documented to show one common code scenario. For more information about All-In-One Code Framework, visit the following Web site:


How to find more All-In-One Code Framework samples

To find more All-In-One Code Framework samples, you can simply click the following link:



↑ Back to the top


References

For more information about WCF Data Services, visit the following website:

For more information about Message Inspectors, visit the following website:For more information about how to create a Custom AppFabric Service Bus Binding, visit the following website:
Rapid publishing disclaimer
Microsoft corporation and/or its respective suppliers make no representations about the suitability, reliability, or accuracy of the information and related graphics contained herein. All such information and related graphics are provided "as is" without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information and related graphics, including all implied warranties and conditions of merchantability, fitness for a particular purpose, workmanlike effort, title and non-infringement. You specifically agree that in no event shall Microsoft and/or its suppliers be liable for any direct, indirect, punitive, incidental, special, consequential damages or any damages whatsoever including, without limitation, damages for loss of use, data or profits, arising out of or in any way connected with the use of or inability to use the information and related graphics contained herein, whether based on contract, tort, negligence, strict liability or otherwise, even if Microsoft or any of its suppliers has been advised of the possibility of damages.

↑ Back to the top


Keywords: kb, kbrapidpub, atdownload, kbnomt, kbinfo, kbsurveynew, kbcodefx

↑ Back to the top

Article Info
Article ID : 2425654
Revision : 5
Created on : 4/30/2020
Published on : 4/30/2020
Exists online : False
Views : 410