public void CheckTalkPageLanguage() { List <string> invalidTalkPageIds = new List <string>(); // Talk: pages don't have a parent_page id so we match based on the page_title _catalog.NewQuery("SELECT page_id, page_title, page_language FROM pages WHERE page_namespace=1") .Execute(delegate(IDataReader reader) { while (reader.Read()) { uint page_id = SysUtil.ChangeType <uint?>(reader["page_id"]) ?? 0; string page_title = SysUtil.ChangeType <string>(reader["page_title"]) ?? ""; string page_language = SysUtil.ChangeType <string>(reader["page_language"]) ?? ""; _catalog.NewQuery("SELECT page_language FROM pages where page_title=?PAGE_TITLE AND page_namespace=0").With("PAGE_TITLE", page_title) .Execute(delegate(IDataReader reader2) { while (reader2.Read()) { string main_page_language = SysUtil.ChangeType <string>(reader2["page_language"]) ?? ""; if (main_page_language != page_language) { invalidTalkPageIds.Add(page_id.ToString()); } } } ); } } ); Assert.IsTrue(invalidTalkPageIds.Count == 0, string.Format(ERR_INVALID_TALK_LANGUAGE, string.Join(",", invalidTalkPageIds.ToArray()))); }
public void Can_cast_byte_to_enum() { var x = (byte)Castable.V2; var y = SysUtil.ChangeType(x, typeof(Castable)); Assert.AreEqual(Castable.V2, y); }
private static XDoc AtXPathNode(XDoc doc, string xpath, Hashtable namespaces) { XDoc result = doc; // check if xpath selects anything other than the current node if (!string.IsNullOrEmpty(xpath) && !xpath.EqualsInvariant(".")) { // check if custom namespace mapping was provided if (namespaces != null) { // initialize a namespace manager XmlNamespaceManager nsm = new XmlNamespaceManager(SysUtil.NameTable); foreach (DictionaryEntry ns in namespaces) { nsm.AddNamespace((string)ns.Key, SysUtil.ChangeType <string>(ns.Value)); } result = doc.AtPath(xpath, nsm); } else { // use default namespace manager result = doc[xpath]; } } return(result); }
public DekiScriptLiteral this[DekiScriptLiteral index] { get { if (index == null) { throw new ArgumentNullException("index"); } if ((index.ScriptType == DekiScriptType.NUM) || (index.ScriptType == DekiScriptType.STR)) { return(this[SysUtil.ChangeType <string>(index.NativeValue)]); } else { throw new DekiScriptBadTypeException(Location.None, index.ScriptType, new[] { DekiScriptType.NUM, DekiScriptType.STR }); } } set { if (index == null) { throw new ArgumentNullException("index"); } if ((index.ScriptType == DekiScriptType.NUM) || (index.ScriptType == DekiScriptType.STR)) { this[SysUtil.ChangeType <string>(index.NativeValue)] = value; } else { throw new DekiScriptBadTypeException(Location.None, index.ScriptType, new[] { DekiScriptType.NUM, DekiScriptType.STR }); } } }
public XDoc GadgetScript( [DekiExtParam("Google gadget script")] string script ) { // validate xml XDoc xml = XDocFactory.From("<html><body>" + script + "</body></html>", MimeType.HTML)["//script"]; if ((xml == null) || !xml.HasName("script")) { throw new ArgumentException("Google gadget must contained in a <script> tag"); } // validate uri XUri uri = xml["@src"].AsUri ?? XUri.Localhost; if (!uri.Host.EqualsInvariantIgnoreCase("gmodules.com") && !uri.Host.EqualsInvariantIgnoreCase("www.gmodules.com")) { throw new ArgumentException("Google gadget must be originating from gmodules.com"); } // remove .js output option uri = uri.WithoutParams("output"); // create <iframe> in which we'll load the gadget return(NewIFrame(uri, SysUtil.ChangeType <float?>(uri.GetParam("w")), SysUtil.ChangeType <float>(uri.GetParam("h")))); }
/// <summary> /// Execute command and return value from the first column in the first row. /// </summary> /// <typeparam name="T">Returned value type</typeparam> /// <returns>Converted value</returns> private T?ReadAs <T>() where T : struct { _log.TraceMethodCall("ReadAs<T>()", typeof(T).FullName, _command.CommandText); QueryStart(); using (IDbConnection connection = _factory.OpenConnection(_connection)) { using (IDbCommand command = CreateExecutableCommand(connection)) { try { object value = command.ExecuteScalar(); if (value == null) { return(null); } if (value is DBNull) { return(null); } return((T)SysUtil.ChangeType(value, typeof(T))); } catch (Exception e) { _log.DebugFormat(e, "ReadAs(): Text: '{0}', Type: {1}", _command.CommandText, _command.CommandType); throw; } finally { QueryFinished(command); } } } }
private DekiScriptLiteral InvokeHelper(DekiScriptRuntime runtime, DekiScriptList args) { // convert passed in arguments object[] arguments = new object[Parameters.Length]; int i = 0; try { for (; i < Parameters.Length; ++i) { var value = args[i].NativeValue; // check if we need to convert the value if ((value != null) && (Parameters[i].NativeType != typeof(object))) { // check for the special case where we cast from XML to STR if ((value is XDoc) && (Parameters[i].NativeType == typeof(string))) { XDoc xml = (XDoc)value; if (xml.HasName("html")) { value = xml["body[not(@target)]"].Contents; } else { value = xml.ToString(); } } else { // rely on the default type conversion rules value = SysUtil.ChangeType(value, Parameters[i].NativeType); } } arguments[i] = value; } } catch { throw new ArgumentException(string.Format("could not convert parameter '{0}' (index {1}) from {2} to {3}", Parameters[i].Name, i, args[i].ScriptTypeName, DekiScriptLiteral.AsScriptTypeName(Parameters[i].ScriptType))); } // invoke method var result = _invoke(runtime, arguments); // check if result is a URI if (result is XUri) { // normalize URI if possible DreamContext context = DreamContext.CurrentOrNull; if (context != null) { result = context.AsPublicUri((XUri)result); } } var literal = DekiScriptLiteral.FromNativeValue(result); try { return(literal.Convert(ReturnType)); } catch (DekiScriptInvalidCastException) { throw new DekiScriptInvalidReturnCastException(Location.None, literal.ScriptType, ReturnType); } }
public Hashtable Args(ArrayList args) { // return a map arguments // if the argument has a name use it, otherwise use the argument index as the name Hashtable result = new Hashtable(); for (int i = 0; i < args.Count; i++) { string arg = String.Empty; try { arg = SysUtil.ChangeType <string>(args[i]); } catch {} int equalIndex = arg.IndexOf("="); if (0 < equalIndex) { string id = arg.Substring(0, equalIndex).Trim(); if (ARG_REGEX.IsMatch(id)) { result[id] = arg.Substring(equalIndex + 1, arg.Length - equalIndex - 1); } else { result[i.ToString()] = arg; } } else { result[i.ToString()] = arg; } } return(result); }
public void Can_cast_string_to_enum() { var x = Castable.V2.ToString(); var y = SysUtil.ChangeType(x, typeof(Castable)); Assert.AreEqual(Castable.V2, y); }
public XDoc SlideShow( [DekiExtParam("list of image URIs")] ArrayList uris, [DekiExtParam("slideshow width (default: 300px)", true)] float?width, [DekiExtParam("slideshow height (default: 300px)", true)] float?height, [DekiExtParam("interval in seconds (default: 5.0)", true)] double?interval, [DekiExtParam("slideshow effect; one of {slideright, slideleft, slideup, squeezeleft, squeezeright, squeezeup, squeezedown, fadeout} (default: 'fadeout')", true)] string effect ) { // convert URIs to XUri objects XUri[] xuris = new XUri[uris.Count]; for (int i = 0; i < uris.Count; ++i) { xuris[i] = SysUtil.ChangeType <XUri>(uris[i]); if (xuris[i] == null) { throw new ArgumentNullException(string.Format("entry {0} is null", i)); } } // create response document string id = "_" + StringUtil.CreateAlphaNumericKey(8); XDoc result = new XDoc("html") .Start("head") .Start("link").Attr("type", "text/css").Attr("rel", "stylesheet").Attr("href", Files.At("slideshow.css")).End() .Start("script").Attr("type", "text/javascript").Attr("src", Files.At("slideshow.js")).End() .End(); result.Start("body") .Start("div").Attr("id", id).Attr("class", "yui-sldshw-displayer").Attr("style", string.Format("width:{0};height:{1};", AsSize(width ?? 300), AsSize(height ?? 300))); // add each image int counter = 0; foreach (XUri uri in xuris) { ++counter; result.Start("img"); result.Attr("id", id + counter); if (counter == 1) { result.Attr("class", "yui-sldshw-active yui-sldshw-frame"); } else { result.Attr("class", "yui-sldshw-cached yui-sldshw-frame"); } result.Attr("src", uri).Attr("onclick", string.Format("{0}.transition();", id)).End(); } result.End().End(); // add code to kick star the slideshow result.Start("tail") .Start("script").Attr("type", "text/javascript") .Value(string.Format("var {0} = new YAHOO.myowndb.slideshow('{0}', {{ interval: {1}, effect: YAHOO.myowndb.slideshow.effects.{2} }}); {0}.loop();", id, (int)((interval ?? 5.0) * 1000), (effect ?? "fadeOut").ToLowerInvariant())) .End(); result.End(); return(result); }
public static IEnumerable <UserBE> GetUsersByQuery(DreamContext context, uint?groupId, out uint totalCount, out uint queryCount) { uint limit, offset; SortDirection sortDir; string sortFieldString; Utils.GetOffsetAndCountFromRequest(context, 100, out limit, out offset, out sortDir, out sortFieldString); // Attempt to read the sort field. If a parsing error occurs, default to undefined. UsersSortField sortField = UsersSortField.UNDEFINED; if (!String.IsNullOrEmpty(sortFieldString)) { try { sortField = SysUtil.ChangeType <UsersSortField>(sortFieldString.Replace('.', '_')); } catch { } } uint?serviceid = context.GetParam <uint>("authprovider", 0); if ((serviceid ?? 0) == 0) { serviceid = null; } string usernamefilter = context.GetParam("usernamefilter", null); string realnamefilter = context.GetParam("fullnamefilter", null); string usernameemailfilter = context.GetParam("usernameemailfilter", null); string rolefilter = context.GetParam("rolefilter", null); bool? activatedfilter = null; bool parsedActivatedFilter; if (bool.TryParse(context.GetParam("activatedfilter", null), out parsedActivatedFilter)) { activatedfilter = parsedActivatedFilter; } bool?seatFilter = null; var seatFilterParam = context.GetParam("seatfilter", null); switch (seatFilterParam) { case null: break; case "seated": case "true": seatFilter = true; break; case "unseated": case "false": seatFilter = false; break; case "recommended": return(DekiContext.Current.LicenseManager.GetSeatRecommendations(offset, limit, out totalCount, out queryCount)); default: throw new ArgumentException("invalid value for seatfilter"); } return(DbUtils.CurrentSession.Users_GetByQuery(usernamefilter, realnamefilter, usernameemailfilter, rolefilter, activatedfilter, groupId, serviceid, seatFilter, sortDir, sortField, offset, limit, out totalCount, out queryCount)); }
public void Can_parse_decimal_in_german_locale() { // set foreign locale Thread.CurrentThread.CurrentCulture = new CultureInfo("de-de"); // parse number var value = SysUtil.ChangeType <decimal>(".999"); Assert.AreEqual(0.999d, value); }
private string[] AsStrings(ArrayList values) { string[] result = new string[values.Count]; for (int i = 0; i < values.Count; ++i) { result[i] = SysUtil.ChangeType <string>(values[i]); } return(result); }
/// <summary> /// Get a typed parameter from the Uri. /// </summary> /// <typeparam name="T">Type of the parameter.</typeparam> /// <param name="uri">Input Uri.</param> /// <param name="key">Parameter key.</param> /// <param name="index">Parameter index.</param> /// <param name="def">Default value to return in case parameter does not exist.</param> /// <returns>Parameter value or default.</returns> public static T GetParam <T>(this XUri uri, string key, int index, T def) { string value = uri.GetParam(key, index, null); if (!string.IsNullOrEmpty(value)) { return((T)SysUtil.ChangeType(value, typeof(T))); } return(def); }
public static bool?BoolCast( [DekiScriptParam("value to cast")] object value ) { try { return(SysUtil.ChangeType <bool>(value)); } catch { return(null); } }
/// <summary> /// Get a named parameter. /// </summary> /// <typeparam name="T">Type to convert parameter to.</typeparam> /// <param name="key"><see cref="DreamFeatureParamAttribute"/> name.</param> /// <returns>Parameter value converted to requested type.</returns> public T GetParam <T>(string key) { string result = GetParam(key); try { return((T)SysUtil.ChangeType(result, typeof(T))); } catch { throw new DreamAbortException(DreamMessage.BadRequest(string.Format("invalid value for feature parameter '{0}'", key))); } }
public void Can_parse_float_in_us_locale() { // set foreign locale Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us"); // parse number var value = SysUtil.ChangeType <float>(".999"); Assert.AreEqual(0.999f, value); }
//--- Methods --- /// <summary> /// Load the configuration into a builder /// </summary> /// <param name="builder">Container builder to public.</param> protected override void Load(ContainerBuilder builder) { if (builder == null) { throw new ArgumentNullException("builder"); } foreach (var component in _config["component"]) { var componentDebug = new DebugStringBuilder(_log.IsDebugEnabled); var implementationTypename = component["@implementation"].AsText; var type = LoadType(component["@type"]); IRegistrationBuilder <object, ConcreteReflectionActivatorData, SingleRegistrationStyle> registrar; var name = component["@name"].AsText; if (string.IsNullOrEmpty(implementationTypename)) { componentDebug.AppendFormat("registering concrete type '{0}'", type.FullName); registrar = builder.RegisterType(type); } else { var concreteType = LoadType(implementationTypename); componentDebug.AppendFormat("registering concrete type '{0}' as '{1}'", concreteType.FullName, type.FullName); registrar = builder.RegisterType(concreteType).As(new TypedService(type)); } if (!string.IsNullOrEmpty(name)) { registrar.Named(name, type); componentDebug.AppendFormat("named '{0}'", name); } registrar.WithParameters( (from parameter in component["parameters/parameter"] let parameterName = parameter["@name"].AsText let parameterValue = parameter["@value"].AsText select new ResolvedParameter( (p, c) => p.Name == parameterName, (p, c) => SysUtil.ChangeType(parameterValue, p.ParameterType)) ).Cast <Parameter>()); // set scope DreamContainerScope scope = _defaultScope; var strScope = component["@scope"].AsText; if (strScope != null) { scope = SysUtil.ParseEnum <DreamContainerScope>(strScope); } componentDebug.AppendFormat(" in '{0}' scope", scope); registrar.InScope(scope); if (_log.IsDebugEnabled) { _log.Debug(componentDebug.ToString()); } } }
private static DreamFeatureAdapter MakeConvertingContextParamGetter(string name, Type type) { return(new DreamFeatureAdapter(name, (context, request, response) => { object value = context.GetParam(name, null); if (value != null) { value = SysUtil.ChangeType(value, type); } return value ?? (type.IsValueType ? Activator.CreateInstance(type) : null); })); }
public override Group[] GetGroups() { List <Group> groups = new List <Group>(); _catalog.NewQuery(string.Format("SELECT title FROM {0}usergroup WHERE {0}usergroup.forumpermissions!=0", _tablePrefix)).Execute(delegate(IDataReader reader) { while (reader.Read()) { groups.Add(new Group(SysUtil.ChangeType <string>(reader[0]))); } }); return(groups.ToArray()); }
//--- Methods --- private Yield FetchResult(string name, XUri input, Hashtable args, Result <XDoc> response) { // build uri XUri uri = new XUri("http://www.dapper.net/RunDapp?v=1").With("dappName", name); if (input != null) { uri = uri.With("applyToUrl", input.ToString()); } if (args != null) { foreach (DictionaryEntry entry in args) { uri = uri.With(VARIABLE_PREFIX + SysUtil.ChangeType <string>(entry.Key), SysUtil.ChangeType <string>(entry.Value)); } } // check if we have a cached result XDoc result; string key = uri.ToString(); lock (_cache) { if (_cache.TryGetValue(key, out result)) { response.Return(result); yield break; } } // fetch result Result <DreamMessage> res; yield return(res = Plug.New(uri).GetAsync()); if (!res.Value.IsSuccessful) { throw new DreamInternalErrorException(string.Format("Unable to process Dapp: ", input)); } if (!res.Value.HasDocument) { throw new DreamInternalErrorException(string.Format("Dapp response is not XML: ", input)); } // add result to cache and start a clean-up timer lock (_cache) { _cache[key] = res.Value.ToDocument(); } TaskTimer.New(TimeSpan.FromSeconds(CACHE_TTL), RemoveCachedEntry, key, TaskEnv.None); response.Return(res.Value.ToDocument()); yield break; }
public static double?NumberCast( [DekiScriptParam("value to cast")] object value ) { if (value == null) { return(null); } try { return(SysUtil.ChangeType <double>(value)); } catch { return(null); } }
/// <summary> /// Get a named parameter. /// </summary> /// <typeparam name="T">Type to convert parameter to.</typeparam> /// <param name="key"><see cref="DreamFeatureParamAttribute"/> name.</param> /// <param name="def">Default value to return in case parameter is not defined.</param> /// <returns>Parameter value converted to requested type.</returns> public T GetParam <T>(string key, T def) where T : struct { string result = GetParam(key, null); if (result != null) { try { return((T)SysUtil.ChangeType <T>(result)); } catch { throw new DreamAbortException(DreamMessage.BadRequest(string.Format("invalid value for feature parameter '{0}'", key))); } } return(def); }
public static T?GetInstanceSettingsValueAs <T>(string key) where T : struct { string value = GetInstanceSettingsValue(key, null); if (value == null) { return(null); } try { return(SysUtil.ChangeType <T>(value)); } catch (Exception e) { _log.WarnExceptionFormat(e, "Unexpected format of configuration setting '{0}'", key); return(null); } }
public static T GetInstanceSettingsValueAs <T>(string key, T def) { var value = GetInstanceSettingsValue(key, null); if (value == null) { return(def); } try { return(SysUtil.ChangeType <T>(value)); } catch (Exception e) { _log.WarnExceptionFormat(e, "Unable to convert configuration setting '{0}' to type '{1}'", key, typeof(T)); return(def); } }
public static string UriAppendQuery( [DekiScriptParam("base uri")] XUri uri, [DekiScriptParam("query parameters to append")] Hashtable args ) { foreach (DictionaryEntry entry in args) { string value = SysUtil.ChangeType <string>(entry.Value); if (value != null) { uri = uri.With((string)entry.Key, value); } } return(uri.ToString()); }
public bool TryGetValue(DekiScriptLiteral index, out DekiScriptLiteral value) { if (index == null) { throw new ArgumentNullException("index"); } if ((index.ScriptType == DekiScriptType.NUM) || (index.ScriptType == DekiScriptType.STR)) { return(TryGetValue(SysUtil.ChangeType <string>(index.NativeValue), out value)); } else { throw new DekiScriptBadTypeException(Location.None, index.ScriptType, new[] { DekiScriptType.NUM, DekiScriptType.STR }); } }
public T EnvAt <T>(string path) { if (path == null) { throw new ArgumentNullException("path"); } DekiScriptMap env = DreamContext.Current.GetState <DekiScriptMap>(); if (env == null) { return(default(T)); } DekiScriptLiteral value = env.GetAt(path); return(SysUtil.ChangeType <T>(value.NativeValue)); }
public DekiScriptLiteral this[DekiScriptLiteral index] { get { if (index == null) { return(DekiScriptNil.Value); } if (index.ScriptType == DekiScriptType.NUM) { return(this[SysUtil.ChangeType <int>(index.NativeValue)]); } else { return(DekiScriptNil.Value); } } }
/// <summary> /// Retrieve an output/return value from the finished command. /// </summary> /// <typeparam name="T">Returned value type</typeparam> /// <param name="key">Name of returned parameter (provided previously using 'WithOutput()' or 'WithInOut()' or 'WithReturn()'</param> /// <param name="def">Value to return if returned value is null or DbNull</param> /// <returns>Converted value</returns> public T At <T>(string key, T def) { object value = ((IDataParameter)_command.Parameters[_factory.ParameterChar + key]).Value; if (value == null) { return(def); } if (value is DBNull) { return(def); } if (value is T) { return((T)value); } return((T)SysUtil.ChangeType(value, typeof(T))); }