コード例 #1
0
ファイル: AgroSearch.cs プロジェクト: trifenix/agro-fenix
        /// <summary>
        /// Toma un objeto de base de datos de persistencia, lo convierte a un entitySearch y lo guarda en azure search.
        /// </summary>
        /// <typeparam name="T">tipo de dato tipo base de datos.</typeparam>
        /// <param name="document">entidad o documento de base de datos de persistencia</param>
        public void AddDocument <T>(T document) where T : DocumentDb
        {
            // obtiene un entitySearch desde una entidad de base de datos de persistencia.
            var entitySearch = Mdm.GetEntitySearch(implements, document, hashOper).Cast <IEntitySearch <GeoPointType> >().ToList();

            // añade a registro
            AddToQueried(nameof(AgroSearch <GeoPointType> .AddDocument), JsonConvert.SerializeObject(entitySearch));


            // añade a base de datos.
            baseMainSearch.AddElements(entitySearch);
        }
コード例 #2
0
            public void Test1()
            {
                // assign
                var assembly = typeof(BarrackTest).Assembly;


                // action
                var globalFilters = Mdm.GetMdm(assembly, "0.0.1", new VersionStructure());



                Assert.True(globalFilters != null);
            }
コード例 #3
0
        /// <summary>
        /// Valida recursivamente una instancia de un objeto, de acuerdo al método para validar,
        /// si es recursivo, busca propiedades de tipo clase y realiza la misma validación.
        /// </summary>
        /// <typeparam name="A">Tipo de atributo a buscar</typeparam>
        /// <param name="element">instancia de objeto donde se buscaran las propiedades que tengan el atributo</param>
        /// <param name="extraValidation">Función que ejecutará la validación</param>
        /// <param name="recursive">determina si la busqueda de atributos es recursiva, si fuese así buscará todas las clases que tiene un objeto y buscará dentro de este el atributo en cada propiedad</param>
        /// <returns>resultado que integra si es valido y los mensajes de error</returns>
        private async Task <ResultValidate> ValidaProperties <A>(object element, Func <object, string, string, Attribute[], Task <ResultValidate> > extraValidation, bool recursive) where A : Attribute
        {
            var  propsInfo = element.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(A), true));
            var  messages  = new List <string>();
            bool valida    = true;


            foreach (var item in propsInfo)
            {
                var validation = await extraValidation(item.GetValue(element), element.GetType().Name, item.Name, item.GetCustomAttributes <Attribute>().ToArray());

                if (!validation.Valid)
                {
                    valida = false;
                    messages.AddRange(validation.Messages);
                }
            }


            // propiedades no primitivas
            var nonPrimitiveProps = element.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(s => !EnumerationExtension.IsPrimitiveAndCollection(s.PropertyType) && !s.PropertyType.IsEnum);

            if (nonPrimitiveProps.Any() && recursive)
            {
                foreach (var propinfo in nonPrimitiveProps)
                {
                    if (propinfo.GetValue(element) != null)
                    {
                        var castedCollectionElement = Mdm.CreateDynamicList(propinfo.GetValue(element));
                        foreach (var item in castedCollectionElement)
                        {
                            var res = await ValidaProperties <A>(item, extraValidation, true);

                            if (!res.Valid)
                            {
                                messages.AddRange(res.Messages);
                                valida = false;
                            }
                        }
                    }
                }
            }



            return(new ResultValidate
            {
                Valid = valida,
                Messages = messages.ToArray()
            });
        }
コード例 #4
0
ファイル: AgroSearch.cs プロジェクト: trifenix/agro-fenix
        /// <summary>
        /// Obtiene un entitySearch desde un objeto de la base de datos
        /// el tipo de dato es por comodidad, si púede revisar internamente convierte cualquier objeto a entitySearch.
        /// Retorna una colección de EntitySearch, una de referencia y el resto local, ver atributos de la clase para más detalle.
        /// Vea EntityIndexAtribute, en el se asigna una referencia local o de referenci
        /// </summary>
        /// <see cref="EntityIndexAtribute"/>
        /// <typeparam name="T2">modelo del objeto que se convertirá a entity Search</typeparam>
        /// <param name="model">objeto a convertir</param>
        /// <returns>Colección de entity Search</returns>
        public IEntitySearch <GeoPointType>[] GetEntitySearch <T2>(T2 model) where T2 : DocumentDb
        {
            // crea un mapper para convertir un IEntitySearch a EntityBaseSearch<GeoPointType>
            var mapperLocal = mapper.CreateMapper();

            // convierte un elemento de persistencia a un entitySearch<GeoPointType>
            var document = Mdm.GetEntitySearch(
                implements,                                                            // asignación de tipos para cada interface de un entitySearch
                model                                                                  // documento a convertir
                , hashOper)
                           .Select(mapperLocal.Map <EntityBaseSearch <GeoPointType> >) // mapea el entitySearch de tipo GetEntitySearchImplementedType y lo convierte en EntityBaseSearch<GeoPointType>.
                           .ToArray();


            return(document);
        }
コード例 #5
0
        public string HashHeader(Type type)
        {
            // obtenemos los diccionarios desde las enumeraciones.
            var dictRel  = Mdm.Reflection.Enumerations.GetDictionaryFromEnum <EntityRelated>();
            var dictEnum = Mdm.Reflection.Enumerations.GetDictionaryFromEnum <EnumRelated>();
            var dictNum  = Mdm.Reflection.Enumerations.GetDictionaryFromEnum <NumRelated>();
            var dictStr  = Mdm.Reflection.Enumerations.GetDictionaryFromEnum <StringRelated>();
            var dictDbl  = Mdm.Reflection.Enumerations.GetDictionaryFromEnum <DoubleRelated>();
            var dictDt   = Mdm.Reflection.Enumerations.GetDictionaryFromEnum <DateRelated>();
            var dictGeo  = Mdm.Reflection.Enumerations.GetDictionaryFromEnum <GeoRelated>();
            var dictBool = Mdm.Reflection.Enumerations.GetDictionaryFromEnum <BoolRelated>();

            // obtiene los índices de la clase
            var indexes = Mdm.PreLoadedDictionary(type);

            if (indexes == null)
            {
                return(string.Empty);
            }



            // asigna colecciones de dictionary de los índices de propiedades de un objeto de una base de datos de persistencia.
            var dict = new JsonDictionaryHeaders
            {
                bl    = indexes.bl.ToDictionary(s => s, s => dictBool[s]),
                dbl   = indexes.dbl.ToDictionary(s => s, s => dictDbl[s]),
                dt    = indexes.dt.ToDictionary(s => s, s => dictDt[s]),
                enm   = indexes.enm.ToDictionary(s => s, s => dictEnum[s]),
                geo   = indexes.geo.ToDictionary(s => s, s => dictGeo[s]),
                index = indexes.index,
                num64 = indexes.num32.ToDictionary(s => s, s => dictNum[s]),
                num32 = indexes.num64.ToDictionary(s => s, s => dictNum[s]),
                rel   = indexes.rel.ToDictionary(s => s, s => dictRel[s]),
                str   = indexes.str.ToDictionary(s => s, s => dictStr[s]),
                sug   = indexes.sug.ToDictionary(s => s, s => dictStr[s])
            };



            // serializa para el hash
            var jsonDict = JsonConvert.SerializeObject(dict);


            // retorna hash
            return(Mdm.Reflection.Cripto.ComputeSha256Hash(jsonDict));
        }
コード例 #6
0
        /// <summary>
        /// Valida las propiedades que usen el atributo Reference, al detectar este atributo, validará si el elemento existe en la base de datos.
        /// </summary>
        /// <param name="elemento">elemento a validar</param>
        /// <param name="className">nombre de la clase a la que pertenece el elemento</param>
        /// <param name="propName">nombre de la propiedad</param>
        /// <param name="attributes">atributos de la propiedad</param>
        /// <returns>resultado que integra si es valido y los mensajes de error</returns>
        private async Task <ResultValidate> ValidaReference(object elemento, string className, string propName, Attribute[] attributes)
        {
            // si es nulo es válido, no válida nulos
            if (elemento == null)
            {
                return(new ResultValidate
                {
                    Valid = true
                });
            }

            // se crea colección desde el objeto
            var castedCollectionElement = Mdm.CreateDynamicList(elemento);

            // si es vacia, no valida, requerido valida.
            if (!castedCollectionElement.Any())
            {
                return(new ResultValidate
                {
                    Valid = true
                });
            }

            // si no es string, no es válido
            if (elemento.GetType() != typeof(string) && elemento.GetType() != typeof(List <string>) && elemento.GetType() != typeof(string[]))
            {
                return(new ResultValidate
                {
                    Valid = false,
                    Messages = new string[] {
                        $"La propiedad del input {className}.{propName} debe ser string, el atributo reference es solo para strings"
                    }
                });
            }

            //obtiene el atributo desde el listado de atributos.
            var attributeLink = (ReferenceAttribute)attributes.FirstOrDefault(s => s.GetType() == typeof(ReferenceAttribute));

            // método que permite saber si un elemento existe
            var mtd = typeof(IExistElement).GetMethod(nameof(IExistElement.ExistsById));

            // asigna el elemento generics desde el tipo que mantiene ReferenceAttribute
            var genericMtd = mtd.MakeGenericMethod(attributeLink.entityOfReference);



            bool valid = true;

            var lst = new List <string>();

            foreach (var item in castedCollectionElement)
            {
                var strElement = (string)item;

                // si es vacio no se valida
                if (string.IsNullOrWhiteSpace(strElement))
                {
                    break;
                }

                // ejecuta el método de busqueda por id, usando el valor de la propiedad.
                var task = (Task <bool>)genericMtd.Invoke(existElement, new[] { item.ToString() });

                // ejecuta asíncrono
                await task.ConfigureAwait(false);

                // obtiene la propiedad result
                var resultProperty = task.GetType().GetProperty("Result");

                // obtiene el valor booleano, true si existe.
                var localValid = (bool)resultProperty.GetValue(task);

                if (!localValid)
                {
                    valid = localValid;
                    lst.Add($"No existe {attributeLink.entityOfReference.Name} con id {item}");
                }
            }



            return(new ResultValidate {
                Valid = valid, Messages = !valid?lst.ToArray() : Array.Empty <string>()
            });
        }
コード例 #7
0
        /// <summary>
        /// Valida si un elemento es requerido, si es el caso verificará si existe un valor en esa propíedad
        /// </summary>
        /// <param name="element">objeto a validar</param>
        /// <param name="className">Nombre de la clase a la que pertenece el objeto</param>
        /// <param name="propName">la propiedad que pertenece el objeto</param>
        /// <param name="attributes">atributos encontrados en la propiedad</param>
        /// <returns>resultado que integra si es valido y los mensajes de error</returns>
        private async Task <ResultValidate> ValidaRequired(object element, string className, string propName, Attribute[] attributes)
        {
            // si es nulo no es válido
            if (element == null)
            {
                return(new ResultValidate
                {
                    Valid = false,
                    Messages = new string[] {
                        $"La propiedad del input {className}.{propName} es obligatorio"
                    }
                });
            }

            // se crea colección desde el objeto
            var castedCollectionElement = Mdm.CreateDynamicList(element);

            // si la lista es vacia, es inválido.
            if (!castedCollectionElement.Any())
            {
                return(new ResultValidate
                {
                    Valid = false,
                    Messages = new string[] {
                        $"La propiedad del input {className}.{propName} es obligatorio, tampoco puede ser una lista vacia"
                    }
                });
            }



            //obtiene el atributo desde el listado de atributos que sean requerido.
            var attributeLink = (RequiredAttribute)attributes.FirstOrDefault(s => s.GetType() == typeof(RequiredAttribute));

            var valid = true;
            var lst   = new List <string>();

            foreach (var item in castedCollectionElement)
            {
                // obtiene el tipo, según el tipo validará.
                var type = item.GetType();
                if (type == typeof(int) || type == typeof(int?) || type == typeof(double) || type == typeof(double?) || type == typeof(decimal) || type == typeof(decimal?))
                {
                    if (item == null)
                    {
                        lst.Add($"{className}.{propName} es obligatorio");
                        valid = false;
                    }
                    else
                    {
                        if (int.TryParse(item.ToString(), out var intResult))
                        {
                            if (intResult == 0)
                            {
                                lst.Add($"{className}.{propName} es obligatorio, ni puede cer cero");
                                valid = false;
                            }
                        }
                    }
                }

                if (type == typeof(bool?) || type == typeof(DateTime?))
                {
                    if (item == null)
                    {
                        lst.Add($"{className}.{propName} es obligatorio");
                        valid = false;
                    }
                }



                if (item == null || string.IsNullOrWhiteSpace(item.ToString()))
                {
                    lst.Add($"{className}.{propName} es obligatorio");
                    valid = false;
                }
            }

            return(new ResultValidate {
                Valid = valid, Messages = lst.ToArray()
            });
        }
コード例 #8
0
        /// <summary>
        /// Valida las propiedades que tengan el atributo Unique,
        /// el atributo indica una propiedad que debe existir un solo valor en toda la base de datos
        /// por tanto, buscará si ya existe el mismo valor en la misma propiedad para una colección de objetos.
        /// La colección de objetos esta determinado por el tipo de objeto del elemento.
        /// si se asigna un id, no considerará el elemento con ese id en la busqueda.
        /// </summary>
        /// <param name="elemento">elemento a validar, una propiedad de un objeto</param>
        /// <param name="className">nombre de la clase</param>
        /// <param name="propName">nombre de la propiedad del elemento</param>
        /// <param name="attributes">atributos encontrados</param>
        /// <param name="id">si se asigna un id, significa que buscará la propiedad y el valor, pero no para ese id.</param>
        /// <returns>resultado que integra si es valido y los mensajes de error</returns>
        private async Task <ResultValidate> ValidaUnique(object elemento, string className, string propName, Attribute[] attributes, string id = null)

        {
            // si el elemento es nulo, es válido.
            if (elemento == null)
            {
                return(new ResultValidate
                {
                    Valid = true
                });
            }

            // se crea colección desde el objeto, con el fin de validar colecciones
            var castedCollectionElement = Mdm.CreateDynamicList(elemento);

            // si la colección esta vacia no validará.
            if (!castedCollectionElement.Any())
            {
                return(new ResultValidate
                {
                    Valid = true
                });
            }


            // si no es string, no debería ser validado.
            if (elemento.GetType() != typeof(string) && elemento.GetType() != typeof(List <string>) && elemento.GetType() != typeof(string[]))
            {
                return(new ResultValidate
                {
                    Valid = false,
                    Messages = new string[] {
                        $"La propiedad del input {className}.{propName} debe ser string, el atributo unique es solo para strings"
                    }
                });
            }

            // nombre de la propiedad a buscar
            var propNameDb = string.Empty;

            // valor de la propiedad a buscar
            var value = string.Empty;


            // atributo que vincula un clase input con una clase de base de datos
            var attributeLink = (BaseIndexAttribute)attributes.FirstOrDefault(s => s.GetType().IsSubclassOf(typeof(BaseIndexAttribute)));

            // si es nulo, se buscará una propiedad con el mismo nombre en la clase de la base de datos (T).
            if (attributeLink == null)
            {
                // información de las propiedad de la clase de la base de datos, que tenga el mismo bombre de la clase input.
                var propDbInfo = typeof(T).GetProperty(propName);

                // si es nulo, significa que no existe vinculo entre la clase input y la clase de la base de datos.
                if (propDbInfo == null)
                {
                    return(new ResultValidate
                    {
                        Valid = false,
                        Messages = new string[] {
                            $"La propiedad del input {className}.{propName} que tiene que ser validada, no existe en el elemento de la base de datos"
                        }
                    });
                }
                // asigna un nombre para lo propiedad
                propNameDb = propDbInfo.Name;
            }

            // busca todas las propiedades que tengan un atributo fenix, que vincula input con base de datos.
            var baseIndexAttributes = typeof(T).GetProperties().Where(pinfo => Mdm.Reflection.Attributes.GetAttribute <BaseIndexAttribute>(pinfo) != null);


            // busca una propiedad de la clase de la base de datos, que tenga los mismos índices.
            var dbPropInfo = baseIndexAttributes.FirstOrDefault(s =>
            {
                var attribute = Mdm.Reflection.Attributes.GetAttribute <BaseIndexAttribute>(s);

                return(attribute.IsEntity == attributeLink.IsEntity && attribute.Index == attributeLink.Index && attribute.KindIndex == attributeLink.KindIndex);
            });

            // si no existe un vinculo, significa que no existe un vinculo entre la propiedad del input y el de la base de datos.
            if (dbPropInfo == null)
            {
                return(new ResultValidate
                {
                    Valid = false,
                    Messages = new string[] {
                        $"La propiedad del input {className}.{propName} que tiene que ser validada, no existe en el elemento de la base de datos (BaseEntitySearch)"
                    }
                });
            }

            // asigna el nombre de la propidad que tiene la propiedad de la clase de la base de datos.
            propNameDb = !string.IsNullOrWhiteSpace(propNameDb)? propNameDb : dbPropInfo.Name;


            bool valid = true;

            var lst = new List <string>();

            foreach (var item in castedCollectionElement)
            {
                // realiza la busqueda en la base de datos
                var localExists = await existElement.ExistsWithPropertyValue <T>(propNameDb, elemento.ToString(), id);

                if (localExists)
                {
                    valid = !localExists;
                    lst.Add($"La propiedad del input {className}.{propName} con valor {elemento} existe previamente en la base de datos");
                }
            }

            return(new ResultValidate
            {
                Valid = valid,
                Messages = lst.ToArray()
            });
        }
コード例 #9
0
        /// <summary>
        /// Borra un elemento de una colección de AgroData,
        /// la colección esta determinada por el tipo de dato.
        /// </summary>
        /// <typeparam name="T">Tipo de dato a eliminar</typeparam>
        /// <param name="id">identificador del elemento a eliminar</param>
        private static void RemoveElementFromDb <T>(string id)
        {
            // índice del tipo en el modelo mdm.
            var index = Mdm.GetIndex(typeof(T));

            // si no tiene atributo
            if (!index.HasValue)
            {
                throw new System.Exception("el objeto debe tener el atributo ReferenceHeader");
            }


            // de acuerdo al tipo de entityRelated eliminará el elemento.
            var entityRelated = (EntityRelated)index.Value;

            switch (entityRelated)
            {
            case EntityRelated.WAITINGHARVEST:
                AgroData.WaitingHarvest = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.WaitingHarvest);
                break;

            case EntityRelated.BARRACK:
                AgroData.Barracks = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.Barracks);
                break;

            case EntityRelated.BUSINESSNAME:
                AgroData.BusinessNames = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.BusinessNames);
                break;

            case EntityRelated.CATEGORY_INGREDIENT:
                AgroData.IngredientCategories = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.IngredientCategories);
                break;

            case EntityRelated.CERTIFIED_ENTITY:
                AgroData.CertifiedEntities = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.CertifiedEntities);
                break;

            case EntityRelated.COSTCENTER:
                AgroData.CostCenters = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.CostCenters);
                break;

            case EntityRelated.DOSES:
                AgroData.Doses = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.Doses);
                break;

            case EntityRelated.INGREDIENT:
                AgroData.Ingredients = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.Ingredients);
                break;

            case EntityRelated.JOB:
                break;

            case EntityRelated.NEBULIZER:
                break;

            case EntityRelated.PHENOLOGICAL_EVENT:
                break;

            case EntityRelated.PLOTLAND:
                break;

            case EntityRelated.PRODUCT:
                AgroData.Products = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.Products);
                break;

            case EntityRelated.ROLE:
                break;

            case EntityRelated.ROOTSTOCK:
                AgroData.Rootstocks = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.Rootstocks);
                break;

            case EntityRelated.SEASON:
                AgroData.Seasons = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.Seasons);
                break;

            case EntityRelated.SECTOR:
                AgroData.Sectors = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.Sectors);
                break;

            case EntityRelated.PREORDER:
                break;

            case EntityRelated.TARGET:
                break;

            case EntityRelated.TRACTOR:
                break;

            case EntityRelated.USER:
                break;

            case EntityRelated.VARIETY:
                AgroData.Varieties = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.Varieties);
                break;

            case EntityRelated.NOTIFICATION_EVENT:
                break;

            case EntityRelated.POLLINATOR:
                break;

            case EntityRelated.ORDER_FOLDER:
                break;

            case EntityRelated.EXECUTION_ORDER:
                break;

            case EntityRelated.ORDER:
                break;

            case EntityRelated.BARRACK_EVENT:
                break;

            case EntityRelated.DOSES_ORDER:
                break;

            case EntityRelated.EXECUTION_ORDER_STATUS:
                break;

            case EntityRelated.SPECIE:
                AgroData.Species = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.Species);
                break;

            case EntityRelated.GEOPOINT:
                break;

            case EntityRelated.BRAND:
                AgroData.Brands = Mdm.Reflection.Collections.DeleteElementInCollection(id, AgroData.Brands);
                break;

            default:
                break;
            }
        }
コード例 #10
0
        /// <summary>
        /// Obtiene un elemento de la colección AgroData, de acuerdo al tipo, seleccionará la colección correspondente para retornar el objeto.
        /// </summary>
        /// <typeparam name="T">Tipo de elemento a retornar</typeparam>
        /// <param name="id">identificador del elemento</param>
        /// <returns></returns>
        private static T GetElement <T>(string id)
        {
            // índice de la clase, de acuerdo al modelo mdm.
            var index = Mdm.GetIndex(typeof(T));

            // excepción si no tiene el atributo.
            if (!index.HasValue)
            {
                throw new System.Exception("el objeto debe tener el atributo ReferenceHeader");
            }

            // de acuerdo al entityRelated entregará el elemento.
            var entityRelated = (EntityRelated)index.Value;

            switch (entityRelated)
            {
            case EntityRelated.WAITINGHARVEST:
                throw new Exception("waitin harvest no es un elemento de base de datos, este elemento no hereda de DocumentBase");

            case EntityRelated.BARRACK:
                return((T)(object)AgroData.Barracks.First(s => s.Id.Equals(id)));

            case EntityRelated.BUSINESSNAME:
                return((T)(object)AgroData.BusinessNames.First(s => s.Id.Equals(id)));

            case EntityRelated.CATEGORY_INGREDIENT:
                return((T)(object)AgroData.IngredientCategories.First(s => s.Id.Equals(id)));

            case EntityRelated.CERTIFIED_ENTITY:
                return((T)(object)AgroData.CertifiedEntities.First(s => s.Id.Equals(id)));

            case EntityRelated.COSTCENTER:
                return((T)(object)AgroData.CostCenters.First(s => s.Id.Equals(id)));

            case EntityRelated.DOSES:
                return((T)(object)AgroData.Doses.First(s => s.Id.Equals(id)));

            case EntityRelated.INGREDIENT:
                return((T)(object)AgroData.Ingredients.First(s => s.Id.Equals(id)));

            case EntityRelated.JOB:
                return((T)(object)AgroData.Jobs.First(s => s.Id.Equals(id)));

            case EntityRelated.NEBULIZER:
                return((T)(object)AgroData.Nebulizers.First(s => s.Id.Equals(id)));

            case EntityRelated.PHENOLOGICAL_EVENT:
                return((T)(object)AgroData.PhenologicalEvents.First(s => s.Id.Equals(id)));

            case EntityRelated.PLOTLAND:
                return((T)(object)AgroData.PlotLands.First(s => s.Id.Equals(id)));

            case EntityRelated.PRODUCT:
                return((T)(object)AgroData.Products.First(s => s.Id.Equals(id)));

            case EntityRelated.ROLE:
                return((T)(object)AgroData.Roles.First(s => s.Id.Equals(id)));

            case EntityRelated.ROOTSTOCK:
                return((T)(object)AgroData.Rootstocks.First(s => s.Id.Equals(id)));

            case EntityRelated.SEASON:
                return((T)(object)AgroData.Seasons.First(s => s.Id.Equals(id)));

            case EntityRelated.SECTOR:
                return((T)(object)AgroData.Sectors.First(s => s.Id.Equals(id)));

            case EntityRelated.PREORDER:
                return((T)(object)AgroData.PreOrders.First(s => s.Id.Equals(id)));

            case EntityRelated.TARGET:
                return((T)(object)AgroData.ApplicationTargets.First(s => s.Id.Equals(id)));

            case EntityRelated.TRACTOR:
                return((T)(object)AgroData.Tractors.First(s => s.Id.Equals(id)));

            case EntityRelated.USER:
                break;

            case EntityRelated.VARIETY:
                return((T)(object)AgroData.Varieties.First(s => s.Id.Equals(id)));

            case EntityRelated.NOTIFICATION_EVENT:
                break;

            case EntityRelated.POLLINATOR:
                break;

            case EntityRelated.ORDER_FOLDER:
                return((T)(object)AgroData.OrderFolders.First(s => s.Id.Equals(id)));

            case EntityRelated.EXECUTION_ORDER:
                break;

            case EntityRelated.ORDER:
                break;

            case EntityRelated.BARRACK_EVENT:
                break;

            case EntityRelated.DOSES_ORDER:
                break;

            case EntityRelated.EXECUTION_ORDER_STATUS:
                break;

            case EntityRelated.SPECIE:
                return((T)(object)AgroData.Species.First(s => s.Id.Equals(id)));

            case EntityRelated.GEOPOINT:
                break;

            case EntityRelated.BRAND:
                return((T)(object)AgroData.Brands.First(s => s.Id.Equals(id)));

            default:
                throw new Exception("not good");
            }
            throw new Exception("not good");
        }
コード例 #11
0
        /// <summary>
        /// Añade un elemento a una colección de AgroData, de acuerdo al tipo de elemento a insertar.
        /// </summary>
        /// <typeparam name="T">Tipo de elemento a insertar</typeparam>
        /// <param name="element">elemento a insertar en una de las colecciones</param>
        private static void AddElement <T>(T element) where T : DocumentBase
        {
            // obtiene el índice desde mdm, utiliza el atributo para identificar a que entitySearch pertenece.
            var index = Mdm.GetIndex(typeof(T));

            // si no tiene el atributo, lanzará error.
            if (!index.HasValue)
            {
                throw new System.Exception("el objeto debe tener el atributo ReferenceHeader");
            }

            // de acuerdo al entityRelated insertaremos en la colección.
            var entityRelated = (EntityRelated)index.Value;

            switch (entityRelated)
            {
            case EntityRelated.WAITINGHARVEST:
                // no es un elemento de base de datos
                break;

            case EntityRelated.BARRACK:
                AgroData.Barracks = Mdm.Reflection.Collections.UpsertToCollection((Barrack)(object)element, AgroData.Barracks);
                break;

            case EntityRelated.BUSINESSNAME:
                AgroData.BusinessNames = Mdm.Reflection.Collections.UpsertToCollection((BusinessName)(object)element, AgroData.BusinessNames);
                break;

            case EntityRelated.CATEGORY_INGREDIENT:
                AgroData.IngredientCategories = Mdm.Reflection.Collections.UpsertToCollection((IngredientCategory)(object)element, AgroData.IngredientCategories);
                break;

            case EntityRelated.CERTIFIED_ENTITY:
                AgroData.CertifiedEntities = Mdm.Reflection.Collections.UpsertToCollection((CertifiedEntity)(object)element, AgroData.CertifiedEntities);
                break;

            case EntityRelated.COSTCENTER:
                AgroData.CostCenters = Mdm.Reflection.Collections.UpsertToCollection((CostCenter)(object)element, AgroData.CostCenters);
                break;

            case EntityRelated.DOSES:
                AgroData.Doses = Mdm.Reflection.Collections.UpsertToCollection((Dose)(object)element, AgroData.Doses);
                break;

            case EntityRelated.INGREDIENT:
                AgroData.Ingredients = Mdm.Reflection.Collections.UpsertToCollection((Ingredient)(object)element, AgroData.Ingredients);
                break;

            case EntityRelated.JOB:
                AgroData.Jobs = Mdm.Reflection.Collections.UpsertToCollection((Job)(object)element, AgroData.Jobs);
                break;

            case EntityRelated.NEBULIZER:
                AgroData.Nebulizers = Mdm.Reflection.Collections.UpsertToCollection((Nebulizer)(object)element, AgroData.Nebulizers);
                break;

            case EntityRelated.PHENOLOGICAL_EVENT:
                AgroData.PhenologicalEvents = Mdm.Reflection.Collections.UpsertToCollection((PhenologicalEvent)(object)element, AgroData.PhenologicalEvents);
                break;

            case EntityRelated.PLOTLAND:
                AgroData.PlotLands = Mdm.Reflection.Collections.UpsertToCollection((PlotLand)(object)element, AgroData.PlotLands);
                break;

            case EntityRelated.PRODUCT:
                AgroData.Products = Mdm.Reflection.Collections.UpsertToCollection((Product)(object)element, AgroData.Products);
                break;

            case EntityRelated.ROLE:
                AgroData.Roles = Mdm.Reflection.Collections.UpsertToCollection((Role)(object)element, AgroData.Roles);
                break;

            case EntityRelated.ROOTSTOCK:
                AgroData.Rootstocks = Mdm.Reflection.Collections.UpsertToCollection((Rootstock)(object)element, AgroData.Rootstocks);
                break;

            case EntityRelated.SEASON:
                AgroData.Seasons = Mdm.Reflection.Collections.UpsertToCollection((Season)(object)element, AgroData.Seasons);
                break;

            case EntityRelated.SECTOR:
                AgroData.Sectors = Mdm.Reflection.Collections.UpsertToCollection((Sector)(object)element, AgroData.Sectors);
                break;

            case EntityRelated.PREORDER:
                AgroData.PreOrders = Mdm.Reflection.Collections.UpsertToCollection((PreOrder)(object)element, AgroData.PreOrders);
                break;

            case EntityRelated.TARGET:
                AgroData.ApplicationTargets = Mdm.Reflection.Collections.UpsertToCollection((ApplicationTarget)(object)element, AgroData.ApplicationTargets);
                break;

            case EntityRelated.TRACTOR:
                AgroData.Tractors = Mdm.Reflection.Collections.UpsertToCollection((Tractor)(object)element, AgroData.Tractors);
                break;

            case EntityRelated.USER:
                break;

            case EntityRelated.VARIETY:
                AgroData.Varieties = Mdm.Reflection.Collections.UpsertToCollection((Variety)(object)element, AgroData.Varieties);
                break;

            case EntityRelated.NOTIFICATION_EVENT:
                AgroData.NotificationEvents = Mdm.Reflection.Collections.UpsertToCollection((NotificationEvent)(object)element, AgroData.NotificationEvents);
                break;

            case EntityRelated.POLLINATOR:
                break;

            case EntityRelated.ORDER_FOLDER:
                AgroData.OrderFolders = Mdm.Reflection.Collections.UpsertToCollection((OrderFolder)(object)element, AgroData.OrderFolders);
                break;

            case EntityRelated.EXECUTION_ORDER:
                break;

            case EntityRelated.ORDER:
                break;

            case EntityRelated.BARRACK_EVENT:
                break;

            case EntityRelated.DOSES_ORDER:
                break;

            case EntityRelated.EXECUTION_ORDER_STATUS:
                break;

            case EntityRelated.SPECIE:
                AgroData.Species = Mdm.Reflection.Collections.UpsertToCollection((Specie)(object)element, AgroData.Species);
                break;

            case EntityRelated.GEOPOINT:
                break;

            case EntityRelated.BRAND:
                AgroData.Brands = Mdm.Reflection.Collections.UpsertToCollection((Brand)(object)element, AgroData.Brands);
                break;

            default:
                throw new System.Exception("not good");
            }
        }