5 // Konstantin Triger <kostat@mainsoft.com>
6 // Atsushi Enomoto <atsushi@ximian.com>
8 // (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
9 // Copyright (C) 2009 Novell, Inc. http://novell.com
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections.Generic;
34 using System.Collections.Specialized;
36 using System.Web.Services;
37 using System.Reflection;
38 using System.Collections;
39 using System.Web.Script.Serialization;
41 using System.Xml.Serialization;
43 using System.ServiceModel;
44 using System.ServiceModel.Description;
46 namespace System.Web.Script.Services
48 internal sealed class JsonResult
50 public readonly object d;
51 public JsonResult (object result) {
56 internal abstract class LogicalTypeInfo
58 public static LogicalTypeInfo CreateTypeInfo (Type t, string filePath)
60 if (t.GetCustomAttributes (typeof (ServiceContractAttribute), false).Length > 0)
61 return new WcfLogicalTypeInfo (t, filePath);
63 return new AsmxLogicalTypeInfo (t, filePath);
66 internal abstract class LogicalMethodInfo
68 readonly MethodInfo _methodInfo;
69 internal readonly ParameterInfo [] _params;
70 internal readonly Dictionary<string, int> _paramMap;
71 LogicalTypeInfo _typeInfo;
73 protected LogicalMethodInfo (LogicalTypeInfo typeInfo, MethodInfo method)
76 _params = MethodInfo.GetParameters ();
80 _paramMap = new Dictionary<string, int> (_params.Length, StringComparer.Ordinal);
81 for (int i = 0; i < _params.Length; i++)
82 _paramMap.Add(_params[i].Name, i);
87 public abstract bool UseHttpGet { get; }
88 public abstract bool EnableSession { get; }
89 public abstract ResponseFormat ResponseFormat { get; }
90 public abstract string MethodName { get; }
91 public MethodInfo MethodInfo { get { return _methodInfo; } }
92 public bool HasParameters { get { return _params != null && _params.Length > 0; } }
93 public IEnumerable<Type> GetParameterTypes () {
95 for (int i = 0; i < _params.Length; i++)
96 yield return _params [i].ParameterType;
98 yield return MethodInfo.ReturnType;
101 public void GenerateMethod (StringBuilder proxy, bool isPrototype, bool isPage) {
103 string service;// = isPage ? "PageMethods" : MethodInfo.DeclaringType.FullName;
105 _typeInfo.GetNamespaceAndServiceName (MethodInfo.DeclaringType, isPage, out ns, out service);
106 string useHttpGet = UseHttpGet ? "true" : "false";
107 string paramMap = GenerateParameters (true);
108 string paramList = GenerateParameters (false);
113 {1}:function({4}succeededCallback, failedCallback, userContext) {{
114 return this._invoke({0}.get_path(), '{1}',{2},{{{3}}},succeededCallback,failedCallback,userContext); }}",
115 service, MethodName, useHttpGet, paramMap, paramList);
120 {0}.{1}= function({2}onSuccess,onFailed,userContext) {{{0}._staticInstance.{1}({2}onSuccess,onFailed,userContext); }}",
121 service, MethodName, paramList);
124 string GenerateParameters (bool isMap) {
128 StringBuilder builder = new StringBuilder ();
130 for (int i = 0; i < _params.Length; i++) {
131 builder.AppendFormat (isMap ? "{0}:{0}" : "{0}", _params [i].Name);
132 builder.Append (',');
138 return builder.ToString ();
141 public abstract void Invoke (HttpRequest request, HttpResponse response);
144 static Hashtable _type_to_logical_type = Hashtable.Synchronized (new Hashtable ());
146 static internal LogicalTypeInfo GetLogicalTypeInfo (Type t, string filePath) {
147 Hashtable type_to_manager = _type_to_logical_type;
148 LogicalTypeInfo tm = (LogicalTypeInfo) type_to_manager [t];
153 tm = CreateTypeInfo (t, filePath);
154 type_to_manager [t] = tm;
159 protected static string EnsureNamespaceRegistered (string ns, string name, StringBuilder proxy, List<string> registeredNamespaces) {
160 if (String.IsNullOrEmpty (ns))
161 return "var " + name;
163 if (!registeredNamespaces.Contains (ns)) {
164 registeredNamespaces.Add (ns);
167 Type.registerNamespace('{0}');",
173 protected virtual void GetNamespaceAndServiceName (Type type, bool isPage, out string ns, out string service)
175 ns = isPage ? String.Empty : type.Namespace;
176 service = isPage ? "PageMethods" : type.FullName;
181 internal readonly Type _type;
182 readonly string _proxy;
183 internal readonly Hashtable _methodMap;
185 protected LogicalTypeInfo (Type t, string filePath)
188 bool isPage = _type.IsSubclassOf (typeof (System.Web.UI.Page));
190 var logicalMethods = GetLogicalMethods (isPage);
191 //_logicalMethods = (LogicalMethodInfo []) list.ToArray (typeof (LogicalMethodInfo));
193 _methodMap = new Hashtable (logicalMethods.Count);
194 for (int i = 0; i < logicalMethods.Count; i++)
195 _methodMap.Add (logicalMethods [i].MethodName, logicalMethods [i]);
199 GetNamespaceAndServiceName (t, isPage, out ns, out service);
201 StringBuilder proxy = new StringBuilder ();
202 List<string> registeredNamespaces = new List<string> ();
203 string scriptTypeDeclaration = EnsureNamespaceRegistered (ns, service, proxy, registeredNamespaces);
206 " + scriptTypeDeclaration + @"=function() {{
207 {0}.initializeBase(this);
209 this._userContext = null;
210 this._succeeded = null;
216 for (int i = 0; i < logicalMethods.Count; i++) {
219 logicalMethods [i].GenerateMethod (proxy, true, isPage);
224 {0}.registerClass('{0}',Sys.Net.WebServiceProxy);
225 {0}._staticInstance = new {0}();
226 {0}.set_path = function(value) {{ {0}._staticInstance.set_path(value); }}
227 {0}.get_path = function() {{ return {0}._staticInstance.get_path(); }}
228 {0}.set_timeout = function(value) {{ {0}._staticInstance.set_timeout(value); }}
229 {0}.get_timeout = function() {{ return {0}._staticInstance.get_timeout(); }}
230 {0}.set_defaultUserContext = function(value) {{ {0}._staticInstance.set_defaultUserContext(value); }}
231 {0}.get_defaultUserContext = function() {{ return {0}._staticInstance.get_defaultUserContext(); }}
232 {0}.set_defaultSucceededCallback = function(value) {{ {0}._staticInstance.set_defaultSucceededCallback(value); }}
233 {0}.get_defaultSucceededCallback = function() {{ return {0}._staticInstance.get_defaultSucceededCallback(); }}
234 {0}.set_defaultFailedCallback = function(value) {{ {0}._staticInstance.set_defaultFailedCallback(value); }}
235 {0}.get_defaultFailedCallback = function() {{ return {0}._staticInstance.get_defaultFailedCallback(); }}
236 {0}.set_path(""{1}"");",
239 for (int i = 0; i < logicalMethods.Count; i++)
240 logicalMethods [i].GenerateMethod (proxy, false, isPage);
242 GenerateTypeRegistrationScript (proxy, registeredNamespaces);
245 _proxy = proxy.ToString ();
248 protected IEnumerable<MemberInfo> GetGenerateScriptTypes () {
249 foreach (LogicalMethodInfo lmi in _methodMap.Values)
250 yield return lmi.MethodInfo;
255 protected static void GenerateTypeRegistrationScript (StringBuilder proxy, Type scriptType, string scriptTypeId, List<string> registeredNamespaces) {
256 string className = scriptType.FullName.Replace ('+', '_');
257 string ns = scriptType.Namespace;
258 string scriptTypeDeclaration = EnsureNamespaceRegistered (ns, className, proxy, registeredNamespaces);
261 if (typeof({0}) === 'undefined') {{", className);
262 if (scriptType.IsEnum) {
265 {0} = function() {{ throw Error.invalidOperation(); }}
267 {0}.registerEnum('{0}', {2});",
269 // This method is also used for WCF, but for enum this should work ...
270 AsmxLogicalTypeInfo.JSSerializer.Serialize(GetEnumPrototypeDictionary (scriptType)),
271 Attribute.GetCustomAttribute (scriptType, typeof (FlagsAttribute)) != null ? "true" : "false");
275 string typeId = String.IsNullOrEmpty (scriptTypeId) ? scriptType.FullName : scriptTypeId;
278 " + scriptTypeDeclaration + @"=gtc(""{1}"");
279 {0}.registerClass('{0}');",
285 static IDictionary <string, object> GetEnumPrototypeDictionary (Type type)
287 var ret = new Dictionary <string, object> ();
288 string [] names = Enum.GetNames (type);
289 Array values = Enum.GetValues (type);
290 for (int i = 0; i < names.Length; i++)
291 ret.Add (names [i], values.GetValue (i));
296 static readonly Type typeOfIEnumerable = typeof (IEnumerable);
297 static readonly Type typeOfIDictionary = typeof (IDictionary);
299 protected static bool ShouldGenerateScript (Type type, bool throwIfNot) {
303 if (Type.GetTypeCode (type) != TypeCode.Object)
306 if (type == typeof (void))
309 if (typeOfIEnumerable.IsAssignableFrom (type) ||
310 typeOfIDictionary.IsAssignableFrom (type) ||
311 type.IsAbstract || type.IsInterface) {
313 ThrowOnIncorrectGenerateScriptAttribute ();
317 // LAMESPEC: MS never create proxies for GenericTypes
318 //&& type.GetGenericTypeDefinition ().GetGenericArguments ().Length > 1
319 if (type.IsGenericType)
322 ConstructorInfo ci = type.GetConstructor (Type.EmptyTypes);
323 if (ci == null || !ci.IsPublic) {
325 ThrowOnIncorrectGenerateScriptAttribute ();
332 static void ThrowOnIncorrectGenerateScriptAttribute () {
333 throw new InvalidOperationException (
334 "Using the GenerateScriptTypes attribute is not supported for types in the following categories: primitive types; DateTime; generic types taking more than one parameter; types implementing IEnumerable or IDictionary; interfaces; Abstract classes; classes without a public default constructor.");
337 protected abstract void GenerateTypeRegistrationScript (StringBuilder proxy, List<string> registeredNamespaces);
339 protected abstract List<LogicalMethodInfo> GetLogicalMethods (bool isPage);
341 public string Proxy { get { return _proxy; } }
343 public LogicalMethodInfo this [string method] {
344 get { return (LogicalMethodInfo) _methodMap [method]; }
348 internal sealed class AsmxLogicalTypeInfo : LogicalTypeInfo
350 #region LogicalMethodInfo
352 public sealed class AsmxLogicalMethodInfo : LogicalTypeInfo.LogicalMethodInfo
354 readonly LogicalTypeInfo _typeInfo;
356 readonly WebMethodAttribute _wma;
358 readonly ScriptMethodAttribute _sma;
360 readonly XmlSerializer _xmlSer;
362 public AsmxLogicalMethodInfo (LogicalTypeInfo typeInfo, MethodInfo method)
363 : base (typeInfo, method)
365 _typeInfo = typeInfo;
367 _wma = (WebMethodAttribute) Attribute.GetCustomAttribute (method, typeof (WebMethodAttribute));
369 _sma = (ScriptMethodAttribute) Attribute.GetCustomAttribute (method, typeof (ScriptMethodAttribute));
371 _sma = ScriptMethodAttribute.Default;
373 if (ScriptMethod.ResponseFormat == ResponseFormat.Xml
374 && MethodInfo.ReturnType != typeof (void)) {
375 Type retType = MethodInfo.ReturnType;
376 if (Type.GetTypeCode (retType) != TypeCode.String || ScriptMethod.XmlSerializeString)
377 _xmlSer = new XmlSerializer (retType);
381 IDictionary<string,object> BuildInvokeParameters (HttpRequest request)
383 return "GET".Equals (request.RequestType, StringComparison.OrdinalIgnoreCase) ?
384 GetNameValueCollectionDictionary (request.QueryString) :
385 (IDictionary<string, object>) JavaScriptSerializer.DefaultSerializer.DeserializeObjectInternal (new StreamReader (request.InputStream, request.ContentEncoding));
388 IDictionary <string, object> GetNameValueCollectionDictionary (NameValueCollection nvc)
390 var ret = new Dictionary <string, object> ();
392 for (int i = nvc.Count - 1; i >= 0; i--)
393 ret.Add (nvc.GetKey (i), nvc.Get (i));
398 public override void Invoke (HttpRequest request, HttpResponse response) {
399 var writer = response.Output;
400 IDictionary<string, object> @params = BuildInvokeParameters (request);
407 pp = new object [_params.Length];
409 foreach (KeyValuePair<string, object> pair in @params) {
410 if (!_paramMap.TryGetValue (pair.Key, out i))
414 ptype = _params [i].ParameterType;
415 if (ptype == typeof (System.Object))
418 pp [i] = AsmxLogicalTypeInfo.JSSerializer.ConvertToType (value, ptype);
422 object target = MethodInfo.IsStatic ? null : Activator.CreateInstance (_typeInfo._type);
423 object result = MethodInfo.Invoke (target, pp);
424 if (_xmlSer != null) {
425 XmlTextWriter xwriter = new XmlTextWriter (writer);
426 xwriter.Formatting = Formatting.None;
427 _xmlSer.Serialize (xwriter, result);
431 result = new JsonResult (result);
432 AsmxLogicalTypeInfo.JSSerializer.Serialize (result, writer);
436 public override string MethodName { get { return String.IsNullOrEmpty (WebMethod.MessageName) ? MethodInfo.Name : WebMethod.MessageName; } }
438 public ScriptMethodAttribute ScriptMethod { get { return _sma; } }
439 public WebMethodAttribute WebMethod { get { return _wma; } }
440 public override bool UseHttpGet { get { return ScriptMethod.UseHttpGet; } }
441 public override bool EnableSession { get { return WebMethod.EnableSession; } }
442 public override ResponseFormat ResponseFormat { get { return ScriptMethod.ResponseFormat; } }
447 //readonly LogicalMethodInfo [] _logicalMethods;
448 internal static readonly JavaScriptSerializer JSSerializer = new JavaScriptSerializer (null, true);
450 protected override List<LogicalMethodInfo> GetLogicalMethods (bool isPage)
452 BindingFlags bindingAttr = isPage ? (BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public) : (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
453 MethodInfo [] all_type_methods = _type.GetMethods (bindingAttr);
454 List<LogicalMethodInfo> logicalMethods = new List<LogicalMethodInfo> (all_type_methods.Length);
455 foreach (MethodInfo mi in all_type_methods) {
457 mi.GetCustomAttributes (typeof (WebMethodAttribute), false).Length > 0)
458 logicalMethods.Add (new AsmxLogicalMethodInfo (this, mi));
460 foreach (Type ifaceType in _type.GetInterfaces ()) {
461 if (ifaceType.GetCustomAttributes (typeof (WebServiceBindingAttribute), false).Length > 0) {
462 MethodInfo found = FindInInterface (ifaceType, mi);
464 if (found.GetCustomAttributes (typeof (WebMethodAttribute), false).Length > 0)
465 logicalMethods.Add (new AsmxLogicalMethodInfo (this, found));
473 return logicalMethods;
476 internal AsmxLogicalTypeInfo (Type t, string filePath)
481 IEnumerable<GenerateScriptTypeAttribute> GetGenerateScriptTypeAttributes () {
482 Hashtable generatedTypes = new Hashtable ();
484 foreach (MemberInfo mi in GetGenerateScriptTypes ()) {
485 GenerateScriptTypeAttribute [] gstas = (GenerateScriptTypeAttribute []) mi.GetCustomAttributes (typeof (GenerateScriptTypeAttribute), true);
486 if (gstas == null || gstas.Length == 0)
489 for (int i = 0; i < gstas.Length; i++) {
490 if (!generatedTypes.Contains (gstas [i].Type)) {
491 if (ShouldGenerateScript (gstas [i].Type, true)) {
492 generatedTypes [gstas [i].Type] = gstas [i].Type;
493 yield return gstas [i];
499 foreach (LogicalMethodInfo lmi in _methodMap.Values) {
500 foreach (Type t in lmi.GetParameterTypes ()) {
501 Type param = GetTypeToGenerate (t);
502 if (!generatedTypes.Contains (param)) {
503 if (ShouldGenerateScript (param, false)) {
504 generatedTypes [param] = param;
505 yield return new GenerateScriptTypeAttribute (param);
512 static Type GetTypeToGenerate (Type type) {
514 return type.GetElementType ();
515 if (type.IsGenericType) {
516 while (type.IsGenericType && type.GetGenericArguments ().Length == 1)
517 type = type.GetGenericArguments () [0];
523 static MethodInfo FindInInterface (Type ifaceType, MethodInfo method) {
524 int nameStartIndex = 0;
525 if (method.IsPrivate) {
526 nameStartIndex = method.Name.LastIndexOf ('.');
527 if (nameStartIndex < 0)
530 if (String.CompareOrdinal (
531 ifaceType.FullName.Replace ('+', '.'), 0, method.Name, 0, nameStartIndex) != 0)
537 foreach (MethodInfo mi in ifaceType.GetMembers ()) {
538 if (method.ReturnType == mi.ReturnType &&
539 String.CompareOrdinal (method.Name, nameStartIndex, mi.Name, 0, mi.Name.Length) == 0) {
540 ParameterInfo [] rpi = method.GetParameters ();
541 ParameterInfo [] lpi = mi.GetParameters ();
542 if (rpi.Length == lpi.Length) {
544 for (int i = 0; i < rpi.Length; i++) {
545 if (rpi [i].ParameterType != lpi [i].ParameterType) {
560 protected override void GenerateTypeRegistrationScript (StringBuilder proxy, List<string> registeredNamespaces)
564 foreach (GenerateScriptTypeAttribute gsta in GetGenerateScriptTypeAttributes ()) {
565 if (!gtc && !gsta.Type.IsEnum) {
568 var gtc = Sys.Net.WebServiceProxy._generateTypedConstructor;");
571 GenerateTypeRegistrationScript (proxy, gsta.Type, gsta.ScriptTypeId, registeredNamespaces);
576 internal class WcfLogicalTypeInfo : LogicalTypeInfo
578 ContractDescription cd;
580 public WcfLogicalTypeInfo (Type type, string filePath)
581 : base (type, filePath)
585 ContractDescription Contract {
588 cd = ContractDescription.GetContract (_type);
593 IEnumerable<KeyValuePair<Type,string>> GetDataContractTypeInfos ()
595 foreach (var od in Contract.Operations) {
596 foreach (var md in od.Messages) {
597 foreach (var pd in md.Body.Parts) {
598 if (ShouldGenerateScript (pd.Type, false))
599 yield return new KeyValuePair<Type,string> (pd.Type, null);
601 if (md.Body.ReturnValue != null && ShouldGenerateScript (md.Body.ReturnValue.Type, false))
602 yield return new KeyValuePair<Type,string> (md.Body.ReturnValue.Type, null);
608 protected override void GetNamespaceAndServiceName (Type type, bool isPage, out string ns, out string service)
610 string name = type.Namespace;
611 int dot = name.LastIndexOf ('.');
613 name = name.Substring (dot + 1);
615 service = name + "." + type.Name;
618 protected override void GenerateTypeRegistrationScript (StringBuilder proxy, List<string> registeredNamespaces)
622 foreach (KeyValuePair<Type,string> pair in GetDataContractTypeInfos ()) {
623 if (!gtc && !pair.Key.IsEnum) {
626 var gtc = Sys.Net.WebServiceProxy._generateTypedConstructor;");
629 GenerateTypeRegistrationScript (proxy, pair.Key, pair.Value, registeredNamespaces);
633 protected override List<LogicalMethodInfo> GetLogicalMethods (bool isPage)
636 throw new NotSupportedException ();
638 var l = new List<LogicalMethodInfo> ();
639 foreach (var od in Contract.Operations)
640 l.Add (new WcfLogicalMethodInfo (this, od));
644 internal class WcfLogicalMethodInfo : LogicalMethodInfo
646 OperationDescription od;
648 public WcfLogicalMethodInfo (LogicalTypeInfo typeInfo, OperationDescription od)
649 : base (typeInfo, od.SyncMethod)
654 public override bool UseHttpGet { get { return true; } } // always
656 // FIXME: could this be enabled?
657 public override bool EnableSession {
658 get { return false; }
661 public override ResponseFormat ResponseFormat {
662 get { return ResponseFormat.Json; } // always
665 public override string MethodName {
666 get { return od.Name; }
669 public override void Invoke (HttpRequest request, HttpResponse response)
671 // invocation is done in WCF part.
672 throw new NotSupportedException ();