public ExperimentObserver(StorageCache cache, ExperimentSettings expSettings, BiomeFilter filter, ScanInterface scanMapInterface, string expid, ModuleScienceExperiment exp = null) { settings = expSettings; biomeFilter = filter; requireControllable = true; if (exp != null) { rerunnable = exp.rerunnable; resettable = exp.resettable; } if (scanMapInterface == null) { scanMapInterface = new DefaultScanInterface(); } scanInterface = scanMapInterface; experiment = ResearchAndDevelopment.GetExperiment(expid); if (experiment == null) { Log.Error("Failed to get experiment '{0}'", expid); } storage = cache; Rescan(); }
protected virtual void PreLoadExecute(IDictionary <string, IStorageContext> storageContexts) { foreach (KeyValuePair <string, IStorageContext> context in storageContexts) { IStorageContext storageContext = context.Value; string sConnection = StorageParser.BuildConnectionString(storageContext.Storage); storageContext.Connection = storageContext.Storage.Pooling ? DbConnectionPoolManager.GetConnection(storageContext.StorageName, sConnection) : DatabaseFactory.GetDbConnection(storageContext.Storage.DatabaseStyle, sConnection); try { if (ConnectionState.Open != storageContext.Connection.State) { storageContext.Connection.Open(); } } catch (Exception exc) { IStorageAttribute storageAttr = (IStorageAttribute)StorageCache.Get(storageContext.StorageName); storageAttr.IsHealth = false; UnhealthyStorage.Add(storageAttr.Name); if (null != Logger) { Logger.WarnFormat("Storage:{0} can not open.Set the health is false and it not used until the health set true.", storageAttr.Name); } IConnectionNotify notify = AlbianServiceRouter.GetService <IConnectionNotify>(); if (null != notify) { Logger.Info("send message when open database is error."); string msg = string.Format("Server:{0},Database:{1},Exception Message:{2}.", storageContext.Storage.Server, storageContext.Storage.Database, exc.Message); notify.SendMessage(msg); } throw exc; } if (storageContext.Storage.Transactional) { storageContext.Transaction = storageContext.Connection.BeginTransaction(IsolationLevel.ReadUncommitted); } foreach (IFakeCommandAttribute fc in storageContext.FakeCommand) { IDbCommand cmd = storageContext.Connection.CreateCommand(); cmd.CommandText = fc.CommandText; cmd.CommandType = CommandType.Text; if (storageContext.Storage.Transactional) { cmd.Transaction = storageContext.Transaction; } foreach (DbParameter para in fc.Paras) { cmd.Parameters.Add(para); } storageContext.Command.Add(cmd); } } }
public ITask BuildQueryTask <T>(string rountingName, int top, IFilterCondition[] where, IOrderByCondition[] orderby) where T : class, IAlbianObject, new() { ITask task = new Task(); IFakeCommandBuilder fakeBuilder = new FakeCommandBuilder(); IStorageContextBuilder storageContextBuilder = new StorageContextBuilder(); IDictionary <string, IStorageContext> storageContexts = storageContextBuilder.GenerateStorageContexts <T>(rountingName, top, where, orderby); task.Context = storageContexts; foreach (KeyValuePair <string, IStorageContext> context in task.Context) { IStorageContext storageContext = context.Value; object oStorage = StorageCache.Get(context.Key); if (null == oStorage) { if (null != Logger) { Logger.ErrorFormat("There is no {0} storage attribute in the storage cached.", storageContext.StorageName); } return(null); } IStorageAttribute storage = (IStorageAttribute)oStorage; storageContext.Storage = storage; } return(task); }
public ITask BuildSaveTask <T>(T target) where T : IAlbianObject { ITask task = new Task(); IFakeCommandBuilder fakeBuilder = new FakeCommandBuilder(); IStorageContextBuilder storageContextBuilder = new StorageContextBuilder(); task.Context = storageContextBuilder.GenerateStorageContexts(target, fakeBuilder.GenerateFakeCommandByRoutings, fakeBuilder.BuildSaveFakeCommandByRouting); foreach (KeyValuePair <string, IStorageContext> context in task.Context) { IStorageContext storageContext = context.Value; object oStorage = StorageCache.Get(context.Key); if (null == oStorage) { if (null != Logger) { Logger.ErrorFormat("There is no {0} storage attribute in the storage cached.", storageContext.StorageName); } return(null); } IStorageAttribute storage = (IStorageAttribute)oStorage; storageContext.Storage = storage; } return(task); }
public static IStorageAttribute GetStorage(string storageName) { if (null == storageName) { throw new ArgumentNullException("storageName"); } if (!StorageCache.Exist(storageName)) { return(null); } return((IStorageAttribute)StorageCache.Get(storageName)); }
public bool Test(string storageName) { IStorageAttribute storageAttr = (IStorageAttribute)StorageCache.Get(storageName); string sConnection = StorageParser.BuildConnectionString(storageAttr); IDbConnection conn = storageAttr.Pooling ? DbConnectionPoolManager.GetConnection(storageName, sConnection) : DatabaseFactory.GetDbConnection(storageAttr.DatabaseStyle, sConnection); try { if (ConnectionState.Open != conn.State) { conn.Open(); } IDbCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT 1 AS Row"; cmd.CommandType = CommandType.Text; object oValue = cmd.ExecuteScalar(); int value; if (int.TryParse(oValue.ToString(), out value) && 1 == value) { return(true); } else { return(false); } } catch (Exception exc) { return(false); } finally { if (ConnectionState.Closed != conn.State) { conn.Close(); } if (storageAttr.Pooling) { DbConnectionPoolManager.RetutnConnection(storageAttr.Name, conn); } else { conn.Dispose(); conn = null; } } }
public NodeCacheBase(BPlusTreeOptions <TKey, TValue> options) { Options = options; LockFactory = Options.LockingFactory; Storage = Options.CreateStorage(); if (Options.UseStorageCache) { Storage = new StorageCache(Storage, Options.CacheKeepAliveMaximumHistory); } NodeSerializer = new NodeSerializer(Options, new NodeHandleSerializer(Storage)); _version = new NodeVersion(); }
public event Callback OnExperimentsScanned = delegate { }; // called whenever the observers rescan the ship, typically void Awake() { vesselStorage = gameObject.AddComponent <StorageCache>(); biomeFilter = gameObject.AddComponent <BiomeFilter>(); scienceAlert = gameObject.GetComponent <ScienceAlert>(); audio = GetComponent <AudioPlayer>() ?? AudioPlayer.Audio; scienceAlert.OnScanInterfaceChanged += OnScanInterfaceChanged; scienceAlert.OnToolbarButtonChanged += OnToolbarButtonChanged; GameEvents.onVesselWasModified.Add(OnVesselWasModified); GameEvents.onVesselChange.Add(OnVesselChanged); GameEvents.onVesselDestroy.Add(OnVesselDestroyed); }
private PermissionManager(string store, string connection) { cache = new StorageCache(connection); try { cache.BuildStorageCache(); //cache.BuildStorageCache(store); } catch (Exception exception) { throw new ApplicationException("Unable to initialize NetSqlAzMan security store", exception); } }
protected override IStorageAttribute ParserStorage(XmlNode node) { if (null == node) { throw new ArgumentNullException("node"); } IStorageAttribute storageAttribute = GenerateStorageAttribute(node); if (string.IsNullOrEmpty(storageAttribute.Uid) && !storageAttribute.IntegratedSecurity) { throw new Exception("the database authentication mechanism is error."); } StorageCache.InsertOrUpdate(storageAttribute.Name, storageAttribute); return(storageAttribute); }
protected void Page_Load(object sender, EventArgs e) { this.storage = this.Session["storage"] as IAzManStorage; if (this.Session["selectedObject"] as IAzManStore != null) { IAzManStore store = ((IAzManStore)this.Session["selectedObject"]); this.applications = new IAzManApplication[store.Applications.Count]; store.Applications.Values.CopyTo(this.applications, 0); } else { this.applications = new IAzManApplication[] { (IAzManApplication)this.Session["selectedObject"] }; } this.Text = "Effective Permissions"; this.Description = String.Empty; this.Title = this.Text; this.reportMode(true); //Build Storage Cache this.storageCache = new StorageCache(this.applications[0].Store.Storage.ConnectionString); this.storageCache.BuildStorageCache(this.applications[0].Store.Name); //Get All Domain Users this.userUPNs = NetSqlAzMan.DirectoryServices.DirectoryServicesUtils.GetAllDomainUsers(); string nowaitpanel = this.Request["nowaitpanel"]; if (String.IsNullOrEmpty(nowaitpanel)) { if (!Page.IsPostBack) { this.showWaitPanelNow(this.pnlWait, this.itemsHierachyPanel); this.RegisterEndClientScript("window.location='rptEffectivePermissions.aspx?nowaitpanel=true';"); } } else if (nowaitpanel == "true") { this.itemsHierachyPanel.Visible = true; this.pnlWait.Visible = false; if (!Page.IsPostBack) { this.buildApplicationsTreeView(); this.itemsHierarchyTreeView.ExpandAll(); } } }
public List <Role> GetUserPermissionsNotification(string userName, string store, string application) { //throw new NotImplementedException(); //string userSid = userId.ToString("X"); //string zeroes = string.Empty; //for (int start = 0; start < 8 - userSid.Length; start++) // zeroes += "0"; string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CatsContext"].ConnectionString; IAzManStorage AzManStore = new SqlAzManStorage(connectionString); StorageCache storage = new StorageCache(connectionString); //storage.BuildStorageCache(store, application); //new AuthorizedItem(){} //AuthorizedItem[] items = storage.GetAuthorizedItems(store, application, AzManStore.GetDBUser(userName).CustomSid.StringValue, DateTime.Now); //AuthorizedItem[] items = storage.GetAuthorizedItems("CATS", application, AzManStore.GetDBUser(userName).CustomSid.StringValue, DateTime.Now, null); var allItems = storage.Storage.GetStore(store).GetApplication(application).Items; ////var d = CheckAccess(AzManStore.GetDBUser(userName), application, "EW Coordinator", AzManStore); var roleItems = ( from t in allItems where t.Value.ItemType == ItemType.Role select t ); var roles = new List <Role>(); foreach (var item in roleItems) { var r = new Role(); r.RoleName = item.Value.Name; r.IsChecked = CheckAccess(AzManStore.GetDBUser(userName), application, item.Value.Name, AzManStore); if (r.IsChecked) { roles.Add(r); } } //AuthorizedItem[] items = storage.GetAuthorizedItems(); //var f =(from t in items where t.Authorization == AuthorizationType.Allow && t.Type == ItemType.Role select new Role { RoleName = t.Name }).ToList(); return(roles); }
public void Check() { while (true) { Hashtable ht = UnhealthyStorage.UnhealthyStorages; if (0 != ht.Count) { foreach (KeyValuePair <string, string> kv in ht) { if (Test(kv.Value)) { IStorageAttribute storageAttr = (IStorageAttribute)StorageCache.Get(kv.Value); storageAttr.IsHealth = true; } } } Thread.Sleep(300 * 1000); } }
/// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception> /// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider has already been initialized.</exception> /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception> public override void Initialize(string name, NameValueCollection config) { if (config["connectionStringName"] == null) { throw new ArgumentNullException("connectionStringName", "Connection String parameter required."); } if (System.Configuration.ConfigurationManager.ConnectionStrings[config["connectionStringName"]] == null) { throw new ApplicationException(String.Format("Connection String name=\"{0}\" not found.", config["connectionStringName"])); } if (config["storeName"] == null) { throw new ArgumentNullException("storeName", "Store Name parameter required."); } if (config["applicationName"] == null) { throw new ArgumentNullException("applicationName", "Application Name parameter required."); } if (config["userLookupType"] == null) { throw new ArgumentNullException("userLookupType", "userLookupType Name parameter required."); } if (config["userLookupType"] != "LDAP" && config["userLookupType"] != "DB") { throw new ArgumentNullException("userLookupType", "userLookupType invalid parameter. Possible values: \"LDAP\", \"DB\"."); } if (config["defaultDomain"] == null) { throw new ArgumentNullException("defaultDomain", "defaultDomain Name parameter required."); } base.Initialize(name, config); this.storeName = config["storeName"]; this.applicationName = config["applicationName"]; this.useWCFCacheService = config["UseWCFCacheService"] == null ? false : Boolean.Parse(config["UseWCFCacheService"]); this.storageCache = new StorageCache(System.Configuration.ConfigurationManager.ConnectionStrings[config["connectionStringName"]].ConnectionString); this.InvalidateCache(true); this.UserLookupType = config["userLookupType"]; this.DefaultDomain = config["defaultDomain"]; }
public byte[] ReadStorage(byte[] key) { // If we already have cached storage data, return it. Otherwise we'll need to cache some. if (!StorageCache.TryGetValue(key, out var val)) { // We obtain the value from our storage trie, cache it, and decode it, as it's RLP encoded. byte[] value = StorageTrie.Get(key); if (value == null) { val = null; } else { val = RLP.Decode(value); } StorageCache[key] = val; } // Return our storage key. return(val); }
public Loader( string downloadRoot, string storageCacheRoot, IAssetFileDatabase database, int parallelDownloadCount = 16, int downloadRetryCount = 3, int timeoutSeconds = 30, int fileWriteBufferSize = 16 * 1024 * 1024, int downloadHandlerBufferSize = 16 * 1024) { _storageCache = new StorageCache(storageCacheRoot, database); _fileWriter = new FileWriter( storageCacheRoot, StorageCache.temporaryFilePostfix, fileWriteBufferSize); _downloadRetryCount = downloadRetryCount; _parallelDownloadCount = parallelDownloadCount; _timeoutSeconds = timeoutSeconds; _database = database; _downloadRoot = downloadRoot + "/"; _downloadHandlerBuffers = new byte[_parallelDownloadCount][]; for (int i = 0; i < _parallelDownloadCount; i++) { _downloadHandlerBuffers[i] = new byte[downloadHandlerBufferSize]; } _assetHandles = new Dictionary <string, AssetHandle>(); _watchingAssetHandles = new List <AssetHandle>(); _downloadHandles = new Dictionary <string, DownloadHandle>(); _waitingDownloadHandles = new LinkedList <DownloadHandle>(); _goingDownloadHandles = new DownloadHandle[_parallelDownloadCount]; // 固定的に取り、バッファとの対応を固定化する _fileHandles = new Dictionary <string, FileHandle>(); _watchingFileHandles = new List <FileHandle>(); }
public void CommitStorageChanges() { // For each storage cache item, we want to flush those changes to the main trie/database. foreach (var key in StorageCache.Keys) { // If the value is null, it means the value is non existent anymore, so we remove the key value pair if (StorageCache[key] == null) { StorageTrie.Remove(key); } else { // Otherwise we set the new value. StorageTrie.Set(key, RLP.Encode(StorageCache[key])); } } // Now we clear our cache. StorageCache.Clear(); // And update our account's storage root hash. StorageRoot = StorageTrie.GetRootNodeHash(); }
protected override IDictionary <string, IStorageAttribute> ParserStorages(XmlNode node) { if (null == node) { throw new ArgumentNullException("node"); } XmlNodeList nodes = node.SelectNodes("Storage"); if (null == nodes || 0 == nodes.Count) { throw new Exception("the Storage node is empty in the Storage..config"); } IDictionary <string, IStorageAttribute> dic = new Dictionary <string, IStorageAttribute>(); int idx = 0; foreach (XmlNode n in nodes) { IStorageAttribute storageAttribute = ParserStorage(n); if (null != storageAttribute) { dic.Add(storageAttribute.Name, storageAttribute); if (0 == idx) { //insert the default storage //the default is the first storage StorageCache.InsertOrUpdate(DefaultStorageName, storageAttribute); } idx++; } } if (0 == dic.Count) { throw new Exception("the error in the storage.config"); } return(dic); }
/****************************************************************************** * Implementation Details ******************************************************************************/ public ExperimentObserver(StorageCache cache, ProfileData.ExperimentSettings expSettings, BiomeFilter filter, ScanInterface scanMapInterface, string expid) { settings = expSettings; biomeFilter = filter; requireControllable = true; if (scanMapInterface == null) { Log.Warning("ExperimentObserver for {0} given null scanning interface. Using default.", expid); scanMapInterface = new DefaultScanInterface(); } scanInterface = scanMapInterface; experiment = ResearchAndDevelopment.GetExperiment(expid); if (experiment == null) { Log.Error("Failed to get experiment '{0}'", expid); } storage = cache; Rescan(); }
public SurfaceSampleObserver(StorageCache cache, ProfileData.ExperimentSettings settings, BiomeFilter filter, ScanInterface scanInterface) : base(cache, settings, filter, scanInterface, "surfaceSample") { }
public EvaReportObserver(StorageCache cache, ProfileData.ExperimentSettings settings, BiomeFilter filter, ScanInterface scanInterface, string expid = "evaReport") : base(cache, settings, filter, scanInterface, expid) { }
/// <summary> /// Prints the body. /// </summary> /// <param name="e">The <see cref="T:System.Drawing.Printing.PrintPageEventArgs"/> instance containing the event data.</param> protected override bool PrintPageBody(PrintPageEventArgs e) { float parentStoreX; float parentStoreY; if (this.applications == null || this.applications.Length == 0) { return(false); } //Build Storage Cache this.storageCache = new StorageCache(this.applications[0].Store.Storage.ConnectionString); this.storageCache.BuildStorageCache(this.applications[0].Store.Name); //Get All Domain Users this.userUPNs = NetSqlAzMan.DirectoryServices.DirectoryServicesUtils.GetAllDomainUsers(); base.SkipLines(e, 1); if (!this.alreadyPrinted.Contains(this.applications[0].Store)) { this.alreadyPrinted.Add(this.applications[0].Store); base.WriteLineString("\t", Properties.Resources.Store_16x16, String.Format("{0}{1}", this.applications[0].Store.Name, (String.IsNullOrEmpty(this.applications[0].Store.Description) ? String.Empty : String.Format(" - {0}", this.applications[0].Store.Description))), e); } parentStoreX = base.lastX + Properties.Resources.Store_16x16.Size.Width / 2; parentStoreY = base.lastY + Properties.Resources.Store_16x16.Size.Height + 3; if (base.EOP) { return(true); } float parentApplicationX = 0.0F; float parentApplicationY = 0.0F; foreach (IAzManApplication app in this.applications) { if (!this.alreadyPrinted.Contains(app)) { base.WriteLineString("\t\t", Properties.Resources.Application_16x16, String.Format("{0}{1}", app.Name, (String.IsNullOrEmpty(app.Description) ? String.Empty : String.Format(" - {0}", app.Description))), e); parentApplicationX = base.lastX + Properties.Resources.Application_16x16.Width / 2; parentApplicationY = base.lastY + Properties.Resources.Application_16x16.Height + 3; this.currentY += 3; e.Graphics.DrawLine(base.pen, e.Graphics.MeasureString("\t\t", this.font).Width + Properties.Resources.Application_16x16.Size.Width + 3, this.currentY, this.right, this.currentY); this.currentY += 3; this.alreadyPrinted.Add(app); if (base.EOP) { return(true); } } //Roles foreach (IAzManItem role in app.Items.Values) { if (role.ItemType == ItemType.Role) { if (this.PrintItem(e, role, 3, parentApplicationX, parentApplicationY)) { return(true); } } } //Tasks foreach (IAzManItem task in app.Items.Values) { if (task.ItemType == ItemType.Task) { if (this.PrintItem(e, task, 3, parentApplicationX, parentApplicationY)) { return(true); } } } //Operations foreach (IAzManItem operation in app.Items.Values) { if (operation.ItemType == ItemType.Operation) { if (this.PrintItem(e, operation, 3, parentApplicationX, parentApplicationY)) { return(true); } } } } return(false); }
public IFakeCommandAttribute GenerateQuery <T>(string rountingName, int top, IFilterCondition[] where, IOrderByCondition[] orderby) where T : class, IAlbianObject, new() { Type type = typeof(T); string fullName = AssemblyManager.GetFullTypeName(type); object oProperties = PropertyCache.Get(fullName); PropertyInfo[] properties; if (null == oProperties) { if (null != Logger) { Logger.Error("Get the object property info from cache is null.Reflection now and add to cache."); } throw new PersistenceException("object property is null in the cache."); } properties = (PropertyInfo[])oProperties; object oAttribute = ObjectCache.Get(fullName); if (null == oAttribute) { if (null != Logger) { Logger.ErrorFormat("The {0} object attribute is null in the object cache.", fullName); } throw new Exception("The object attribute is null"); } StringBuilder sbSelect = new StringBuilder(); StringBuilder sbCols = new StringBuilder(); StringBuilder sbWhere = new StringBuilder(); StringBuilder sbOrderBy = new StringBuilder(); IObjectAttribute objectAttribute = (IObjectAttribute)oAttribute; IRoutingAttribute routing; if (!objectAttribute.RoutingAttributes.TryGetValue(rountingName, out routing)) { if (null != Logger) { Logger.WarnFormat("There is not routing of the {} object.Albian use the default routing tempate.", rountingName); } routing = objectAttribute.RountingTemplate; } if (0 == (PermissionMode.R & routing.Permission)) { if (null != Logger) { Logger.WarnFormat("The routing permission {0} is no enough.", routing.Permission); } return(null); } IStorageAttribute storageAttr = (IStorageAttribute)StorageCache.Get(routing.StorageName); if (null == storageAttr) { if (null != Logger) { Logger.WarnFormat( "No {0} rounting mapping storage attribute in the sotrage cache.Use default storage.", routing.Name); } storageAttr = (IStorageAttribute)StorageCache.Get(StorageParser.DefaultStorageName); } if (!storageAttr.IsHealth) { if (null != Logger) { Logger.WarnFormat("Routing:{0},Storage:{1} is not health.", routing.Name, storageAttr.Name); } return(null); } IDictionary <string, IMemberAttribute> members = objectAttribute.MemberAttributes; T target = AlbianObjectFactory.CreateInstance <T>(); foreach (PropertyInfo property in properties) { IMemberAttribute member = members[property.Name]; if (!member.IsSave) { continue; } sbCols.AppendFormat("{0},", member.FieldName); if (null != where) { foreach (IFilterCondition condition in where) //have better algorithm?? { if (condition.PropertyName == property.Name) { property.SetValue(target, condition.Value, null); //Construct the splite object break; } } } if (null != orderby) { foreach (IOrderByCondition order in orderby) { if (order.PropertyName == property.Name) { sbOrderBy.AppendFormat("{0} {1},", member.FieldName, System.Enum.GetName(typeof(SortStyle), order.SortStyle)); break; } } } } if (0 != sbOrderBy.Length) { sbOrderBy.Remove(sbOrderBy.Length - 1, 1); } if (0 != sbCols.Length) { sbCols.Remove(sbCols.Length - 1, 1); } IList <DbParameter> paras = new List <DbParameter>(); if (null != where && 0 != where.Length) { foreach (IFilterCondition condition in where) { IMemberAttribute member = members[condition.PropertyName]; if (!member.IsSave) { continue; } sbWhere.AppendFormat(" {0} {1} {2} {3} ", Utils.GetRelationalOperators(condition.Relational), member.FieldName, Utils.GetLogicalOperation(condition.Logical), DatabaseFactory.GetParameterName(storageAttr.DatabaseStyle, member.FieldName)); paras.Add(DatabaseFactory.GetDbParameter(storageAttr.DatabaseStyle, member.FieldName, member.DBType, condition.Value, member.Length)); } } string tableFullName = Utils.GetTableFullName(routing, target); switch (storageAttr.DatabaseStyle) { case DatabaseStyle.MySql: { sbSelect.AppendFormat("SELECT {0} FROM {1} WHERE 1=1 {2} {3} {4}", sbCols, tableFullName, sbWhere, 0 == sbOrderBy.Length ? string.Empty : string.Format("ORDER BY {0}", sbOrderBy), 0 == top ? string.Empty : string.Format("LIMIT {0}", top) ); break; } case DatabaseStyle.Oracle: { if (0 == top) { sbSelect.AppendFormat("SELECT {0} FROM {1} WHERE 1=1 {2} {3}", sbCols, tableFullName, sbWhere, 0 == sbOrderBy.Length ? string.Empty : string.Format("ORDER BY {0}", sbOrderBy)); } else { sbSelect.AppendFormat("SELECT A.* FROM (SELECT {0} FROM {1} WHERE 1=1 {2} {3})A WHERE ROWNUM <= {4}", sbCols, tableFullName, sbWhere, 0 == sbOrderBy.Length ? string.Empty : string.Format("ORDER BY {0}", sbOrderBy), top); } break; } case DatabaseStyle.SqlServer: default: { sbSelect.AppendFormat("SELECT {0} {1} FROM {2} WHERE 1=1 {3} {4}", 0 == top ? string.Empty : string.Format("TOP {0}", top), sbCols, tableFullName, sbWhere, 0 == sbOrderBy.Length ? string.Empty : string.Format("ORDER BY {0}", sbOrderBy)); break; } } IFakeCommandAttribute fakeCommand = new FakeCommandAttribute { CommandText = sbSelect.ToString(), Paras = ((List <DbParameter>)paras).ToArray(), StorageName = storageAttr.Name, }; return(fakeCommand); }
public ITask BuildCreateTask <T>(IList <T> target) where T : IAlbianObject { ITask task = new Task(); IFakeCommandBuilder fakeBuilder = new FakeCommandBuilder(); IStorageContextBuilder storageContextBuilder = new StorageContextBuilder(); foreach (T o in target) { IDictionary <string, IStorageContext> storageContexts = storageContextBuilder.GenerateStorageContexts(o, fakeBuilder . GenerateFakeCommandByRoutings, fakeBuilder . BuildCreateFakeCommandByRouting); if (null == storageContexts || 0 == storageContexts.Count) { if (null != Logger) { Logger.Error("The storagecontexts is empty."); } throw new Exception("The storagecontexts is null."); } if (null == task.Context || 0 == task.Context.Count) { task.Context = storageContexts; continue; } foreach (KeyValuePair <string, IStorageContext> storageContext in storageContexts) { if (task.Context.ContainsKey(storageContext.Key)) { task.Context[storageContext.Key].FakeCommand = task.Context.ContainsKey(storageContext.Key) ? Utils.Concat( task.Context[storageContext.Key]. FakeCommand, storageContext.Value.FakeCommand) : storageContext.Value.FakeCommand; } else { task.Context.Add(storageContext); } } } foreach (KeyValuePair <string, IStorageContext> context in task.Context) { IStorageContext storageContext = context.Value; object oStorage = StorageCache.Get(context.Key); if (null == oStorage) { if (null != Logger) { Logger.ErrorFormat("There is no {0} storage attribute in the storage cached.", storageContext.StorageName); } return(null); } IStorageAttribute storage = (IStorageAttribute)oStorage; storageContext.Storage = storage; } return(task); }
public IFakeCommandAttribute BuildCreateFakeCommandByRouting <T>(PermissionMode permission, T target, IRoutingAttribute routing, IObjectAttribute objectAttribute, PropertyInfo[] properties) where T : IAlbianObject { if (null == routing) { throw new ArgumentNullException("routing"); } if (null == properties || 0 == properties.Length) { throw new ArgumentNullException("properties"); } if (null == objectAttribute) { throw new ArgumentNullException("objectAttribute"); } if (0 == (permission & routing.Permission)) { if (null != Logger) { Logger.WarnFormat("The routing permission {0} is no enough.", permission); } return(null); } //create the connection string IStorageAttribute storageAttr = (IStorageAttribute)StorageCache.Get(routing.StorageName); if (null == storageAttr) { if (null != Logger) { Logger.WarnFormat( "No {0} rounting mapping storage attribute in the sotrage cache.Use default storage.", routing.Name); } storageAttr = (IStorageAttribute)StorageCache.Get(StorageParser.DefaultStorageName); } if (!storageAttr.IsHealth) { if (null != Logger) { Logger.WarnFormat("Routing:{0},Storage:{1} is not health.", routing.Name, storageAttr.Name); } return(null); } var sbInsert = new StringBuilder(); var sbCols = new StringBuilder(); var sbValues = new StringBuilder(); IList <DbParameter> paras = new List <DbParameter>(); //create the hash table name string tableFullName = Utils.GetTableFullName(routing, target); //build the command text IDictionary <string, IMemberAttribute> members = objectAttribute.MemberAttributes; foreach (PropertyInfo property in properties) { object value = property.GetValue(target, null); if (null == value) { continue; } IMemberAttribute member = members[property.Name]; if (!member.IsSave) { continue; } sbCols.AppendFormat("{0},", member.FieldName); string paraName = DatabaseFactory.GetParameterName(storageAttr.DatabaseStyle, member.FieldName); sbValues.AppendFormat("{0},", paraName); paras.Add(DatabaseFactory.GetDbParameter(storageAttr.DatabaseStyle, paraName, member.DBType, value, member.Length)); } int colsLen = sbCols.Length; if (0 < colsLen) { sbCols.Remove(colsLen - 1, 1); } int valLen = sbValues.Length; if (0 < valLen) { sbValues.Remove(valLen - 1, 1); } sbInsert.AppendFormat("INSERT INTO {0} ({1}) VALUES({2}) ", tableFullName, sbCols, sbValues); IFakeCommandAttribute fakeCmd = new FakeCommandAttribute { CommandText = sbInsert.ToString(), Paras = ((List <DbParameter>)paras).ToArray(), StorageName = routing.StorageName }; return(fakeCmd); }
private void CheckNodeAccess(TreeNode tn) { var tag = (ItemType)tn.Tag; string sItemType = String.Empty; switch (tag) { case ItemType.Role: sItemType = "Role"; break; case ItemType.Task: sItemType = "Task"; break; case ItemType.Operation: sItemType = "Operation"; break; } AuthorizationType auth = AuthorizationType.Neutral; string sAuth = String.Empty; DateTime chkStart = DateTime.Now; TimeSpan elapsedTime = TimeSpan.Zero; DateTime chkEnd = DateTime.Now; List <KeyValuePair <string, string> > attributes = null; //Cache Build if (chkUserPermisisonCache.Checked && _UserPermissionCache == null) { txtDetails.Text += "Building UserPermissionCache ... " + Environment.NewLine; _UserPermissionCache = new UserPermissionCache(_Storage, _Store.Name, _Application.Name, _DbUser, true, false); chkEnd = DateTime.Now; elapsedTime = (TimeSpan)chkEnd.Subtract(chkStart); txtDetails.Text += String.Format("[{0} mls.]\r\n", elapsedTime.TotalMilliseconds) + Environment.NewLine; } else if (chkStorageCache.Checked && _StorageCache == null) { txtDetails.Text += "Building StorageCache ... " + Environment.NewLine; _StorageCache = new StorageCache(_Storage.ConnectionString); _StorageCache.BuildStorageCache(_Store.Name, _Application.Name); chkEnd = DateTime.Now; elapsedTime = (TimeSpan)chkEnd.Subtract(chkStart); txtDetails.Text += String.Format("[{0} mls.]\r\n", elapsedTime.TotalMilliseconds) + Environment.NewLine; } chkStart = DateTime.Now; elapsedTime = TimeSpan.Zero; txtDetails.Text += String.Format("{0} {1} '{2}' ... ", "Check Access Test on", sItemType, tn.Text); try { if (chkUserPermisisonCache.Checked) { auth = _UserPermissionCache.CheckAccess( tn.Text, !String.IsNullOrEmpty(txtValidFor.Text) ? Convert.ToDateTime(txtValidFor.Text) : DateTime.Now, out attributes); } else if (this.chkStorageCache.Checked) { auth = _StorageCache.CheckAccess( _Store.Name, _Application.Name, tn.Text, _DbUser.CustomSid.StringValue, !String.IsNullOrEmpty(txtValidFor.Text) ? Convert.ToDateTime(txtValidFor.Text) : DateTime.Now, false, out attributes); } else { auth = _Storage.CheckAccess( _Store.Name, _Application.Name, tn.Text, _DbUser, !String.IsNullOrEmpty(txtValidFor.Text) ? Convert.ToDateTime(txtValidFor.Text) : DateTime.Now, false, out attributes); } chkEnd = DateTime.Now; elapsedTime = (TimeSpan)chkEnd.Subtract(chkStart); sAuth = "Neutral"; switch (auth) { case AuthorizationType.AllowWithDelegation: sAuth = "Allow with Delegation"; break; case AuthorizationType.Allow: sAuth = "Allow"; break; case AuthorizationType.Deny: sAuth = "Deny"; break; case AuthorizationType.Neutral: sAuth = "Neutral"; break; } //tn.ToolTip = sAuth; txtDetails.Text += String.Format("{0} [{1} mls.]", sAuth, elapsedTime.TotalMilliseconds) + Environment.NewLine; if (attributes != null && attributes.Count > 0) { txtDetails.Text += String.Format(" {0} attribute(s) found:", attributes.Count) + Environment.NewLine; int attributeIndex = 0; foreach (KeyValuePair <string, string> attr in attributes) { txtDetails.Text += String.Format(" {0}) Key: {1} Value: {2}", ++attributeIndex, attr.Key, attr.Value) + Environment.NewLine; } } } catch (Exception ex) { sAuth = "Check Access Test Error"; txtDetails.Text += String.Format("{0} [{1} mls.]", ex.Message, elapsedTime.TotalMilliseconds) + Environment.NewLine; } tn.Text = String.Format("{0} - ({1})", tn.Text, sAuth.ToUpper()); foreach (TreeNode tnChild in tn.Nodes) { CheckNodeAccess(tnChild); } }
internal static void startStorageBuildCache(string storeName, string applicationName) { //Design Feature 1: If Not already building cache ... ignore new InvalidateCache lock (CacheService.locker) { if (!CacheService.buildingCache) { CacheService.buildingCache = true; WindowsCacheService.writeEvent(String.Format("Invalidate Cache invoked from user '{0}'. Store: '{1}' - Application: '{2}'.", ((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()).Name, storeName ?? String.Empty, applicationName ?? String.Empty), System.Diagnostics.EventLogEntryType.Information); Boolean AsyncCacheBuilding; if (!Boolean.TryParse(ConfigurationManager.AppSettings["AsyncCacheBuilding"], out AsyncCacheBuilding)) AsyncCacheBuilding = true; //Design Feature 2: Async Cache Building if (AsyncCacheBuilding) { System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(o => { try { StorageCache sc = new StorageCache(Properties.Settings.Default.NetSqlAzManStorageCacheConnectionString); sc.BuildStorageCache(storeName, applicationName); if (CacheService.storageCache != null) { //Design Feature 3: When Build ... replace the old cache with new one //3.1) This means that while building ... User can invoke CheckAccess on the OLD cache //3.2) Replacement is thread safe lock (CacheService.storageCache) { CacheService.storageCache = sc; } } else { CacheService.storageCache = sc; } WindowsCacheService.writeEvent("Cache Built (Async).", System.Diagnostics.EventLogEntryType.Information); } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Cache building error (Async):\r\n{0}\r\n\r\nStack Track:\r\n{1}", ex.Message, ex.StackTrace), System.Diagnostics.EventLogEntryType.Error); } finally { lock (CacheService.locker) { CacheService.buildingCache = false; } } } )); } else { //Sync Cache Build try { StorageCache sc = new StorageCache(Properties.Settings.Default.NetSqlAzManStorageCacheConnectionString); sc.BuildStorageCache(storeName, applicationName); if (CacheService.storageCache != null) { //Design Feature 3: When Build ... replace the old cache with new one //3.1) This means that while building ... User can invoke CheckAccess on the OLD cache //3.2) Replacement is thread safe lock (CacheService.storageCache) { CacheService.storageCache = sc; } } else { CacheService.storageCache = sc; } WindowsCacheService.writeEvent("Cache Built (Sync).", System.Diagnostics.EventLogEntryType.Information); } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Cache building error (Sync):\r\n{0}\r\n\r\nStack Track:\r\n{1}", ex.Message, ex.StackTrace), System.Diagnostics.EventLogEntryType.Error); } finally { lock (CacheService.locker) { CacheService.buildingCache = false; } } } } else { WindowsCacheService.writeEvent("Invalidate Cache invoked while building cache. Command ignored.", System.Diagnostics.EventLogEntryType.Warning); } } }
private void checkAccessTest(TreeNode tn) { string sItemType = String.Empty; if (tn.ImageUrl.EndsWith("Role_16x16.gif")) { sItemType = "Role"; } else if (tn.ImageUrl.EndsWith("Task_16x16.gif")) { sItemType = "Task"; } else { sItemType = "Operation"; } AuthorizationType auth = AuthorizationType.Neutral; string sAuth = String.Empty; DateTime chkStart = DateTime.Now; TimeSpan elapsedTime = TimeSpan.Zero; DateTime chkEnd = DateTime.Now; List <KeyValuePair <string, string> > attributes = null; //Cache Build if (this.chkCache.Checked && this.cache == null) { this.WriteDetailMessage("Building UserPermissionCache ..."); if (this.wid != null) { this.cache = new NetSqlAzMan.Cache.UserPermissionCache(this.application.Store.Storage, this.application.Store.Name, this.application.Name, this.wid, true, false); } else if (this.dbuser != null) { this.cache = new NetSqlAzMan.Cache.UserPermissionCache(this.application.Store.Storage, this.application.Store.Name, this.application.Name, this.dbuser, true, false); } chkEnd = DateTime.Now; elapsedTime = (TimeSpan)chkEnd.Subtract(chkStart); this.WriteLineDetailMessage(String.Format("[{0} mls.]\r\n", elapsedTime.TotalMilliseconds)); } else if (this.chkStorageCache.Checked && this.storageCache == null) { this.WriteDetailMessage("Building StorageCache ..."); this.storageCache = new NetSqlAzMan.Cache.StorageCache(this.application.Store.Storage.ConnectionString); this.storageCache.BuildStorageCache(this.application.Store.Name, this.application.Name); chkEnd = DateTime.Now; elapsedTime = (TimeSpan)chkEnd.Subtract(chkStart); this.WriteLineDetailMessage(String.Format("[{0} mls.]\r\n", elapsedTime.TotalMilliseconds)); } chkStart = DateTime.Now; elapsedTime = TimeSpan.Zero; this.WriteDetailMessage(String.Format("{0} {1} '{2}' ... ", "Check Access Test on", sItemType, tn.Text)); try { if (this.wid != null) { if (this.chkCache.Checked) { auth = this.cache.CheckAccess(tn.Text, !String.IsNullOrEmpty(this.dtValidFor.Text) ? Convert.ToDateTime(this.dtValidFor.Text) : DateTime.Now, out attributes); } else if (this.chkStorageCache.Checked) { auth = this.storageCache.CheckAccess(this.application.Store.Name, this.application.Name, tn.Text, this.wid.GetUserBinarySSid(), this.wid.GetGroupsBinarySSid(), !String.IsNullOrEmpty(this.dtValidFor.Text) ? Convert.ToDateTime(this.dtValidFor.Text) : DateTime.Now, false, out attributes); } else { auth = this.application.Store.Storage.CheckAccess(this.application.Store.Name, this.application.Name, tn.Text, this.wid, !String.IsNullOrEmpty(this.dtValidFor.Text) ? Convert.ToDateTime(this.dtValidFor.Text) : DateTime.Now, false, out attributes); } } else if (this.dbuser != null) { if (this.chkCache.Checked) { auth = this.cache.CheckAccess(tn.Text, !String.IsNullOrEmpty(this.dtValidFor.Text) ? Convert.ToDateTime(this.dtValidFor.Text) : DateTime.Now, out attributes); } else if (this.chkStorageCache.Checked) { auth = this.storageCache.CheckAccess(this.application.Store.Name, this.application.Name, tn.Text, this.dbuser.CustomSid.StringValue, !String.IsNullOrEmpty(this.dtValidFor.Text) ? Convert.ToDateTime(this.dtValidFor.Text) : DateTime.Now, false, out attributes); } else { auth = this.application.Store.Storage.CheckAccess(this.application.Store.Name, this.application.Name, tn.Text, this.dbuser, !String.IsNullOrEmpty(this.dtValidFor.Text) ? Convert.ToDateTime(this.dtValidFor.Text) : DateTime.Now, false, out attributes); } } chkEnd = DateTime.Now; elapsedTime = (TimeSpan)chkEnd.Subtract(chkStart); sAuth = "Neutral"; switch (auth) { case AuthorizationType.AllowWithDelegation: sAuth = "Allow with Delegation"; break; case AuthorizationType.Allow: sAuth = "Allow"; break; case AuthorizationType.Deny: sAuth = "Deny"; break; case AuthorizationType.Neutral: sAuth = "Neutral"; break; } tn.ToolTip = sAuth; this.WriteLineDetailMessage(String.Format("{0} [{1} mls.]", sAuth, elapsedTime.TotalMilliseconds)); if (attributes != null && attributes.Count > 0) { this.WriteLineDetailMessage(String.Format(" {0} attribute(s) found:", attributes.Count)); int attributeIndex = 0; foreach (KeyValuePair <string, string> attr in attributes) { this.WriteLineDetailMessage(String.Format(" {0}) Key: {1} Value: {2}", ++attributeIndex, attr.Key, attr.Value)); } } } catch (Exception ex) { sAuth = "Check Access Test Error"; this.WriteLineDetailMessage(String.Format("{0} [{1} mls.]", ex.Message, elapsedTime.TotalMilliseconds)); } tn.Text = String.Format("{0} - ({1})", tn.Text, sAuth.ToUpper()); foreach (TreeNode tnChild in tn.ChildNodes) { this.checkAccessTest(tnChild); } }
public RequiresCrew(StorageCache cache, ProfileData.ExperimentSettings settings, BiomeFilter filter, ScanInterface scanInterface, string expid) : base(cache, settings, filter, scanInterface, expid) { this.requireControllable = false; }
internal static void startStorageBuildCache(string storeName, string applicationName) { //Design Feature 1: If Not already building cache ... ignore new InvalidateCache lock (CacheService.locker) { if (!CacheService.buildingCache) { CacheService.buildingCache = true; WindowsCacheService.writeEvent(String.Format("Invalidate Cache invoked from user '{0}'. Store: '{1}' - Application: '{2}'.", ((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()).Name, storeName ?? String.Empty, applicationName ?? String.Empty), System.Diagnostics.EventLogEntryType.Information); Boolean AsyncCacheBuilding; if (!Boolean.TryParse(ConfigurationManager.AppSettings["AsyncCacheBuilding"], out AsyncCacheBuilding)) { AsyncCacheBuilding = true; } //Design Feature 2: Async Cache Building if (AsyncCacheBuilding) { System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(o => { try { StorageCache sc = new StorageCache(Properties.Settings.Default.NetSqlAzManStorageCacheConnectionString); sc.BuildStorageCache(storeName, applicationName); if (CacheService.storageCache != null) { //Design Feature 3: When Build ... replace the old cache with new one //3.1) This means that while building ... User can invoke CheckAccess on the OLD cache //3.2) Replacement is thread safe lock (CacheService.storageCache) { CacheService.storageCache = sc; } } else { CacheService.storageCache = sc; } WindowsCacheService.writeEvent("Cache Built (Async).", System.Diagnostics.EventLogEntryType.Information); } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Cache building error (Async):\r\n{0}\r\n\r\nStack Track:\r\n{1}", ex.Message, ex.StackTrace), System.Diagnostics.EventLogEntryType.Error); } finally { lock (CacheService.locker) { CacheService.buildingCache = false; } } } )); } else { //Sync Cache Build try { StorageCache sc = new StorageCache(Properties.Settings.Default.NetSqlAzManStorageCacheConnectionString); sc.BuildStorageCache(storeName, applicationName); if (CacheService.storageCache != null) { //Design Feature 3: When Build ... replace the old cache with new one //3.1) This means that while building ... User can invoke CheckAccess on the OLD cache //3.2) Replacement is thread safe lock (CacheService.storageCache) { CacheService.storageCache = sc; } } else { CacheService.storageCache = sc; } WindowsCacheService.writeEvent("Cache Built (Sync).", System.Diagnostics.EventLogEntryType.Information); } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Cache building error (Sync):\r\n{0}\r\n\r\nStack Track:\r\n{1}", ex.Message, ex.StackTrace), System.Diagnostics.EventLogEntryType.Error); } finally { lock (CacheService.locker) { CacheService.buildingCache = false; } } } } else { WindowsCacheService.writeEvent("Invalidate Cache invoked while building cache. Command ignored.", System.Diagnostics.EventLogEntryType.Warning); } } }
public Loader(string storageCacheRoot, bool useHashInStorageCache) { _storageCache = new StorageCache(storageCacheRoot, useHashInStorageCache); this.loadLimit = long.MaxValue; }