コード例 #1
0
        /// <summary>
        /// Validates autorization token string
        /// </summary>
        /// <param name="settingsProvider">settings provider to be used in the validation</param>
        /// <param name="authToken">token string to be validated</param>
        /// <returns>validated token object</returns>
        public static SecurityTokenPayloadType GetValidatedToken <SecurityTokenPayloadType>(ISettingsProvider settingsProvider, string authToken)
        {
            var tokenHandler         = new JwtSecurityTokenHandler();
            var validationParameters = GetValidationParameters(settingsProvider);

            SecurityToken            token;
            SecurityTokenPayloadType tokenPayload = default(SecurityTokenPayloadType);

            try {
                tokenHandler.ValidateToken(authToken, validationParameters, out token);
                string tokenString = token.ToString();
                string payload     = tokenString.Substring(tokenString.IndexOf('.') + 1);
                tokenPayload = JsonConvert.DeserializeObject <SecurityTokenPayloadType>(payload);
            } catch (Exception e) {
                OSTrace.Error("Token validation failed.", e);
            }
            return(tokenPayload);
        }
        public static void FixRegistrySettingsPermissions()
        {
            try {
                var rs   = new RegistrySecurity();
                var rule = new RegistryAccessRule(new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null),
                                                  RegistryRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow);
                rs.AddAccessRule(rule);

                using (RegistryKey subKey = Registry.LocalMachine.CreateSubKey(osRegistryKey)) {
                    if (subKey != null)
                    {
                        subKey.SetAccessControl(rs);
                    }
                }
            } catch (Exception ex) {
                OSTrace.Error("FixRegistrySettingsPermissions: Failed to grant permissions to settings registry key.", ex);
            }
        }
コード例 #3
0
        public void Dispose()
        {
            try {
                if (!isDisposed)
                {
                    FreeupResources(/*commit*/ false);
                }
            } catch (Exception e) {
                // avoid errors during dispose
#if debug
                throw new Exception("Crashed on dispose, check for leaks!!!!", e);
#else
                OSTrace.Error("Error while disposing", e);
#endif
            } finally {
                isDisposed = true;
            }
        }
コード例 #4
0
        protected bool IsResponseValid(HttpWebResponse response, string responseString)
        {
            ResponseSecurityTokenPayload payload = null;
            var authorizationHeader = response.Headers[AuthorizationHeaderKey];

            if (authorizationHeader == null)
            {
                OSTrace.Error("Authorization header is null");
                return(false);
            }

            var stringToken = authorizationHeader.RemoveIfStartsWith(AuthorizationTokenType);

            payload = SecurityTokenAPI.GetValidatedToken <ResponseSecurityTokenPayload>(RuntimeSettingsProvider.Instance, stringToken);
            if (payload == null)
            {
                return(false);
            }
            return(ValidateConsumerAndProducerKeys(payload.ConsumerKey, payload.ProducerKey) &&
                   IsResponsePayloadValid(responseString, payload));
        }
        public static bool IsLocalMachineAddress(string hostnameOrIP, out bool error)
        {
            error = false;
            if (IsLoopbackAddress(hostnameOrIP))
            {
                return(true);
            }
            try {
                IPAddress[] hostnameIPs  = Dns.GetHostAddresses(hostnameOrIP.Trim());
                IPAddress[] localhostIPs = Dns.GetHostAddresses(Dns.GetHostName());

                HashSet <IPAddress> localIPs = new HashSet <IPAddress>();
                localIPs.AddRange(localhostIPs);
                // #617204 ensure we also include the IP addresses configured for the interfaces, when detecting if an address is local or not
                localIPs.AddRange(GetAllIpAddresses());

                return(localIPs.Any(ip => hostnameIPs.Contains(ip)));
            } catch (Exception e) {
                OSTrace.Error("Checking if address is local address", e);
                error = true;
                return(true);
            }
        }
コード例 #6
0
 public static bool IsLocalMachineAddress(string hostnameOrIP, out bool error)
 {
     error = false;
     if (IsLoopbackAddress(hostnameOrIP))
     {
         return(true);
     }
     try {
         IPAddress[] hostnameIPs  = Dns.GetHostAddresses(hostnameOrIP.Trim());
         IPAddress[] localhostIPs = Dns.GetHostAddresses(Dns.GetHostName());
         // Short-circuit early if possible because GetAllIpAddresses is an expensive call (assessed via profiling)
         if (ContainsAnyIpAddress(localhostIPs, hostnameIPs))
         {
             return(true);
         }
         // #617204 ensure we also include the IP addresses configured for the interfaces, when detecting if an address is local or not
         return(ContainsAnyIpAddress(GetAllIpAddresses(), hostnameIPs));
     } catch (Exception e) {
         OSTrace.Error("Checking if address is local address", e);
         error = true;
         return(true);
     }
 }
 private void HandleException(Exception e)
 {
     OSTrace.Error("", e);
 }
コード例 #8
0
        protected IEnumerable <ITableSourceForeignKeyInfo> GetForeignKeys(IEnumerable <CacheTableSourceInfo> tableSources)
        {
            string paramPrefix = DatabaseServices.ExecutionService.ParameterPrefix;
            string tableNames  = "";

            try {
                tableNames = "'" + tableSources.Select(t => t.Name).StrCat("','") + "'";
                IList <ITableSourceForeignKeyInfo> foreignKeys = new List <ITableSourceForeignKeyInfo>();

                using (IDbConnection conn = DatabaseServices.TransactionService.CreateConnection()) {
                    foreach (CacheTableSourceInfo tableSource in tableSources)
                    {
                        string query = string.Format(
                            @"SELECT t.TABLE_NAME, c.CONSTRAINT_NAME, c.COLUMN_NAME, c.REFERENCED_TABLE_NAME, 
                                     c.REFERENCED_COLUMN_NAME, r.DELETE_RULE
                              FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
                                INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS t ON c.CONSTRAINT_NAME = t.CONSTRAINT_NAME 
                                INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS r ON r.CONSTRAINT_NAME = t.CONSTRAINT_NAME
                              WHERE t.CONSTRAINT_TYPE = 'FOREIGN KEY' 
                                AND t.TABLE_SCHEMA = {0} 
                                AND c.CONSTRAINT_SCHEMA = {0} 
                                AND r.CONSTRAINT_SCHEMA = {0} 
                                AND t.TABLE_NAME = {1}", paramPrefix + "schema", paramPrefix + "table");

                        IDbCommand cmd = DatabaseServices.ExecutionService.CreateCommand(conn, query);
                        DatabaseServices.ExecutionService.CreateParameter(cmd, paramPrefix + "schema", DbType.String, tableSource.Database.Name);
                        DatabaseServices.ExecutionService.CreateParameter(cmd, paramPrefix + "table", DbType.String, tableSource.Name);
                        cmd.CommandTimeout = QueryTimeout;
                        using (IDataReader reader = cmd.ExecuteReader()) {
                            while (reader.Read())
                            {
                                string tableName            = (string)reader["TABLE_NAME"];
                                string foreignKeyName       = (string)reader["CONSTRAINT_NAME"];
                                string columnName           = (string)reader["COLUMN_NAME"];
                                string referencedColumnName = (string)reader["REFERENCED_COLUMN_NAME"];
                                string referencedTableName  = (string)reader["REFERENCED_TABLE_NAME"];
                                bool   isCascadeDelete      = "CASCADE".EqualsIgnoreCase((string)reader["DELETE_RULE"]);

                                string                     qualifiedReferencedTableName = GetQualifiedIdentifier(tableSource.Database.Name, referencedTableName);
                                ITableSourceInfo           referencedTableSource        = new CacheTableSourceInfo(DatabaseServices, tableSource.Database, referencedTableName, qualifiedReferencedTableName);
                                ITableSourceForeignKeyInfo foreignKeyInfo = new CacheTableSourceForeignKeyInfo(tableSource, foreignKeyName, columnName, referencedTableSource, referencedColumnName, isCascadeDelete);
                                foreignKeys.Add(foreignKeyInfo);
                            }
                        }

                        // Also check if there are relationships defined on columns, these also get added as a foreign key
                        // If a relationship is found check if this column does not already have a foreign key, if it has then
                        // do not add another foreign key.
                        // If a column references another object the type will not start with %Library, so we check for all runtimetypes
                        // taht do not start with %, this indicates reference to another object. Further we only want to know about references to other
                        // persistent objects.
                        string queryRelationships = string.Format(
                            @"SELECT P.SqlFieldName AS COLUMN_NAME, P.RuntimeType AS RUNTIME_TYPE, P.Collection, 
                                     P.Relationship AS RELATIONSHIP, P.Cardinality,  
                                     P.Parent, P.SqlListDelimiter, P.SqlListType, P.Name AS ColumnName 
                               FROM %Dictionary.CompiledClass C, %Dictionary.CompiledProperty P 
                               WHERE P.parent = C.ID 
                                 AND NOT P.RuntimeType %STARTSWITH '%' 
                                 AND C.SqlSchemaName = {0}
                                 AND C.SqlTableName  = {1}", paramPrefix + "schema", paramPrefix + "table");

                        IDbCommand cmdRelationships = DatabaseServices.ExecutionService.CreateCommand(conn, queryRelationships);
                        DatabaseServices.ExecutionService.CreateParameter(cmdRelationships, paramPrefix + "schema", DbType.String, tableSource.Database.Name);
                        DatabaseServices.ExecutionService.CreateParameter(cmdRelationships, paramPrefix + "table", DbType.String, tableSource.Name);
                        cmdRelationships.CommandTimeout = QueryTimeout;

                        using (IDataReader readerRel = cmdRelationships.ExecuteReader()) {
                            while (readerRel.Read())
                            {
                                string runtimeType = (string)readerRel["RUNTIME_TYPE"];
                                // Check if the Runtime Type is that of a persistent object
                                bool   isPersistentType    = false;
                                string queryPersistentType = string.Format(
                                    @"SELECT ID, Name, ClassType FROM %Dictionary.CompiledClass WHERE Name = '" + runtimeType + @"'");
                                IDbCommand cmdPersistentType = DatabaseServices.ExecutionService.CreateCommand(conn, queryPersistentType);
                                using (IDataReader readerPersistent = cmdPersistentType.ExecuteReader()) {
                                    if (readerPersistent.Read())
                                    {
                                        string classType = (string)readerPersistent["ClassType"];
                                        isPersistentType = classType.CompareTo("persistent") == 0 ? true : false;
                                    }
                                }

                                if (isPersistentType)
                                {
                                    // Check if there is such a foreign key
                                    string referencedTableName = ExtractTableNameFromQualifiedName(runtimeType);
                                    string columnName          = (string)readerRel["COLUMN_NAME"];
                                    int    idx = foreignKeys.IndexOf(t => t.ColumnName.EqualsIgnoreCase(columnName));

                                    if (idx < 0)
                                    {
                                        // Add a foreign key constraint which is named this column's name pre-pended with "FK_"[referenced table name]
                                        // and the referenced column is the "ID" column of the referenced table.
                                        string                     foreignKeyName = "FK_" + referencedTableName + "_" + columnName;
                                        string                     qualifiedReferencedTableName = GetQualifiedIdentifier(tableSource.Database.Name, referencedTableName);
                                        ITableSourceInfo           referencedTableSource        = new CacheTableSourceInfo(DatabaseServices, tableSource.Database, referencedTableName, qualifiedReferencedTableName);
                                        ITableSourceForeignKeyInfo foreignKeyInfo = new CacheTableSourceForeignKeyInfo(tableSource, foreignKeyName, columnName, referencedTableSource, "ID", false);
                                        foreignKeys.Add(foreignKeyInfo);
                                    }
                                }
                            }
                        }
                    } // foreach
                }

                return(foreignKeys);
            }
            catch (Exception e) {
                OSTrace.Error(string.Format("Failed to retrieve foreign key information from database. Tables: {0}", tableNames), e);
                return(new List <ITableSourceForeignKeyInfo>());
            }
        }
コード例 #9
0
        protected TransactionInfo GetAndReserveFromPoolUnchecked()
        {
            TransactionInfo[] transactions;
            lock (TransactionPool.SyncRoot) {
                transactions = TransactionPool.Values.Cast <TransactionInfo>().ToArray();
            }

            foreach (TransactionInfo transInfo in transactions)
            {
                if (transInfo.Free)
                {
                    lock (transInfo) {
                        if (transInfo.Free)
                        {
                            DateTime lastChange = transInfo.LastChange;
                            transInfo.Reserve();

                            //#52135, we already have nice checks for the pooled connections
                            if (transInfo.Transaction.Connection == null || transInfo.Connection.State == ConnectionState.Closed)
                            {
                                // build exception report
                                IDbConnection shadowConnection = transInfo.Connection;
                                string        exceptTxt        = "Connection in transaction is null or closed (TransactionInfo Status: ";
                                try {
                                    if (shadowConnection == null)
                                    {
                                        exceptTxt += "Connection=null, ";
                                    }
                                    else
                                    {
                                        exceptTxt += String.Format("Connection.State=='{0}', ", shadowConnection.State.ToString());
                                    }

                                    exceptTxt += String.Format("Free='{0}', CreationTime='{1}', LastChange='{2}', ReaderCount='{3}')",
                                                               transInfo.Free, transInfo.CreationTime, lastChange, transInfo.ReaderCount);

                                    int numTransactions = transactions.Length;
                                    int numFree         = CountFreeTransactionsInPool(transactions);
                                    exceptTxt += String.Format(". (Pool Status: Total={0}, Free={1})", numTransactions, numFree);
                                } catch {
                                } finally {
                                    // remove and cleanup everything
                                    TransactionPool.Remove(transInfo.Transaction);

                                    transInfo.Transaction.Dispose();

                                    if (transInfo.Connection != null)
                                    {
                                        transInfo.Connection.Dispose();
                                    }
                                }
                                throw new InvalidTransactionException(exceptTxt);
                            }
                            else
                            {
#if DEBUG_DBCONNECTIONPOOLING
                                OSTrace.Info("DBConnectionPooling[TID=" + transInfo.Transaction.GetHashCode() + "] - reserved from pool");
                                OSTrace.Error(new StackTrace().ToString());
#endif
                                return(transInfo);
                            }
                        }
                    }
                }
            }
            // No free transaction found. Add a new one and return it.
            return(AddToPoolAndReserve());
        }
        /// <summary>
        /// Executes a command(s) and returns the value of the first column of the first row in the resultset returned by the query.
        /// This implementation logs exceptions.
        /// </summary>
        /// <param name="cmd">The command to execute.</param>
        /// <returns>An object with the resulting first row and first column of the query defined in the query command.</returns>
        public override object ExecuteScalar(IDbCommand cmd)
        {
            object returnObject = null;

            try {
                // The Caché database cannot handle multiple SQL commands in one call.
                // Therefore have to parse the SQL statements, execute each and return only the last one's value.
                // We have to build a new cmd (IDbCommand) for each SQL statement, we also have to parse the parameters (IDataParameterColelction)
                // to get the parameters (IDataParameter) of each SQL statement to add the correct parameters to the cmd.
                // Execute each with ExecuteNonQuery, we are not interested in the return, then for the last statement execute
                // the command with ExecuteScalar() and return this result.
                // If there is only one SQL statement this is east, simply call ExecuteScalar.

                string   cmdText          = cmd.CommandText;
                string   pattern          = @"(?<!@)@\w{1,}"; // Looks for parameter prefixed with @ and excludes anything starting with @@.
                Regex    rgx              = new Regex(pattern, RegexOptions.IgnoreCase);
                int      numSqlStatements = 0;
                char[]   delimiterChars   = { ';' };
                string[] sqlStatements    = cmdText.Split(delimiterChars);

                // Check if last statement is empty
                if (sqlStatements.Length > 0)
                {
                    string sqlLast = sqlStatements[sqlStatements.Length - 1].Trim();
                    numSqlStatements = sqlLast.Length == 0 ? sqlStatements.Length - 1 : sqlStatements.Length;
                }

                if (numSqlStatements > 1)
                {
                    for (int i = 0; i < numSqlStatements; i++)
                    {
                        string sqlStatement = sqlStatements[i];
                        using (IDbCommand newCmd = CreateCommand(cmd.Connection, sqlStatement)) {
                            // Copy all the current command's parameters to the new command.
                            newCmd.CommandTimeout   = cmd.CommandTimeout;
                            newCmd.CommandType      = cmd.CommandType;
                            newCmd.Transaction      = cmd.Transaction;
                            newCmd.UpdatedRowSource = cmd.UpdatedRowSource;

                            // Now parse and add Parameters
                            MatchCollection matchColl = rgx.Matches(sqlStatement);
                            foreach (Match m in matchColl)
                            {
                                IDbDataParameter dataParam = (IDbDataParameter)cmd.Parameters[m.Value];
                                IDbDataParameter newParam  = CreateParameter(newCmd, dataParam.ParameterName, dataParam.DbType, dataParam.Value);
                                SetParameterDirection(newParam, dataParam.Direction);
                            }

                            // Is this the last SQL statement?
                            if (i == (numSqlStatements - 1))
                            {
                                returnObject = newCmd.ExecuteScalar();
                            }
                            else
                            {
                                newCmd.ExecuteNonQuery();
                            }
                        }
                    }
                }
                else
                {
                    returnObject = cmd.ExecuteScalar();
                }

                return(returnObject);
            }
            catch (DbException e) {
                OSTrace.Error("Error executing ExecuteScalar (" + e.Message + ") with statement:" + Environment.NewLine + cmd.CommandText);
                throw;
            }
        }
コード例 #11
0
 private void HandleRequestTracerException(Exception e)
 {
     OSTrace.Error("", e);
 }