/// <summary> /// Remove Authorization Delegate /// </summary> private void RemoveDelegate() { // USER MUST BE A MEMBER OF SQL DATABASE ROLE: NetSqlAzMan_Users //Sql Storage connection string string sqlConnectionString = "data source=(local);initial catalog=NetSqlAzManStorage;user id=netsqlazmanuser;password=password"; //Create an instance of SqlAzManStorage class IAzManStorage storage = new SqlAzManStorage(sqlConnectionString); IAzManStore mystore = storage.GetStore("My Store"); //or storage["My Store"] IAzManApplication myapp = mystore.GetApplication("My Application"); IAzManItem myop = myapp.GetItem("My Operation"); //Retrieve current user identity (delegating user) WindowsIdentity userIdentity = ((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()); //for Windows Applications //WindowsIdentity userIdentity = this.Request.LogonUserIdentity; //for ASP.NET Applications //Retrieve delegate user Login NTAccount delegateUserLogin = new NTAccount("DOMAIN", "delegateuseraccount"); //Retrieve delegate user SID SecurityIdentifier delegateSID = (SecurityIdentifier)delegateUserLogin.Translate(typeof(SecurityIdentifier)); IAzManSid delegateNetSqlAzManSID = new SqlAzManSID(delegateSID); //Estabilish delegate authorization (only Allow or Deny) RestrictedAuthorizationType delegateAuthorization = RestrictedAuthorizationType.Allow; //Remove delegate and all custom attributes myop.DeleteDelegateAuthorization(userIdentity, delegateNetSqlAzManSID, delegateAuthorization); }
protected void btnCreateStore_Click(object sender, EventArgs e) { IAzManStorage storage = new SqlAzManStorage(ConfigurationManager.ConnectionStrings["NetSqlAzManStorage"].ConnectionString); storage.OpenConnection(); try { storage.BeginTransaction(AzManIsolationLevel.ReadUncommitted); IAzManStore store = storage.CreateStore("Store Created Programmatically", "store description"); for (int i = 0; i < 10; i++) { IAzManApplication app = store.CreateApplication("App " + i.ToString(), "application description"); IAzManItem prevItem = null; for (int j = 0; j < 10; j++) { IAzManItem item = app.CreateItem("Item " + j.ToString(), "item description", ItemType.Operation); if (prevItem != null) { item.AddMember(prevItem); } prevItem = item; } } storage.CommitTransaction(); } catch { storage.RollBackTransaction(); throw; } finally { storage.CloseConnection(); } }
/// <summary> /// Check Access from your Application [FOR Windows Users ONLY]. /// </summary> /// <param name="dbUserName">DB Username</param> private void CheckAccessPermissionsForDBUsers(string dbUserName) { // REMBER: // Modify dbo.GetDBUsers Table-Function to customize DB User list. // USER MUST BE A MEMBER OF SQL DATABASE ROLE: NetSqlAzMan_Readers //Sql Storage connection string string sqlConnectionString = "data source=(local);initial catalog=NetSqlAzManStorage;user id=netsqlazmanuser;password=password"; //Create an instance of SqlAzManStorage class IAzManStorage storage = new SqlAzManStorage(sqlConnectionString); //Retrieve DB User identity from dbo.GetDBUsers Table-Function IAzManDBUser dbUser = storage.GetDBUser(dbUserName); AuthorizationType auth = storage.CheckAccess("My Store", "My Application", "My Operation", dbUser, DateTime.Now, true); switch (auth) { case AuthorizationType.AllowWithDelegation: //Yes, I can ... and I can delegate break; case AuthorizationType.Allow: //Yes, I can break; case AuthorizationType.Neutral: case AuthorizationType.Deny: //No, I cannot break; } }
/// <summary> /// Removes a role from the data source for the configured applicationName. /// </summary> /// <param name="roleName">The name of the role to delete.</param> /// <param name="throwOnPopulatedRole">If true, throw an exception if roleName has one or more members and do not delete roleName.</param> /// <returns> /// true if the role was successfully deleted; otherwise, false. /// </returns> public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString)) { IAzManApplication application = storage[this.storeName][this.applicationName]; IAzManItem role = application[roleName]; if (role == null) { throw new ArgumentNullException("roleName"); } if (roleName.Trim() == String.Empty) { throw new ArgumentException("roleName parameter cannot be empty."); } if (role.ItemType != ItemType.Role) { throw new ArgumentException(String.Format("{0} must be a Role.", roleName), "roleName"); } if (throwOnPopulatedRole && application[roleName].GetMembers().Length > 0) { throw new ProviderException(String.Format("{0} has one or more members and cannot be deleted.", roleName)); } role.Delete(); //Rebuild StorageCache this.InvalidateCache(false); return(true); } }
private AuthorizationType NetSqlAzManTestDirectCheckAccess() { WindowsIdentity userIdentity = this.Request.LogonUserIdentity; IAzManStorage storage = new SqlAzManStorage(NetSqlAzManStorePath); return(storage.CheckAccess("Store Test", "Application Test", this.txtDirectItem.Text, userIdentity, DateTime.Now, true)); }
/// <summary> /// افزودن نقش به کاربر /// </summary> public bool AddUserToRole(string userName, string roleName) { try { WindowsIdentity wi = new WindowsIdentity(GetUserNameWithoutDomain(userName) + _fullDomainName); AzmanSid sid = new AzmanSid(wi); IAzManStorage storage = new SqlAzManStorage(_azManConnectionString); storage.OpenConnection(); //اگر نقش مورد نظر در ای زد من تعریف شده بود if (RoleExists(roleName)) { IAzManItem itemRole = storage[_storageName][_applicationName][roleName]; //نقش به کاربر اختصاص داده شود IAzManAuthorization auth = itemRole.CreateAuthorization(sid, WhereDefined.LDAP, sid, WhereDefined.LDAP, AuthorizationType.Allow, null, null); } storage.CloseConnection(); result = true; } catch (Exception ex) { //log ex } return(result); }
/// <summary> /// حذف نقش از کاربر /// </summary> public bool RemoveUserFromRole(string userName, string role) { fullUserName = GetUserNameWithoutDomain(userName) + _fullDomainName; try { WindowsIdentity wi = new WindowsIdentity(fullUserName); AzmanSid sid = new AzmanSid(wi); IAzManStorage storage = new SqlAzManStorage(_azManConnectionString); storage.OpenConnection(); //دریافت نقش IAzManItem itemRole = storage[_storageName][_applicationName][role]; //دریافت اطلاعات کاربرانی که با این نقش احراز هویت شده اند IAzManAuthorization[] authorizations = itemRole.GetAuthorizations(); var userAuth = authorizations.FirstOrDefault(a => a.SID.StringValue == sid.StringValue); if (userAuth != null) { userAuth.Delete(); } storage.CloseConnection(); result = true; } catch (Exception ex) { //log ex } return(result); }
public List <Application> GetUserPermissionsNotification(string UserName) { var apps = new List <Application>(); //try //{ const string store = "CATS"; string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CatsContext"].ConnectionString; IAzManStorage storage = new SqlAzManStorage(connectionString); IAzManStore mystore = storage.GetStore(store); //or storage["My Store"] // IAzManApplication myapp = mystore.GetApplication(application); List <IAzManApplication> Applications = mystore.GetApplications().ToList(); //_provider.Initialize("AuthorizationRoleProvider", ConfigureAuthorizationRoleProvider("CATS","Early warning")); //Dictionary<string, IAzManApplication> Applications = _provider.GetStorage().Stores["CATS"].Applications; foreach (var app in Applications) { apps.Add(new Application() { ApplicationName = app.Name, Roles = GetUserPermissionsNotification(UserName, "CATS", app.Name) }); } return(apps); //} //catch(Exception ex) //{ // var s = ex.Message; // return apps; //} }
public bool AddRole(string user, string application, string role) { const string store = "CATS"; string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CatsContext"].ConnectionString; IAzManStorage storage = new SqlAzManStorage(connectionString); IAzManStore mystore = storage.GetStore(store); //or storage["My Store"] IAzManApplication myapp = mystore.GetApplication(application); //mystore.GetApplications(); IAzManItem azManRole = myapp.GetItem(role); IAzManAuthorization dele = azManRole.CreateAuthorization( mystore.GetDBUser("Admin").CustomSid, WhereDefined.Database, mystore.GetDBUser(user).CustomSid, WhereDefined.Database, AuthorizationType.AllowWithDelegation, null, null ); //IAzManAuthorization del = azManRole.CreateDelegateAuthorization(mystore.GetDBUser("Admin"),mystore.GetDBUser(user).CustomSid,RestrictedAuthorizationType.Allow, null,null); return(true); }
/// <summary> /// بررسی وجود نقش برای کاربر /// </summary> public bool IsInRole(string userName, string roleName) { fullUserName = GetUserNameWithoutDomain(userName) + _fullDomainName; try { WindowsIdentity wi = new WindowsIdentity(fullUserName); AzmanSid sid = new AzmanSid(wi); var storage = new SqlAzManStorage(_azManConnectionString); storage.OpenConnection(); //اگر نقش مورد نظر موجود بود if (RoleExists(roleName)) { IAzManItem itemRole = storage[_storageName][_applicationName][roleName]; IAzManAuthorization[] authorizations = itemRole.GetAuthorizations(); //اگر کاربر با این نقش احراز هویت شده result = authorizations.Any(i => i.SID.StringValue == sid.StringValue); } storage.CloseConnection(); } catch (Exception ex) { //log ex } return(result); }
/// <summary> /// Gets a list of users in the specified role for the configured applicationName. /// </summary> /// <param name="roleName">The name of the role to get the list of users for.</param> /// <returns> /// A string array containing the names of all the users who are members of the specified role for the configured applicationName. /// </returns> public override string[] GetUsersInRole(string roleName) { using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString)) { IAzManApplication application = storage[this.storeName][this.applicationName]; IAzManItem role = application[roleName]; if (role.ItemType != ItemType.Role) { throw new ArgumentException(String.Format("{0} must be a Role.", roleName), "roleName"); } IAzManAuthorization[] authz = role.GetAuthorizations(); List <string> users = new List <string>(); foreach (IAzManAuthorization auth in authz) { if (auth.AuthorizationType == AuthorizationType.Allow || auth.AuthorizationType == AuthorizationType.AllowWithDelegation) { if (auth.SidWhereDefined == WhereDefined.Local || auth.SidWhereDefined == WhereDefined.LDAP) { string displayName; auth.GetMemberInfo(out displayName); users.Add(displayName); } else if (auth.SidWhereDefined == WhereDefined.Database) { users.Add(application.GetDBUser(auth.SID).UserName); } } } return(users.ToArray()); } }
/// <summary> /// Adds the specified user names to the specified roles for the configured applicationName. /// </summary> /// <param name="usernames">A string array of user names to be added to the specified roles.</param> /// <param name="roleNames">A string array of the role names to add the specified user names to.</param> public override void AddUsersToRoles(string[] usernames, string[] roleNames) { using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString)) { try { storage.OpenConnection(); storage.BeginTransaction(); IAzManApplication application = storage[this.storeName][this.applicationName]; foreach (string roleName in roleNames) { IAzManItem role = application.GetItem(roleName); if (role.ItemType != ItemType.Role) { throw new ArgumentException(String.Format("{0} must be a Role.", roleName)); } foreach (string username in usernames) { IAzManSid owner = new SqlAzManSID(((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()).User); WhereDefined whereDefined = WhereDefined.LDAP; if (this.userLookupType == "LDAP") { string fqun = this.getFQUN(username); NTAccount ntaccount = new NTAccount(fqun); if (ntaccount == null) { throw SqlAzManException.UserNotFoundException(username, null); } IAzManSid sid = new SqlAzManSID(((SecurityIdentifier)(ntaccount.Translate(typeof(SecurityIdentifier))))); if (sid == null) { throw SqlAzManException.UserNotFoundException(username, null); } role.CreateAuthorization(owner, whereDefined, sid, WhereDefined.LDAP, AuthorizationType.Allow, null, null); } else { var dbuser = application.GetDBUser(username); IAzManSid sid = dbuser.CustomSid; role.CreateAuthorization(owner, whereDefined, sid, WhereDefined.Database, AuthorizationType.Allow, null, null); } } } storage.CommitTransaction(); //Rebuild StorageCache this.InvalidateCache(false); } catch { storage.RollBackTransaction(); throw; } finally { storage.CloseConnection(); } } }
private AuthorizationType NetSqlAzManTestCheckAccess() { WindowsIdentity userIdentity = WindowsIdentity.GetCurrent(); IAzManStorage storage = new SqlAzManStorage(NetSqlAzManStorePath); IAzManItem item = storage["Store Test"]["Application Test"][this.txtItem.Text]; return(item.CheckAccess(userIdentity, DateTime.Now)); }
protected void Button2_Click(object sender, EventArgs e) { IAzManStorage storage = new SqlAzManStorage("data source=(local);Initial Catalog=NetSqlAzManStorage;user id=sa;password="******"Andrea"); UserPermissionCache cache = new UserPermissionCache(storage, "Store Stress Test", "Application0", andrea, true, true); Session["cache"] = cache; }
/// <summary> /// Gets the DB user. /// </summary> /// <param name="dbUserName">Name of the db user.</param> /// <returns></returns> /// <remarks>Thread-Safe</remarks> public virtual IAzManDBUser GetDBUser(string dbUserName) { using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString)) { IAzManApplication application = storage[this.storeName][this.applicationName]; return(application.GetDBUser(dbUserName)); } }
private void WebConsole_Load(object sender, EventArgs e) { _SqlConnString = GlobalVars.SqlConnectionString; Session["storage"] = new SqlAzManStorage(_SqlConnString); SetAttributes(); LoadNavTree(); }
/// <summary> /// Adds a new role to the data source for the configured applicationName. /// </summary> /// <param name="roleName">The name of the role to create.</param> public override void CreateRole(string roleName) { using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString)) { IAzManApplication application = storage[this.storeName][this.applicationName]; application.CreateItem(roleName, String.Empty, ItemType.Role); } //Rebuild StorageCache this.InvalidateCache(false); }
internal static void TestConnection(string connectionString) { SqlAzManStorage.VerifyStorageDB(connectionString); SqlAzManStorage storage = new SqlAzManStorage(connectionString); string dbVersion = storage.DatabaseVesion; string netsqlazmanRunTimeVersion = storage.GetType().Assembly.GetName().Version.ToString(); if (!String.Equals(netsqlazmanRunTimeVersion.Substring(0, 6), dbVersion.Substring(0, 6), StringComparison.InvariantCultureIgnoreCase)) { MessageBox.Show(String.Format("NetSqlAzMan Run-Time Version: {0}\r\nNetSqlAzMan Database Version: {1}", netsqlazmanRunTimeVersion, dbVersion), "Warning: Version mismatch", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private void TestSuNetSqlAzMan(string connectionString, int max) { WindowsIdentity id = WindowsIdentity.GetCurrent(); int rnd = new Random().Next(max); IAzManStorage storage = new SqlAzManStorage(connectionString); storage.OpenConnection(); AuthorizationType res = storage.CheckAccess("Store Stress Test", "Application" + rnd.ToString(), "Operation" + rnd.ToString(), id, DateTime.Now, true, new KeyValuePair <string, object>("chiave", "valore")); //AuthorizationType res = storage.CheckAccess("Store Stress Test", "Application" + rnd.ToString(), "Operation" + rnd.ToString(), storage.GetDBUser("Andrea"), DateTime.Now, true, new KeyValuePair<string, object>("chiave", "valore")); storage.CloseConnection(); storage.Dispose(); }
private void TestConnection(string connectionString) { SqlAzManStorage.VerifyStorageDB(connectionString); SqlAzManStorage storage = new SqlAzManStorage(connectionString); string dbVersion = storage.DatabaseVesion; string netsqlazmanRunTimeVersion = storage.GetType().Assembly.GetName().Version.ToString(); if (!String.Equals(netsqlazmanRunTimeVersion.Substring(0, 6), dbVersion.Substring(0, 6), StringComparison.InvariantCultureIgnoreCase)) { this.Page.ClientScript.RegisterStartupScript(typeof(string), "postBackAlert", String.Format("window.alert('{0}');", String.Format("Warning: Version mismatch !!!\\r\\nNetSqlAzMan Run-Time Version: {0}\r\nNetSqlAzMan Database Version: {1}", netsqlazmanRunTimeVersion, dbVersion)), true); } }
protected void Button1_Click(object sender, EventArgs e) { IAzManStorage storage = new SqlAzManStorage("data source=(local);Initial Catalog=NetSqlAzManStorage;user id=sa;password="******"Store Stress Test", "Application0", "Role0", this.Request.LogonUserIdentity, DateTime.Now, false).ToString(); this.TextBox1.Text += storage.CheckAccess("Store Stress Test", "Application0", "Operation0", this.Request.LogonUserIdentity, DateTime.Now, false).ToString(); } //Application0.Security.CheckAccessHelper chk = new Application0.Security.CheckAccessHelper("data source=.;Initial Catalog=NetSqlAzManStorage;Integrated Security=SSPI", this.Request.LogonUserIdentity); // this.TextBox1.Text = chk.CheckAccess(Application0.Security.CheckAccessHelper.Operation.Operation0).ToString(); }
internal void OnStartInternal() { try { //Start serviceHost if (this.serviceHost != null) { this.serviceHost.Close(); } // Create a ServiceHost for the CacheService type and // provide the base address. this.serviceHost = new ServiceHost(typeof(CacheService)); // Open the ServiceHostBase to create listeners and start // listening for messages. this.serviceHost.Open(); //Check storage connection string using (SqlAzManStorage s = new SqlAzManStorage(Properties.Settings.Default.NetSqlAzManStorageCacheConnectionString)) { s.OpenConnection(); s.CloseConnection(); } //Start cache building in a new thread this.setNextExecution(); CacheService.startStorageBuildCache(); #if TEST while (true) { System.Threading.Thread.Sleep(500); System.Windows.Forms.Application.DoEvents(); } #endif this.faultState = false; System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(o => this.Setup())); } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Error:\r\n{0}\r\n\r\nStack Trace:\r\n{1}", ex.Message, ex.StackTrace), EventLogEntryType.Error); this.faultState = true; this.timer1.Interval = 60000; //Retry after 1 minute this.timer1.Start(); } }
internal void OnStartInternal() { try { //Start serviceHost if (this.serviceHost != null) { this.serviceHost.Close(); } // Create a ServiceHost for the CacheService type and // provide the base address. this.serviceHost = new ServiceHost(typeof(CacheService)); // Open the ServiceHostBase to create listeners and start // listening for messages. this.serviceHost.Open(); //Check storage connection string using (SqlAzManStorage s = new SqlAzManStorage(Properties.Settings.Default.NetSqlAzManStorageCacheConnectionString)) { s.OpenConnection(); s.CloseConnection(); } //Start cache building in a new thread this.setNextExecution(); CacheService.startStorageBuildCache(); #if TEST while (true) { System.Threading.Thread.Sleep(500); System.Windows.Forms.Application.DoEvents(); } #endif this.faultState = false; System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(o=>this.Setup())); } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Error:\r\n{0}\r\n\r\nStack Trace:\r\n{1}", ex.Message, ex.StackTrace), EventLogEntryType.Error); this.faultState = true; this.timer1.Interval = 60000; //Retry after 1 minute this.timer1.Start(); } }
/// <summary> /// Create a Full Storage through .NET code /// </summary> private void CreateFullStorage() { // USER MUST BE A MEMBER OF SQL DATABASE ROLE: NetSqlAzMan_Administrators //Sql Storage connection string string sqlConnectionString = "data source=(local);initial catalog=NetSqlAzManStorage;user id=netsqlazmanuser;password=password"; //Create an instance of SqlAzManStorage class IAzManStorage storage = new SqlAzManStorage(sqlConnectionString); //Open Storage Connection storage.OpenConnection(); //Begin a new Transaction storage.BeginTransaction(AzManIsolationLevel.ReadUncommitted); //Create a new Store IAzManStore newStore = storage.CreateStore("My Store", "Store description"); //Create a new Basic StoreGroup IAzManStoreGroup newStoreGroup = newStore.CreateStoreGroup(SqlAzManSID.NewSqlAzManSid(), "My Store Group", "Store Group Description", String.Empty, GroupType.Basic); //Retrieve current user SID IAzManSid mySid = new SqlAzManSID(((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()).User); //Add myself as sid of "My Store Group" IAzManStoreGroupMember storeGroupMember = newStoreGroup.CreateStoreGroupMember(mySid, WhereDefined.Local, true); //Create a new Application IAzManApplication newApp = newStore.CreateApplication("New Application", "Application description"); //Create a new Role IAzManItem newRole = newApp.CreateItem("New Role", "Role description", ItemType.Role); //Create a new Task IAzManItem newTask = newApp.CreateItem("New Task", "Task description", ItemType.Task); //Create a new Operation IAzManItem newOp = newApp.CreateItem("New Operation", "Operation description", ItemType.Operation); //Add "New Operation" as a sid of "New Task" newTask.AddMember(newOp); //Add "New Task" as a sid of "New Role" newRole.AddMember(newTask); //Create an authorization for myself on "New Role" IAzManAuthorization auth = newRole.CreateAuthorization(mySid, WhereDefined.Local, mySid, WhereDefined.Local, AuthorizationType.AllowWithDelegation, null, null); //Create a custom attribute IAzManAttribute <IAzManAuthorization> attr = auth.CreateAttribute("New Key", "New Value"); //Create an authorization for DB User "Andrea" on "New Role" IAzManAuthorization auth2 = newRole.CreateAuthorization(mySid, WhereDefined.Local, storage.GetDBUser("Andrea").CustomSid, WhereDefined.Local, AuthorizationType.AllowWithDelegation, null, null); //Commit transaction storage.CommitTransaction(); //Close connection storage.CloseConnection(); }
/// <summary> /// Handles the Elapsed event of the timer1 control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Timers.ElapsedEventArgs"/> instance containing the event data.</param> private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { this.timer1.Stop(); if (DateTime.Now < this.nextExecution && !this.faultState) { TimeSpan delta = this.nextExecution.Subtract(DateTime.Now); double d = delta.TotalMilliseconds; if (d > int.MaxValue) { this.timer1.Interval = int.MaxValue; } else { if (d > 0) { this.timer1.Interval = d; } } } else if (DateTime.Now >= this.nextExecution || this.faultState) { //Check storage connection string using (SqlAzManStorage s = new SqlAzManStorage(Properties.Settings.Default.NetSqlAzManStorageCacheConnectionString)) { s.OpenConnection(); s.CloseConnection(); } CacheService.startStorageBuildCache(); this.faultState = false; this.setNextExecution(); } } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Error:\r\n{0}\r\n\r\nStack Trace:\r\n{1}", ex.Message, ex.StackTrace), EventLogEntryType.Error); this.faultState = true; this.timer1.Interval = 60000; //Retry after 1 minute } finally { this.timer1.Start(); } }
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); }
private void btnGetStorage_Click(object sender, EventArgs e) { using (NetSqlAzManSR.NetSqlAzManWCFServiceClient c = new NetSqlAzManWCFServiceWinTest.NetSqlAzManSR.NetSqlAzManWCFServiceClient()) { try { c.Open(); SqlAzManStorage storage = (SqlAzManStorage)c.CreateStorageInstance("data source=.;Initial Catalog=NetSqlAzManStorage;user id=sa;password="******"Eidos"); store.CreateApplication("Prova", ""); var apps = store.Applications; } finally { ((IDisposable)c).Dispose(); } } }
/// <summary> /// Removes the specified user names from the specified roles for the configured applicationName. /// </summary> /// <param name="usernames">A string array of user names to be removed from the specified roles.</param> /// <param name="roleNames">A string array of role names to remove the specified user names from.</param> public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString)) { try { storage.OpenConnection(); storage.BeginTransaction(); IAzManApplication application = storage[this.storeName][this.applicationName]; foreach (string roleName in roleNames) { IAzManItem role = application.GetItem(roleName); if (role.ItemType != ItemType.Role) { throw new ArgumentException(String.Format("{0} must be a Role.", roleName)); } foreach (IAzManAuthorization auth in role.GetAuthorizations()) { string displayName; auth.GetMemberInfo(out displayName); foreach (string username in usernames) { if (String.Compare(this.getFQUN(username), displayName, true) == 0) { auth.Delete(); } } } } storage.CommitTransaction(); //Rebuild StorageCache this.InvalidateCache(false); } catch { storage.RollBackTransaction(); throw; } finally { storage.CloseConnection(); } } }
private void CreaStrutturaSuNetSqlAzMan(string connectionString, int n) { this.Clessidra(true); this.StartTimer(); WindowsIdentity id = WindowsIdentity.GetCurrent(); IAzManStorage storage = new SqlAzManStorage(connectionString); storage.ENS.AuthorizationCreated += new NetSqlAzMan.ENS.AuthorizationCreatedDelegate(ENS_AuthorizationCreated); try { IAzManStore s = storage["Store Stress Test"]; if (s != null) { s.Delete(); } } catch { } storage.OpenConnection(); storage.BeginTransaction(AzManIsolationLevel.ReadUncommitted); IAzManStore store = storage.CreateStore("Store Stress Test", String.Empty); this.pb.Maximum = n - 1; for (int a = 0; a < n; a++) { IAzManApplication app = store.CreateApplication("Application" + a.ToString(), String.Empty); this.pb.Value = a; Application.DoEvents(); for (int i = 0; i < n; i++) { IAzManItem role = app.CreateItem("Role" + i.ToString(), String.Empty, ItemType.Role); IAzManItem task = app.CreateItem("Task" + i.ToString(), String.Empty, ItemType.Task); IAzManItem op = app.CreateItem("Operation" + i.ToString(), String.Empty, ItemType.Operation); role.AddMember(task); task.AddMember(op); role.CreateAuthorization(new SqlAzManSID(id.User), WhereDefined.LDAP, new SqlAzManSID(id.User), WhereDefined.LDAP, AuthorizationType.Allow, null, null); //add current Windows user //role.CreateAuthorization(new SqlAzManSID(id.User), WhereDefined.LDAP, new SqlAzManSID(storage.GetDBUser("Andrea").CustomSid.BinaryValue, true), WhereDefined.Database, AuthorizationType.Allow, null, null); //add Andrea DB User } } //storage.RollBackTransaction(); storage.CommitTransaction(); storage.CloseConnection(); this.StopTimer(this.txtNetSqlAzManElapsed); this.Clessidra(false); }
/// <summary> /// Check Access from your Application [FOR Windows Users ONLY]. /// </summary> /// <param name="userIdentity">Windows User Identity.</param> private void CheckAccessPermissionsForWindowsUsers(WindowsIdentity userIdentity, bool useCache) { // USER MUST BE A MEMBER OF SQL DATABASE ROLE: NetSqlAzMan_Readers //Sql Storage connection string string sqlConnectionString = "data source=(local);initial catalog=NetSqlAzManStorage;user id=netsqlazmanuser;password=password"; //Create an instance of SqlAzManStorage class IAzManStorage storage = new SqlAzManStorage(sqlConnectionString); //To Pass current user identity: //WindowsIdentity.GetCurrent() -> for Windows Applications //this.Request.LogonUserIdentity -> for ASP.NET Applications List <KeyValuePair <string, string> > attributes; AuthorizationType auth; if (useCache) { //Build the cache Only one time per session/application/user NetSqlAzMan.Cache.UserPermissionCache cache = new NetSqlAzMan.Cache.UserPermissionCache(storage, "My Store", "My Application", userIdentity, true, true); //Then Check Access auth = cache.CheckAccess("My Operation", DateTime.Now, out attributes); } else { auth = storage.CheckAccess("My Store", "My Application", "My Operation", userIdentity, DateTime.Now, true, out attributes); } switch (auth) { case AuthorizationType.AllowWithDelegation: //Yes, I can ... and I can delegate break; case AuthorizationType.Allow: //Yes, I can break; case AuthorizationType.Neutral: case AuthorizationType.Deny: //No, I cannot break; } //Do something with attributes found }
/// <summary> /// دریافت لیست نقش های کاربر /// </summary> public IEnumerable <RoleOutput> GetUserRolesByUserName(string Username) { var userRoles = new List <RoleOutput>(); try { IAzManStorage storage = new SqlAzManStorage(_azManConnectionString); storage.OpenConnection(); //دریافت لیست نقش ها IAzManItem[] azManRoles = storage[_storageName][_applicationName].GetItems(ItemType.Role); storage.CloseConnection(); var fullUserName = GetUserNameWithoutDomain(Username) + _fullDomainName; WindowsIdentity wi = new WindowsIdentity(fullUserName); foreach (IAzManItem role in azManRoles) { AuthorizationType AuthType = role.CheckAccess(wi, DateTime.Now, new KeyValuePair <string, object> [0]); if (AuthType == AuthorizationType.Allow || AuthType == AuthorizationType.AllowWithDelegation) { AzmanSid sid = new AzmanSid(wi); if (role.GetAuthorizationsOfMember(sid)[0].Attributes.Keys.Contains("IsActive")) { if (!Convert.ToBoolean(role.GetAuthorizationsOfMember(sid)[0].Attributes["IsActive"].Value)) { continue; } } //اگر نقش برای این کاربر مجاز بود به لیست اضافه شود userRoles.Add(new RoleOutput { Name = role.Name, Description = role.Description }); } } } catch (Exception ex) { //log } return(userRoles); }
private void buildApplicationCacheMultiThread() { try { DateTime globalNow = DateTime.Now; this.storage.OpenConnection(); this.collectPermissionData(); List<ItemCheckAccessResult> results = new List<ItemCheckAccessResult>(); IAzManSid sid = this.windowsIdentity != null ? new SqlAzManSID(this.windowsIdentity.User) : this.dbUser.CustomSid; List<ManualResetEvent> waitHandles = new List<ManualResetEvent>(); Hashtable allResult = new Hashtable(); int index = 0; Exception lastException = null; foreach (String itemname in this.items) { var drAuthorization = this.dtAuthorizations.Where(t => t.ItemName == itemname).FirstOrDefault(); if (drAuthorization == null) drAuthorization = new BuildUserPermissionCacheResult2() { ItemName = itemname, ValidFrom = null, ValidTo = null }; //string itemName = drAuthorization.ItemName; ManualResetEvent waitHandle = new ManualResetEvent(false); waitHandles.Add(waitHandle); //New Thread Pool ThreadPool.QueueUserWorkItem(new WaitCallback( delegate(object o) { IAzManStorage clonedStorage = new SqlAzManStorage(((SqlAzManStorage)this.storage).db.Connection.ConnectionString); int localIndex = (int)((object[])o)[0]; ManualResetEvent localWaitHandle = (ManualResetEvent)((object[])o)[1]; BuildUserPermissionCacheResult2 localAuth = (BuildUserPermissionCacheResult2)((object[])o)[2]; DateTime now = (DateTime)((object[])o)[3]; string itemName = localAuth.ItemName; try { clonedStorage.OpenConnection(); ItemCheckAccessResult result = new ItemCheckAccessResult(itemName); result.ValidFrom = localAuth.ValidFrom.HasValue ? localAuth.ValidFrom.Value : DateTime.MinValue; result.ValidTo = localAuth.ValidTo.HasValue ? localAuth.ValidTo.Value : DateTime.MaxValue; List<KeyValuePair<string, string>> attributes = null; DateTime validFor = localAuth.ValidFrom.HasValue ? localAuth.ValidFrom.Value : now; if (this.windowsIdentity != null) { if (this.retrieveAttributes) result.AuthorizationType = clonedStorage.CheckAccess(this.storeName, this.applicationName, itemName, this.windowsIdentity, validFor, false, out attributes, this.contextParameters); else result.AuthorizationType = clonedStorage.CheckAccess(this.storeName, this.applicationName, itemName, this.windowsIdentity, validFor, false, this.contextParameters); } else if (this.dbUser != null) { if (this.retrieveAttributes) result.AuthorizationType = clonedStorage.CheckAccess(this.storeName, this.applicationName, itemName, this.dbUser, validFor, false, out attributes, this.contextParameters); else result.AuthorizationType = clonedStorage.CheckAccess(this.storeName, this.applicationName, itemName, this.dbUser, validFor, false, this.contextParameters); } result.Attributes = attributes; //Thread safety lock (allResult.SyncRoot) { allResult.Add(localIndex, new object[] { itemName, result }); } } catch (Exception ex) { lastException = ex; } finally { clonedStorage.CloseConnection(); localWaitHandle.Set(); } }), new object[] { index, waitHandle, drAuthorization, globalNow }); index++; } if (lastException != null) throw lastException; int count = index; //Wait for all threads: http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic28609.aspx if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) { // WaitAll for multiple handles on an STA thread is not supported. // ...so wait on each handle individually. foreach (ManualResetEvent myWaitHandle in waitHandles) { myWaitHandle.WaitOne(); } } else { WaitHandle.WaitAll(waitHandles.ToArray()); } //Extends all results index = 0; for (int i = 0; i < count; i++) { object[] values = (object[])allResult[index++]; string itemName = (string)((object[])values)[0]; ItemCheckAccessResult result = (ItemCheckAccessResult)((object[])values)[1]; results.Add(result); this.extendResultToMembers(itemName, result, results); } this.checkAccessTimeSlice = results.ToArray(); } finally { this.storage.CloseConnection(); } }
/// <summary> /// Handles the Elapsed event of the timer1 control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Timers.ElapsedEventArgs"/> instance containing the event data.</param> private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { this.timer1.Stop(); if (DateTime.Now < this.nextExecution && !this.faultState) { TimeSpan delta = this.nextExecution.Subtract(DateTime.Now); double d = delta.TotalMilliseconds; if (d > int.MaxValue) this.timer1.Interval = int.MaxValue; else { if (d > 0) { this.timer1.Interval = d; } } } else if (DateTime.Now >= this.nextExecution || this.faultState) { //Check storage connection string using (SqlAzManStorage s = new SqlAzManStorage(Properties.Settings.Default.NetSqlAzManStorageCacheConnectionString)) { s.OpenConnection(); s.CloseConnection(); } CacheService.startStorageBuildCache(); this.faultState = false; this.setNextExecution(); } } catch (Exception ex) { WindowsCacheService.writeEvent(String.Format("Error:\r\n{0}\r\n\r\nStack Trace:\r\n{1}", ex.Message, ex.StackTrace), EventLogEntryType.Error); this.faultState = true; this.timer1.Interval = 60000; //Retry after 1 minute } finally { this.timer1.Start(); } }
/// <summary> /// Gets a value indicating whether the specified user is in the specified role for the configured applicationName. /// </summary> /// <param name="username">The user name to search for.</param> /// <param name="roleName">The role to search in.</param> /// <returns> /// true if the specified user is in the specified role for the configured applicationName; otherwise, false. /// </returns> public override bool IsUserInRole(string username, string roleName) { if (this.userLookupType == "LDAP") { WindowsIdentity wid = null; if (String.Compare(((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()).Name, this.getFQUN(username), true) == 0) { wid = ((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()); } if (wid == null) { wid = new WindowsIdentity(this.getUpn(this.getFQUN(username))); //Kerberos Protocol Transition: Works in W2K3 native domain only } if (!this.useWCFCacheService) return (from t in this.storageCache.GetAuthorizedItems(this.storeName, this.applicationName, wid.GetUserBinarySSid(), wid.GetGroupsBinarySSid(), DateTime.Now) where t.Type == ItemType.Role && (t.Authorization == AuthorizationType.Allow || t.Authorization == AuthorizationType.AllowWithDelegation) && t.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase) select t).Count() > 0; else { using (NetSqlAzManWCFCacheService.CacheServiceClient csc = new NetSqlAzManWCFCacheService.CacheServiceClient()) { try { return (from t in csc.GetAuthorizedItemsForWindowsUsers(this.storeName, this.applicationName, wid.GetUserBinarySSid(), wid.GetGroupsBinarySSid(), DateTime.Now, null) where t.Type == NetSqlAzManWCFCacheService.ItemType.Role && (t.Authorization == NetSqlAzManWCFCacheService.AuthorizationType.Allow || t.Authorization == NetSqlAzManWCFCacheService.AuthorizationType.AllowWithDelegation) && t.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase) select t).Count() > 0; } finally { ((IDisposable)csc).Dispose(); } } } } else { using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString)) { IAzManApplication application = storage[this.storeName][this.applicationName]; IAzManDBUser dbUser = application.GetDBUser(username); if (!this.useWCFCacheService) return (from t in this.storageCache.GetAuthorizedItems(this.storeName, this.applicationName, dbUser.CustomSid.StringValue, DateTime.Now) where t.Type == ItemType.Role && (t.Authorization == AuthorizationType.Allow || t.Authorization == AuthorizationType.AllowWithDelegation) && t.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase) select t).Count() > 0; else { using (NetSqlAzManWCFCacheService.CacheServiceClient csc = new NetSqlAzManWCFCacheService.CacheServiceClient()) { try { return (from t in csc.GetAuthorizedItemsForDatabaseUsers(this.storeName, this.applicationName, dbUser.CustomSid.StringValue, DateTime.Now, null) where t.Type == NetSqlAzManWCFCacheService.ItemType.Role && (t.Authorization == NetSqlAzManWCFCacheService.AuthorizationType.Allow || t.Authorization == NetSqlAzManWCFCacheService.AuthorizationType.AllowWithDelegation) && t.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase) select t).Count() > 0; } finally { ((IDisposable)csc).Dispose(); } } } } } }
/// <summary> /// Removes the specified user names from the specified roles for the configured applicationName. /// </summary> /// <param name="usernames">A string array of user names to be removed from the specified roles.</param> /// <param name="roleNames">A string array of role names to remove the specified user names from.</param> public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString)) { try { storage.OpenConnection(); storage.BeginTransaction(); IAzManApplication application = storage[this.storeName][this.applicationName]; foreach (string roleName in roleNames) { IAzManItem role = application.GetItem(roleName); if (role.ItemType != ItemType.Role) throw new ArgumentException(String.Format("{0} must be a Role.", roleName)); foreach (IAzManAuthorization auth in role.GetAuthorizations()) { string displayName; auth.GetMemberInfo(out displayName); foreach (string username in usernames) { if (String.Compare(this.getFQUN(username), displayName, true) == 0) { auth.Delete(); } } } } storage.CommitTransaction(); //Rebuild StorageCache this.InvalidateCache(false); } catch { storage.RollBackTransaction(); throw; } finally { storage.CloseConnection(); } } }
/// <summary> /// Gets the DB user. /// </summary> /// <param name="dbUserName">Name of the db user.</param> /// <returns></returns> /// <remarks>Thread-Safe</remarks> public virtual IAzManDBUser GetDBUser(string dbUserName) { using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString)) { IAzManApplication application = storage[this.storeName][this.applicationName]; return application.GetDBUser(dbUserName); } }
/// <summary> /// Gets a list of users in the specified role for the configured applicationName. /// </summary> /// <param name="roleName">The name of the role to get the list of users for.</param> /// <returns> /// A string array containing the names of all the users who are members of the specified role for the configured applicationName. /// </returns> public override string[] GetUsersInRole(string roleName) { using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString)) { IAzManApplication application = storage[this.storeName][this.applicationName]; IAzManItem role = application[roleName]; if (role.ItemType != ItemType.Role) throw new ArgumentException(String.Format("{0} must be a Role.", roleName), "roleName"); IAzManAuthorization[] authz = role.GetAuthorizations(); List<string> users = new List<string>(); foreach (IAzManAuthorization auth in authz) { if (auth.AuthorizationType == AuthorizationType.Allow || auth.AuthorizationType == AuthorizationType.AllowWithDelegation) { if (auth.SidWhereDefined == WhereDefined.Local || auth.SidWhereDefined == WhereDefined.LDAP) { string displayName; auth.GetMemberInfo(out displayName); users.Add(displayName); } else if (auth.SidWhereDefined == WhereDefined.Database) { users.Add(application.GetDBUser(auth.SID).UserName); } } } return users.ToArray(); } }
/// <summary> /// Removes a role from the data source for the configured applicationName. /// </summary> /// <param name="roleName">The name of the role to delete.</param> /// <param name="throwOnPopulatedRole">If true, throw an exception if roleName has one or more members and do not delete roleName.</param> /// <returns> /// true if the role was successfully deleted; otherwise, false. /// </returns> public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString)) { IAzManApplication application = storage[this.storeName][this.applicationName]; IAzManItem role = application[roleName]; if (role == null) throw new ArgumentNullException("roleName"); if (roleName.Trim() == String.Empty) throw new ArgumentException("roleName parameter cannot be empty."); if (role.ItemType != ItemType.Role) throw new ArgumentException(String.Format("{0} must be a Role.", roleName), "roleName"); if (throwOnPopulatedRole && application[roleName].GetMembers().Length > 0) { throw new ProviderException(String.Format("{0} has one or more members and cannot be deleted.", roleName)); } role.Delete(); //Rebuild StorageCache this.InvalidateCache(false); return true; } }
/// <summary> /// Adds the specified user names to the specified roles for the configured applicationName. /// </summary> /// <param name="usernames">A string array of user names to be added to the specified roles.</param> /// <param name="roleNames">A string array of the role names to add the specified user names to.</param> public override void AddUsersToRoles(string[] usernames, string[] roleNames) { using (IAzManStorage storage = new SqlAzManStorage(this.storageCache.ConnectionString)) { try { storage.OpenConnection(); storage.BeginTransaction(); IAzManApplication application = storage[this.storeName][this.applicationName]; foreach (string roleName in roleNames) { IAzManItem role = application.GetItem(roleName); if (role.ItemType != ItemType.Role) throw new ArgumentException(String.Format("{0} must be a Role.", roleName)); foreach (string username in usernames) { IAzManSid owner = new SqlAzManSID(((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent()).User); WhereDefined whereDefined = WhereDefined.LDAP; if (this.userLookupType == "LDAP") { string fqun = this.getFQUN(username); NTAccount ntaccount = new NTAccount(fqun); if (ntaccount == null) throw SqlAzManException.UserNotFoundException(username, null); IAzManSid sid = new SqlAzManSID(((SecurityIdentifier)(ntaccount.Translate(typeof(SecurityIdentifier))))); if (sid == null) throw SqlAzManException.UserNotFoundException(username, null); role.CreateAuthorization(owner, whereDefined, sid, WhereDefined.LDAP, AuthorizationType.Allow, null, null); } else { var dbuser = application.GetDBUser(username); IAzManSid sid = dbuser.CustomSid; role.CreateAuthorization(owner, whereDefined, sid, WhereDefined.Database, AuthorizationType.Allow, null, null); } } } storage.CommitTransaction(); //Rebuild StorageCache this.InvalidateCache(false); } catch { storage.RollBackTransaction(); throw; } finally { storage.CloseConnection(); } } }
/// <summary> /// Build a cache version of the Storage. /// </summary> /// <param name="storeNameFilter">The store name filter.</param> /// <param name="applicationNameFilter">The application name filter.</param> public void BuildStorageCache(string storeNameFilter, string applicationNameFilter) { System.Diagnostics.Debug.WriteLine(String.Format("Cache Building started at {0}", DateTime.Now)); SqlAzManStorage newStorage = new SqlAzManStorage(this.storage.ConnectionString); //Just iterate over all collections to cache all values var dummy1 = newStorage.Mode; var dummy2 = newStorage.LogInformations; var dummy3 = newStorage.LogOnDb; var dummy4 = newStorage.LogOnEventLog; var dummy5 = newStorage.LogWarnings; var dummy6 = newStorage.IAmAdmin; var dummy7 = newStorage.LogErrors; //Clean Biz Rule Assembly Cache SqlAzManItem.ClearBizRuleAssemblyCache(); NetSqlAzManStorageDataContext db = newStorage.db; newStorage.OpenConnection(); try { #region VALIDATION if (!String.IsNullOrEmpty(storeNameFilter)) storeNameFilter = storeNameFilter.Trim(); if (!String.IsNullOrEmpty(applicationNameFilter)) applicationNameFilter = applicationNameFilter.Trim(); IQueryable<StoresResult> filteredStoresByName = null; if (String.IsNullOrWhiteSpace(storeNameFilter) || !storeNameFilter.Contains(';')) { filteredStoresByName = from s in db.Stores() where !String.IsNullOrEmpty(storeNameFilter) && s.Name.Contains(storeNameFilter.Trim()) || String.IsNullOrEmpty(storeNameFilter) select s; } else { var storeNamesFilter = (from t in storeNameFilter.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) select t.Trim()).ToArray(); foreach (String storeNameFilterItem in storeNamesFilter) { var filteredStoresByNameLocal = from s in db.Stores() where storeNamesFilter.Contains(s.Name) select s; if (filteredStoresByName != null) filteredStoresByName = filteredStoresByName.Union(filteredStoresByNameLocal); else filteredStoresByName = filteredStoresByNameLocal; } } if (!String.IsNullOrWhiteSpace(storeNameFilter) && filteredStoresByName.Count() == 0) throw new ArgumentOutOfRangeException("storeNameFilter"); IQueryable<ApplicationsResult> filteredApplicationsByName = null; if (String.IsNullOrWhiteSpace(applicationNameFilter) || !applicationNameFilter.Contains(';')) { filteredApplicationsByName = from s in filteredStoresByName join a in db.Applications() on s.StoreId equals a.StoreId where !String.IsNullOrEmpty(applicationNameFilter) && a.Name.Contains(applicationNameFilter.Trim()) || String.IsNullOrEmpty(applicationNameFilter) select a; } else { var applicationNamesFilter = (from t in applicationNameFilter.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) select t.Trim()).ToArray(); foreach (String applicationNameFilterItem in applicationNamesFilter) { var filteredApplicationsByNameLocal = from a in db.Applications() where applicationNamesFilter.Contains(a.Name) select a; if (filteredApplicationsByName != null) filteredApplicationsByName = filteredApplicationsByName.Union(filteredApplicationsByNameLocal); else filteredApplicationsByName = filteredApplicationsByNameLocal; } } if (!String.IsNullOrEmpty(applicationNameFilter) && filteredApplicationsByName.Count() == 0) throw new ArgumentOutOfRangeException("applicationNameFilter"); #endregion VALIDATION SqlAzManENS ens = (SqlAzManENS)newStorage.ENS; List<StoresResult> allStores; List<StoreAttributesResult> allStoreAttributes; List<StoreGroupsResult> allStoreGroups; List<StoreGroupMembersResult> allStoreGroupMembers; List<ApplicationsResult> allApplications; List<ApplicationAttributesResult> allApplicationAttributes; List<ApplicationGroupsResult> allApplicationGroups; List<ApplicationGroupMembersResult> allApplicationGroupMembers; List<ItemsResult> allItems; List<ItemsHierarchyResult> allItemsHierarchy; List<ItemAttributesResult> allItemAttributes; List<ItemsResult> allBizRulesId; List<BizRulesResult> allBizRules; List<AuthorizationsResult> allAuthorizations; List<AuthorizationAttributesResult> allAuthorizationAttributes; //Cache All data (of StoreNameFilter / ApplicationNameFilter) if (String.IsNullOrEmpty(storeNameFilter) && String.IsNullOrEmpty(applicationNameFilter)) { #region LINQ QUERIES (Not Filtered) var allStoresQ = (from s in db.Stores() orderby s.Name select s).ToList(); var allStoreAttributesQ = (from sa in db.StoreAttributes() orderby sa.AttributeKey select sa).ToList(); var allStoreGroupsQ = (from sg in db.StoreGroups() orderby sg.Name select sg).ToList(); var allStoreGroupMembersQ = (from sgm in db.StoreGroupMembers() select sgm).ToList(); var allApplicationsQ = (from a in db.Applications() orderby a.Name select a).ToList(); var allApplicationAttributesQ = (from aa in db.ApplicationAttributes() orderby aa.AttributeKey select aa).ToList(); var allApplicationGroupsQ = (from ag in db.ApplicationGroups() orderby ag.Name select ag).ToList(); var allApplicationGroupMembersQ = (from agm in db.ApplicationGroupMembers() select agm).ToList(); var allItemsQ = (from i in db.Items() orderby i.Name select i).ToList(); var allItemsHierarchyQ = (from ih in db.ItemsHierarchy() select ih).ToList(); var allItemAttributesQ = (from ia in db.ItemAttributes() select ia).ToList(); var allBizRulesQ = (from br in db.BizRules() select br).ToList(); var allAuthorizationsQ = (from a in db.Authorizations() select a).ToList(); var allAuthorizationAttributesQ = (from aa in db.AuthorizationAttributes() orderby aa.AttributeKey select aa).ToList(); //Retrieve all records (without JOIN clause) allStores = (allStoresQ).ToList(); allStoreAttributes = (allStoreAttributesQ).ToList(); allStoreGroups = (allStoreGroupsQ).ToList(); allStoreGroupMembers = (allStoreGroupMembersQ).ToList(); allApplications = (allApplicationsQ).ToList(); allApplicationAttributes = (allApplicationAttributesQ).ToList(); allApplicationGroups = (allApplicationGroupsQ).ToList(); allApplicationGroupMembers = (allApplicationGroupMembersQ).ToList(); allItems = (allItemsQ).ToList(); allItemsHierarchy = (allItemsHierarchyQ).ToList(); allItemAttributes = (allItemAttributesQ).ToList(); allBizRules = (allBizRulesQ).ToList(); allAuthorizations = (allAuthorizationsQ).ToList(); allAuthorizationAttributes = (allAuthorizationAttributesQ).ToList(); #endregion LINQ QUERIES (Not Filtered) } else { #region LINQ QUERIES (Filtered) var filteredStores = (from s in filteredStoresByName select s.StoreId.Value).ToList(); var filteredApplications = (from a in filteredApplicationsByName select a.ApplicationId.Value).ToList(); var allStoresFQ = (from s in db.Stores() where filteredStores.Contains(s.StoreId.Value) orderby s.Name select s); var allStoreAttributesFQ = (from sa in db.StoreAttributes() where filteredStores.Contains(sa.StoreId.Value) orderby sa.AttributeKey select sa); var allStoreGroupsFQ = (from sg in db.StoreGroups() where filteredStores.Contains(sg.StoreId.Value) orderby sg.Name select sg); var allStoreGroupMembersFQ = (from sgm in db.StoreGroupMembers() join sg in allStoreGroupsFQ on sgm.StoreGroupId equals sg.StoreGroupId select sgm); var allApplicationsFQ = (from a in db.Applications() where filteredApplications.Contains(a.ApplicationId.Value) orderby a.Name select a); var allApplicationAttributesFQ = (from aa in db.ApplicationAttributes() where filteredApplications.Contains(aa.ApplicationId.Value) orderby aa.AttributeKey select aa); var allApplicationGroupsFQ = (from ag in db.ApplicationGroups() where filteredApplications.Contains(ag.ApplicationId.Value) orderby ag.Name select ag); var allApplicationGroupMembersFQ = (from agm in db.ApplicationGroupMembers() join ag in allApplicationGroupsFQ on agm.ApplicationGroupId equals ag.ApplicationGroupId select agm); var allItemsFQ = (from i in db.Items() join a in allApplicationsFQ on i.ApplicationId equals a.ApplicationId orderby i.Name select i); var allItemsHierarchyFQ = (from ih in db.ItemsHierarchy() join i in allItemsFQ on ih.ItemId equals i.ItemId select ih); var allItemAttributesFQ = (from ia in db.ItemAttributes() join ai in allItemsFQ on ia.ItemId equals ai.ItemId select ia); var allBizRulesIdFQ = (from ai in allItemsFQ where ai.BizRuleId != null select ai); var allBizRulesFQ = (from br in db.BizRules() join ab in allBizRulesIdFQ on br.BizRuleId equals ab.BizRuleId select br); var allAuthorizationsFQ = (from a in db.Authorizations() join ai in allItemsFQ on a.ItemId equals ai.ItemId select a); var allAuthorizationAttributesFQ = (from aa in db.AuthorizationAttributes() join a in allAuthorizationsFQ on aa.AuthorizationId equals a.AuthorizationId orderby aa.AttributeKey select aa); //Retrieve filtered records (with JOIN clause) allStores = (allStoresFQ).ToList(); allStoreAttributes = (allStoreAttributesFQ).ToList(); allStoreGroups = (allStoreGroupsFQ).ToList(); allStoreGroupMembers = (allStoreGroupMembersFQ).ToList(); allApplications = (allApplicationsFQ).ToList(); allApplicationAttributes = (allApplicationAttributesFQ).ToList(); allApplicationGroups = (allApplicationGroupsFQ).ToList(); allApplicationGroupMembers = (allApplicationGroupMembersFQ).ToList(); allItems = (allItemsFQ).ToList(); allItemsHierarchy = (allItemsHierarchyFQ).ToList(); allItemAttributes = (allItemAttributesFQ).ToList(); allBizRulesId = (allBizRulesIdFQ).ToList(); allBizRules = (allBizRulesFQ).ToList(); allAuthorizations = (allAuthorizationsFQ).ToList(); allAuthorizationAttributes = (allAuthorizationAttributesFQ).ToList(); #endregion LINQ QUERIES (Filtered) } #region CACHE BUILDING //Stores var stores = allStores.ToDictionary<StoresResult, string, IAzManStore>(sr => sr.Name, sr => { byte netsqlazmanFixedServerRole = 0; if (newStorage.IAmAdmin) { netsqlazmanFixedServerRole = 3; } else { var res1 = db.CheckStorePermissions(sr.StoreId, 2); var res2 = db.CheckStorePermissions(sr.StoreId, 1); if (res1.HasValue && res1.Value) netsqlazmanFixedServerRole = 2; else if (res2.HasValue && res2.Value) netsqlazmanFixedServerRole = 1; } return new SqlAzManStore(db, newStorage, sr.StoreId.Value, sr.Name, sr.Description, netsqlazmanFixedServerRole, ens); }); newStorage.stores = stores; foreach (IAzManStore store in newStorage.Stores.Values) { //Store Groups var storeGroups = allStoreGroups.Where(sgr => sgr.StoreId == store.StoreId).ToDictionary<StoreGroupsResult, string, IAzManStoreGroup>(sgr => sgr.Name, sgr => { return new SqlAzManStoreGroup(db, store, sgr.StoreGroupId.Value, new SqlAzManSID(sgr.ObjectSid.ToArray()), sgr.Name, sgr.Description, sgr.LDapQuery, (GroupType)sgr.GroupType.Value, ens); }); ((SqlAzManStore)store).storeGroups = (from sgv in storeGroups.Values where sgv.Store.StoreId == store.StoreId select sgv).ToDictionary(sg => sg.Name); foreach (IAzManStoreGroup storeGroup in store.StoreGroups.Values) { //Store Groups Members if (storeGroup.GroupType == GroupType.Basic) { var storeGroupMembers = allStoreGroupMembers.Where(sgm => sgm.StoreGroupId == storeGroup.StoreGroupId).ToDictionary<StoreGroupMembersResult, IAzManSid, IAzManStoreGroupMember>(sgm => new SqlAzManSID(sgm.ObjectSid.ToArray(), (WhereDefined)sgm.WhereDefined.Value == WhereDefined.Database), sgm => { return new SqlAzManStoreGroupMember(db, storeGroup, sgm.StoreGroupMemberId.Value, new SqlAzManSID(sgm.ObjectSid.ToArray(), (WhereDefined)sgm.WhereDefined.Value == WhereDefined.Database), (WhereDefined)sgm.WhereDefined.Value, sgm.IsMember.Value, ens); }); ((SqlAzManStoreGroup)storeGroup).members = storeGroupMembers; } else if (storeGroup.GroupType == GroupType.LDapQuery) { this.getCachedLDAPQueryResults(storeGroup); } } //Store Attributes var storeAttributes = allStoreAttributes.Where(sa => sa.StoreId == store.StoreId).ToDictionary<StoreAttributesResult, string, IAzManAttribute<IAzManStore>>(sa => sa.AttributeKey, sa => { return new SqlAzManStoreAttribute(db, store, sa.StoreAttributeId.Value, sa.AttributeKey, sa.AttributeValue, ens); }); ((SqlAzManStore)store).attributes = storeAttributes; //Applications var applications = allApplications.Where(a => a.StoreId == store.StoreId).ToDictionary<ApplicationsResult, string, IAzManApplication>(a => a.Name, a => { byte netsqlazmanFixedServerRole = 0; if (store.IAmAdmin) { netsqlazmanFixedServerRole = 3; } else { var r1 = db.CheckApplicationPermissions(a.ApplicationId.Value, 2); var r2 = db.CheckApplicationPermissions(a.ApplicationId.Value, 1); if (r1.HasValue && r1.Value) netsqlazmanFixedServerRole = 2; else if (r2.HasValue && r2.Value) netsqlazmanFixedServerRole = 1; } return new SqlAzManApplication(db, store, a.ApplicationId.Value, a.Name, a.Description, netsqlazmanFixedServerRole, ens); }); ((SqlAzManStore)store).applications = applications; foreach (IAzManApplication application in store.Applications.Values) { //Application Groups var applicationGroups = allApplicationGroups.Where(ag => ag.ApplicationId == application.ApplicationId).ToDictionary<ApplicationGroupsResult, string, IAzManApplicationGroup>(ag => ag.Name, ag => { return new SqlAzManApplicationGroup(db, application, ag.ApplicationGroupId.Value, new SqlAzManSID(ag.ObjectSid.ToArray()), ag.Name, ag.Description, ag.LDapQuery, (GroupType)ag.GroupType, ens); }); ((SqlAzManApplication)application).applicationGroups = applicationGroups; foreach (IAzManApplicationGroup applicationGroup in application.ApplicationGroups.Values) { if (applicationGroup.GroupType == GroupType.Basic) { //Application Group Members var applicationGroupMembers = allApplicationGroupMembers.Where(agm => agm.ApplicationGroupId == applicationGroup.ApplicationGroupId).ToDictionary<ApplicationGroupMembersResult, IAzManSid, IAzManApplicationGroupMember>(agm => new SqlAzManSID(agm.ObjectSid.ToArray(), (WhereDefined)agm.WhereDefined.Value == WhereDefined.Database), agm => { return new SqlAzManApplicationGroupMember(db, applicationGroup, agm.ApplicationGroupMemberId.Value, new SqlAzManSID(agm.ObjectSid.ToArray(), (WhereDefined)agm.WhereDefined.Value == WhereDefined.Database), (WhereDefined)agm.WhereDefined.Value, agm.IsMember.Value, ens); }); ((SqlAzManApplicationGroup)applicationGroup).members = applicationGroupMembers; } else if (applicationGroup.GroupType == GroupType.LDapQuery) { this.getCachedLDAPQueryResults(applicationGroup); } } //Application Attributes var applicationAttributes = allApplicationAttributes.Where(sa => sa.ApplicationId == application.ApplicationId).ToDictionary<ApplicationAttributesResult, string, IAzManAttribute<IAzManApplication>>(sa => sa.AttributeKey, sa => { return new SqlAzManApplicationAttribute(db, application, sa.ApplicationAttributeId.Value, sa.AttributeKey, sa.AttributeValue, ens); }); ((SqlAzManApplication)application).attributes = applicationAttributes; //Items var items = allItems.Where(i => i.ApplicationId == application.ApplicationId).ToDictionary<ItemsResult, string, IAzManItem>(i => i.Name, i => { BizRulesResult bizRule = null; if (i.BizRuleId.HasValue) { bizRule = (from br in allBizRules where br.BizRuleId == i.BizRuleId select br).First(); } return new SqlAzManItem(db, application, i.ItemId.Value, i.Name, i.Description, (ItemType)i.ItemType, bizRule != null ? bizRule.BizRuleSource : String.Empty, bizRule != null ? (BizRuleSourceLanguage)bizRule.BizRuleLanguage.Value : default(BizRuleSourceLanguage), ens); }); Dictionary<int, IAzManItem> itemsById = items.Values.ToDictionary(f => f.ItemId); Dictionary<int, List<int>> allItemsHierarchyByMemberId = new Dictionary<int, List<int>>(); foreach (var itemHierarchy in allItemsHierarchy) { if (!allItemsHierarchyByMemberId.ContainsKey(itemHierarchy.MemberOfItemId.Value)) allItemsHierarchyByMemberId.Add(itemHierarchy.MemberOfItemId.Value, new List<int>()); allItemsHierarchyByMemberId[itemHierarchy.MemberOfItemId.Value].Add(itemHierarchy.ItemId.Value); } ((SqlAzManApplication)application).items = items; var itemsOfApplication = (from i in allItems where i.ApplicationId == application.ApplicationId select i).ToList(); foreach (string itemKey in application.Items.Keys) { IAzManItem item = application.Items[itemKey]; //Debug.WriteLine(item.Name); var itemAttributes = allItemAttributes.Where(sa => sa.ItemId == item.ItemId).ToDictionary<ItemAttributesResult, string, IAzManAttribute<IAzManItem>>(sa => sa.AttributeKey, sa => { return new SqlAzManItemAttribute(db, item, sa.ItemAttributeId.Value, sa.AttributeKey, sa.AttributeValue, ens); }); ((SqlAzManItem)item).attributes = itemAttributes; if (allItemsHierarchyByMemberId.ContainsKey(item.ItemId)) { ((SqlAzManItem)item).members = (from i in itemsById join h in allItemsHierarchyByMemberId[item.ItemId] on i.Key equals h select i.Value).ToDictionary(f => f.Name); } else { ((SqlAzManItem)item).members = new Dictionary<string, IAzManItem>(); } //Authorizations var authorizations = allAuthorizations.Where(a => a.ItemId == item.ItemId).ToDictionary<AuthorizationsResult, int, IAzManAuthorization>(a => a.AuthorizationId.Value, a => { //return new SqlAzManAuthorization(db, item, a.AuthorizationId.Value, new SqlAzManSID(a.OwnerSid.ToArray()), (WhereDefined)a.OwnerSidWhereDefined, new SqlAzManSID(a.ObjectSid.ToArray()), (WhereDefined)a.ObjectSidWhereDefined, (AuthorizationType)a.AuthorizationType, a.ValidFrom, a.ValidTo, ens); //Thanks to: K.Overmars - [email protected] (http://sourceforge.net/tracker/index.php?func=detail&aid=1939219&group_id=165814&atid=836877) return new SqlAzManAuthorization(db, item, a.AuthorizationId.Value, new SqlAzManSID(a.OwnerSid.ToArray(), a.OwnerSidWhereDefined == (byte)(WhereDefined.Database)), (WhereDefined)a.OwnerSidWhereDefined, new SqlAzManSID(a.ObjectSid.ToArray(), a.ObjectSidWhereDefined == (byte)(WhereDefined.Database)), (WhereDefined)a.ObjectSidWhereDefined, (AuthorizationType)a.AuthorizationType, a.ValidFrom, a.ValidTo, ens); }).Values.ToList(); ((SqlAzManItem)item).authorizations = authorizations; if (authorizations.Count > 0) { foreach (IAzManAuthorization authorization in item.Authorizations) { //Authorization Attributes var authorizationAttributes = allAuthorizationAttributes.Where(sa => sa.AuthorizationId == authorization.AuthorizationId).ToDictionary<AuthorizationAttributesResult, string, IAzManAttribute<IAzManAuthorization>>(sa => sa.AttributeKey, sa => { return new SqlAzManAuthorizationAttribute(db, authorization, sa.AuthorizationAttributeId.Value, sa.AttributeKey, sa.AttributeValue, ens); }); ((SqlAzManAuthorization)authorization).attributes = authorizationAttributes; } } //Biz Rules if (!String.IsNullOrEmpty(item.BizRuleSource)) item.LoadBizRuleAssembly(); } } } lock (this) { System.Diagnostics.Debug.WriteLine("StorageCache Built."); this.storage = newStorage; } #endregion CACHE BUILDING } finally { newStorage.CloseConnection(); } }
internal static void TestConnection(string connectionString) { SqlAzManStorage.VerifyStorageDB(connectionString); SqlAzManStorage storage = new SqlAzManStorage(connectionString); string dbVersion = storage.DatabaseVesion; string netsqlazmanRunTimeVersion = storage.GetType().Assembly.GetName().Version.ToString(); if (!String.Equals(netsqlazmanRunTimeVersion.Substring(0,6), dbVersion.Substring(0,6), StringComparison.InvariantCultureIgnoreCase)) { MessageBox.Show(String.Format("NetSqlAzMan Run-Time Version: {0}\r\nNetSqlAzMan Database Version: {1}", netsqlazmanRunTimeVersion, dbVersion), "Warning: Version mismatch",MessageBoxButtons.OK, MessageBoxIcon.Warning); } }