private StringBuilder BuildProxyScript(Incubator incubator, string connectionName = "") { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("$(document).ready(function(){"); if (!string.IsNullOrEmpty(connectionName)) { stringBuilder.AppendFormat("\tdao.{0} = {{}};\r\n", connectionName); } stringBuilder.AppendLine("\t(function(d, $, win){"); stringBuilder.AppendLine("\t\t\"use strict\";"); stringBuilder.AppendLine("\t\td.ctors = d.ctors || {};"); stringBuilder.AppendLine("\t\td.fks = d.fks || [];"); stringBuilder.AppendLine(GetBodyAndMeta(incubator).ToString()); stringBuilder.AppendFormat("\t}})(dao.{0} || dao, jQuery, window || {{}});\r\n", connectionName); stringBuilder.AppendLine("});"); return(stringBuilder); }
/// <summary> /// Instantiate a new SQLiteDatabase instance where the database /// file will be placed into the specified directoryPath using the /// specified connectionName as the file name /// </summary> /// <param name="directoryPath"></param> /// <param name="connectionName"></param> public SQLiteDatabase(string directoryPath, string connectionName) : base() { DirectoryInfo directory = new DirectoryInfo(directoryPath); if (!directory.Exists) { directory.Create(); } ConnectionStringResolver = new SQLiteConnectionStringResolver { Directory = directory }; ConnectionName = connectionName; ServiceProvider = new Incubator(); ServiceProvider.Set <DbProviderFactory>(SQLiteFactory.Instance); Register(); }
public static ExecutionTargetInfo ResolveExecutionTarget(string path, Incubator serviceProvider, ProxyAlias[] proxyAliases) { ExecutionTargetInfo result = new ExecutionTargetInfo(); Queue <string> split = new Queue <string>(path.DelimitSplit("/", ".")); while (split.Count > 0) { string currentChunk = split.Dequeue(); string upperred = currentChunk.ToUpperInvariant(); if (string.IsNullOrEmpty(result.ClassName)) { if (!serviceProvider.HasClass(currentChunk) && proxyAliases != null) { ProxyAlias alias = proxyAliases.Where(pa => pa.Alias.Equals(currentChunk)).FirstOrDefault(); if (alias != null) { result.ClassName = alias.ClassName; } else { result.ClassName = currentChunk; } } else { result.ClassName = currentChunk; } } else if (string.IsNullOrEmpty(result.MethodName)) { result.MethodName = currentChunk; } else if (string.IsNullOrEmpty(result.Ext)) { result.Ext = currentChunk; } } return(result); }
private ProxyAlias[] GetProxyAliases(Incubator incubator) { List <ProxyAlias> results = new List <ProxyAlias>(); results.AddRange(BamConf.ProxyAliases); incubator.ClassNames.Each(cn => { Type currentType = incubator[cn]; ProxyAttribute attr; if (currentType.HasCustomAttributeOfType <ProxyAttribute>(out attr)) { if (!string.IsNullOrEmpty(attr.VarName) && !attr.VarName.Equals(currentType.Name)) { results.Add(new ProxyAlias(attr.VarName, currentType)); } } }); return(results.ToArray()); }
public void ExecuteOrderedParamsTest() { Incubator inc = new Incubator(); inc.Set(new Echo()); string value = "hello there ".RandomLetters(8); object id = "some value"; string inputString = "{{'jsonrpc': '2.0', 'method': 'Send', 'id': '{0}', 'params': ['{1}']}}"._Format(id, value); IHttpContext context = GetPostContextWithInput(inputString); IJsonRpcRequest parsed = JsonRpcMessage.Parse(context); JsonRpcRequest request = (JsonRpcRequest)parsed; request.Incubator = inc; JsonRpcResponse response = request.Execute(); Expect.IsTrue(response.GetType().Equals(typeof(JsonRpcResponse))); Expect.AreEqual(value, response.Result); Expect.IsNull(response.Error); Expect.AreEqual(id, response.Id); }
public void RegisterProxiedClasses() { string serviceProxyRelativePath = ServiceProxyRelativePath; List <string> registered = new List <string>(); ForEachProxiedClass((type) => { this.AddCommonService(type, type.Construct()); }); BamConf.AppConfigs.Each(appConf => { string name = appConf.Name.ToLowerInvariant(); Incubator serviceProvider = new Incubator(); AppServiceProviders[name] = new Incubator(); DirectoryInfo appServicesDir = new DirectoryInfo(appConf.AppRoot.GetAbsolutePath(serviceProxyRelativePath)); if (appServicesDir.Exists) { Action <Type> serviceAdder = (type) => { object instance; if (type.TryConstruct(out instance, ex => Logger.AddEntry("RegisterProxiedClasses: Unable to construct instance of type {0}: {1}", ex, type.Name, ex.Message))) { SubscribeIfLoggable(instance); AddAppService(appConf.Name, instance); } }; ForEachProxiedClass(appServicesDir, serviceAdder); ForEachProxiedClass(appConf, appServicesDir, serviceAdder); } else { Logger.AddEntry("{0} directory not found", LogEventType.Warning, appServicesDir.FullName); } AddConfiguredServiceProxyTypes(appConf); }); }
public static void ShouldRecreateSchemaSQLite() { Database reproduceIn = RegisterSQLiteForConnection("ReproSchemaSQLite"); DropAllTables(reproduceIn); Incubator sp = reproduceIn.ServiceProvider; SQLiteRegistrar.Register(reproduceIn.ServiceProvider); SchemaWriter writer = sp.GetNew <SchemaWriter>(); Expect.IsTrue(writer is SQLiteSqlStringBuilder); Expect.IsTrue(writer.WriteSchemaScript <Item>(), "WriteSchemaScript returned false instead of true"); Exception e; bool executeResult = writer.TryExecute(reproduceIn, out e); Expect.IsNull(e, e == null ? "" : e.Message); // no exception should have occurred Expect.IsTrue(executeResult, "TryExecute returned false instead of true"); Expect.IsFalse(writer.WriteSchemaScript <Item>(), "WriteSchemaScript returned true instead of false"); }
public void EnemyBuilding_LevelUp(out GameObject current) { GameObject cur_building = Enemy_CurrentBuildingBase.GetComponent <BulidingControl>().CurrentBuilding; var Buildingscript = cur_building.GetComponent <Incubator>(); if (Buildingscript.NextLevel.GetComponent <Incubator>().ResourceCost <= GameManager.EnemyResources) { GameManager.EnemyResources -= Buildingscript.NextLevel.GetComponent <Incubator>().ResourceCost; GameObject go = Instantiate(Buildingscript.NextLevel, Enemy_CurrentBuildingBase.transform); go.transform.Rotate(go.transform.up, 180); Destroy(cur_building); go.tag = "EnemyControl"; Incubator buildingscript = go.GetComponent <Incubator>(); buildingscript.UI_View = Enemy_CurrentBuildingBase.GetComponent <BulidingControl>().UI_View; Enemy_CurrentBuildingBase.GetComponent <BulidingControl>().CurrentBuilding = go; current = go; } else { current = null; } }
public override void ExecuteResult(ControllerContext context) { StringBuilder output = new StringBuilder(); if (string.IsNullOrEmpty(ClassName)) { Tag message = new Tag("div", new { Class = "error" }).Text("ClassName not specified"); output = new StringBuilder(message.ToHtmlString()); } else { Incubator incubator = ServiceProxySystem.Incubator; Type type; incubator.Get(ClassName, out type); if (type == null) { Tag message = new Tag("div", new { Class = "error" }).Text("The specified className ({0}) was not registered in the ServiceProxySystem"._Format(ClassName)); output = new StringBuilder(message.ToHtmlString()); } else { InputFormBuilder formBuilder = new InputFormBuilder(type); formBuilder.Layout = Layout; Dictionary <string, object> defaults = new Dictionary <string, object>(); if (Defaults != null) { defaults = Defaults.PropertiesToDictionary(); } TagBuilder tag = formBuilder.MethodForm(MethodName, defaults); output = new StringBuilder(tag.ToMvcHtml().ToString()); } } HttpResponseBase response = context.HttpContext.Response; response.Write(output.ToString()); }
public void PlayerBuilding_LevelUp() { GameObject cur_building = Player_CurrentBuildingBase.GetComponent <BulidingControl>().CurrentBuilding; if (cur_building) { var Buildingscript = cur_building.GetComponent <Incubator>(); if (Buildingscript.NextLevel) { if (Buildingscript.NextLevel.GetComponent <Incubator>().ResourceCost <= GameManager.PlayerResources) { GameManager.PlayerResources -= Buildingscript.NextLevel.GetComponent <Incubator>().ResourceCost; GameObject go = Instantiate(Buildingscript.NextLevel, Player_CurrentBuildingBase.transform); Destroy(cur_building); go.tag = "PlayerControl"; Incubator buildingscript = go.GetComponent <Incubator>(); buildingscript.UI_View = Player_CurrentBuildingBase.GetComponent <BulidingControl>().UI_View; Player_CurrentBuildingBase.GetComponent <BulidingControl>().CurrentBuilding = go; GetBuildingData(); } else { WarningInfo.GetComponent <Text>().text = "资源不足"; Instantiate(WarningInfo, WarningParent); } } else { WarningInfo.GetComponent <Text>().text = "建筑已达到最大等级"; Instantiate(WarningInfo, WarningParent); } } else { Debug.Log("CurrentBuilding is empty"); } }
// PUT: odata/Incubators(5) public IHttpActionResult Put([FromODataUri] int key, Delta <Incubator> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Incubator incubator = db.Incubators.Find(key); if (incubator == null) { return(NotFound()); } patch.Put(incubator); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!IncubatorExists(key)) { return(NotFound()); } else { throw; } } return(Updated(incubator)); }
public void Can_clone_DtoWithDictionary() { var expected = new DtoWithDictionary() { Lookup = new Dictionary <string, Simple>() { { "foo", new Simple() { Id = 1 } }, { "bar", new Simple() { Id = 2 } }, } }; var clone = Incubator.Clone(expected); Assert.AreNotSame(expected, clone); Assert.AreNotSame(expected.Lookup, clone.Lookup); Assert.AreEqual(expected.Lookup.Keys.OrderBy(x => x).ToArray(), clone.Lookup.Keys.OrderBy(x => x).ToArray()); Assert.AreNotSame(expected.Lookup["foo"], clone.Lookup["foo"]); Assert.AreEqual(expected.Lookup["foo"].Id, clone.Lookup["foo"].Id); }
public static bool Prefix(Incubator __instance, GUIHand hand) { if (skipPrefix) { return(true); } // Request a simulation lock on the incubator so that we can authoritatively spawn the resulting creatures if (__instance.powered && !__instance.hatched && Inventory.main.container.Contains(TechType.HatchingEnzymes)) { SimulationOwnership simulationOwnership = NitroxServiceLocator.LocateService <SimulationOwnership>(); // the server only knows about the the main incubator platform which is the direct parent GameObject platform = __instance.gameObject.transform.parent.gameObject; NitroxId id = NitroxEntity.GetId(platform); HandInteraction <Incubator> context = new HandInteraction <Incubator>(__instance, hand); LockRequest <HandInteraction <Incubator> > lockRequest = new LockRequest <HandInteraction <Incubator> >(id, SimulationLockType.EXCLUSIVE, ReceivedSimulationLockResponse, context); simulationOwnership.RequestSimulationLock(lockRequest); } return(false); }
public static JsonRpcRequest Create <T>(Incubator incubator, string methodName, params object[] parameters) { return(Create <T>(incubator, (object)Guid.NewGuid().ToString(), methodName, parameters)); }
public void Register(Incubator incubator) { FirebirdSqlRegistrar.Register(incubator); }
/// <summary> /// Register the speicified generic type T as a ServiceProxy responder. /// </summary> /// <typeparam name="T"></typeparam> public static void Register <T>() { Initialize(); Incubator.Construct <T>(); }
public Simulator(Environment environment, byte[] Code) { this._code = Code; this._environment = environment; Incubator incubator = new Incubator(); SimulatedCreature = incubator.Incubate(_code); SimulatedCreature.CreatureAboutToDigest += (sender, e) => { if (CreatureAboutToDigest != null) { CreatureAboutToDigest(sender, e); } }; SimulatedCreature.CreatureDigestionCostRemoved += (sender, e) => { if (CreatureDigestionCostRemoved != null) { CreatureDigestionCostRemoved(sender, e); } }; SimulatedCreature.CreatureEnzymeCostRemoved += (sender, e) => { if (CreatureEnzymeCostRemoved != null) { CreatureEnzymeCostRemoved(sender, e); } }; SimulatedCreature.EatDecisionPredicatePrepared += (sender, e) => { if (EatDecisionPredicatePrepared != null) { EatDecisionPredicatePrepared(sender, e); } }; SimulatedCreature.EatDecisionResolved += (sender, e) => { if (EatDecisionResolved != null) { EatDecisionResolved(sender, e); } }; SimulatedCreature.PotentialExtractionCalcaulated += (sender, e) => { if (PotentialExtractionCalcaulated != null) { PotentialExtractionCalcaulated(sender, e); } }; SimulatedCreature.ActualEnergyExtracted += (sender, e) => { if (ActualEnergyExtracted != null) { ActualEnergyExtracted(sender, e); } }; SimulatedCreature.EnzymeEvaluated += (sender, e) => { if (EnzymeEvaluated != null) { EnzymeEvaluated(sender, e); } }; SimulatedCreature.EnzymeProcessCompleted += (sender, e) => { if (EnzymeProcessCompleted != null) { EnzymeProcessCompleted(sender, e); } }; SimulatedCreature.CreatureDied += (sender, e) => { if (CreatureDied != null) { CreatureDied(sender, e); } }; }
public ExecutionRequestResolver(Incubator serviceContainer) { }
public ExecutionRequest(RequestWrapper request, ResponseWrapper response, ProxyAlias[] aliases, Incubator serviceProvider) : this(request, response, aliases) { Context = new HttpContextWrapper(); ServiceProvider = serviceProvider; OnAnyInstanciated(this); }
public static void Unregister <T>() { Incubator.Remove <T>(); }
/// <summary> /// Register the instance of T. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance"></param> public static void Register <T>(T instance) { Initialize(); Incubator.Set <T>(instance); }
public void ClearCommonServices() { _commonServiceProvider = new Incubator(); AddCommonService(_commonSecureChannel); }
public static StringBuilder GenerateCSharpProxyCode(string defaultBaseAddress, string[] classNames, string nameSpace, string contractNamespace, Incubator incubator, ILogger logger = null, bool includeLocalMethods = false) { logger = logger ?? Log.Default; List <Type> types = new List <Type>(); classNames.Each(new { Logger = logger, Types = types }, (ctx, cn) => { Type type = incubator[cn]; if (type == null) { ctx.Logger.AddEntry("Specified class name was not registered: {0}", LogEventType.Warning, cn); } else { ctx.Types.Add(type); } }); Args.ThrowIf(types.Count == 0, "None of the specified classes were found: {0}", string.Join(", ", classNames)); return(GenerateCSharpProxyCode(defaultBaseAddress, nameSpace, contractNamespace, types.ToArray(), includeLocalMethods)); }
public static SecureExecutionRequest Create <T>(IHttpContext context, string methodName, Incubator serviceProvider, params object[] parameters) { string jsonParams = ApiParameters.ParametersToJsonParamsArray(parameters).ToJson(); SecureExecutionRequest request = new SecureExecutionRequest(context, typeof(T).Name, methodName, jsonParams); request.ServiceProvider = serviceProvider; return(request); }
public async Task <IActionResult> Create([Bind("IncubatorModelId,MonitoringDeviceId,Id,Name,Description,IdentityUserId")] Incubator incubator) { var monitoringDevices = _context.MonitoringDevices.Select(m => m.Id).ToList(); var incubatorsMonitoringDevices = _context.Incubators.Select(i => i.MonitoringDeviceId).ToList(); if (incubator.MonitoringDeviceId != 0 && !monitoringDevices.Contains(incubator.MonitoringDeviceId)) { ViewBag.NoMonitoringDevice = true; ViewData["IncubatorModelId"] = new SelectList(_context.Set <IncubatorModel>(), "Id", "Capacity", incubator.IncubatorModelId); return(View(incubator)); } if (incubator.MonitoringDeviceId == 0) { incubator.MonitoringDeviceId = 2; } incubator.IdentityUser = await GetCurrentUserAsync(); incubator.IdentityUserId = await GetCurrentUserId(); if (ModelState.IsValid) { var dateAdded = DateTime.Now.Date; _context.Add(incubator); await _context.SaveChangesAsync(); incubator = _context.Incubators.Include(i => i.IncubatorModel).SingleOrDefault(i => i.Id == incubator.Id); for (byte rack = 1; rack <= incubator.IncubatorModel.RackHeight; rack++) { var rackIn = new Rack { IncubatorId = incubator.Id, RackNumber = rack, }; _context.Add(rackIn); await _context.SaveChangesAsync(); for (byte rackCol = 1; rackCol <= incubator.IncubatorModel.RackLength; rackCol++) { for (byte rackRow = 1; rackRow <= incubator.IncubatorModel.RackWidth; rackRow++) { var tray = new Tray { Column = rackCol, Row = rackRow, EggTypeId = _context.EggTypes.SingleOrDefault(eT => eT.Name == "None").Id, RackId = _context.Racks.Where(r => r.IncubatorId == incubator.Id).SingleOrDefault(r => r.RackNumber == rack).Id, DateAdded = DateTime.Now.Date, CandlingDate = DateTime.Now.Date, HatchPreparationDate = DateTime.Now.Date, HatchDate = DateTime.Now.Date }; _context.Add(tray); await _context.SaveChangesAsync(); } } } return(RedirectToAction(nameof(Index))); } ViewData["IncubatorModelId"] = new SelectList(_context.Set <IncubatorModel>(), "Id", "Capacity", incubator.IncubatorModelId); return(View(incubator)); }
internal static StringBuilder GenerateJsProxyScript(Incubator incubator, string[] classes, bool includeLocal = false) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("(function(b, d, $, win){"); stringBuilder.AppendLine(DaoProxyRegistration.GetDaoJsCtorScript(incubator, classes).ToString()); foreach (string className in classes) { Type type = incubator[className]; string varName = GetVarName(type); string var = string.Format("\tb.{0}", className); stringBuilder.Append(var); stringBuilder.Append(" = {};\r\n"); stringBuilder.Append(var); stringBuilder.Append(".proxyName = \"{0}\";\r\n"._Format(varName)); foreach (MethodInfo method in type.GetMethods()) { if (WillProxyMethod(method, includeLocal)) { stringBuilder.AppendLine(GetMethodCall(type, method)); } } MethodInfo modelTypeMethod = type.GetMethod("GetDaoType"); if (modelTypeMethod != null && modelTypeMethod.ReturnType == typeof(Type)) { Type modelType = (Type)modelTypeMethod.Invoke(null, null); stringBuilder.Append("\td.entities = d.entities || {};"); stringBuilder.Append("\td.fks = d.fks || [];"); stringBuilder.AppendFormat("\td.entities.{0} = b.{0};\r\n", className); stringBuilder.AppendFormat("\td.entities.{0}.ctx = '{1}';\r\n", className, Dao.ConnectionName(modelType)); stringBuilder.AppendFormat("\td.entities.{0}.cols = [];\r\n", className); PropertyInfo[] modelProps = modelType.GetProperties(); foreach (PropertyInfo prop in modelProps) { if (prop.HasCustomAttributeOfType(out ColumnAttribute col)) { string typeName = prop.PropertyType.Name; if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) { typeName = prop.PropertyType.GetGenericArguments()[0].Name; } stringBuilder.AppendFormat("\td.entities.{0}.cols.push({{name: '{1}', type: '{2}', nullable: {3} }});\r\n", className, col.Name, typeName, col.AllowNull ? "true" : "false"); } if (prop.HasCustomAttributeOfType(out ForeignKeyAttribute fk)) { stringBuilder.AppendFormat("\td.fks.push({{ pk: '{0}', pt: '{1}', fk: '{2}', ft: '{3}', nullable: {4} }});\r\n", fk.ReferencedKey, fk.ReferencedTable, fk.Name, fk.Table, fk.AllowNull ? "true" : "false"); } } } stringBuilder.AppendFormat("\twin.{0} = win.{0} || {{}};\r\n", varName); stringBuilder.AppendFormat("\t$.extend(win.{0}, {1});\r\n", varName, var.Trim()); stringBuilder.AppendFormat("\twin.{0}.className = '{1}';\r\n", varName, className); stringBuilder.AppendFormat("\td.{0} = b.{1};\r\n", varName, className); } stringBuilder.AppendLine("})(bam, dao, jQuery, window || {});"); return(stringBuilder); }
public void AddServices(Incubator incubator) { BamConf.Server.AddAppServies(Name, incubator); }
public static JsonRpcRequest Create <T>(Incubator incubator, object id, string methodName, params object[] parameters) { return(Create(incubator, id, typeof(T).GetMethod(methodName, parameters.Select(p => p.GetType()).ToArray()), parameters)); }
public void Register(Incubator incubator) { MsSqlRegistrar.Register(incubator); }
public static JsonRpcRequest Create(Incubator incubator, MethodInfo method, params object[] parameters) { return(Create(incubator, (object)Guid.NewGuid().ToString(), method, parameters)); }