Esempio n. 1
0
        /// <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);
        }
Esempio n. 2
0
    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();
        }
    }
Esempio n. 3
0
        /// <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);
        }
Esempio n. 4
0
        /// <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>
        /// 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();
                }
            }
        }
Esempio n. 6
0
        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();
        }
        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();
            }
        }
Esempio n. 8
0
        /// <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();
     }
 }
Esempio n. 10
0
        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>
 /// 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();
         }
     }
 }
Esempio n. 12
0
        /// <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);
        }
Esempio n. 13
0
        /// <summary>
        /// دریافت لیست کل نقش ها
        /// </summary>
        public IEnumerable <RoleOutput> GetAllRoles()
        {
            var roles = new List <RoleOutput>();

            try
            {
                IAzManStorage storage = new SqlAzManStorage(_azManConnectionString);
                storage.OpenConnection();
                IAzManItem[] azRoles = storage[_storageName][_applicationName].GetItems(ItemType.Role);
                storage.CloseConnection();
                roles = azRoles.Select(r => new RoleOutput {
                    Name = r.Name, Description = r.Description
                }).ToList();
            }
            catch (Exception ex)
            {
                //log ex
            }

            return(roles);
        }
 /// <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>
        /// 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();
                }
            }
        }
Esempio n. 16
0
        /// <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();
            }
        }
Esempio n. 17
0
        private void btnTestNetSqlAzMan_Click(object sender, EventArgs e)
        {
            this.Clessidra(true);
            this.StartTimer();
            int n   = int.Parse(this.txtNetSqlAzManThreads.Text);
            int max = int.Parse(this.txtUnita.Text);

            this.pb.Maximum = n - 1;
            if (!this.chkNetSqlAzManMultiThread.Checked)
            {
                if (!this.chkCache.Checked)
                {
                    for (int i = 0; i < n; i++)
                    {
                        this.TestSuNetSqlAzMan(this.txtNetSqlAzManConnectionString.Text, max);
                        this.pb.Value = i;
                        Application.DoEvents();
                    }
                }
                else
                {
                    WindowsIdentity id      = WindowsIdentity.GetCurrent();
                    IAzManStorage   storage = new SqlAzManStorage(this.txtNetSqlAzManConnectionString.Text);
                    storage.OpenConnection();
                    int rnd = new Random().Next(max);
                    NetSqlAzMan.Cache.UserPermissionCache c = new NetSqlAzMan.Cache.UserPermissionCache(storage, "Store Stress Test", "Application" + rnd.ToString(), id, true, true);
                    for (int i = 0; i < n; i++)
                    {
                        List <KeyValuePair <string, string> > attr;
                        AuthorizationType res = c.CheckAccess("Operation" + rnd.ToString(), DateTime.Now, out attr);
                        this.pb.Value = i;
                        Application.DoEvents();
                    }
                    storage.CloseConnection();
                    storage.Dispose();
                }
            }
            else
            {
                Thread[] tt = new Thread[n];
                //Threads Prepare
                for (int i = 0; i < n; i++)
                {
                    tt[i] = new Thread(new ThreadStart(this.TestSuNetSqlAzManForThread));
                    tt[i].Start();
                    this.pb.Value = i;
                }
                //Threads Consume
                for (int i = 0; i < n; i++)
                {
                    tt[i].Join();
                    this.pb.Value = i;
                }
                //Threads Destroy
                for (int i = 0; i < n; i++)
                {
                    tt[i]         = null;
                    this.pb.Value = i;
                }
            }
            this.StopTimer(this.txtNetSqlAzManElapsed);
            this.Clessidra(false);
        }
        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();
            }
        }
Esempio n. 19
0
        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();
            }
        }
        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>
 /// 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();
     }
 }