Merge pull request #1502 from madrang/SafeHandle.CloseTestDispose
[mono.git] / mcs / class / System.Web.Services / System.Web.Services.Protocols / SoapDocumentationHandler.cs
1 //
2 // System.Web.Services.Protocols.SoapDocumentationHandler.cs
3 //
4 // Author:
5 //   Lluis Sanchez Gual (lluis@ximian.com)
6 //
7 // Copyright (C) Ximian, Inc. 2003
8 //
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System;
32 using System.Web;
33 using System.IO;
34 using System.Globalization;
35 using System.Xml;
36 using System.Text;
37 using System.Xml.Serialization;
38 using System.Xml.Schema;
39 using System.Web.Compilation;
40 using System.Web.Services.Description;
41 using System.Web.Services.Discovery;
42 using System.Web.Services.Configuration;
43 using System.Configuration;
44 using System.CodeDom;
45 using System.CodeDom.Compiler;
46 using Microsoft.CSharp;
47 using System.Web.UI;
48
49 namespace System.Web.Services.Protocols
50 {
51         internal class SoapDocumentationHandler: WebServiceHandler
52         {
53                 SoapTypeStubInfo _typeStubInfo;
54                 ServiceDescriptionCollection _descriptions;
55                 XmlSchemas _schemas;
56                 string _url;
57                 IHttpHandler _pageHandler = null;
58
59                 public SoapDocumentationHandler (Type type, HttpContext context): base (type)
60                 {
61                         _url = context.Request.Url.ToString();
62                         int i = _url.IndexOf ('?');
63                         if (i != -1) _url = _url.Substring (0,i);
64                         _typeStubInfo = (SoapTypeStubInfo) TypeStubManager.GetTypeStub (ServiceType, "Soap");
65                         
66                         HttpRequest req = context.Request;
67                         string key = null;
68                         if (req.QueryString.Count == 1) {
69                                 key = req.QueryString.GetKey (0);
70                                 if (key == null)
71                                         key = req.QueryString [0];
72
73                                 if (key != null)
74                                         key = key.ToLower (CultureInfo.InvariantCulture);
75                         }
76                                 
77                         if (key == "wsdl" || key == "schema" || key == "code" || key == "disco")
78                                 return;
79                                 
80                         string help = WebServicesSection.Current.WsdlHelpGenerator.Href;
81                         string path = Path.GetDirectoryName (ConfigurationManager.OpenMachineConfiguration().FilePath);
82                         string appPath = AppDomain.CurrentDomain.GetData (".appPath").ToString ();
83                         string vpath;
84                         if (path.StartsWith (appPath)) {
85                                 vpath = path.Substring (appPath.Length);
86                                 vpath = vpath.Replace ("\\", "/");
87                         } else {
88                                 vpath = "/";
89                         }
90
91                         if (vpath.EndsWith ("/"))
92                                 vpath += help;
93                         else
94                                 vpath += "/" + help;
95
96                         string physPath = Path.Combine (path, help);
97                         
98                         if (!File.Exists (physPath))
99                                 throw new InvalidOperationException ("Documentation page '" + physPath + "' not found");
100
101                         _pageHandler = PageParser.GetCompiledPageInstance (vpath, physPath, context);
102                 }
103
104                 internal IHttpHandler PageHandler {
105                         get { return _pageHandler; }
106                 }
107
108                 public override bool IsReusable 
109                 {
110                         get { return false; }
111                 }
112
113                 public override void ProcessRequest (HttpContext context)
114                 {
115                         if (_pageHandler != null)
116                         {
117                                 context.Items["wsdls"] = GetDescriptions ();
118                                 context.Items["schemas"] = GetSchemas ();
119                                 _pageHandler.ProcessRequest (context);
120                         }
121                         else
122                         {
123                                 HttpRequest req = context.Request;
124                                 string key = req.QueryString.GetKey (0);
125                                 if (key == null)
126                                         key = req.QueryString [0];
127
128                                 if (key != null)
129                                         key = key.ToLower (CultureInfo.InvariantCulture);
130
131                                 if (key  == "wsdl") GenerateWsdlDocument (context, req.QueryString ["wsdl"]);
132                                 else if (key == "schema") GenerateSchema (context, req.QueryString ["schema"]);
133                                 else if (key == "code") GenerateCode (context, req.QueryString ["code"]);
134                                 else if (key == "disco") GenerateDiscoDocument (context);
135                                 else throw new Exception ("This should never happen");
136                         }
137                 }
138
139                 void GenerateWsdlDocument (HttpContext context, string wsdlId)
140                 {
141                         int di = 0;
142                         if (wsdlId != null && wsdlId != "") di = int.Parse (wsdlId);
143                         
144                         context.Response.ContentType = "text/xml; charset=utf-8";
145                         XmlTextWriter xtw = new XmlTextWriter (context.Response.OutputStream, new UTF8Encoding (false));
146                         xtw.Formatting = Formatting.Indented;
147                         GetDescriptions() [di].Write (xtw);
148                 }
149                 
150                 void GenerateDiscoDocument (HttpContext context)
151                 {
152                         ServiceDescriptionCollection descs = GetDescriptions ();
153                         
154                         DiscoveryDocument doc = new DiscoveryDocument ();
155                         ContractReference cref = new ContractReference ();
156                         cref.Ref = _url + "?wsdl";
157                         cref.DocRef = _url;
158                         doc.References.Add (cref);
159                         
160                         foreach (ServiceDescription desc in descs)
161                                 foreach (Service ser in desc.Services)
162                                         foreach (Port port in ser.Ports)
163                                         {
164                                                 SoapAddressBinding sab = port.Extensions.Find (typeof(SoapAddressBinding)) as SoapAddressBinding;
165                                                 if (sab != null)
166                                                 {
167                                                         System.Web.Services.Discovery.SoapBinding dsb = new System.Web.Services.Discovery.SoapBinding ();
168                                                         dsb.Address = sab.Location;
169                                                         dsb.Binding = port.Binding;
170                                                         doc.AdditionalInfo.Add (dsb);
171                                                 }
172                                         }
173
174                         context.Response.ContentType = "text/xml; charset=utf-8";
175                         XmlTextWriter xtw = new XmlTextWriter (context.Response.OutputStream, new UTF8Encoding (false));
176                         xtw.Formatting = Formatting.Indented;
177                         doc.Write (xtw);
178                 }
179                 
180                 void GenerateSchema (HttpContext context, string schemaId)
181                 {
182                         int di = -1;
183                         if (schemaId != null && schemaId != "") {
184                                 try {
185                                         di = int.Parse (schemaId);
186                                 } catch {
187                                         XmlSchemas xss = GetSchemas ();
188                                         for (int i = 0; i < xss.Count; i++) {
189                                                 if (xss [i].Id == schemaId) {
190                                                         di = i;
191                                                         break;
192                                                 }
193                                         }
194                                 }
195                                 if (di < 0)
196                                         throw new InvalidOperationException (String.Format ("HTTP parameter 'schema' needs to specify an Id of a schema in the schemas. {0} points to nowhere.", schemaId));
197                         }
198                         context.Response.ContentType = "text/xml; charset=utf-8";
199                         XmlTextWriter xtw = new XmlTextWriter (context.Response.OutputStream, new UTF8Encoding (false));
200                         xtw.Formatting = Formatting.Indented;
201                         GetSchemas() [di].Write (xtw);
202                 }
203
204                 void GenerateCode (HttpContext context, string langId)
205                 {
206                         context.Response.ContentType = "text/plain; charset=utf-8";
207                         CodeNamespace codeNamespace = new CodeNamespace();
208                         CodeCompileUnit codeUnit = new CodeCompileUnit();
209                         
210                         codeUnit.Namespaces.Add (codeNamespace);
211
212                         ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
213                         
214                         foreach (ServiceDescription sd in GetDescriptions ())
215                                 importer.AddServiceDescription(sd, null, null);
216
217                         foreach (XmlSchema sc in GetSchemas())
218                                 importer.Schemas.Add (sc);
219
220                         importer.Import(codeNamespace, codeUnit);
221                         
222                         if (langId == null || langId == "") langId = "cs";
223                         CodeDomProvider provider = GetProvider (langId);
224                         ICodeGenerator generator = provider.CreateGenerator();
225                         CodeGeneratorOptions options = new CodeGeneratorOptions();
226                         
227                         generator.GenerateCodeFromCompileUnit(codeUnit, context.Response.Output, options);
228                 }
229                 
230                 private CodeDomProvider GetProvider(string langId)
231                 {
232                         // FIXME these should be loaded dynamically using reflection
233                         CodeDomProvider provider;
234                         
235                         switch (langId.ToUpper())
236                         {
237                             case "CS":
238                                     provider = new CSharpCodeProvider();
239                                     break;
240                             
241                             default:
242                                     throw new Exception("Unknown language: " + langId);
243                         }
244
245                         return provider;
246                 }
247                 
248                 internal ServiceDescriptionCollection GetDescriptions ()
249                 {
250                         if (_descriptions == null)
251                         {
252                                 ServiceDescriptionReflector reflector = new ServiceDescriptionReflector ();
253                                 reflector.Reflect (ServiceType,_url);
254                                 _schemas = reflector.Schemas;
255                                 _descriptions = reflector.ServiceDescriptions;
256                         }
257                         return _descriptions;
258                 }
259                 
260                 internal XmlSchemas GetSchemas()
261                 {
262                         GetDescriptions();
263                         return _schemas;
264                 }
265         }
266 }