public override void Setup(IDictionary<string, object> table) { table.AddOrSet("config", ConfigStr); table.AddOrSet("cpath", Environment.GetEnvironmentVariable("LUA_CPATH_5_2") ?? Environment.GetEnvironmentVariable("LUA_CPATH") ?? String.Join(";", new[] { "!\\?.dll", "!\\loadall.dll", ".\\?.dll" })); table.AddOrSet("path", Environment.GetEnvironmentVariable("LUA_PATH_5_2") ?? Environment.GetEnvironmentVariable("LUA_PATH") ?? String.Join(";", new[] { "!\\lua\\" + "?.lua", "!\\lua\\" + "?\\init.lua", "!\\" + "?.lua", "!\\" + "?\\init.lua", ".\\?.lua" })); table.AddOrSet("loaded", new LuaTable(Context)); table.AddOrSet("preload", new LuaTable(Context)); table.AddOrSet("searchers", new LuaTable(Context)); // TODO: fill with searchers table.AddOrSet("loadlib", (Func<string, string, object>)Loadlib); table.AddOrSet("searchpath", (Func<string, string, string, string, object>) SearchPath); }
public static void AddOrSetAll <TK, TV>(this IDictionary <TK, TV> dictionary, IEnumerable <KeyValuePair <TK, TV> > enumer) { foreach (KeyValuePair <TK, TV> kvp in enumer) { dictionary.AddOrSet(kvp.Key, kvp.Value); } }
private bool AddPackageProvider(string name, IPackageProvider provider, ulong version, IRequest request) { // wrap this in a caller-friendly wrapper lock (_packageProviders) { if (_packageProviders.ContainsKey(name)) { if (version > _packageProviders[name].Version) { // remove the old provider first. // todo: this won't remove the plugin domain and unload the code yet // we'll have to do that later. _packageProviders.Remove(name); } else { return(false); } } request.Debug("Loading provider {0}".format(name, provider.GetPackageProviderName())); provider.InitializeProvider(request); _packageProviders.AddOrSet(name, new PackageProvider(provider) { Version = version }).Initialize(request); } return(true); }
private bool AddDownloader(string name, IDownloader provider, ulong version, IRequest request) { lock (Downloaders) { if (Downloaders.ContainsKey(name)) { if (version > Downloaders[name].Version) { // remove the old provider first. // todo: this won't remove the plugin domain and unload the code yet // we'll have to do that later. Downloaders.Remove(name); } else { return(false); } } request.Debug("Loading Downloader {0}".format(name, provider.GetDownloaderName())); provider.InitializeProvider(request); Downloaders.AddOrSet(name, new Downloader(provider) { Version = version }).Initialize(request); } return(true); }
internal static TValue GetOrCreateEntryIfDefault <TKey, TValue>(this IDictionary <TKey, TValue> dictionary, TKey key, Func <TValue> valueFunction) { lock (dictionary) { return(dictionary.ContainsKey(key) ? dictionary[key] : dictionary.AddOrSet(key, valueFunction())); } }
protected override bool ReceiveRecover(object message) { return(message.Match() .With <CustomerIndexed>(e => { _customers.AddOrSet(e.Customer.Id, e.Customer); }) .With <CustomerRemovedEvent>(e => { _customers.Remove(e.Id); }) .With <SnapshotOffer>(offer => { _customers = (Dictionary <Guid, CustomerEntity>)offer.Snapshot; }) .WasHandled); }
public static TValue GetOrAdd <TKey, TValue>(this IDictionary <TKey, TValue> dictionary, TKey key, Func <TValue> valueFunction) { lock (dictionary) { return(dictionary.ContainsKey(key) ? dictionary[key] : dictionary.AddOrSet(key, valueFunction())); } }
public static IDictionary <string, object> Merge(this IDictionary <string, object> dictionary, IDictionary <string, object> merge) { foreach (var kvp in merge) { dictionary.AddOrSet(kvp); } return(dictionary); }
internal bool RegisterProvidersViaMetaProvider(IMetaProvider provider, FourPartVersion asmVersion, IHostApi request) { var found = false; var metaProviderName = provider.GetMetaProviderName(); FourPartVersion metaProviderVersion = provider.GetProviderVersion(); if (!_metaProviders.ContainsKey(metaProviderName)) { // Meta Providers can't be replaced at this point _metaProviders.AddOrSet(metaProviderName, provider); } try { provider.InitializeProvider(request.As <IRequest>()); var metaProvider = provider; provider.GetProviderNames().ParallelForEach(name => { // foreach (var name in provider.GetProviderNames()) { var instance = metaProvider.CreateProvider(name); if (instance != null) { // check if it's a Package Provider if (typeof(IPackageProvider).CanDynamicCastFrom(instance)) { try { found = found | RegisterPackageProvider(instance.As <IPackageProvider>(), asmVersion, request); } catch (Exception e) { e.Dump(); } } // check if it's a Services Provider if (typeof(IArchiver).CanDynamicCastFrom(instance)) { try { found = found | RegisterArchiver(instance.As <IArchiver>(), asmVersion, request); } catch (Exception e) { e.Dump(); } } if (typeof(IDownloader).CanDynamicCastFrom(instance)) { try { found = found | RegisterDownloader(instance.As <IDownloader>(), asmVersion, request); } catch (Exception e) { e.Dump(); } } } }); } catch (Exception e) { e.Dump(); } return(found); }
private bool AddMetaProvider(string name, IMetaProvider provider, ulong version, IRequest request) { // wrap this in a caller-friendly wrapper if (_metaProviders.ContainsKey(name)) { // Meta Providers can't be replaced at this point return(false); } _metaProviders.AddOrSet(name, provider); return(true); }
private void AddCommandNames(IEnumerable <PSObject> cmdsOrAliases) { foreach (var item in cmdsOrAliases) { var cmdName = GetPropertyValue(item, "Name").ToLower(CultureInfo.CurrentCulture); var name = cmdName.Replace("-", ""); if (name.Is()) { _commands.AddOrSet(name, item); } } }
private Downloader RegisterDownloader(IDownloader provider, FourPartVersion asmVersion, IHostApi request) { string name = null; try { FourPartVersion ver = provider.GetProviderVersion(); var version = ver == 0 ? asmVersion : ver; name = provider.GetDownloaderName(); if (string.IsNullOrWhiteSpace(name)) { return(null); } // Initialize the provider before locking the collection // that way we're not blocking others on non-deterministic actions. request.Debug("Initializing provider '{0}'".format(name)); provider.InitializeProvider(request.As <IRequest>()); request.Debug("Provider '{0}' Initialized".format(name)); lock (Downloaders) { if (Downloaders.ContainsKey(name)) { if (version > Downloaders[name].Version) { // remove the old provider first. // todo: this won't remove the plugin domain and unload the code yet // we'll have to do that later. Downloaders.Remove(name); } else { return(null); } } request.Debug("Using Downloader Provider {0}".format(name)); var downloader = new Downloader(provider) { Version = version }; downloader.Initialize(request); Downloaders.AddOrSet(name, downloader); return(downloader); } } catch (Exception e) { request.Debug("Provider '{0}' Failed".format(name)); e.Dump(); } return(null); }
private void Index(Group group) { _groups.AddOrSet(group.ID, group); foreach (var entry in group.Entries) { _entries.AddOrSet(entry.ID, entry); } foreach (var child in group.Groups) { Index(child); } }
public void Add(Field field) { if (field == null) { throw new ArgumentNullException("field"); } if (_fields.Values.Count(p => p.Equals(field)) > 1) { throw new ArgumentException("Duplicate Exception", string.Format("duplicate found for {0}", field.Name)); } if (!_fields.Values.Contains(field)) { _fields.AddOrSet(field.Name, field); } }
public override void Setup(IDictionary<string, object> table) { table.AddOrSet("time", (Func<LuaTable, double>)Time ); table.AddOrSet("difftime", (Func<double, double, double>) ((t2, t1) => t2 - t1)); //table.AddOrSet("date", (Func<object, object>)Date); // TODO table.AddOrSet("exit", (Action<double>)(e => Environment.Exit((int)e))); table.AddOrSet("getenv", (Func<string, string>) Environment.GetEnvironmentVariable); table.AddOrSet("remove", (Func<string, object>) Delete); table.AddOrSet("rename", (Func<string, string, object>) Rename); }
private bool AddServicesProvider(string name, IServicesProvider provider, ulong version, IRequest request) { if (_servicesProviders.ContainsKey(name)) { if (version > _servicesProviders[name].Version) { // remove the old provider first. // todo: this won't remove the plugin domain and unload the code yet // we'll have to do that later. _servicesProviders.Remove(name); } else { return(false); } } _servicesProviders.AddOrSet(name, new ServicesProvider(provider) { Version = version }).Initialize(request); return(true); }
internal bool RegisterProvidersViaMetaProvider(IMetaProvider provider, FourPartVersion asmVersion, IHostApi request) { var found = false; var metaProviderName = provider.GetMetaProviderName(); lock (_metaProviders) { if (!_metaProviders.ContainsKey(metaProviderName)) { // Meta Providers can't be replaced at this point _metaProviders.AddOrSet(metaProviderName, provider); } } try { provider.InitializeProvider(request.As <IRequest>()); provider.GetProviderNames().ParallelForEach(name => { found = LoadViaMetaProvider(provider, name, asmVersion, request); }); } catch (Exception e) { e.Dump(); } return(found); }
private bool RegisterDownloader(IDownloader provider, FourPartVersion asmVersion, IHostApi request) { try { FourPartVersion ver = provider.GetProviderVersion(); var version = ver == 0 ? asmVersion : ver; var name = provider.GetDownloaderName(); lock (Downloaders) { if (Downloaders.ContainsKey(name)) { if (version > Downloaders[name].Version) { // remove the old provider first. // todo: this won't remove the plugin domain and unload the code yet // we'll have to do that later. Downloaders.Remove(name); } else { return(false); } } request.Debug("Loading Downloader {0}".format(name, provider.GetDownloaderName())); provider.InitializeProvider(request.As <IRequest>()); Downloaders.AddOrSet(name, new Downloader(provider) { Version = version }).Initialize(request); } return(true); } catch (Exception e) { e.Dump(); } return(false); }
public static IDictionary <string, object> AddOrSet(this IDictionary <string, object> dictionary, KeyValuePair <string, object> keyValuePair) { return(dictionary.AddOrSet(keyValuePair.Key, keyValuePair.Value)); }
public override void Setup(IDictionary<string,object> table) { const double Math_Tau = 2.0 * Math.PI; // http://tauday.com table.AddOrSet("huge", Double.MaxValue); // Basic operations table.AddOrSet("abs", (Func<double, double>)Math.Abs); table.AddOrSet("mod", (Func<double, double, double>)((a, b) => a % b)); table.AddOrSet("modf", (Func<double, double, Varargs>)((a, b) => { long r; long q = Math.DivRem((long) a, (long) b, out r); return new Varargs(q, r); })); table.AddOrSet("floor", (Func<double, double>) Math.Floor); table.AddOrSet("ceil", (Func<double, double>) Math.Ceiling); table.AddOrSet("min", (Func<double, double, double>) Math.Min); table.AddOrSet("max", (Func<double, double, double>) Math.Max); // Exponetial and logarithmic table.AddOrSet("sqrt", (Func<double, double>) Math.Sqrt); table.AddOrSet("pow", (Func<double, double, double>) Math.Pow); table.AddOrSet("exp", (Func<double, double>) Math.Exp); table.AddOrSet("log", (Func<double, double>) Math.Log); table.AddOrSet("log10", (Func<double, double>) Math.Log10); // Trigonometrical table.AddOrSet("pi", Math.PI); table.AddOrSet("tau", Math_Tau); table.AddOrSet("deg", (Func<double, double>)(r => r * 360.0 / Math_Tau)); table.AddOrSet("rad", (Func<double, double>)(d => d / 360.0 * Math_Tau)); table.AddOrSet("cos", (Func<double, double>) Math.Cos); table.AddOrSet("sin", (Func<double, double>) Math.Sin); table.AddOrSet("tan", (Func<double, double>)Math.Tan); table.AddOrSet("acos", (Func<double, double>)Math.Acos); table.AddOrSet("asin", (Func<double, double>)Math.Asin); table.AddOrSet("atan", (Func<double, double>)Math.Atan); table.AddOrSet("atan2", (Func<double, double, double>)Math.Atan2); // Splitting on powers of 2 //table.AddOrSet("frexp", (Func<double, double>) Math.??); //table.AddOrSet("ldexp", (Func<double, double, double>) Math.??); // Pseudo-random numbers table.AddOrSet("randomseed", (Func<double, double>)(x => { rand = new Random((int)x); return rand.NextDouble(); })); table.AddOrSet("random", (Func<Varargs, double>)Random); // overloaded }
/// <summary> /// TBD /// </summary> /// <typeparam name="TKey">TBD</typeparam> /// <typeparam name="TValue">TBD</typeparam> /// <param name="hash">TBD</param> /// <param name="key">TBD</param> /// <param name="value">TBD</param> /// <returns>TBD</returns> public static IDictionary <TKey, TValue> AddAndReturn <TKey, TValue>(this IDictionary <TKey, TValue> hash, TKey key, TValue value) { hash.AddOrSet(key, value); return(hash); }
public override void Setup(IDictionary<string, object> table) { table.AddOrSet("getlocal", (Func<object, object, Varargs>)GetLocal); table.AddOrSet("setlocal", (Func<object, object, object, object>)SetLocal); }
/* ----------------------------------------------------------------- */ /// /// AddOrSet(T, U) /// /// <summary> /// Adds or sets the specified key-value pair. /// </summary> /// /// <param name="src">Dictionary collection.</param> /// <param name="key">Key element to be set.</param> /// <param name="value">Value element to be set.</param> /// /* ----------------------------------------------------------------- */ public static void AddOrSet <T, U>(this IDictionary <T, U> src, T key, U value) => src.AddOrSet(key, value, (x, y) => y);
public static TValue GetOrSetIfDefault <TKey, TValue>(this IDictionary <TKey, TValue> dictionary, TKey key, Func <TValue> valueFunction) { lock (dictionary) { return(!dictionary.ContainsKey(key) || ((object)default(TValue) == (object)dictionary[key]) ? dictionary.AddOrSet(key, valueFunction()) : dictionary[key]); } }
public override void Setup(IDictionary<string, object> table) { table.AddOrSet("len", (Func<string, double>) (s => s.Length)); table.AddOrSet("upper", (Func<string, string>) (s => s.ToUpperInvariant())); table.AddOrSet("lower", (Func<string, string>)(s => s.ToLowerInvariant())); table.AddOrSet("rep", (Func<string, double, string>) ((s, r) => s.Repeat((int)Math.Round(r, MidpointRounding.ToEven)))); table.AddOrSet("sub", (Func<string, double, double, string>)Subst); // TODO: varargs table.AddOrSet("char", (Func<double[], string>) Char); // TODO: varargs table.AddOrSet("byte", (Func<string, double, double, double[]>) Byte); // TODO: varargs table.AddOrSet("find", (Func<string, string, int?, bool?, object[]>)Find); }
/* * // not needed anymore, we do the type resolution ourselves now. * * private static readonly string[] _hideKnownAssemblies = new[] { * "ServiceStack", // exclude the service stack assembly * "ClrPlus", * "b03f5f7f11d50a3a", // Microsoft * "b77a5c561934e089", // Microsoft * "31bf3856ad364e35" // Microsoft * }; * * private static IEnumerable<Assembly> GetActiveAssemblies() { * return AppDomain.CurrentDomain.GetAssemblies().Where(each => !_hideKnownAssemblies.Any(x => each.FullName.IndexOf(x) > -1)); * } */ public override void Configure(Container container) { _configured = true; // Feature disableFeatures = Feature.Jsv | Feature.Soap; SetConfig(new EndpointHostConfig { // EnableFeatures = Feature.All.Remove(disableFeatures), //all formats except of JSV and SOAP DebugMode = true, //Show StackTraces in service responses during development WriteErrorsToResponse = false, //Disable exception handling DefaultContentType = ContentType.Json, //Change default content type AllowJsonpRequests = true, //Enable JSONP requests ServiceName = "RestService", }); #if DEBUG LogManager.LogFactory = new DebugLogFactory(); #endif using (var ps = RunspacePool.Dynamic()) { foreach (var restCommand in _activeCommands) { PSObject command = ps.LookupCommand(restCommand.Name); if (command != null) { var cmdletInfo = (command.ImmediateBaseObject as CmdletInfo); if (cmdletInfo != null) { dynamic d = new AccessPrivateWrapper((ServiceController as ServiceController)); // for each type we're adding, see if it's already been added already. if (!d.requestExecMap.ContainsKey(cmdletInfo.ImplementingType)) { (ServiceController as ServiceController).RegisterGService(GetTypeFactory(cmdletInfo.ImplementingType), cmdletInfo.ImplementingType); (ServiceController as ServiceController).RegisterNService(GetTypeFactory(cmdletInfo.ImplementingType), cmdletInfo.ImplementingType); } ReverseLookup.AddOrSet(cmdletInfo.ImplementingType, restCommand); Routes.Add(cmdletInfo.ImplementingType, "/" + restCommand.PublishAs + "/", "GET"); } else { throw new ClrPlusException("command isn't cmdletinfo: {0}".format(command.GetType())); } } } } Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new CustomBasicAuthProvider(), // new CustomCredentialsAuthProvider(), } )); // stick a request filter in to validate that the user has the right to actually // call this method. RequestFilters.Add((request, response, requestDto) => { var restCommand = ReverseLookup[requestDto.GetType()]; // is this one of the restCommands? // and does it has roles defined? if (restCommand != null && !restCommand.Roles.IsNullOrEmpty()) { // ensure we're authenticated if the user passed the right stuff in the request try { AuthenticateAttribute.AuthenticateIfBasicAuth(request, response); } catch (Exception e) { Console.WriteLine(e.Message); response.StatusCode = 401; response.AddHeader("WWW-Authenticate", "Basic realm=\"rest-service\""); response.StatusDescription = "Unauthorized"; response.EndServiceStackRequest(false); return; } // get the session object. var session = request.GetSession(false); // check if we got our authentication. if (!session.IsAuthenticated) { response.StatusCode = 401; response.AddHeader("WWW-Authenticate", "Basic realm=\"rest-service\""); response.StatusDescription = "Unauthorized"; response.EndServiceStackRequest(false); return; } // validate the user has the role. if (!restCommand.Roles.Any(session.HasRole)) { response.StatusCode = 403; response.StatusDescription = "Forbidden"; response.EndServiceStackRequest(false); } var req = (requestDto as IHasSession); if (req != null) { req.Session = session; } } }); }
public static void Set(string path, params string[] locales) => locales.Each(locale => _locales.AddOrSet(locale, new Locale($"{path}/{locale}.json")));
public override void Setup(IDictionary<string, object> table) { table.AddOrSet("import", (Func<string,object[], LuaTable>)ImportType); table.AddOrSet("method", (Func<object, string, object>)InteropGetMethod); table.AddOrSet("call", (Func<object, string, object[], object>)InteropCallMethod); table.AddOrSet("setvalue", (Func<object, string, object, object>)InteropSetValue); table.AddOrSet("getvalue", (Func<object, string, object>)InteropGetValue); table.AddOrSet("subscribe", (Action<object, string, Delegate>)InteropSubscribeEvent); table.AddOrSet("unsubscribe", (Action<object, string, Delegate>)InteropUnsubscribeEvent); table.AddOrSet("makearray", (Func<object, object, object>)MakeArray); table.AddOrSet("iterate", (Func<object, object[], object>)InteropEnumerate); }
private PackageProvider AnalyzeModule(PsRequest request, string modulePath, Version requiredVersion, bool force, PSModuleInfo psModuleInfo = null) { if (string.IsNullOrWhiteSpace(modulePath)) { return(null); } request.Debug("Attempting to load PowerShell Provider Module [{0}]", modulePath); if (string.Equals(Path.GetExtension(modulePath), ".dll", StringComparison.OrdinalIgnoreCase)) { if (psModuleInfo != null) { // fake provider and returns it var result = new PackageProvider(new DefaultPackageProvider(psModuleInfo.Name, psModuleInfo.Version.ToString())) { ProviderPath = modulePath, Version = psModuleInfo.Version, IsLoaded = false }; AddToPackageProviderCacheTable(result); return(result); } else { // psmoduleinfo is only null when this function is called in loadavailableprovider // but in that case we want to load the provider directly anyway so we can do this // if the path is a .dll then we ask packagemanagement to load it for us // it will also register the dll PackageManagementService.LoadProviderAssembly(request, modulePath, true); // now let's checked whether we can find it in the list of loaded providers foreach (var loadedProvider in PackageManagementService.PackageProviders) { // the one loaded should have the same path if (string.Equals(loadedProvider.ProviderPath, modulePath, StringComparison.OrdinalIgnoreCase)) { return(loadedProvider); } } // if we reached here then we have failed to load the provider :( return(null); } } string requiredVersionString = requiredVersion.ToString(); var provider = Create(request, modulePath, requiredVersionString, force); if (provider != null) { var providerName = provider.GetPackageProviderName(); if (!string.IsNullOrWhiteSpace(providerName)) { request.Debug(string.Format(CultureInfo.CurrentCulture, Resources.Messages.SuccessfullyLoadedModule, modulePath)); // looks good to me, let's add this to the list of moduels this meta provider can create. var packageProvider = new PackageProvider(provider.As <IPackageProvider>()) { IsLoaded = true, Version = provider.GetProviderVersion(), ProviderPath = modulePath }; // take out powershell get var psgetprovider = PackageManagementService.PackageProviders.FirstOrDefault(pv => string.Equals(pv.ProviderName, PowerShellGet, StringComparison.OrdinalIgnoreCase)); if (psModuleInfo != null) { // add swidtag information using moduleinfo // however, this won't give us as much information yet // we may have to fill this up later ProvideSwidTagInformation(packageProvider, psModuleInfo); } AddToPackageProviderCacheTable(packageProvider); _availableProviders.AddOrSet(providerName, provider); return(packageProvider); } else { provider.Dispose(); provider = null; request.Debug(string.Format(CultureInfo.CurrentCulture, Resources.Messages.ProviderNameIsNullOrEmpty, modulePath)); } } return(null); }
public void AddMacro(string key, string value) { _macros.AddOrSet(key.ToLower(), value); }