public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { if (IsStatic && obj != null) { throw new InvalidOperationException("Static methods cannot have a target"); } if (!IsStatic && obj == null) { throw new InvalidOperationException("Instance methods must have a target"); } var args = new JsArray(); if (typeArguments != null) { foreach (var typeArgument in typeArguments) { args.push(typeArgument.thisType); } } if (parameters != null) { foreach (var argument in parameters) { args.push(argument.As <JsObject>()); } } return(Jsni.apply(jsMethod, obj.As <JsObject>(), args)); }
public static object InternalToObject(JsTypeFunction enumType, object value) { var enumsByValue = enumsByTypeAndValue[enumType.TypeName]; Enum result = enumsByValue.GetOrDefault(value); if (result != null) { return(result); } else { // Otherwise it's an enum value that isn't represented by a declared member. In // this case, we need to box the value and then force it to be recognized as the // enum type. result = Jsni.@new(Jsni.reference("Number"), value.As <JsObject>()).As <Enum>(); foreach (var property in enumType.member("prototype")) { result.As <JsObject>()[property] = enumType.member("prototype")[property]; } foreach (var property in Jsni.type <Enum>().member("prototype")) { result.As <JsObject>()[property] = Jsni.type <Enum>().member("prototype")[property]; } result.___type = enumType; result.As <JsObject>().memberset("value", value.As <JsObject>()); enumsByValue[value] = result; return(result); } }
private static void GetBrowserInfo(this Window window) { if (browserProduct != null) { return; } var userAgent = window.Navigator.UserAgent; var match = userAgent.match(Jsni.regex(@"(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)", "i")) ?? Jsni.array(); if (Jsni.regex("trident", "i").test(match[1].As <JsString>())) { browserProduct = "MSIE"; browserVersion = (Jsni.regex(@"\brv[ :]+(\d+(\.\d+)?)", "g").exec(userAgent) ?? new string[0])[1] ?? ""; return; } if (match[2]) { browserProduct = match[1].As <JsString>(); browserVersion = match[2].As <JsString>(); } else { browserProduct = window.Navigator.AppName; browserVersion = window.Navigator.AppVersion; } var tailVersion = userAgent.match(Jsni.regex(@"version\/([\.\d]+)", "i")); if (tailVersion != null) { browserVersion = tailVersion[1].As <JsString>(); } }
public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { if (IsStatic && obj != null) { throw new InvalidOperationException("Static methods cannot have a target"); } if (!IsStatic && obj == null) { throw new InvalidOperationException("Instance methods must have a target"); } var args = new JsArray(); if (typeArguments != null) { foreach (var typeArgument in typeArguments) { args.push(typeArgument.thisType); } } if (parameters != null) { var parametersArray = parameters.As <JsArray>(); for (var i = 0; i < parametersArray.length; i++) { var argument = parametersArray[i].As <JsObject>(); args.push(argument.As <JsObject>()); } } var target = IsStatic ? DeclaringType.thisType : obj; return(Jsni.apply(jsMethod, target.As <JsObject>(), args)); }
public void ForIn() { var counter = 0; var jsObject = Jsni.@object(new { One = 1, Two = 2 }); jsObject.forin(x => counter += jsObject[x]); QUnit.AreEqual(counter, 3); }
static CultureInfo() { CurrentCulture = new CultureInfo(); // Set up default culture var navigator = Jsni.reference("window").member("navigator"); currentCultureName = (navigator.member("userLanguage") ?? navigator.member("language") ?? navigator.member("browserLanguage") ?? navigator.member("systemLanguage")).As <string>(); }
public void Clear() { foreach (var bucket in buckets) { var hashCode = bucket.HashCode; Jsni.delete(storage[hashCode]); } count = 0; }
public async Task TrueAsyncTestTaskT() { var taskCompletionSource = new TaskCompletionSource <int>(); Jsni.setTimeout(() => taskCompletionSource.SetResult(4), 0); var value = await taskCompletionSource.Task; AssertEquals(value, 4); }
public static long Parse(string s) { var result = Jsni.parseInt(s); if (Jsni.isNaN(result)) { throw new FormatException("String not convertible to long: " + s); } return(result.As <long>()); }
public static int Parse(string s, int radix) { var result = Jsni.parseInt(s, radix); if (Jsni.isNaN(result)) { throw new FormatException("String not convertible to int: " + s); } return(result.As <int>()); }
private void Test(int x) { Jsni.code("console.warn('test', x)"); if (x > 10) { Jsni.code("throw { value: x, data: this.GetFoo() }"); } while (Jsni.code("x === 100").As <bool>()) { } }
public static bool TryParse(string s, out int result) { var returnValue = Jsni.parseInt(s); if (Jsni.isNaN(returnValue)) { result = 0; return(false); } result = returnValue.As <int>(); return(true); }
/// <summary> /// Sorts the elements in the entire <see cref="T:System.Collections.Generic.List`1"/> using the specified comparer. /// </summary> /// <param name="comparer">The <see cref="T:System.Collections.Generic.IComparer`1"/> implementation to use when comparing elements, or null to use the default comparer <see cref="P:System.Collections.Generic.Comparer`1.Default"/>.</param><exception cref="T:System.InvalidOperationException"><paramref name="comparer"/> is null, and the default comparer <see cref="P:System.Collections.Generic.Comparer`1.Default"/> cannot find implementation of the <see cref="T:System.IComparable`1"/> generic interface or the <see cref="T:System.IComparable"/> interface for type <paramref name="T"/>.</exception><exception cref="T:System.ArgumentException">The implementation of <paramref name="comparer"/> caused an error during the sort. For example, <paramref name="comparer"/> might not return 0 when comparing an item with itself.</exception> public void Sort(IComparer <T> comparer) { if (comparer == null) { throw new ArgumentNullException("comparer"); } if (Count <= 0) { return; } storage.sort(Jsni.function((x, y) => comparer.Compare(x.As <T>(), y.As <T>()).As <JsNumber>())); }
public static Event CreateCustomEvent(this Document document, string eventType, object args) { try { return(Jsni.@new(Jsni.reference("CustomEvent"), eventType, args.As <JsObject>()).As <Event>()); } catch (Exception e) { var evt = document.CreateEvent("CustomEvent"); evt.As <JsObject>().member("initCustomEvent").invoke(eventType, false, true, args.As <JsObject>()); return(evt); } }
public void Stop() { if (timeoutHandle != null) { Jsni.clearTimeout(timeoutHandle); timeoutHandle = null; } if (intervalHandle != null) { Jsni.clearInterval(intervalHandle); intervalHandle = null; } }
/// <summary> /// Gets the assemblies that have been loaded into the execution context of this application domain. /// </summary> /// /// <returns> /// An array of assemblies in this application domain. /// </returns> /// <exception cref="T:System.AppDomainUnloadedException">The operation is attempted on an unloaded application domain. </exception><filterpriority>2</filterpriority> public Assembly[] GetAssemblies() { var array = Jsni.reference("$assemblies").As <JsArray>(); var result = new Assembly[array.length]; for (var i = 0; i < result.Length; i++) { var getAssembly = array[i].As <JsFunction>(); result[i] = getAssembly.invoke().As <Assembly>(); } return(result); }
public async Task CancelDelay() { var source = new CancellationTokenSource(); var canceled = false; Jsni.setTimeout(() => source.Cancel(), 1); try { await Task.Delay(3000, source.Token); } catch (TaskCanceledException) { canceled = true; } AssertTrue(canceled); }
/// <summary> /// When overridden in a derived class, sets the property value for a specified object that has the specified binding, index, and culture-specific information. /// </summary> /// <param name="obj">The object whose property value will be set. </param><param name="value">The new property value. </param><param name="invokeAttr">A bitwise combination of the following enumeration members that specify the invocation attribute: InvokeMethod, CreateInstance, Static, GetField, SetField, GetProperty, or SetProperty. You must specify a suitable invocation attribute. For example, to invoke a static member, set the Static flag. </param><param name="binder">An object that enables the binding, coercion of argument types, invocation of members, and retrieval of <see cref="T:System.Reflection.MemberInfo"/> objects through reflection. If <paramref name="binder"/> is null, the default binder is used. </param><param name="index">Optional index values for indexed properties. This value should be null for non-indexed properties. </param><param name="culture">The culture for which the resource is to be localized. If the resource is not localized for this culture, the <see cref="P:System.Globalization.CultureInfo.Parent"/> property will be called successively in search of a match. If this value is null, the culture-specific information is obtained from the <see cref="P:System.Globalization.CultureInfo.CurrentUICulture"/> property. </param><exception cref="T:System.ArgumentException">The <paramref name="index"/> array does not contain the type of arguments needed.-or- The property's set accessor is not found. </exception><exception cref="T:System.Reflection.TargetException">The object does not match the target type, or a property is an instance property but <paramref name="obj"/> is null. </exception><exception cref="T:System.Reflection.TargetParameterCountException">The number of parameters in <paramref name="index"/> does not match the number of parameters the indexed property takes. </exception><exception cref="T:System.MethodAccessException">There was an illegal attempt to access a private or protected method inside a class. </exception><exception cref="T:System.Reflection.TargetInvocationException">An error occurred while setting the property value. For example, an index value specified for an indexed property is out of range. The <see cref="P:System.Exception.InnerException"/> property indicates the reason for the error.</exception> public void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { if (SetMethod == null) { throw new InvalidOperationException("Property '" + DeclaringType.FullName + "." + Name + "' does not have a setter."); } var args = Jsni.@new(Jsni.reference("Array"), (1 + (index != null ? index.Length : 0)).As <JsObject>()).As <JsArray>(); // new object[1 + (index != null ? index.Length : 0)]; args[0] = value.As <JsObject>(); for (var i = 1; i < args.length; i++) { args[i] = index[i - 1].As <JsObject>(); } SetMethod.Invoke(obj, invokeAttr, binder, args.As <object[]>(), culture); }
public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken) { var completionSource = new TaskCompletionSource <object>(); var token = Jsni.setTimeout( () => { completionSource.SetResult(null); }, millisecondsDelay); cancellationToken.Register(() => { Jsni.clearTimeout(token); completionSource.TrySetCanceled(cancellationToken); }); return(completionSource.Task); }
// ReSharper disable once RedundantOverridenMember /* * public override string GetStringHashCode() * { * // We need to override it to make sure this method gets added to the String prototype. * return this; * } */ public override int GetHashCode() { var result = Jsni.@this().member("$hashCode"); if (result == null) { var hash = 0; for (var i = 0; i < Length; i++) { var character = this.As <JsString>().charCodeAt(i); hash = ((hash << 5) - hash) + character; hash = hash & hash; // Convert to 32bit integer } result = hash.As <JsObject>(); Jsni.@this().memberset("$hashCode", result); } return(result.As <int>()); }
public async Task TryCatchTrueAsync() { var taskCompletionSource = new TaskCompletionSource <int>(); Jsni.setTimeout(() => taskCompletionSource.SetResult(4), 0); bool flag = false; try { await taskCompletionSource.Task; throw new Exception(); } catch (Exception ex) { flag = true; } AssertTrue(flag); }
public void Change(TimeSpan dueTime, TimeSpan period) { // Clear any existing timers Stop(); // Set up a timeout to fire the timer if (dueTime.TotalMilliseconds == 0) { intervalHandle = Jsni.setInterval(OnTimeout, (int)period.TotalMilliseconds); } else { timeoutHandle = Jsni.setTimeout( () => { callback(state); timeoutHandle = null; intervalHandle = Jsni.setInterval(OnTimeout, (int)period.TotalMilliseconds); }, (int)dueTime.TotalMilliseconds); } }
public void IndexerOverride() { Jsni.reference("window").memberset("IndexerOverride", Jsni.@object(new { items = Jsni.array(), item = Jsni.function((index, value) => { if (Jsni.arguments().As <JsArray>().length == 1) { return(Jsni.@this().member("items").As <JsArray>()[index]); } else { Jsni.@this().member("items").As <JsArray>()[index] = value; return(null); } }) })); var indexerOverride = Jsni.reference("window").member("IndexerOverride").As <IndexerOverrideClass>(); indexerOverride[3] = "foo"; QUnit.AreEqual(indexerOverride[3], "foo"); }
public bool Remove(TKey key) { var hashCode = comparer.GetHashCode(key).ToString(); var bucket = storage[hashCode].As <Bucket>(); if (bucket != null) { var items = bucket.Items.Where(x => comparer.Equals(x.Key, key)).GetEnumerator(); if (items.MoveNext()) { var item = items.Current; items.Dispose(); bucket.Items.Remove(item); if (bucket.Items.Count == 0) { Jsni.delete(storage[hashCode]); } count--; return(true); } } return(false); }
/// <summary> /// When implemented in a derived class, invokes the constructor reflected by this ConstructorInfo with the specified arguments, under the constraints of the specified Binder. /// </summary> /// /// <returns> /// An instance of the class associated with the constructor. /// </returns> /// <param name="invokeAttr">One of the BindingFlags values that specifies the type of binding. </param><param name="binder">A Binder that defines a set of properties and enables the binding, coercion of argument types, and invocation of members using reflection. If <paramref name="binder"/> is null, then Binder.DefaultBinding is used. </param><param name="parameters">An array of type Object used to match the number, order and type of the parameters for this constructor, under the constraints of <paramref name="binder"/>. If this constructor does not require parameters, pass an array with zero elements, as in Object[] parameters = new Object[0]. Any object in this array that is not explicitly initialized with a value will contain the default value for that object type. For reference-type elements, this value is null. For value-type elements, this value is 0, 0.0, or false, depending on the specific element type. </param><param name="culture">A <see cref="T:System.Globalization.CultureInfo"/> used to govern the coercion of types. If this is null, the <see cref="T:System.Globalization.CultureInfo"/> for the current thread is used. </param><exception cref="T:System.ArgumentException">The <paramref name="parameters"/> array does not contain values that match the types accepted by this constructor, under the constraints of the <paramref name="binder"/>. </exception><exception cref="T:System.Reflection.TargetInvocationException">The invoked constructor throws an exception. </exception><exception cref="T:System.Reflection.TargetParameterCountException">An incorrect number of parameters was passed. </exception><exception cref="T:System.NotSupportedException">Creation of <see cref="T:System.TypedReference"/>, <see cref="T:System.ArgIterator"/>, and <see cref="T:System.RuntimeArgumentHandle"/> types is not supported.</exception><exception cref="T:System.Security.SecurityException">The caller does not have the necessary code access permissions.</exception><exception cref="T:System.MemberAccessException">The class is abstract.-or- The constructor is a class initializer. </exception><exception cref="T:System.MethodAccessException">The constructor is private or protected, and the caller lacks <see cref="F:System.Security.Permissions.ReflectionPermissionFlag.MemberAccess"/>. </exception> public object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { return(Jsni.member(jsConstructor, "$new").apply(jsConstructor, parameters.As <JsArray>())); }
public static string UrlDecode(string s) { return(Jsni.decodeURIComponent(s)); }
public static string UrlEncode(string s) { return(Jsni.encodeURIComponent(s)); }
public static bool IsDigit(char c) { return(Jsni.regex("^\\d+$").test(c.As <JsString>())); }
public static bool IsWhiteSpace(char c) { return(Jsni.regex("\\s").test(c.As <JsString>())); }
public static double Parse(string s) { return(Jsni.parseFloat(s.As <JsString>()).As <double>()); }