Пример #1
0
        /// <summary>
        /// Cria o comparador para ordena os resultado da consulta.
        /// </summary>
        /// <param name="query">Informações da consulta.</param>
        /// <param name="descriptor">Descritor com assinatura dos dados do resultado.</param>
        /// <returns></returns>
        private static IComparer <Record> CreateSortComparer(QueryInfo query, Record.RecordDescriptor descriptor)
        {
            IComparer <Record> comparer = null;
            var fields = new List <Colosoft.Query.RecordSortComparer.Field>();

            foreach (var sortPart in query.Sort)
            {
                var sortPartName = sortPart.Name;
                if (string.IsNullOrEmpty(sortPartName))
                {
                    throw new InvalidOperationException(ResourceMessageFormatter.Create(() => Properties.Resources.NotSupportedException_InvalidSortEntryFormat).Format());
                }
                for (var i = 0; i < descriptor.Count; i++)
                {
                    if (descriptor[i].Name == sortPartName)
                    {
                        fields.Add(new Colosoft.Query.RecordSortComparer.Field(i, sortPart.Reverse));
                        break;
                    }
                }
            }
            if (fields.Count > 0)
            {
                comparer = new Colosoft.Query.RecordSortComparer(fields);
            }
            return(comparer);
        }
Пример #2
0
        /// <summary>
        /// Verifica se os dados são válidos.
        /// </summary>
        public AssemblyRepositoryValidateResult Validate()
        {
            var result = new List <AssemblyRepositoryValidateResult.Entry>();

            foreach (var instance in _maintenanceInstances)
            {
                try
                {
                    var executeResult = instance.Execute();
                    if (executeResult.HasError)
                    {
                        result.Add(new AssemblyRepositoryValidateResult.Entry(ResourceMessageFormatter.Create(() => Properties.Resources.AssemblyRepository_ValidateMaintenanceError, instance.Name), AssemblyRepositoryValidateResult.EntryType.Error));
                        foreach (var i in executeResult.Where(f => f.Type == AssemblyRepositoryMaintenanceExecuteResult.EntryType.Error))
                        {
                            result.Add(new AssemblyRepositoryValidateResult.Entry(i.Message, AssemblyRepositoryValidateResult.EntryType.Error, i.Error));
                        }
                    }
                }
                catch (Exception ex)
                {
                    result.Add(new AssemblyRepositoryValidateResult.Entry(ResourceMessageFormatter.Create(() => Properties.Resources.AssemblyRepository_MaintenanceError, instance.Name, Diagnostics.ExceptionFormatter.FormatException(ex, true)), AssemblyRepositoryValidateResult.EntryType.Error, ex));
                }
            }
            return(new AssemblyRepositoryValidateResult(result));
        }
Пример #3
0
        /// <summary>
        /// Remove o item do filho associado com a entidade do link.
        /// </summary>
        /// <param name="linkEntity">Instancia da entidade do link</param>
        private void RemoveChildItem(TEntity linkEntity)
        {
            if (!(linkEntity is IEntityOfModel))
            {
                throw new ArgumentException(ResourceMessageFormatter.Create(() => Properties.Resources.EntityLinkList_ExpectedEntityOfModel).Format(), "linkEntity");
            }
            var     linkDataModel = ((IEntityOfModel)linkEntity).DataModel;
            IEntity childItem     = null;

            foreach (IEntityOfModel i in _child)
            {
                if (_linkInfo.Equals(linkDataModel, i.DataModel))
                {
                    childItem = i;
                    break;
                }
            }
            if (childItem != null)
            {
                var childList = (System.Collections.IList)_child;
                if (!(_child is Colosoft.Threading.IReentrancyController) || !((Colosoft.Threading.IReentrancyController)_child).IsReentrancy)
                {
                    childList.Remove(childItem);
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Trata o erro da resposta.
        /// </summary>
        /// <param name="response"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private static Exception HandleErrorResponse(WebResponse response, WebExceptionStatus status)
        {
            Exception exception    = null;
            var       httpResponse = (HttpWebResponse)response;

            try
            {
                if (httpResponse != null && httpResponse.StatusCode == HttpStatusCode.Unauthorized)
                {
                    return(new Exception("Unauthorized : " + httpResponse.Server));
                }
                string message = ResourceMessageFormatter.Create(() => Properties.Resources.InvalidServerResponse, httpResponse != null ? FormatHttpStatus(httpResponse) : status.ToString()).Format();
                string name    = null;
                for (int i = 0; i < response.Headers.Count; i++)
                {
                    if (response.Headers.Keys[i] == "X-Exception")
                    {
                        name = response.Headers.GetValues(i)[0];
                        using (var reader = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
                        {
                            message = reader.ReadToEnd();
                            break;
                        }
                    }
                }
                exception = new Exception(message);
            }
            catch (Exception exception2)
            {
                return(exception2);
            }
            return(exception);
        }
Пример #5
0
        /// <summary>
        /// Recupera o endereço pelo nome informado.
        /// </summary>
        /// <param name="addressName"></param>
        /// <param name="servicesContext">Contexto de serviços.</param>
        /// <returns></returns>
        private ServiceAddress Get(string addressName, string servicesContext)
        {
            ServicesConfigurationEntry result = null;
            var key = new ServiceAddressKey(addressName, servicesContext);

            lock (_serviceAddress)
                if (_serviceAddress.TryGetValue(key, out result))
                {
                    return(result.Address);
                }
            var addressProvider = GetServiceAddressProvider();

            if (addressName == addressProvider.ProviderAddressName)
            {
                throw new InvalidOperationException(ResourceMessageFormatter.Create(() => Properties.Resources.ImpossibleRecoverAddressProviderAddress, addressName).Format());
            }
            if (addressProvider != null)
            {
                var addresses = addressProvider.GetServiceAddresses(addressName, servicesContext);
                if (addresses != null && addresses.Length > 0)
                {
                    Add(addresses[new Random().Next(0, addresses.Length - 1)], servicesContext);
                }
                else
                {
                    throw new ServiceConfigurationException(string.Format(Properties.Resources.ServiceConfiguration_AddressNotFoundInAddressProvider, addressName, servicesContext));
                }
                lock (_serviceAddress)
                    if (_serviceAddress.TryGetValue(key, out result))
                    {
                        return(result.Address);
                    }
            }
            throw new ServiceConfigurationException(string.Format(Properties.Resources.ServiceConfiguration_AddressNotFound, addressName));
        }
Пример #6
0
 /// <summary>
 /// Executa o predicado.
 /// </summary>
 /// <param name="queryContext">Contexto da consulta.</param>
 /// <param name="nextPredicate"></param>
 internal override void Execute(QueryContext queryContext, Predicate nextPredicate)
 {
     if (_typeName == "*")
     {
         throw new ParserException(ResourceMessageFormatter.Create(() => Properties.Resources.ParserException_StartIsNotSupported).Format());
     }
     if (queryContext.IndexManager == null)
     {
         throw new ParserException(ResourceMessageFormatter.Create(() => Properties.Resources.ParserException_IndexIsNotDefined, _typeName).Format());
     }
     queryContext.TypeName = _typeName;
     if (queryContext.Index == null)
     {
         if ((queryContext.AttributeValues == null || queryContext.AttributeValues.Count != 1))
         {
             throw new ParserException(ResourceMessageFormatter.Create(() => Properties.Resources.ParserException_IndexIsNotDefined, _typeName).Format());
         }
         queryContext.Index = new AttributeIndex(null, queryContext.Cache.Context.CacheRoot.Name);
     }
     else if (nextPredicate == null && queryContext.PopulateTree)
     {
         queryContext.Tree.Populate(queryContext.Index.GetEnumerator(_typeName, false));
         queryContext.Tree.Populate(queryContext.Index.GetEnumerator(_typeName, true));
     }
     else
     {
         nextPredicate.Execute(queryContext, null);
     }
 }
Пример #7
0
        /// <summary>
        /// Inicializa a instancia.
        /// </summary>
        /// <param name="instanceId"></param>
        /// <param name="threadSafe"></param>
        protected void Initialize(Guid instanceId, bool threadSafe)
        {
            _isThreadSafe = threadSafe;
            bool flag = false;

            try
            {
                _disposedEvent = new ManualResetEvent(false);
                _startedEvent  = new ManualResetEvent(false);
                if (_isThreadSafe)
                {
                    Startup(true);
                }
                else
                {
                    _hostManagementThread = new Thread(HostManagementThread);
                    _hostManagementThread.Start();
                    _startedEvent.WaitOne();
                }
                if (_hostManagementException != null)
                {
                    throw new ApplicationException(ResourceMessageFormatter.Create(() => Properties.Resources.UnhandledExceptionError).Format(), _hostManagementException);
                }
                flag = true;
            }
            finally
            {
                if (!flag)
                {
                    this.Dispose();
                }
            }
        }
Пример #8
0
 /// <summary>
 /// Aplica a validação.
 /// </summary>
 /// <param name="currentTarget"></param>
 /// <param name="propertyName"></param>
 /// <param name="propertyLabel"></param>
 /// <param name="objectToValidate"></param>
 /// <param name="validationResults"></param>
 /// <param name="messageProvider"></param>
 public void DoValidate(object currentTarget, string propertyName, IPropertyLabel propertyLabel, object objectToValidate, ValidationResult validationResults, IValidationMessageProvider messageProvider)
 {
     if (objectToValidate == null)
     {
         validationResults.Invalid(ValidationResultType.Error, ResourceMessageFormatter.Create(() => Properties.Resources.Validators_NotNullValidator_MessageTemplate, ((propertyLabel != null) && (propertyLabel.Title != null) && (!String.IsNullOrWhiteSpace(propertyLabel.Title.Format()))) ? propertyLabel.Title : propertyName.GetFormatter(), ValidatorsHelper.GetCurrentTargetName(currentTarget)));
     }
 }
Пример #9
0
        /// <summary>
        /// Registra um tipo compacto.
        /// </summary>
        /// <param name="type"></param>
        public static void RegisterCompactType(Type type)
        {
            type.Require("type").NotNull();
            if (TypeSurrogateSelector.GetSurrogateForTypeStrict(type, null) != null)
            {
                throw new ArgumentException(ResourceMessageFormatter.Create(() => Properties.Resources.Argument_TypeAlreadyRegistered2, type.FullName).Format());
            }
            ISerializationSurrogate surrogate = null;

            if (typeof(IDictionary).IsAssignableFrom(type))
            {
                surrogate = new IDictionarySerializationSurrogate(type);
            }
            else if (type.IsArray)
            {
                surrogate = new ArraySerializationSurrogate(type);
            }
            else if (typeof(IList).IsAssignableFrom(type))
            {
                surrogate = new IListSerializationSurrogate(type);
            }
            else if (typeof(ICompactSerializable).IsAssignableFrom(type))
            {
                surrogate = new ICompactSerializableSerializationSurrogate(type);
            }
            else if (typeof(Enum).IsAssignableFrom(type))
            {
                surrogate = new EnumSerializationSurrogate(type);
            }
            if (surrogate == null)
            {
                throw new ArgumentException(ResourceMessageFormatter.Create(() => Properties.Resources.Argument_NoAppropriateSurrogateFound, type.FullName).Format());
            }
            TypeSurrogateSelector.RegisterTypeSurrogate(surrogate);
        }
Пример #10
0
        /// <summary>
        /// Recupera os dados do perfil.
        /// </summary>
        /// <param name="info">Informações usadas para recuperar o perfil.</param>
        /// <returns></returns>
        public IProfile GetProfile(ProfileInfo info)
        {
            if (info == null)
            {
                return(null);
            }
            ProfileProviderServiceReference.Profile result = null;

            try
            {
                result = ProfileProviderClient.GetProfile(Convert(info));
            }
            catch (System.ServiceModel.EndpointNotFoundException ex)
            {
                throw new ProfileProviderException(
                          ResourceMessageFormatter.Create(() => Properties.Resources.RemoteProfileProvider_GetProfileCommunicationError).Format(), ex);
            }
            catch (System.ServiceModel.FaultException <System.ServiceModel.ExceptionDetail> ex)
            {
                throw new ProfileProviderException(
                          ResourceMessageFormatter.Create(() => Properties.Resources.RemoteProfileProvider_GetProfileFaultException, ex.Message).Format(), ex);
            }

            return(result == null ? null : new Wrappers.ProfileWrapper(result, this));
        }
Пример #11
0
        /// <summary>
        /// Registra o tipo da entidade que será geranciada.
        /// </summary>
        /// <param name="entityType"></param>
        public void Register(Type entityType)
        {
            entityType.Require("entityType").NotNull();
            IEnumerable <EntityEventInfo> infos = null;
            var typeName = new Reflection.TypeName(entityType.AssemblyQualifiedName);

            if (IsRegistered(typeName))
            {
                return;
            }
            try
            {
                infos = GetEventInfo(typeName);
            }
            catch (Exception ex)
            {
                throw new RegisterEntityEventException(ResourceMessageFormatter.Create(() => Properties.Resources.EntityEventManager_GetEntityEventInfosError, typeName.FullName), ex);
            }
            Registered(typeName);
            if (infos != null)
            {
                foreach (var i in infos)
                {
                    Register(typeName, i);
                }
            }
        }
Пример #12
0
 /// <summary>
 /// Verifica se existem itens com o nome publicados.
 /// </summary>
 /// <param name="value">Instancia.</param>
 /// <param name="namedTags">Dicionário com as tags nomeadas.</param>
 /// <param name="typeMap"></param>
 private static void CheckDuplicateIndexName(object value, NamedTagsDictionary namedTags, TypeInfoMap typeMap)
 {
     if (namedTags != null && value != null && typeMap != null)
     {
         int handleId = 0;
         if (value is CacheItemRecord)
         {
             handleId = typeMap.GetHandleId(((CacheItemRecord)value).TypeName);
         }
         else
         {
             handleId = typeMap.GetHandleId(value.GetType());
         }
         if (handleId != -1)
         {
             foreach (string str2 in typeMap.GetAttribList(handleId))
             {
                 if (namedTags.Contains(str2))
                 {
                     throw new Exception(ResourceMessageFormatter.Create(() => Properties.Resources.Exception_DuplicateIndexName).Format());
                 }
             }
         }
     }
 }
Пример #13
0
        /// <summary>
        /// Cria um creator a partir do tipo informado.
        /// </summary>
        /// <param name="type"></param>
        public QueryResultObjectCreator(Type type)
        {
            type.Require("type").NotNull();
            var emptyConstructor = type.GetConstructor(new Type[0]);

            if (emptyConstructor == null)
            {
                _creator = new Func <object>(() => {
                    throw new QueryException(ResourceMessageFormatter.Create(() => Properties.Resources.Exception_NotFoundEmptyConstructorForType, type.FullName).Format());
                });
            }
            else
            {
                _creator = new Func <object>(() => {
                    try
                    {
                        return(Activator.CreateInstance(type));
                    }
                    catch (System.Reflection.TargetInvocationException ex)
                    {
                        throw ex.InnerException;
                    }
                });
            }
        }
        /// <summary>
        /// Valida os dados do usuário.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public override void Validate(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException();
            }
            IValidateUserResult result = null;

            try
            {
                result = Membership.ValidateUser(userName, password);
            }
            catch (Exception ex)
            {
                var ex2 = ex;
                if (ex2 is System.Reflection.TargetInvocationException)
                {
                    ex2 = ex2.InnerException;
                }
                Log.Write(ResourceMessageFormatter.Create(() => Colosoft.Properties.Resources.Exception_FailOnValidateUser), ex2, Logging.Priority.Medium);
                throw ex2;
            }
            if (result.Status != AuthenticationStatus.Success)
            {
                throw new System.ServiceModel.FaultException("Unknown Username or Incorrect Password");
            }
        }
Пример #15
0
 /// <summary>
 /// Construtor padrão.
 /// </summary>
 public AuthenticationService()
 {
     _configurationSection = System.Configuration.ConfigurationManager.GetSection("colosoft.security.remote.server") as RemoteServerConfigurationSection;
     if (_configurationSection == null)
     {
         throw new InvalidOperationException(ResourceMessageFormatter.Create(() => Colosoft.Security.Remote.Server.Properties.Resources.InvalidOperationException_ServerConfigurationNotFound).Format());
     }
 }
Пример #16
0
 /// <summary>
 /// Formata o texto de um <see cref="GroupByEntry"/>
 /// </summary>
 /// <param name="groupby">Coluna de group by a ser formatada</param>
 /// <returns>Retorna o próprio objeto</returns>
 private DefaultSqlQueryParser Format(GroupByEntry groupby)
 {
     if (groupby.Term == null)
     {
         throw new InvalidOperationException(ResourceMessageFormatter.Create(() => Properties.Resources.InvalidOperationException_FoundEmptyGroupByEntry).Format());
     }
     return(Format(groupby.Term));
 }
Пример #17
0
 /// <summary>
 /// Adiciona um item para a coleção.
 /// </summary>
 /// <param name="item"></param>
 public void Add(T item)
 {
     if (_filter != null && _filter(item) == false)
     {
         throw new InvalidOperationException(ResourceMessageFormatter.Create(() => Properties.Resources.InvalidOperation_ItemIsNotMatchingWithFilter).Format());
     }
     _collection.Add(item);
 }
Пример #18
0
 /// <summary>
 /// Aplica o predicado.
 /// </summary>
 /// <param name="o"></param>
 /// <returns></returns>
 public override bool ApplyPredicate(object o)
 {
     if (_typeName == "*")
     {
         throw new ParserException(ResourceMessageFormatter.Create(() => Properties.Resources.ParserException_StartIsNotSupported).Format());
     }
     return(o.GetType().Name == _typeName);
 }
Пример #19
0
        /// <summary>
        /// Executa uma procedure no banco de dados.
        /// </summary>
        /// <param name="action">Informação da ação de persistência.</param>
        /// <param name="transaction">Transação de persistência.</param>
        /// <returns>Retorna resultado da ação de persistência.</returns>
        protected virtual PersistenceActionResult ExecuteProcedureCommand(PersistenceAction action, IPersistenceTransactionExecuter transaction)
        {
            var trans = (PersistenceTransactionExecuter)transaction;
            var outputParametersIndexes = new List <int>();
            var procedure = CreateProcedure(action);

            if (action.Parameters != null)
            {
                for (int i = 0; i < action.Parameters.Count; i++)
                {
                    var paramDirection = (System.Data.ParameterDirection)((int)action.Parameters[i].Direction);
                    procedure.AddParameter(new GDAParameter(action.Parameters[i].Name, action.Parameters[i].Value, paramDirection)
                    {
                        Size = action.Parameters[i].Size
                    });
                    if (action.Parameters[i].Direction != Colosoft.Query.ParameterDirection.Input)
                    {
                        outputParametersIndexes.Add(i);
                    }
                }
            }
            var    da     = new DataAccess(trans.Transaction.ProviderConfiguration);
            object result = null;

            try
            {
                result = da.ExecuteScalar(trans.Transaction, procedure);
            }
            catch (GDAException ex)
            {
                Exception ex2 = ex;
                if (ex.InnerException is System.Data.Common.DbException || ex.InnerException is DataException)
                {
                    ex2 = ex.InnerException;
                }
                ex2 = new DataException(ResourceMessageFormatter.Create(() => Properties.Resources.Exception_ExecuteDatabaseCommand, ex2.Message).Format(), ex2);
                action.NotifyError(ex2);
                return(new PersistenceActionResult {
                    Success = false,
                    AffectedRows = -1,
                    FailureMessage = ex2.Message
                });
            }
            foreach (int index in outputParametersIndexes)
            {
                action.Parameters[index].Value = procedure[index];
            }
            action.NotifyExecution();
            var presult = new PersistenceActionResult()
            {
                ActionId   = action.ActionId,
                Parameters = action.Parameters.ToArray(),
                Result     = result,
                Success    = true
            };

            return(presult);
        }
 /// <summary>
 /// Verifica se a instancia está ocupada, e caso
 /// esteja dispara uma exception.
 /// </summary>
 private void CheckIsBusy()
 {
     if (IsBusy)
     {
         throw new DetailsInvalidOperationException(
                   ResourceMessageFormatter.Create(
                       () => Properties.Resources.RemoteDataEntryDownloader_DownloaderIsBusy));
     }
 }
Пример #21
0
        /// <summary>
        /// Registra o tipo compacto.
        /// </summary>
        /// <param name="type">Tipo que será registrado.</param>
        /// <param name="typeHandle">Número do manipulador do tipo.</param>
        public static void RegisterCompactType(Type type, short typeHandle)
        {
            type.Require("type").NotNull();
            ISerializationSurrogate surrogateForTypeStrict = null;

            surrogateForTypeStrict = TypeSurrogateSelector.GetSurrogateForTypeStrict(type, null);
            if (surrogateForTypeStrict != null)
            {
                if (surrogateForTypeStrict.TypeHandle != typeHandle)
                {
                    throw new ArgumentException(ResourceMessageFormatter.Create(() => Properties.Resources.Argument_TypeAlreadyRegisteredWithDifferentHandle, type.FullName).Format());
                }
            }
            else
            {
                if (typeof(IDictionary).IsAssignableFrom(type))
                {
                    if (type.IsGenericType)
                    {
                        surrogateForTypeStrict = new GenericIDictionarySerializationSurrogate(typeof(IDictionary <, >));
                    }
                    else
                    {
                        surrogateForTypeStrict = new IDictionarySerializationSurrogate(type);
                    }
                }
                else if (type.IsArray)
                {
                    surrogateForTypeStrict = new ArraySerializationSurrogate(type);
                }
                else if (typeof(IList).IsAssignableFrom(type))
                {
                    if (type.IsGenericType)
                    {
                        surrogateForTypeStrict = new GenericIListSerializationSurrogate(typeof(IList <>));
                    }
                    else
                    {
                        surrogateForTypeStrict = new IListSerializationSurrogate(type);
                    }
                }
                else if (typeof(ICompactSerializable).IsAssignableFrom(type))
                {
                    surrogateForTypeStrict = new ICompactSerializableSerializationSurrogate(type);
                }
                else if (typeof(Enum).IsAssignableFrom(type))
                {
                    surrogateForTypeStrict = new EnumSerializationSurrogate(type);
                }
                if (surrogateForTypeStrict == null)
                {
                    throw new ArgumentException(ResourceMessageFormatter.Create(() => Properties.Resources.Argument_NoAppropriateSurrogateFoundForType, type.FullName).Format());
                }
                TypeSurrogateSelector.RegisterTypeSurrogate(surrogateForTypeStrict, typeHandle);
            }
        }
Пример #22
0
        /// <summary>
        /// Pré-configura os exports do tipo informado.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="contractName"></param>
        public void PreConfigure(Type type, string contractName)
        {
            PreConfigureResult result = null;

            PreConfigure(type, contractName, out result);
            if (!result.Success)
            {
                throw new PreConfigureException(ResourceMessageFormatter.Create(() => Properties.Resources.ExportConfigurator_NotFoundExportForType, result.Types[0].FullName));
            }
        }
        /// <summary>
        /// Recupera as propriedades que compõem as chave do tipo da instancia informado.
        /// </summary>
        /// <param name="instanceType">Tipo da instancia.</param>
        /// <returns></returns>
        protected override IEnumerable <string> GetKeyProperties(Type instanceType)
        {
            var typeMetadata = TypeSchema.GetTypeMetadata(instanceType.FullName);

            if (typeMetadata == null)
            {
                throw new Exception(ResourceMessageFormatter.Create(() => Properties.Resources.Exception_TypeMetadataNotFound, instanceType.FullName).Format());
            }
            return(typeMetadata.GetKeyProperties().Select(f => f.Name));
        }
Пример #24
0
 /// <summary>
 /// Move para o próximo nome de tipo que será processado.
 /// </summary>
 /// <returns></returns>
 private bool MoveNextTypeMetadata()
 {
     while (_typeMetadatasEnumerator != null && _typeMetadatasEnumerator.MoveNext())
     {
         var typeMetadata = _typeMetadatasEnumerator.Current;
         _loader.Observer.OnStageChanged(new CacheLoaderStage("LoadingType", ResourceMessageFormatter.Create(() => Properties.Resources.CacheLoader_LoadingTypeName, typeMetadata.FullName)));
         _loader.Observer.OnCurrentProgressChanged(new System.ComponentModel.ProgressChangedEventArgs((_position++ *100 / _typeMetadatasCount), null));
         if (_loader.Observer is IDataCacheLoaderObserver)
         {
             ((IDataCacheLoaderObserver)_loader.Observer).OnBeginLoadTypeMetadata(typeMetadata);
         }
         var typeName = new Colosoft.Reflection.TypeName(!string.IsNullOrEmpty(typeMetadata.Assembly) ? string.Format("{0}, {1}", typeMetadata.FullName, typeMetadata.Assembly) : typeMetadata.FullName);
         Query.IQueryResult result = null;
         try
         {
             var columns = new List <Query.ProjectionEntry>(typeMetadata.Select(f => new Query.ProjectionEntry(f.Name, null)));
             if (typeMetadata.IsVersioned && !columns.Exists(f => {
                 var column = f.GetColumnInfo();
                 return(column != null && StringComparer.InvariantCultureIgnoreCase.Equals(column.Name, "RowVersion"));
             }))
             {
                 columns.Add(new ProjectionEntry("RowVersion", null));
             }
             result            = _loader.SourceContext.CreateQuery().From(new Query.EntityInfo(typeMetadata.FullName)).Select(new Query.Projection(columns)).NoUseCache().Execute();
             _recordEnumerator = result.GetEnumerator();
         }
         catch (Exception ex)
         {
             var args = new CacheLoaderErrorEventArgs(ResourceMessageFormatter.Create(() => Properties.Resources.DataCacheLoader_CreateQueryError, typeMetadata.FullName), ex);
             _loader.OnLoadError(typeName, args);
             if (_loader.Observer is IDataCacheLoaderObserver)
             {
                 ((IDataCacheLoaderObserver)_loader.Observer).OnEndLoadTypeMetadata(typeMetadata, ex);
             }
             continue;
         }
         _currentTypeName  = typeName;
         _currentGenerator = _loader.RecordKeyFactory.CreateGenerator(_currentTypeName);
         return(true);
     }
     _currentTypeName  = null;
     _currentGenerator = null;
     if (_recordEnumerator != null)
     {
         try
         {
             _recordEnumerator.Dispose();
         }
         catch
         {
         }
     }
     _recordEnumerator = null;
     return(false);
 }
Пример #25
0
        /// <summary>
        /// Valida os dados do token.
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public IValidateUserResult ValidateToken(string token)
        {
            var servicesContext = Colosoft.Net.ServicesConfiguration.Current != null ?
                                  Colosoft.Net.ServicesConfiguration.Current.ServicesContext : null;

            AuthenticationHost.ValidateUserResult result = null;

            try
            {
                result = AuthenticationClient.ValidateToken(token, servicesContext);
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                result = new AuthenticationHost.ValidateUserResult
                {
                    Status  = AuthenticationHost.AuthenticationStatus.ErrorInCommunication,
                    Message = ResourceMessageFormatter.Create(() => Properties.Resources.RemoteUserProvider_ValidateTokenErrorEndpointNotFound).Format()
                };
            }
            catch (System.ServiceModel.FaultException <DetailsException> )
            {
                result = new AuthenticationHost.ValidateUserResult
                {
                    Status  = AuthenticationHost.AuthenticationStatus.UnknownError,
                    Message = ResourceMessageFormatter.Create(() => Properties.Resources.RemoteUserProvider_ValidateTokenFaultException).Format()
                };
            }
            catch (System.ServiceModel.CommunicationException)
            {
                result = new AuthenticationHost.ValidateUserResult
                {
                    Status  = AuthenticationHost.AuthenticationStatus.ErrorInCommunication,
                    Message = ResourceMessageFormatter.Create(() => Properties.Resources.RemoteUserProvider_ValidateUserErrorInCommunication).Format()
                };
            }
            catch (TimeoutException)
            {
                result = new AuthenticationHost.ValidateUserResult
                {
                    Status  = AuthenticationHost.AuthenticationStatus.ErrorInCommunication,
                    Message = ResourceMessageFormatter.Create(() => Properties.Resources.RemoteUserProvider_ValidateUserErrorInCommunicationTimeout).Format()
                };
            }
            catch (Exception ex)
            {
                result = new AuthenticationHost.ValidateUserResult
                {
                    Status  = AuthenticationHost.AuthenticationStatus.UnknownError,
                    Message = ResourceMessageFormatter.Create(() =>
                                                              Properties.Resources.RemoteUserProvider_ValidateTokenUnknownError,
                                                              Colosoft.Diagnostics.ExceptionFormatter.FormatException(ex, true)).Format()
                };
            }
            return(Convert(result));
        }
Пример #26
0
        /// <summary>
        /// Recupera a descrição dos modos de pesquias.
        /// </summary>
        /// <returns></returns>
        public static Dictionary <ProfileSearchMode, IMessageFormattable> GetDescriptions()
        {
            var result = new Dictionary <ProfileSearchMode, IMessageFormattable>();

            result.Add(ProfileSearchMode.All, ResourceMessageFormatter.Create(() => Properties.Resources.ProfileSearchMode_All));
            result.Add(ProfileSearchMode.Source, ResourceMessageFormatter.Create(() => Properties.Resources.ProfileSearchMode_Source));
            result.Add(ProfileSearchMode.Self, ResourceMessageFormatter.Create(() => Properties.Resources.ProfileSearchMode_Self));
            result.Add(ProfileSearchMode.Seller, ResourceMessageFormatter.Create(() => Properties.Resources.ProfileSearchMode_Seller));
            result.Add(ProfileSearchMode.Intermediate, ResourceMessageFormatter.Create(() => Properties.Resources.ProfileSearchMode_Intermediate));
            return(result);
        }
Пример #27
0
 /// <summary>
 /// Recupera a propriedade pelo código.
 /// </summary>
 /// <param name="propertyCode">Código da propriedade</param>
 /// <returns>Retorna os metadados da propriedade</returns>
 IPropertyMetadata ITypeMetadata.GetProperty(int propertyCode)
 {
     try
     {
         return(_propertiesDictionaryKeyPropertyCode[propertyCode]);
     }
     catch (KeyNotFoundException ex)
     {
         throw new Exception(ResourceMessageFormatter.Create(() => Server.Properties.Resources.PropertyCodeNotMapped, propertyCode.ToString()).Format(), ex);
     }
 }
Пример #28
0
 /// <summary>
 /// Recupera do alvo.
 /// </summary>
 /// <param name="currentTarget"></param>
 /// <returns></returns>
 public static IMessageFormattable GetCurrentTargetName(object currentTarget)
 {
     if (currentTarget is INamedType)
     {
         return(((INamedType)currentTarget).InstanceDescriptor);
     }
     else if (currentTarget != null)
     {
         return(currentTarget.GetType().Name.GetFormatter());
     }
     return(ResourceMessageFormatter.Create(() => Properties.Resources.ValidatorsHelper_Unamed));
 }
Пример #29
0
 /// <summary>
 /// Encontra uma entidade interando pelo vetor de entidades do QueryInfo baseano no alias e adiciona ela no dicionário de Entidades interno
 /// </summary>
 /// <param name="alias">alias da entidade</param>
 /// <returns>Entidade a ser retornada ou nulo caso não seja encontratada</returns>
 private EntityInfo FindAndAddEntity(string alias)
 {
     foreach (var entity in Entities)
     {
         if (alias == entity.Alias)
         {
             EntityAliasDictionary.Add(alias, entity);
             return(entity);
         }
     }
     throw new InvalidOperationException(ResourceMessageFormatter.Create(() => Properties.Resources.InvalidOperationException_NotFoundEntityFromAlias, alias).Format());
 }
Пример #30
0
        /// <summary>
        /// Executa a ação para apagar os ados do registro no cache.
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        private PersistenceActionResult ExecuteDeleteAction(PersistenceAction action)
        {
            var typeMetadata = _typeSchema.GetTypeMetadata(action.EntityFullName);

            if (typeMetadata == null)
            {
                return new PersistenceActionResult {
                           Success        = false,
                           FailureMessage = ResourceMessageFormatter.Create(() => Properties.Resources.CachePersistenceExecuter_TypeMetadataNotFound, action.EntityFullName).Format(),
                }
            }
            ;
            var query = GetActionQuery(action, typeMetadata).CreateQueryInfo();

            Queries.QueryResultSet queryResult = null;
            try
            {
                queryResult = ((CacheDataSource)_sourceContext.DataSource).ExecuteInCache(query);
            }
            catch (Exception ex)
            {
                return(new PersistenceActionResult {
                    Success = false,
                    FailureMessage = ResourceMessageFormatter.Create(() => Properties.Resources.CachePersistenceExecuter_ExecuteQueryInCacheError, Colosoft.Diagnostics.ExceptionFormatter.FormatException(ex, true)).Format()
                });
            }
            var typeName     = new Colosoft.Reflection.TypeName(action.EntityFullName);
            var keyGenerator = _keyFactory.Value.CreateGenerator(typeName);
            var recordKeys   = new List <RecordKey>();

            using (var recordEnumerator = new Colosoft.Caching.Queries.QueryResultSetRecordEnumerator(_typeSchema, Cache, queryResult, query))
            {
                while (recordEnumerator.MoveNext())
                {
                    recordKeys.Add(RecordKeyFactory.Instance.Create(typeName, recordEnumerator.Current));
                    try
                    {
                        Cache.Remove(recordEnumerator.CurrentKey, new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation));
                    }
                    catch (Exception ex)
                    {
                        return(new PersistenceActionResult {
                            Success = false,
                            FailureMessage = ex.Message
                        });
                    }
                }
            }
            return(new PersistenceActionResult {
                Success = true,
                Result = new DeleteActionResult(recordKeys)
            });
        }