public override void Run() { base.Run(); using (var context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { var f = new EntityFactory(context); var entity = f.LoadEntity(RootEntitity); // TODO: move masking logic to entity factory! var entityGroupMask = EntityGroup.All; if (Cluster || Domain || Federation || Layout || Jobs) { if (!Cluster) entityGroupMask &= ~EntityGroup.Cluster; if (!Domain) entityGroupMask &= ~EntityGroup.Domain; if (!Federation) entityGroupMask &= ~EntityGroup.Federation; if (!Layout) entityGroupMask &= ~EntityGroup.Layout; if (!Jobs) entityGroupMask &= ~EntityGroup.Jobs; } using (var outfile = new StreamWriter(Output)) { f.Serialize(entity, outfile, entityGroupMask, ExcludeUserCreated); } } }
protected override IEnumerable<KeyValuePair<string, DatasetBase>> LoadAllDatasets() { var ef = new EntityFactory(context); var federation = ef.LoadEntity<Federation>(federationName); federation.LoadDatabaseDefinitions(true); // Load database definitions foreach (var dd in federation.DatabaseDefinitions.Values.Where(d => d.RunningState == RunningState.Running)) { // Make sure it's not a reserved database definition if (!ReservedDatabaseDefinitions.Contains(dd.Name)) { var ds = DatasetFactory.CreateDataset(dd); yield return new KeyValuePair<string, DatasetBase>(ds.Name, ds); } } federation.LoadRemoteDatabases(true); // Load remote databases foreach (var rd in federation.RemoteDatabases.Values.Where(d => d.RunningState == RunningState.Running)) { // Make sure it's not a reserved database definition if (!ReservedDatabaseDefinitions.Contains(rd.Name)) { var ds = DatasetFactory.CreateDataset(rd); yield return new KeyValuePair<string, DatasetBase>(ds.Name, ds); } } }
public override void Run() { base.Run(); Console.Write("Creating admin user... "); using (Context context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { try { var f = new EntityFactory(context); var c = f.LoadEntity<Cluster>(clusterName); var ci = new ClusterInstaller(c); ci.GenerateAdmin(false, adminUsername, adminEmail, adminPassword); } catch (Exception ex) { Console.WriteLine("failed."); Console.WriteLine(ex.Message); context.RollbackTransaction(); } } Console.WriteLine("done."); }
protected Guid ScheduleExportTableJob(string schemaName, string tableName, string path, QueueType queueType) { var queue = String.Format("Graywulf.Controller.Controller.{0}", queueType.ToString()); using (var context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { var user = SignInTestUser(context); var ef = new EntityFactory(context); var f = ef.LoadEntity<Federation>(Federation.AppSettings.FederationName); var format = new FileFormatFactory().GetFileFormatDescription("Jhu.Graywulf.Format.CsvFile"); var source = new Jhu.Graywulf.Schema.Table() { Dataset = user.GetUserDatabaseInstance(f.MyDBDatabaseVersion).GetDataset(), // TODO: fix this SchemaName = schemaName, TableName = tableName }; var etf = new ExportTableFactory(context); var ji = etf.ScheduleAsJob( source, path, format, queue, ""); ji.Save(); return ji.Guid; } }
protected void DuplicateUsernameValidator_ServerValidate(object source, ServerValidateEventArgs args) { if (RegistryUser == null) { EntityFactory ef = new EntityFactory(RegistryContext); args.IsValid = !ef.CheckEntityDuplicate(EntityType.User, Guid.Empty, Domain.Guid, args.Value); } }
protected void Ok_Click(object sender, EventArgs e) { var f = new EntityFactory(RegistryContext); var entity = f.LoadEntity(new Guid(Request.QueryString["guid"])); Response.ContentType = "text/xml"; f.Serialize(entity, Response.Output, EntityType.AllCluster); Response.End(); }
public override void Execute(PageBase page) { page.Response.Output.WriteLine( "Testing registry entry: {0}", Name); var ef = new EntityFactory(page.RegistryContext); var e = ef.LoadEntity(Name); page.Response.Output.WriteLine("Entry retrieved: {0}", e.Guid); }
protected override void Execute(CodeActivityContext activityContext) { QueryPartitionBase queryPartition = QueryPartition.Get(activityContext); switch (queryPartition.Query.ExecutionMode) { case ExecutionMode.SingleServer: queryPartition.InitializeQueryObject(null, null, true); break; case ExecutionMode.Graywulf: using (var context = ContextManager.Instance.CreateContext(this, activityContext, ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { var scheduler = activityContext.GetExtension<IScheduler>(); //queryPartition.DatabaseVersionName = queryPartition.Query.SourceDatabaseVersionName; TODO: delete queryPartition.InitializeQueryObject(context, scheduler, false); var dss = queryPartition.FindRequiredDatasets(); // Check if there are any Graywulf datasets referenced in the query var assignmydb = (dss.Values.FirstOrDefault(ds => !ds.IsSpecificInstanceRequired) == null); // *** TODO: replace this whole thing to use JOIN graphs // If no graywulf datasets are used, use the server containing myDB, // otherwise ask the scheduler for an appropriate server if (dss.Count == 0 || assignmydb) { // use MyDB's server var ef = new EntityFactory(context); var federation = queryPartition.FederationReference.Value; var user = ef.LoadEntity<User>(context.UserGuid); var di = user.GetUserDatabaseInstance(federation.MyDBDatabaseVersion); queryPartition.AssignedServerInstance = di.ServerInstance; } else { // Assign new server instance var si = new ServerInstance(context); si.Guid = scheduler.GetNextServerInstance( dss.Values.Where(x => !x.IsSpecificInstanceRequired).Select(x => x.DatabaseDefinition.Guid).ToArray(), queryPartition.Query.SourceDatabaseVersionName, null); si.Load(); queryPartition.AssignedServerInstance = si; } queryPartition.InitializeQueryObject(context, scheduler, true); EntityGuid.Set(activityContext, queryPartition.AssignedServerInstance.Guid); } break; } }
protected void DropMyDBTable(string schemaName, string tableName) { using (var context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { var ef = new EntityFactory(context); var federation = ef.LoadEntity<Federation>(Federation.AppSettings.FederationName); var user = SignInTestUser(context); var di = user.GetUserDatabaseInstance(federation.MyDBDatabaseVersion); DropTable(di.GetConnectionString().ConnectionString, "dbo", "SqlQueryTest_SimpleQueryTest"); } }
protected override void Execute(CodeActivityContext activityContext) { var entityguid = EntityGuid.Get(activityContext); using (var context = ContextManager.Instance.CreateContext(this, activityContext, ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { var ef = new EntityFactory(context); var e = ef.LoadEntity(entityguid); e.ReleaseLock(false); } }
/// <summary> /// Returns an intialized JobInstance. /// </summary> /// <param name="jobDefinitionName"></param> /// <param name="queueName"></param> /// <param name="comments"></param> /// <returns></returns> /// <remarks>The parameters of the job are not initialized.</remarks> protected JobInstance CreateJobInstance(string jobDefinitionName, string queueName, string comments) { var ef = new EntityFactory(Context); var jd = ef.LoadEntity<JobDefinition>(jobDefinitionName); var job = jd.CreateJobInstance(queueName, Jhu.Graywulf.Registry.ScheduleType.Queued); job.Name = String.Format("{0}_{1}", Context.UserName, job.JobID); job.Comments = comments; return job; }
public override void Run() { using (var context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { var f = new EntityFactory(context); using (var infile = new StreamReader(Input)) { f.Deserialize(infile); } } }
protected override void Application_Start(object sender, EventArgs e) { base.Application_Start(sender, e); using (var context = Jhu.Graywulf.Registry.ContextManager.Instance.CreateContext(Registry.ConnectionMode.AutoOpen, Registry.TransactionMode.DirtyRead)) { var ef = new EntityFactory(context); var federation = ef.LoadEntity<Federation>(Federation.AppSettings.FederationName); Application[Constants.ApplicationShortTitle] = federation.ShortTitle; Application[Constants.ApplicatonLongTitle] = federation.LongTitle; } }
protected override void Application_Start(object sender, EventArgs e) { base.Application_Start(sender, e); // Load domain settings using (var context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { var ef = new EntityFactory(context); var domain = ef.LoadEntity<Domain>(Domain.AppSettings.DomainName); Application[Constants.ApplicationShortTitle] = domain.ShortTitle; Application[Constants.ApplicatonLongTitle] = domain.LongTitle; } }
public override void Run() { using (Context context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { EntityFactory ef = new EntityFactory(context); Federation f = (Federation)ef.LoadStronglyTypedEntity(Federation.AppSettings.FederationName); QueryFactory qf = new SqlQueryFactory(); QueryBase query = qf.CreateQuery(File.ReadAllText(inputFile), ExecutionMode.Graywulf, outputTable, taskName); string queuename = String.Format("{0}.{1}", f.ControllerMachine.GetFullyQualifiedName(), queueName); JobInstance job = qf.ScheduleAsJob(query, queueName); job.Save(); } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { SignInForm.Text = String.Format("Welcome to {0}", Application[Jhu.Graywulf.Web.Constants.ApplicationShortTitle]); // Load clusters EntityFactory cf = new EntityFactory(RegistryContext); foreach (Registry.Cluster c in cf.FindAll<Registry.Cluster>()) { ClusterList.Items.Add(new ListItem(c.Name, c.Guid.ToString())); } ClusterList.SelectedIndex = 0; } }
private void ScheduleTestJob() { using (Context context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { var ef = new EntityFactory(context); var f = ef.LoadEntity<Federation>(Federation.AppSettings.FederationName); var jd = ef.LoadEntity<JobDefinition>(String.Format("{0}.{1}", Cluster.AppSettings.ClusterName, typeof(Jhu.Graywulf.Jobs.Test.TestJob).Name)); var queuename = String.Format("{0}.{1}", f.ControllerMachine.GetFullyQualifiedName(), Constants.MaintenanceQueueName); var job = jd.CreateJobInstance(queuename, ScheduleType.Queued); job.Save(); } }
public override void Run() { using (var context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { var f = new EntityFactory(context); var entity = f.LoadEntity(EntityName); // *** TODO: create mask from input parameters var mask = EntityType.AllCluster | EntityType.AllDomain | EntityType.AllFederation | EntityType.AllLayou | EntityType.AllSecurity | EntityType.AllJobs; //mask = (EntityType)((int)mask & ~(0x0400)); // Leave out job instances using (var outfile = new StreamWriter(Output)) { f.Serialize(entity, outfile, mask); } } }
protected override void Execute(CodeActivityContext activityContext) { // get/init workflow arguments string databaseVersionName = DatabaseVersionName.Get(activityContext); Queue<Guid> sourceDatabaseInstanceGuids = new Queue<Guid>(); Queue<Guid> destinationDatabaseInstanceGuids = new Queue<Guid>(); using (Context context = ContextManager.Instance.CreateContext(this, activityContext, ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { EntityFactory ef = new EntityFactory(context); DatabaseVersion dv = ef.LoadEntity<DatabaseVersion>(databaseVersionName); EntityGuid.Set(activityContext, dv.Guid); dv.DatabaseDefinition.LoadDatabaseInstances(false); foreach (DatabaseInstance di in dv.DatabaseDefinition.DatabaseInstances.Values) { if (Entity.StringComparer.Compare(di.DatabaseVersion.Name, dv.Name) == 0) { if (di.ServerInstance.Machine.RunningState == RunningState.Running) { if (di.DeploymentState == DeploymentState.Deployed && di.RunningState == RunningState.Attached) { sourceDatabaseInstanceGuids.Enqueue(di.Guid); } else if (di.DeploymentState == DeploymentState.New || di.DeploymentState == DeploymentState.Undeployed) { destinationDatabaseInstanceGuids.Enqueue(di.Guid); } } } } } SourceDatabaseInstanceGuids.Set(activityContext, sourceDatabaseInstanceGuids); DestinationDatabaseInstanceGuids.Set(activityContext, destinationDatabaseInstanceGuids); if (sourceDatabaseInstanceGuids.Count == 0 || destinationDatabaseInstanceGuids.Count == 0) { throw new InvalidOperationException(ExceptionMessages.NoDatabasesToCopy); } }
protected void Ok_Click(object sender, EventArgs e) { if (IsValid) { LoadItem(); item.ConcurrencyVersion = (long)ViewState["ConcurrencyVersion"]; // TODO // Discover again var update = new List<Entity>(); var delete = new List<Entity>(); var create = new List<Entity>(); item.Discover(update, delete, create); var ef = new EntityFactory(RegistryContext); ef.ApplyChanges(update, delete, create); Response.Redirect(item.GetDetailsUrl()); } }
protected PassOneEntityTests() { Factory = new EntityFactory(); TestUser = new User() { Id = 100, FirstName = "Peter", LastName = "Varner-Howland", Username = "******", Password = "******", k = _testKey, v = _testVector }; TestUser2 = new User() { Id = 200, FirstName = "Arwen", LastName = "Varner-Howland", Username = "******", Password = "******", k = _testKey, v = _testVector }; TestCredentials = new Credential() { Title = "Regis WorldClass", Url = "https://worldclass.regis.edu/", Username = "******", Password = "******", Email = "*****@*****.**", Id = 100 }; TestCredentials2 = new Credential() { Title = "Regis InSite", Url = "https://in2.regis.edu/CookieAuth.dll?GetLogon?curl=Z2F&reason=0&formdir=6", Username = "******", Password = "******", Email = "*****@*****.**", Id = 200 }; }
protected Guid ScheduleMirroDatabaseJob(QueueType queueType) { var queue = String.Format("Graywulf.Controller.Controller.{0}", queueType.ToString()); using (var context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { SignInTestUser(context); var ef = new EntityFactory(context); var jd = ef.LoadEntity<JobDefinition>(Cluster.AppSettings.ClusterName, typeof(MirrorDatabaseJob).Name); var ji = jd.CreateJobInstance(queue, ScheduleType.Queued); ji.Parameters["DatabaseVersionName"].SetValue("Graywulf.VOServices.SkyQuery.Galex.STAT"); ji.Save(); return ji.Guid; } }
public static void RunSanityCheck() { // Test persistence service connection using (SqlConnection cn = new SqlConnection(PersistenceConnectionString)) { cn.Open(); } // Test well-formated variables TimeSpan ts; ts = PollingInterval; ts = AppDomainIdle; // Test cluster registry settings using (Context context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { EntityFactory ef = new EntityFactory(context); ef.LoadEntity<Registry.Cluster>(Registry.AppSettings.ClusterName); } }
private void GetServerSettings(schema::DatasetBase ds, out string connectionString, out DbProviderFactory dbf) { EntityFactory ef = new EntityFactory(RegistryContext); Entity db = ef.LoadEntity(EntityType.Unknown, Jhu.Graywulf.Registry.AppSettings.FederationName, ds.Name); if (StringComparer.InvariantCultureIgnoreCase.Compare(ds.Name, MyDBDatabaseDefinition.Name) == 0) { // In case of myDB connectionString = ((schema::SqlServer.SqlServerDataset)SchemaManager.Datasets[MyDBDatabaseDefinition.Name]).ConnectionString; dbf = DbProviderFactories.GetFactory(ds.ProviderName); } else if (db is DatabaseDefinition) { // In case of a Graywulf database definition DatabaseDefinition dd = (DatabaseDefinition)db; dd.LoadDatabaseVersions(false); DatabaseVersion rs = dd.DatabaseVersions.Values.First(r => r.Name == "HOT"); // ***** TODO: this should come from the job settings... dd.LoadDatabaseInstances(false); List<DatabaseInstance> dis = new List<DatabaseInstance>(dd.DatabaseInstances.Values.Where(dii => dii.DatabaseVersionReference.Guid == rs.Guid)); // Pick a random server Random rnd = new Random(); DatabaseInstance di = dis[rnd.Next(dis.Count)]; connectionString = di.GetConnectionString().ConnectionString; dbf = System.Data.SqlClient.SqlClientFactory.Instance; } else if (db is RemoteDatabase) { RemoteDatabase rd = (RemoteDatabase)db; connectionString = ds.GetSpecializedConnectionString(rd.ConnectionString, rd.IntegratedSecurity, rd.Username, rd.Password, false); dbf = DbProviderFactories.GetFactory(ds.ProviderName); } else { throw new InvalidOperationException(); } }
void Awake () { TextAsset XMLTextAsset = (TextAsset) Resources.Load(levelPath + levelName); xmlDoc = new XmlDocument(); xmlDoc.LoadXml(XMLTextAsset.text); startingGold = int.Parse(xmlDoc.SelectSingleNode("/level/startingGold").InnerText); entityFactory = EntityFactory.GetInstance(); monsterGUIManager = GameObject.Find("MonsterGUIManager").GetComponent<MonsterGUIManager>(); waveManager = GameObject.Find("WaveManager").GetComponent<HeroWaveManager>(); if (playerStatusManager == null) playerStatusManager = GameObject.Find("PlayerStatusManager").GetComponent<PlayerStatusManager>(); //waveManager.onSpawnNewHero += HandleOnSpawnNewHero; waveManager.onWaveCompletedSpawning += HandleOnWaveCompletedSpawning; waveManager.onAllWaveEnemiesDefeated += HandleOnWaveEnemiesDefeated; waveManager.onNextWaveStarted += HandleOnNextWaveStarted; }
/// <summary> /// Returns <b>true</b> if the entity can be deleted. /// </summary> /// <remarks> /// TODO Add remarks when delete code is done. /// </remarks> public bool CanDelete(bool checkRecursive, bool checkReferencing) { // Do entity verifications if (system) return false; if (deleted) return false; if (LockOwner != Guid.Empty) return false; // First make sure it's not deployed or transient // Only new and undeployed entities can be deleted if ((deploymentState & (DeploymentState.New | DeploymentState.Undeployed)) == 0) { return false; } if (checkRecursive) { // Make sure all children can be deleted LoadAllChildren(true); foreach (Entity e in EnumerateAllChildren()) { if (!e.CanDelete(checkRecursive, checkReferencing)) { return false; } } } if (checkReferencing) { // Check if there are any referencing entities var ef = new EntityFactory(Context); if (ef.FindReferencing(this).Count() > 0) { return false; } } return true; }
public override void Run() { Console.Write("Creating admin user group and user... "); using (Context context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { var f = new EntityFactory(context); var c = f.LoadEntity<Cluster>(clusterName); var u = new User(c) { Name = adminUsername, Email = adminEmail, DeploymentState = Registry.DeploymentState.Deployed, }; u.SetPassword(adminPassword); u.Save(); // TODO: create admin group membership } Console.WriteLine("done."); }
public override void Run() { base.Run(); using (var context = ContextManager.Instance.CreateContext(ConnectionMode.AutoOpen, TransactionMode.AutoCommit)) { try { var f = new EntityFactory(context); using (var infile = new StreamReader(Input)) { f.Deserialize(infile, IgnoreDuplicates); } } catch (Exception ex) { Console.WriteLine("Importing xml file failed."); Console.WriteLine(ex.Message); context.RollbackTransaction(); } } }
public new async Task BindModelAsync(ModelBindingContext bindingContext) { var modelType = bindingContext.ModelType; var controllerContext = bindingContext.ActionContext; if (modelType.As <IEntity>()) { var fact = EntityFactory.CreateOperate(modelType); if (fact != null) { var rvs = controllerContext.RouteData.Values; var pks = fact.Table.PrimaryKeys; var uk = fact.Unique; IEntity entity = null; if (uk != null) { // 查询实体对象用于编辑 if (rvs[uk.Name] != null) { entity = GetEntity(fact.EntityType, rvs[uk.Name]) ?? fact.FindByKeyForEdit(rvs[uk.Name]); } if (entity == null) { entity = fact.Create(); } } else if (pks.Length > 0) { // 查询实体对象用于编辑 var vs = pks.Select(e => rvs[e.Name]).ToArray(); entity = GetEntity(fact.EntityType, vs); if (entity == null) { var req = controllerContext.HttpContext.Request; var exp = new WhereExpression(); foreach (var item in pks) { exp &= item.Equal(req.GetRequestValue(item.Name).ChangeType(item.Type)); } entity = fact.Find(exp); } if (entity == null) { entity = fact.Create(); } } if (entity != null) { var fs = controllerContext.HttpContext.Request.Form; // 提前填充动态字段的扩展属性 foreach (var item in fact.Fields) { if (item.IsDynamic && fs.ContainsKey(item.Name)) { entity.SetItem(item.Name, fs[item.Name]); } } bindingContext.Result = ModelBindingResult.Success(entity); } if (entity == null) { bindingContext.Result = ModelBindingResult.Success(fact.Create()); } } await base.BindModelAsync(bindingContext); } }
public static Entity Instanciate(string name) { //returns an new Entity based on the name //if it does not exist, it reads the json blueprint for the Entity Entity result = null; InitDictionaries(); if (Entities.ContainsKey(name)) { Entity ent = Entities[name]; if (isEntityFlyWeight(ent)) { result = ent; } else { //copy all the attributes that are flyweight //and make new attributes that are not based on the json result = new Entity(ent.Name); for (int i = 0; i < ent.AttributeCount; i++) { Attribute att = ent[i]; if (att.NewInstance) { att = (Attribute)Activator.CreateInstance( att.GetType(), new object[] { result, att.GetDataPacket() }); } result.addAttribute(att); } result.Awake(); } } else { //make make the entity from json //save it to the directory //call the Instacne funciton (this function) again and set it to result TextAsset entityRecipe = Resources.Load <TextAsset>(name); DataPacket entityData = JsonConvert.DeserializeObject <DataPacket>(entityRecipe.text); Entity entity = new Entity((string)entityData.Values["Name"]); List <string> keys = new List <string>(entityData.DataPackets.Keys); foreach (string key in keys) { DataPacket attributeData = entityData.DataPackets[key]; Attribute att = (Attribute)Activator.CreateInstance( Type.GetType(key), new object[] { entity, attributeData }); entity.addAttribute(att); } entity.Awake(); Entities.Add(name, entity); result = EntityFactory.Instanciate(name); } return(result); }
private void RegisterDataLayer(Prototype prototype, WindsorContainer container) { EntityFactory.RegisterEntities(prototype, NamingConstants.DataLayerProjectName, container); ResourceFactory.RegisterResources(GetRequiredResources().ToList(), prototype, NamingConstants.DataLayerProjectName, container); }
/// <summary> /// Зарегистрировать клиент. /// </summary> public static void Initialize() { LocalizationManager.Instance.AssignCurrentCulture(); // Управление кэшами. var cacheConfigProvider = new CacheConfigProvider(null); Dependency.RegisterInstance <ICacheManager>(new CacheManagerImplementation(cacheConfigProvider)); // Плагины. Dependency.RegisterInstance <Sungero.Plugins.IPluginManager>(new Sungero.Plugins.PluginManager(new Sungero.Domain.Client.ClientPluginDiscoverer(), new Sungero.Plugins.PluginSettingsLoader())); ServiceContext.Instance.ApplicationExit += (s, a) => { throw a.Exception; }; if (UserCredentialsManager.IsRegistered) { return; } // Перенаправление вывода, чтобы не писать лишнюю информацию на экран. var consoleOut = Console.Out; try { Console.SetOut(System.IO.TextWriter.Null); Sungero.Domain.Client.SystemInfo.Tenant = CommandLine.options.Tenant; AuthenticationHelper.Register(CommandLine.options, false); Console.SetOut(consoleOut); } catch (InvalidSecurityException ex) { Console.SetOut(consoleOut); throw new InvalidSecurityException(ex.IsInternal, new LocalizedString("No access rights to the system - invalid username or password."), ex); } catch (Exception) { Console.SetOut(consoleOut); throw; } #region Загрузка модулей. ClientDevelopmentUpdater.Instance.RefreshDevelopment(); MetadataService.ConfigurationSettingsPaths = new Sungero.Domain.ClientConfigurationSettingsPaths(); ClientLazyAssembliesResolver.Instance.LinkToAssembliesFolder(ClientDevelopmentUpdater.Instance.CacheFolder); var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; var developmentDirectory = ClientDevelopmentUpdater.Instance.CacheFolder; Dependency.RegisterType <IClientLinqExtensions, ClientLinqExtensionsService>(); Dependency.RegisterType <IHyperlinkEntityCache, HyperlinkEntityCacheImplementer>(); Dependency.RegisterType <IHyperlinkDisplayTextCache, HyperlinkDisplayTextCacheImplementer>(); LoadModules(baseDirectory, "*Client.dll"); LoadModules(developmentDirectory, null); EntityFactory.ConfigureUnityContainer(); #endregion var tenantCulture = TenantInfo.Culture; if (!LocalizationManager.Instance.ClientUICulture.Equals(tenantCulture)) { Log.WarnFormat("Client culture changed to {0}", tenantCulture); LocalizationManager.Instance.SetSystemLanguage(tenantCulture.Name); LocalizationManager.Instance.AssignCurrentCulture(); Cleanup(); AuthenticationHelper.Register(CommandLine.options, false); } }
public static FUIStoryWin Create(Entity domain, GObject go) { return(EntityFactory.Create <FUIStoryWin, GObject>(domain, go)); }
public async Task <ServiceResult> AddExpForContinuousLearningAsync(string userId, IList <TodayWord> todayWords) { try { // comple all words bool isPass = IsPassAllWords(todayWords); if (isPass == true) { // Assume int numberOfContDays = 1; // get user ApplicationUser user = await this.m_userRepository.FindEntityAsync(t => t.Id == userId); // Check if hasvalue if (user.LastDiligentDate.HasValue == false) { // Do nothing } else { // get number of conts days numberOfContDays = (DateTime.Now - user.LastDiligentDate.Value).Days; } // if lastday if (numberOfContDays == 1) { // Update counter user.ContinousCounter = user.ContinousCounter + 1; // update current date user.LastDiligentDate = DateTime.Now; // check and increase exp int contExp = this.GetExpOfContinuous(user.ContinousCounter); // check if user archive max bonus score if (user.ContinousCounter == 180) { // reset counter user.ContinousCounter = 0; } else { // Do nothing } if (contExp == 0) { // Do nothing // Do not write any records } else { // create exp history UserExperience expRecord = EntityFactory .CreateUserExperience(userId, Constraint.MemberExpSystem.ContinuousLearning.ID, Constraint.MemberExpSystem.ContinuousLearning.NAME, contExp); // insert to db await this.m_userExperienceRepository.InsertAsync(expRecord); // save changes await this.m_userExperienceRepository.SaveChangesAsync(); } // finally, update exp for user user.CurrentExp = user.CurrentExp + contExp; // Update table await this.m_userRepository.UpdateAsync(user); // save changes await this.m_userRepository.SaveChangesAsync(); // return successfull return(ServiceResult.Success); } else { // Update user data // reset user.LastDiligentDate = DateTime.Now; user.ContinousCounter = 1; // create exp history UserExperience expRecord = EntityFactory .CreateUserExperience(userId, Constraint.MemberExpSystem.ContinuousLearning.ID, Constraint.MemberExpSystem.ContinuousLearning.NAME, 20); // insert to db await this.m_userExperienceRepository.InsertAsync(expRecord); // save changes await this.m_userExperienceRepository.SaveChangesAsync(); // finally, update exp for user // add 20 exp for first use user.CurrentExp = user.CurrentExp + 20; // Update table await this.m_userRepository.UpdateAsync(user); // save changes await this.m_userRepository.SaveChangesAsync(); // return successfull return(ServiceResult.Success); } } else { // Not update counter return(ServiceResult.Success); } } catch (Exception ex) { // return errors return(ServiceResult.AddError(ex.Message)); } }
/// <summary> /// NeedDataSource event handler of the generic grid /// </summary> /// <param name="source"></param> /// <param name="e"></param> private void GenericGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e) { try { this.MasterTableView.FilterExpression = this.IndFilterExpression; if (!_UseAutomaticEntityBinding && _VirtualDataSource == null) { return; } //Clear the columns in the master table this.MasterTableView.Columns.Clear(); //Add the edit column AddEditColumn(); //Add the delete column (checkbox column) AddDeleteColumn(); DataSet sourceDS = new DataSet(); if (_UseAutomaticEntityBinding) { //Instantiate the referenced object IGenericEntity viewEntity = EntityFactory.GetEntityInstance(_EntityType, SessionManager.GetSessionValueNoRedirect((IndBasePage)this.Page, SessionStrings.CONNECTION_MANAGER)); ((GenericUserControl)this.Parent.Parent).SetViewEntityProperties(viewEntity); //Get all entities in this catalogue sourceDS = viewEntity.GetAll(true); //Creates a new GenericEntity object with the correct instance that will be used to add the logical column object connectionManager = SessionManager.GetSessionValueNoRedirect((IndBasePage)this.Page, SessionStrings.CONNECTION_MANAGER); //Add the logical column EntityFactory.GetEntityInstance(this.EntityType, connectionManager).CreateLogicalKeyColumn(sourceDS.Tables[0]); } else { if (!(_VirtualDataSource is DataSet) && !(_VirtualDataSource is DataTable)) { throw new IndException(ApplicationMessages.MessageWithParameters(ApplicationMessages.EXCEPTION_VIRTUAL_DATASOURCE_OF_TYPE_NOT_SUPPORTED, _VirtualDataSource.GetType().ToString())); } if (_VirtualDataSource is DataSet) { sourceDS = (DataSet)_VirtualDataSource; } if (_VirtualDataSource is DataTable) { sourceDS.Tables.Add((DataTable)_VirtualDataSource); } } //Add the data columns (with data from the db) to the grid AddDataColumns(sourceDS); if (_UseAutomaticEntityBinding) { CurrentUser currentUser = SessionManager.GetSessionValueRedirect((IndBasePage)this.Page, SessionStrings.CURRENT_USER) as CurrentUser; if (currentUser.HasEditPermission(ApplicationConstants.MODULE_HOURLY_RATE) && _EntityType == typeof(HourlyRate)) { AddColumnHeaderControl("Value", " <input type=\"image\" id=\"btnMassAttr\" class=\"IndImageButton\" title=\"Mass Attribution\" src=\"Images/mass_attribution_up.gif\" onclick=\"if (ShowPopUpWithoutPostBack('UserControls/Catalogs/HourlyRate/HRMassAttribution.aspx',520,560, '" + ResolveUrl("~/Default.aspx?SessionExpired=1") + "')){ __doPostBack('" + this.Page.ClientID + "',null);}return false;\""); } //Hide the columns that must not be shown (like Id) HideColumns(); } //Bind the grid to the dataset this.DataSource = sourceDS; SetDateColumnFormatString(); } catch (IndException ex) { ControlHierarchyManager.ReportError(ex); return; } catch (Exception ex) { ControlHierarchyManager.ReportError(new IndException(ex)); return; } }
internal static Boolean MakeFormView(Type entityType, String vpath, List <FieldItem> fields) { var tmp = @"@using NewLife; @using XCode; @using XCode.Configuration; @{ var entity = Model; var fields = ViewBag.Fields as IList<FieldItem>; var isNew = (entity as IEntity).IsNullKey; } @foreach (var item in fields) { if (!item.IsIdentity) { <div class=""@cls""> @Html.Partial(""_Form_Item"", new Pair(entity, item)) </div> } } @Html.Partial(""_Form_Footer"", entity) @if (this.Has(PermissionFlags.Insert, PermissionFlags.Update)) { <div class=""clearfix form-actions col-sm-12 col-md-12""> <label class=""control-label col-xs-4 col-sm-5 col-md-5""></label> <button type=""submit"" class=""btn btn-success btn-sm""><i class=""glyphicon glyphicon-@(isNew ? ""plus"" : ""save"")""></i><strong>@(isNew ? ""新增"" : ""保存"")</strong></button> <button type=""button"" class=""btn btn-danger btn-sm"" onclick=""history.go(-1);""><i class=""glyphicon glyphicon-remove""></i><strong>取消</strong></button> </div> }"; var sb = new StringBuilder(); var fact = EntityFactory.CreateOperate(entityType); sb.AppendLine($"@model {entityType.FullName}"); var str = tmp.Substring(null, "@foreach"); sb.Append(str); var set = Setting.Current; var cls = set.FormGroupClass; if (cls.IsNullOrEmpty()) { cls = "form-group col-xs-12 col-sm-6 col-lg-4"; } var ident = new String(' ', 4 * 1); foreach (var item in fields) { if (item.IsIdentity) { continue; } sb.AppendLine($"<div class=\"{cls}\">"); BuildFormItem(item, sb, fact); sb.AppendLine("</div>"); } var p = tmp.IndexOf(@"@Html.Partial(""_Form_Footer"""); sb.Append(tmp.Substring(p)); File.WriteAllText(vpath.GetFullPath().EnsureDirectory(true), sb.ToString(), Encoding.UTF8); return(true); }
internal static Boolean MakeListView(Type entityType, String vpath, List <FieldItem> fields) { var tmp = @"@using NewLife; @using NewLife.Web; @using XCode; @using XCode.Configuration; @using XCode.Membership; @using NewLife.Cube; @using System.Web.Mvc; @using System.Web.Mvc.Ajax; @using System.Web.Mvc.Html; @using System.Web.Routing; @{ var fact = ViewBag.Factory as IEntityOperate; var page = ViewBag.Page as Pager; var fields = ViewBag.Fields as IList<FieldItem>; var set = ViewBag.PageSetting as PageSetting; //var provider = ManageProvider.Provider; } <table class=""table table-bordered table-hover table-striped table-condensed""> <thead> <tr> @if (set.EnableSelect) { <th class=""text-center"" style=""width:10px;""><input type=""checkbox"" id=""chkAll"" title=""全选"" /></th> } @foreach(var item in fields) { var sortUrl = item.OriField != null ? page.GetSortUrl(item.OriField.Name) : page.GetSortUrl(item.Name); if (item.PrimaryKey) { <th class=""text-center hidden-md hidden-sm hidden-xs""><a href=""@Html.Raw(sortUrl)"">@item.DisplayName</a></th> } else { <th class=""text-center""><a href=""@Html.Raw(sortUrl)"">@item.DisplayName</a></th> } } @if (this.Has(PermissionFlags.Detail, PermissionFlags.Update, PermissionFlags.Delete)) { <th class=""text-center"" style=""min-width:100px;"">操作</th> } </tr> </thead> <tbody> @foreach (var entity in Model) { <tr> @if (set.EnableSelect) { <td class=""text-center""><input type=""checkbox"" name=""keys"" value=""@entity.ID"" /></td> } @foreach (var item in fields) { @Html.Partial(""_List_Data_Item"", new Pair(entity, item)) } @if (this.Has(PermissionFlags.Detail, PermissionFlags.Update, PermissionFlags.Delete)) { <td class=""text-center""> @Html.Partial(""_List_Data_Action"", (Object)entity) </td> } </tr> } @if (page.State != null) { var entity = page.State as IEntity; <tr> @if (set.EnableSelect) { <td></td> } @Html.Partial(""_List_Data_Stat"", page.State) @if (this.Has(PermissionFlags.Detail, PermissionFlags.Update, PermissionFlags.Delete)) { <td></td> } </tr> } </tbody> </table>"; var sb = new StringBuilder(); var fact = EntityFactory.CreateOperate(entityType); sb.AppendFormat("@model IList<{0}>", entityType.FullName); sb.AppendLine(); tmp = tmp.Replace("page.State as IEntity", "page.State as " + entityType.FullName); var str = tmp.Substring(null, " @foreach"); // 如果有用户字段,则启用provider if (fields.Any(f => f.Name.EqualIgnoreCase("CreateUserID", "UpdateUserID"))) { str = str.Replace("//var provider", "var provider"); } sb.Append(str); var ident = new String(' ', 4 * 3); foreach (var item in fields) { // 缩进 sb.Append(ident); var name = item.OriField?.Name ?? item.Name; var des = item.DisplayName ?? item.Name; // 样式 if (item.PrimaryKey) { sb.Append(@"<th class=""text-center hidden-md hidden-sm hidden-xs"""); } else { sb.Append(@"<th class=""text-center"""); } // 固定宽度 if (item.Type == typeof(DateTime)) { var width = item.Name.EndsWithIgnoreCase("Date") ? 80 : 134; sb.AppendFormat(@" style=""min-width:{0}px;""", width); } // 备注 if (!item.Description.IsNullOrEmpty() && item.Description != des) { sb.AppendFormat(@" title=""{0}""", item.Description); } // 内容 sb.AppendFormat(@"><a href=""@Html.Raw(page.GetSortUrl(""{1}""))"">{0}</a></th>", des, name); sb.AppendLine(); } var ps = new Int32[2]; str = tmp.Substring(" @if (this.Has", " @foreach (var item in fields)", 0, ps); if (fact.Unique != null) { str = str.Replace("@entity.ID", "@entity." + fact.Unique.Name); } else { str = str.Replace("@entity.ID", ""); } sb.Append(" @if (this.Has"); sb.Append(str); ident = new String(' ', 4 * 4); foreach (var item in fields) { // 缩进 sb.Append(ident); //sb.AppendLine(@"@Html.Partial(""_List_Data_Item"", new Pair(entity, item))"); if (item.PrimaryKey) { sb.AppendFormat(@"<td class=""text-center hidden-md hidden-sm hidden-xs"">@entity.{0}</td>", item.Name); } else { switch (Type.GetTypeCode(item.Type)) { case TypeCode.Boolean: sb.AppendLine(@"<td class=""text-center"">"); sb.Append(ident); sb.AppendFormat(@" <i class=""glyphicon glyphicon-@(entity.{0} ? ""ok"" : ""remove"")"" style=""color: @(entity.{0} ? ""green"" : ""red"");""></i>", item.Name); sb.AppendLine(); sb.Append(ident); sb.Append(@"</td>"); break; case TypeCode.DateTime: if (item.Name.EndsWithIgnoreCase("Date")) { sb.AppendFormat(@"<td>@entity.{0}.ToString(""yyyy-MM-dd"")</td>", item.Name); } else { sb.AppendFormat(@"<td>@entity.{0}.ToFullString("""")</td>", item.Name); } break; case TypeCode.Decimal: sb.AppendFormat(@"<td class=""text-right"">@entity.{0}.ToString(""n2"")</td>", item.Name); break; case TypeCode.Single: case TypeCode.Double: sb.AppendFormat(@"<td class=""text-right"">@entity.{0}.ToString(""n2"")</td>", item.Name); break; case TypeCode.Byte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: // 特殊处理枚举 if (item.Type.IsEnum) { sb.AppendFormat(@"<td class=""text-center"">@entity.{0}</td>", item.Name); } else if (item.Name.EqualIgnoreCase("CreateUserID", "UpdateUserID")) { BuildUser(item, sb); } else { sb.AppendFormat(@"<td class=""text-right"">@entity.{0}.ToString(""n0"")</td>", item.Name); } break; case TypeCode.String: if (item.Map != null && item.Map.Provider != null) { var prv = item.Map.Provider; sb.AppendFormat(@"<td><a href=""{1}?{2}=@entity.{3}"">@entity.{0}</a></td>", item.Name, prv.EntityType.Name, prv.Key, item.OriField?.Name); } else if (item.Name.EqualIgnoreCase("CreateIP", "UpdateIP")) { BuildIP(item, sb); } else { sb.AppendFormat(@"<td>@entity.{0}</td>", item.Name); } break; default: sb.AppendFormat(@"<td>@entity.{0}</td>", item.Name); break; } } sb.AppendLine(); } // 构造统计 str = BuildStat(fields); sb.Append(" @if"); var str2 = tmp.Substring(" @if", null, ps[1]); str = str2.Replace(" @Html.Partial(\"_List_Data_Stat\", page.State)", str); sb.Append(str); //sb.Append("@if (page.State != null)"); //sb.Append(tmp.Substring("@if (page.State != null)", null, ps[1])); File.WriteAllText(vpath.GetFullPath().EnsureDirectory(true), sb.ToString(), Encoding.UTF8); return(true); }
/// <summary>创建日志,未写入</summary> /// <param name="category">类型</param> /// <param name="action">操作</param> /// <param name="success">成功</param> /// <param name="remark">备注</param> /// <param name="userid">用户</param> /// <param name="name">名称</param> /// <param name="ip">地址</param> public virtual Log CreateLog(String category, String action, Boolean success, String remark, Int32 userid = 0, String name = null, String ip = null) { if (category.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(category)); } var factory = EntityFactory.CreateOperate(typeof(Log)); var log = factory.Create() as Log; log.Category = category; log.Action = action; log.Success = success; // 加上关联编号 if (remark.StartsWithIgnoreCase("ID=")) { var fi = factory.Table.Identity; if (fi != null) { log.LinkID = remark.Substring("ID=", ",").ToInt(); } } if (userid > 0) { log.CreateUserID = userid; } if (!name.IsNullOrEmpty()) { log.UserName = name; } if (!ip.IsNullOrEmpty()) { log.CreateIP = ip; } // 获取当前登录信息 if (log.CreateUserID == 0 || name.IsNullOrEmpty()) { // 当前登录用户 var prv = Provider2 ?? ManageProvider.Provider; //var user = prv?.Current ?? HttpContext.Current?.User?.Identity as IManageUser; var user = prv?.Current; if (user != null) { if (log.CreateUserID == 0) { log.CreateUserID = user.ID; } if (log.UserName.IsNullOrEmpty()) { log.UserName = user + ""; } } } if (log.CreateIP.IsNullOrEmpty()) { log.CreateIP = ManageProvider.UserHost; } log.Remark = remark; log.CreateTime = DateTime.Now; return(log); }
/// <summary>输出实体对象日志</summary> /// <param name="action">操作</param> /// <param name="entity">实体</param> /// <param name="error">错误信息</param> public void WriteLog(String action, IEntity entity, String error = null) { if (!Enable) { return; } var type = entity.GetType(); var fact = EntityFactory.CreateOperate(type); // 构造字段数据的字符串表示形式 var sb = Pool.StringBuilder.Get(); if (error.IsNullOrEmpty()) { sb.Append(error); } foreach (var fi in fact.Fields) { if ((action == "修改" || action == "Update") && !fi.PrimaryKey && !entity.IsDirty(fi.Name)) { continue; } var v = entity[fi.Name]; // 空字符串不写日志 if (action is "添加" or "删除" or "Insert" or "Delete") { if (v + "" == "") { continue; } if (v is Boolean b && !b) { continue; } if (v is Int32 vi && vi == 0) { continue; } if (v is DateTime dt && dt == DateTime.MinValue) { continue; } } // 日志里面不要出现密码 if (fi.Name.EqualIgnoreCase("pass", "password")) { v = null; } if (v is DateTime dt2) { v = dt2.ToFullString(); } sb.Separate(",").AppendFormat("{0}={1}", fi.Name, v); } // 对象链接 var linkId = 0; var uk = fact.Unique; if (uk != null && uk.IsIdentity) { linkId = entity[uk.Name].ToInt(); } var userid = 0; var name = ""; if (entity is IManageUser user) { userid = user.ID; name = user + ""; } //WriteLog(entity.GetType(), action, error.IsNullOrEmpty(), sb.Put(true), userid, name); var category = fact.Table.DataTable.DisplayName; if (category.IsNullOrEmpty()) { category = type.GetDisplayName() ?? type.GetDescription() ?? type.Name; } var log = CreateLog(category, action, error.IsNullOrEmpty(), sb.Put(true), userid, name); log.LinkID = linkId; log.SaveAsync(); }
/// <summary> /// Gets entity object for table from its factory /// This method only simplifies the factory calls /// </summary> /// <returns>Entity object</returns> public static TimeSeriesStrip GetEntityObjectT() { return((TimeSeriesStrip)EntityFactory.GetEntityObject(vTimeSeriesStrip.EntityName, GetSourceTypeEnum.Table)); }
/// <summary>创建模型。对于有Key的请求,使用FindByKeyForEdit方法先查出来数据,而不是直接反射实例化实体对象</summary> /// <param name="bindingContext"></param> /// <returns></returns> protected override Object CreateModel(ModelBindingContext bindingContext) { var modelType = bindingContext.ModelType; if (!modelType.As <IEntity>()) { return(base.CreateModel(bindingContext)); } var fact = EntityFactory.CreateOperate(modelType); if (fact == null) { return(base.CreateModel(bindingContext)); } // 尝试从body读取json格式的参数 var ctx = bindingContext.HttpContext; var request = ctx.Request; if (request.GetRequestBody <Object>() != null) { ctx.Items["EntityBody"] = ctx.Items["RequestBody"]; var cubeBodyValueProvider = new CubeBodyValueProvider(bindingContext.ValueProvider, ctx.Items["EntityBody"] as NullableDictionary <String, Object>); // 添加body提供者,从body中取值,只取第一层, // 下面的BindProperty方法,以前从body中并没有处理值的格式, // 强行绑定会出错记录在ModelState,在api中返回400错误,mvc不会 bindingContext.ValueProvider = cubeBodyValueProvider; } var pks = fact.Table.PrimaryKeys; var uk = fact.Unique; IEntity entity = null; if (uk != null) { // 查询实体对象用于编辑 var id = bindingContext.ValueProvider.GetValue(uk.Name); if (id != ValueProviderResult.None) { entity = fact.FindByKeyForEdit(id.ToString()); } } else if (pks.Length > 0) { // 查询实体对象用于编辑 var exp = new WhereExpression(); foreach (var item in pks) { var v = bindingContext.ValueProvider.GetValue(item.Name); if (v == ValueProviderResult.None) { continue; } exp &= item.Equal(v.ChangeType(item.Type)); } entity = fact.Find(exp); } return(entity ?? fact.Create(true)); }
/// <summary>创建模型。对于有Key的请求,使用FindByKeyForEdit方法先查出来数据,而不是直接反射实例化实体对象</summary> /// <param name="bindingContext"></param> /// <returns></returns> protected override Object CreateModel(ModelBindingContext bindingContext) { var modelType = bindingContext.ModelType; if (modelType.As <IEntity>()) { var fact = EntityFactory.CreateOperate(modelType); if (fact != null) { var rvs = bindingContext.ActionContext.RouteData.Values; var pks = fact.Table.PrimaryKeys; var uk = fact.Unique; IEntity entity = null; if (uk != null) { // 查询实体对象用于编辑 var id = rvs[uk.Name]; //if (id != null) entity = GetEntity(fact.EntityType, id) ?? fact.FindByKeyForEdit(id); if (id != null) { entity = fact.FindByKeyForEdit(id); } if (entity == null) { entity = fact.Create(); } } else if (pks.Length > 0) { // 查询实体对象用于编辑 var req = bindingContext.HttpContext.Request.Query; var exp = new WhereExpression(); foreach (var item in pks) { var v = req[item.Name].FirstOrDefault(); exp &= item.Equal(v.ChangeType(item.Type)); } entity = fact.Find(exp); if (entity == null) { entity = fact.Create(); } } if (entity != null) { var fs = bindingContext.HttpContext.Request.Form; // 提前填充动态字段的扩展属性 foreach (var item in fact.Fields) { if (item.IsDynamic && fs.ContainsKey(item.Name)) { entity.SetItem(item.Name, fs[item.Name]); } } return(entity); } return(fact.Create()); } } return(base.CreateModel(bindingContext)); }
private IEnumerable <IEntity> Select(IEntityType type, bool useView, String where, params object[] arguments) { lock (_dbsync) { string[] columns = GetColumns(type); int n; String cmdKey = type.Name + where + useView; SqliteCommand cmd; if (!_commands.TryGetValue(cmdKey, out cmd)) { String tableName = type.TableName; String columnNames = ""; // ReSharper disable once LoopCanBeConvertedToQuery foreach (string column in columns) { columnNames = columnNames + string.Format("{0}{1}", string.IsNullOrEmpty(columnNames) ? "" : ",", column); } if (!useView) { columnNames = columnNames + ",IsTombstone"; } columnNames = columnNames + ",IsDirty"; cmd = new SqliteCommand { Connection = ActiveConnection, CommandText = String.Format("SELECT {0} FROM [{1}]{2}", columnNames, useView ? tableName : "_" + tableName, String.IsNullOrEmpty(@where) ? "" : " " + @where) }; n = 1; foreach (object p in arguments) { cmd.Parameters.AddWithValue(String.Format("@p{0}", n), p); n++; } cmd.Prepare(); _commands.Add(cmdKey, cmd); } else { for (int i = 0; i < arguments.Length; i++) { cmd.Parameters[i].Value = arguments[i]; } } var list = new List <IEntity>(); using (SqliteDataReader r = cmd.ExecuteReader()) { if (r.HasRows) { while (r.Read()) { IEntity entity = EntityFactory.CreateInstance(type); n = 0; foreach (string column in columns) { Type t = type.GetPropertyType(column); if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable <>)) { t = Nullable.GetUnderlyingType(t); } object value = r[n]; if (value is DBNull) { value = null; } else { if (t == typeof(IDbRef)) { value = DbRef.FromString(value.ToString()); } else { if (t == typeof(Guid)) { Guid g; if (!Guid.TryParse(value.ToString(), out g)) { if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable <>)) { value = null; } else { throw new ArgumentException(String.Format("Can't convert value '{0}' to System.Guid", value)); } } else { value = g; } } else { value = Convert.ChangeType(value, t); } } } entity.SetValue(column, value); n++; } bool isTombstone = !useView && (long)r["IsTombstone"] != 0; var sqliteEntity = (ISqliteEntity)entity; sqliteEntity.IsTombstone = isTombstone; sqliteEntity.Load((long)r["IsDirty"] != 0); list.Add(entity); } } } return(list); } }
/////////////////////////// Static access methods //////////////////////// /// <summary> /// Gets entity service from its factory /// This method only simplifies the factory calls /// </summary> /// <param name="additionalDataKey">additional data key. it can be empty</param> /// <returns>Entity service</returns> public static ITimeSeriesStripService GetService(string additionalDataKey = "") { return((ITimeSeriesStripService)EntityFactory.GetEntityServiceByName(vTimeSeriesStrip.EntityName, additionalDataKey)); }
private MediaChannel GetChannelDetails(MediaServicesAccountConfig account, IChannel ch) { var channel = EntityFactory.BuildChannelFromIChannel(ch); return(channel); }
/// <summary> /// Adds the base and user currency rates to client context. /// </summary> /// <description> /// Assemble the multi-currency rate information and add it to the ClientContextService for use by the currency control and column. /// </description> /// <param name="pageWorkItem">The page work item.</param> public static void AddBaseUserCurrencyRatesToClientContext(PageWorkItem pageWorkItem) { //Assemble the multi-currency rate information and add it to the ClientContextService for use by the //Currency column control. var ccs = pageWorkItem.Services.Get <ClientContextService>(); //Get Exchange Rate Type: Base Rate. var optionSvc = ApplicationContext.Current.Services.Get <ISystemOptionsService>(); var baseCode = optionSvc.BaseCurrency; if (!string.IsNullOrEmpty(baseCode)) { var baseRate = "1"; if (ccs.CurrentContext.ContainsKey("BaseRateCode")) { ccs.CurrentContext["BaseRateCode"] = baseCode; } else { ccs.CurrentContext.Add("BaseRateCode", baseCode); } if (ccs.CurrentContext.ContainsKey("BaseRate")) { ccs.CurrentContext["BaseRate"] = baseRate; } else { ccs.CurrentContext.Add("BaseRate", baseRate); } } //Get Exchange Rate Type, My Rate from User Options Service. var userOption = ApplicationContext.Current.Services.Get <IUserOptionsService>(); var userExCode = !string.IsNullOrEmpty(userOption.GetCommonOption("Currency", "General")) ? userOption.GetCommonOption("Currency", "General") : baseCode; if (!string.IsNullOrEmpty(userExCode)) { //Set the rate from My Rate code. var er = EntityFactory.GetRepository <IExchangeRate>().FindFirstByProperty("CurrencyCode", userExCode); if (er == null) { return; } var userExRate = er.Rate.GetValueOrDefault(1).ToString(); if (userExRate == "0") { userExRate = "1"; } //Set My Rate and Code on the service. if (ccs.CurrentContext.ContainsKey("MyRateCode")) { ccs.CurrentContext["MyRateCode"].Equals(userExCode); } else { ccs.CurrentContext.Add("MyRateCode", userExCode); } if (ccs.CurrentContext.ContainsKey("MyRate")) { ccs.CurrentContext["MyRate"].Equals(userExRate); } else { ccs.CurrentContext.Add("MyRate", userExRate); } } }
public void SpawnMob(long entityId, Guid uuid, EntityType type, PlayerLocation position, Microsoft.Xna.Framework.Vector3 velocity) { Entity entity = null; if (EntityFactory.ModelByType(type, out var renderer, out EntityData knownData)) { //if (Enum.TryParse(knownData.Name, out type)) //{ // entity = type.Create(null); //} entity = type.Create(null); if (entity == null) { entity = new Entity((int)type, null, BaseClient); } //if (knownData.Height) { entity.Height = knownData.Height; } //if (knownData.Width.HasValue) entity.Width = knownData.Width; if (string.IsNullOrWhiteSpace(entity.NameTag) && !string.IsNullOrWhiteSpace(knownData.Name)) { entity.NameTag = knownData.Name; } } if (entity == null) { Log.Warn($"Could not create entity of type: {(int) type}:{type.ToString()}"); return; } if (renderer == null) { var def = AlexInstance.Resources.BedrockResourcePack.EntityDefinitions.FirstOrDefault(x => x.Value.Filename.Replace("_", "").Equals(type.ToString().ToLowerInvariant())); if (!string.IsNullOrWhiteSpace(def.Key)) { EntityModel model; if (ModelFactory.TryGetModel(def.Value.Geometry["default"], out model) && model != null) { var textures = def.Value.Textures; string texture; if (!textures.TryGetValue("default", out texture)) { texture = textures.FirstOrDefault().Value; } if (AlexInstance.Resources.BedrockResourcePack.Textures.TryGetValue(texture, out Bitmap bmp)) { Texture2D t = TextureUtils.BitmapToTexture2D(AlexInstance.GraphicsDevice, bmp); renderer = new EntityModelRenderer(model, t); } } } } if (renderer == null) { Log.Debug($"Missing renderer for entity: {type.ToString()} ({(int) type})"); return; } if (renderer.Texture == null) { Log.Debug($"Missing texture for entity: {type.ToString()} ({(int) type})"); return; } entity.ModelRenderer = renderer; entity.KnownPosition = position; entity.Velocity = velocity; entity.EntityId = entityId; entity.UUID = new UUID(uuid.ToByteArray()); BaseClient.WorldProvider.SpawnEntity(entityId, entity); }
public async Task <ServiceResult> AddExpForLearnWordAsync(string userId, string wordId, int score, string url = "") { try { int maxScore = 0; // Get learn histories of user based on word IQueryable <LearnWordHistory> histories = this.m_userHistoryRepository .Select(t => t.UserId == userId && t.WordId == wordId); // first learn if (histories.Count() == 0) { // Do nothing } else { // Calculate total score user get from this word maxScore = histories.Max(t => t.ArchivedScore); } // If user archive max score // Not save result if (maxScore >= 10) { return(ServiceResult.Success); } else { // create new score int newScore = 0; // check if add new score larger than 10 if (maxScore >= score) { return(ServiceResult.Success); } else { newScore = score - maxScore; // create exp record UserExperience experience = EntityFactory .CreateUserExperience(userId, Constraint.MemberExpSystem.UserLearnWord.ID, url, newScore); // insert record into database await this.m_userExperienceRepository.InsertAsync(experience); // save changes await this.m_userExperienceRepository.SaveChangesAsync(); // get current user ApplicationUser user = await this.m_userRepository.FindEntityAsync(t => t.Id == userId); // get new exp int newExp = user.CurrentExp + newScore; // Update user.CurrentExp = newExp; // update record await this.m_userRepository.UpdateAsync(user); // save changes await this.m_userRepository.SaveChangesAsync(); // return successful return(ServiceResult.Success); } } } catch (Exception ex) { // return error return(ServiceResult.AddError(ex.Message)); } }
public static FUIStoryWin CreateInstance(Entity domain) { return(EntityFactory.CreateWithParent <FUIStoryWin, GObject>(domain, CreateGObject())); }
private bool CreateZombie(ZombieAgent zombie, PlayerZone zone) { if (!CanSpawnActiveZombie()) { return(false); } var world = GameManager.Instance.World; Chunk chunk = (Chunk)world.GetChunkSync(World.toChunkXZ(Mathf.FloorToInt(zombie.pos.x)), 0, World.toChunkXZ(Mathf.FloorToInt(zombie.pos.z))); if (chunk == null) { #if DEBUG Log.Out("[WalkerSim] Chunk not loaded at {0} {1}", zombie.pos, zombie.pos.z); #endif return(false); } int height = world.GetTerrainHeight(Mathf.FloorToInt(zombie.pos.x), Mathf.FloorToInt(zombie.pos.z)); Vector3 spawnPos = new Vector3(zombie.pos.x, height + 1.0f, zombie.pos.z); if (!CanZombieSpawnAt(spawnPos)) { #if DEBUG Log.Out("[WalkerSim] Unable to spawn zombie at {0}, CanMobsSpawnAtPos failed", spawnPos); #endif return(false); } if (zombie.classId == -1) { zombie.classId = _biomeData.GetZombieClass(world, chunk, (int)spawnPos.x, (int)spawnPos.z, _prng); if (zombie.classId == -1) { int lastClassId = -1; zombie.classId = EntityGroups.GetRandomFromGroup("ZombiesAll", ref lastClassId); #if DEBUG Log.Out("Used fallback for zombie class!"); #endif } } EntityZombie zombieEnt = EntityFactory.CreateEntity(zombie.classId, spawnPos) as EntityZombie; if (zombieEnt == null) { #if DEBUG Log.Error("[WalkerSim] Unable to create zombie entity!, Entity Id: {0}, Pos: {1}", zombie.classId, spawnPos); #endif return(false); } zombieEnt.bIsChunkObserver = true; { // Send zombie towards a random position in the zone. Vector3 targetPos = GetRandomZonePos(zone); if (targetPos == Vector3.zero) { zombieEnt.SetInvestigatePosition(zone.center, 6000, false); } else { zombieEnt.SetInvestigatePosition(targetPos, 6000, false); } } // If the zombie was previously damaged take health to this one. if (zombie.health != -1) { zombieEnt.Health = zombie.health; } else { zombie.health = zombieEnt.Health; } zombieEnt.IsHordeZombie = true; zombieEnt.IsBloodMoon = _state.IsBloodMoon; zombieEnt.SetSpawnerSource(EnumSpawnerSource.StaticSpawner); world.SpawnEntityInWorld(zombieEnt); zombie.entityId = zombieEnt.entityId; zombie.currentZone = zone; zombie.lifeTime = world.GetWorldTime(); zone.numZombies++; #if DEBUG Log.Out("[WalkerSim] Spawned zombie {0} at {1}", zombieEnt, spawnPos); #endif lock (_activeZombies) { _activeZombies.Add(zombie); } return(true); }
/// <summary> /// Handles the RowCommand event of the ContactMarketing control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCommandEventArgs"/> instance containing the event data.</param> protected void ContactMarketing_RowCommand(object sender, GridViewCommandEventArgs e) { ITargetResponse targetResponse = null; string targetId = String.Empty; string responseId = String.Empty; try { int rowIndex = Convert.ToInt32(e.CommandArgument); targetId = grdContactMarketing.DataKeys[rowIndex].Values[0].ToString(); responseId = grdContactMarketing.DataKeys[rowIndex].Values[1].ToString(); if (!string.IsNullOrEmpty(responseId)) { targetResponse = EntityFactory.GetRepository <ITargetResponse>().Get(responseId); } } catch { } switch (e.CommandName.ToUpper()) { case "EDIT": if (String.IsNullOrEmpty(targetId)) { AddResponseAndTarget(); } else { if (targetResponse == null) { targetResponse = EntityFactory.Create <ITargetResponse>(); ICampaignTarget target = EntityFactory.GetRepository <ICampaignTarget>().Get(targetId); targetResponse.Campaign = target.Campaign; targetResponse.CampaignTarget = target; } ShowResponseView(targetResponse); } break; case "DELETE": if (targetResponse != null) { ICampaignTarget campaignTarget = targetResponse.CampaignTarget; if (campaignTarget.TargetResponses.Count <= 1) { campaignTarget.Status = GetLocalResourceObject("TargetStatus_Removed").ToString(); } campaignTarget.TargetResponses.Remove(targetResponse); targetResponse.Delete(); LoadMarketing(); } else { RemoveTargetAssociation(targetId); } break; case "REMOVE": RemoveTargetAssociation(targetId); break; case "SORT": break; } }
/// <summary> /// Handles the RowCommand event of the grdStages control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCommandEventArgs"/> instance containing the event data.</param> protected void grdStages_RowCommand(object sender, GridViewCommandEventArgs e) { int rowIndex = Convert.ToInt32(e.CommandArgument); string id = grdStages.DataKeys[rowIndex].Value.ToString(); string[] result = id.Split(':'); switch (e.CommandName) { case "AddTask": if (result[1] == "S") { LoadTaskView(GetLocalResourceObject("DialogCaption_AddTask").ToString(), "Add", result[0], String.Empty); } break; case "Edit": if (result[1] == "S") //Stage { LoadStageView(GetLocalResourceObject("DialogCaption_EditStage").ToString(), "Edit", result[0]); } else if (result[1] == "T") //Task { LoadTaskView(GetLocalResourceObject("DialogCaption_EditTask").ToString(), "Edit", String.Empty, result[0]); } break; case "Complete": if (result[1] == "S") //Stage { LoadStageView(GetLocalResourceObject("DialogCaption_CompleteStage").ToString(), "Complete", result[0]); } else if (result[1] == "T") //Task { LoadTaskView(GetLocalResourceObject("DialogCaption_CompleteTask").ToString(), "Complete", String.Empty, result[0]); } break; case "Delete": if (result[1] == "S") //Stage { ICampaignStage stage = EntityFactory.GetById <ICampaignStage>(result[0]); if (stage != null) { stage.Campaign.CampaignStages.Remove(stage); stage.Delete(); } } else if (result[1] == "T") //Task { ICampaignTask task = EntityFactory.GetById <ICampaignTask>(result[0]); if (task != null) { task.CampaignStage.CampaignTasks.Remove(task); task.Campaign.CampaignTasks.Remove(task); task.Delete(); } } break; } if (PageWorkItem != null) { IPanelRefreshService refresher = PageWorkItem.Services.Get <IPanelRefreshService>(); if (refresher != null) { refresher.RefreshAll(); } } }
public new void TearDown() { EntityFactory.Dispose(); NewSandboxProject(); }
protected override Schedule CreateSandboxSchedule() { return(EntityFactory.Create(() => Instance.Create.Schedule(SandboxName, TimeSpan.FromDays(14), TimeSpan.FromDays(0)))); }
public void InitSinglePlayerServer(WorldParameters worldParam) { if (Server != null) { throw new InvalidOperationException("Already initialized"); } _worldParam = worldParam; _serverFactory = new EntityFactory(); _serverFactory.Config = _worldParam.Configuration; var dbPath = Path.Combine(_vars.ApplicationDataPath, "Server", "Singleplayer", worldParam.WorldName, "ServerWorld.db"); logger.Info("Local world db path is {0}", dbPath); _serverSqliteStorageSinglePlayer = new SqliteStorageManager(dbPath, _serverFactory, worldParam); _serverSqliteStorageSinglePlayer.Register("local", "qwe123".GetSHA1Hash(), UserRole.Administrator); var settings = new XmlSettingsManager <ServerSettings>(@"Server\localServer.config"); settings.Load(); settings.Save(); //Utopia New Landscape Test IWorldProcessor processor = null; IEntitySpawningControler entitySpawningControler = null; switch (worldParam.Configuration.WorldProcessor) { case WorldConfiguration.WorldProcessors.Flat: processor = new FlatWorldProcessor(); break; case WorldConfiguration.WorldProcessors.Utopia: processor = new UtopiaProcessor(worldParam, _serverFactory, _landscapeEntityManager); entitySpawningControler = new UtopiaEntitySpawningControler((UtopiaWorldConfiguration)worldParam.Configuration); break; default: break; } var worldGenerator = new WorldGenerator(worldParam, processor); worldGenerator.EntitySpawningControler = entitySpawningControler; //Old s33m3 landscape //IWorldProcessor processor1 = new s33m3WorldProcessor(worldParam); //IWorldProcessor processor2 = new LandscapeLayersProcessor(worldParam, _serverFactory); //var worldGenerator = new WorldGenerator(worldParam, processor1, processor2); //Vlad Generator //var planProcessor = new PlanWorldProcessor(wp, _serverFactory); //var worldGenerator = new WorldGenerator(wp, planProcessor); settings.Settings.ChunksCountLimit = 1024 * 3; // better use viewRange * viewRange * 3 var port = 4815; while (!TcpConnectionListener.IsPortFree(port)) { port++; } settings.Settings.ServerPort = port; _server = new ServerCore(settings, worldGenerator, _serverSqliteStorageSinglePlayer, _serverSqliteStorageSinglePlayer, _serverSqliteStorageSinglePlayer, _serverSqliteStorageSinglePlayer, _serverFactory, worldParam); _serverFactory.LandscapeManager = Server.LandscapeManager; _serverFactory.DynamicEntityManager = Server.AreaManager; _serverFactory.GlobalStateManager = Server.GlobalStateManager; _serverFactory.ScheduleManager = Server.Scheduler; _serverFactory.ServerSide = true; _server.Initialize(); Server.ConnectionManager.LocalMode = true; Server.ConnectionManager.Listen(); Server.LoginManager.PlayerEntityNeeded += LoginManagerPlayerEntityNeeded; Server.LoginManager.GenerationParameters = default(Utopia.Shared.World.PlanGenerator.GenerationParameters); // planProcessor.WorldPlan.Parameters; Server.Clock.SetCurrentTimeOfDay(UtopiaTimeSpan.FromHours(12)); }
/// <summary> /// Gets entity object for view from its factory /// This method only simplifies the factory calls /// </summary> /// <returns>Entity object</returns> public static vTimeSeriesStrip GetEntityObjectV() { return((vTimeSeriesStrip)EntityFactory.GetEntityObject(vTimeSeriesStrip.EntityName, GetSourceTypeEnum.View)); }
public UserDatabaseInstance GenerateUserDatabaseInstance(DatabaseVersion databaseVersion) { // TODO: this part probably needs some optimization // Load server instances that can store user databases var ef = new EntityFactory(Context); var sis = ef.FindAll<ServerInstance>() .Where(i => i.ServerVersionReference.Guid == databaseVersion.ServerVersionReference.Guid) .OrderBy(i => i.Machine.Number) .ToArray(); if (sis.Length == 0) { throw new InvalidOperationException("At least one server instance has to configured for the database version."); // TODO } // Get current number of user databases var dd = databaseVersion.DatabaseDefinition; dd.LoadDatabaseInstances(false); var dbnum = dd.DatabaseInstances.Count; // Find a server that is available int off = 0; int sin = 0; while (off < sis.Length) { sin = (dbnum + 1 + off) % sis.Length; bool ok = true; var diag = sis[sin].RunDiagnostics(); foreach (var d in diag) { if (d.Status != DiagnosticMessageStatus.OK) { ok = false; break; } } if (ok) { break; } off++; } // Default slice (FULL) dd.LoadSlices(false); var sl = dd.Slices[Constants.FullSliceName]; // Create physical database instance var ddi = new DatabaseInstanceInstaller(databaseVersion.DatabaseDefinition); var di = ddi.GenerateDatabaseInstance( sis[sin], sl, databaseVersion); di.Save(); // Add user database mapping var udi = new UserDatabaseInstance(user); udi.DatabaseVersion = databaseVersion; udi.DatabaseInstance = di; udi.Save(); return udi; }
public ToolBarUi(PlayerEntityManager player, IconFactory iconFactory, InputsManager inputManager, EntityFactory factory) { _playerManager = player; _factory = factory; Name = "Toolbar"; int nbrButton = _playerManager.PlayerCharacter.Toolbar.Count; _toolbarSlots = new List <InventoryCell>(nbrButton); //float fromX = ((bounds.Right.Offset - bounds.Left.Offset) - (ButtonSize * (nbrButton))) / 2; for (int x = 0; x < nbrButton; x++) { var btn = new InventoryCell(null, iconFactory, new Vector2I(0, x), inputManager) { //Bounds = new UniRectangle(fromX + (x * ButtonSize), 0, ButtonSize, ButtonSize) DrawCellBackground = false }; btn.MouseDown += BtnMouseDown; btn.MouseUp += btn_MouseUp; btn.MouseEnter += btn_MouseEnter; btn.MouseLeave += btn_MouseLeave; var bluePrintId = _playerManager.PlayerCharacter.Toolbar[x]; if (bluePrintId != 0) { btn.Slot = _playerManager.PlayerCharacter.FindSlot(s => s.Item.BluePrintId == bluePrintId); if (btn.Slot == null) { try { btn.Slot = new ContainedSlot { Item = (IItem)_factory.CreateFromBluePrint(bluePrintId) }; } catch (ArgumentOutOfRangeException) { _playerManager.PlayerCharacter.Toolbar[x] = 0; logger.Error("Unable to create entity from Id = {0}. Configuration was probably changed.", bluePrintId); } } } _toolbarSlots.Add(btn); Children.Add(btn); } }
protected override void GetInitializedQuery_Graywulf(QueryBase query, string queryString, string outputTable) { var federationname = Federation.AppSettings.FederationName; var ef = new EntityFactory(Context); var federation = ef.LoadEntity<Federation>(federationname); var jd = ef.LoadEntity<JobDefinition>(federationname, typeof(SqlQueryJob).Name); var user = new User(Context); user.Guid = Context.UserGuid; user.Load(); // Load settings // **** TODO: this always takes settings from SqlQueryJob!! var settings = Jhu.Graywulf.Registry.Util.LoadSettings<Settings>(jd.Settings); query.ExecutionMode = ExecutionMode.Graywulf; query.FederationReference.Name = federationname; query.QueryString = queryString; query.SourceDatabaseVersionName = settings[Settings.HotDatabaseVersionName]; query.StatDatabaseVersionName = settings[Settings.StatDatabaseVersionName]; query.QueryTimeout = int.Parse(settings[Settings.LongQueryTimeout]); // Add MyDB as custom source var mydbds = new GraywulfDataset(); mydbds.Name = settings[Settings.DefaultDatasetName]; mydbds.DefaultSchemaName = settings[Settings.DefaultSchemaName]; mydbds.DatabaseInstance.Value = user.GetUserDatabaseInstance(federation.MyDBDatabaseVersion); mydbds.CacheSchemaConnectionString(); query.CustomDatasets.Add(mydbds); query.DefaultDataset = mydbds; // Set up MYDB for destination // ****** TODO add output table name to settings */ query.Destination.Table = new Table() { Dataset = mydbds, SchemaName = settings[Settings.DefaultSchemaName], TableName = String.IsNullOrWhiteSpace(outputTable) ? "outputtable" : outputTable }; query.Destination.Operation = DestinationTableOperation.Drop | DestinationTableOperation.Create; // Set up temporary database var tempds = new GraywulfDataset(); tempds.IsOnLinkedServer = false; tempds.DatabaseVersion.Value = federation.TempDatabaseVersion; query.TemporaryDataset = tempds; query.TemporaryDataset.DefaultSchemaName = settings[Settings.TemporarySchemaName]; // Set up code database var codeds = new GraywulfDataset(); codeds.Name = "Code"; // *** TODO codeds.IsOnLinkedServer = false; codeds.DatabaseVersion.Value = federation.CodeDatabaseVersion; query.CodeDataset = codeds; query.CodeDataset.DefaultSchemaName = "dbo"; // *** TODO }
protected override Project CreateSandboxProject(Project rootProject) { return(EntityFactory.CreateProjectWithSchedule(SandboxName, rootProject)); }