Esempio n. 1
0
        public IHttpActionResult GetName(int key)
        {
            EdmEntityObjectCollection customers = GetCustomers();
            EdmEntityObject           customer  = customers.FirstOrDefault(e =>
            {
                object customerId;
                if (e.TryGetPropertyValue("CustomerId", out customerId))
                {
                    return((int)customerId == key);
                }

                return(false);
            }) as EdmEntityObject;

            if (customer == null)
            {
                return(NotFound());
            }

            object name;

            customer.TryGetPropertyValue("Name", out name);
            if (name == null)
            {
                return(NotFound());
            }

            return(Ok(name, name.GetType()));
        }
Esempio n. 2
0
        public object GetProperty(string property, EdmEntityObject entity)
        {
            object value;

            entity.TryGetPropertyValue(property, out value);
            return(value);
        }
Esempio n. 3
0
        public IHttpActionResult PatchCustomerBySSN([FromODataUri] string ssnKey, EdmEntityObject delta)
        {
            IList <string>   changedPropertyNames = delta.GetChangedPropertyNames().ToList();
            IEdmEntityObject originalCustomer     = null;

            foreach (var customer in AlternateKeysDataSource.Customers)
            {
                object value;
                if (customer.TryGetPropertyValue("SSN", out value))
                {
                    string stringKey = (string)value;
                    if (ssnKey == stringKey)
                    {
                        originalCustomer = customer;
                    }
                }
            }

            if (originalCustomer == null)
            {
                return(NotFound());
            }

            object nameValue;

            delta.TryGetPropertyValue("Name", out nameValue);
            //Assert.NotNull(nameValue);
            //string strName = Assert.IsType<string>(nameValue);
            dynamic original = originalCustomer;

            //original.Name = strName;
            original.Name = nameValue;

            return(Ok(originalCustomer));
        }
Esempio n. 4
0
        public IHttpActionResult PostUntypedSimpleOpenCustomer(EdmEntityObject customer)
        {
            object nameValue;

            customer.TryGetPropertyValue("Name", out nameValue);
            Type nameType;

            customer.TryGetPropertyType("Name", out nameType);
            return(null);
        }
Esempio n. 5
0
        public IHttpActionResult PutStatement(int key, int navKey, EdmEntityObject statementObject)
        {
            Statement newStatement = new Statement();
            var       properties   = typeof(Statement).GetProperties();

            foreach (PropertyInfo propertyInfo in properties)
            {
                object value;
                statementObject.TryGetPropertyValue(propertyInfo.Name, out value);
                propertyInfo.SetValue(newStatement, value);
            }
            return(Ok(newStatement));
        }
Esempio n. 6
0
            public IHttpActionResult GetCustomer(int key, [FromODataUri] EdmEntityObject customer)
            {
                Assert.NotNull(customer);

                StringBuilder        sb            = new StringBuilder();
                IEnumerable <string> propertyNames = customer.GetChangedPropertyNames();

                foreach (string name in propertyNames)
                {
                    object value;
                    customer.TryGetPropertyValue(name, out value);
                    sb.Append(name + "=").Append(value).Append(",");
                }

                return(Ok("GetCustomer(" + sb.ToString() + ")"));
            }
Esempio n. 7
0
        public ITestActionResult PatchCustomerBySSN([FromODataUri] string ssnKey, [FromBody] EdmEntityObject delta)
        {
            Assert.Equal("SSN-6-T-006", ssnKey);

            IList <string> changedPropertyNames = delta.GetChangedPropertyNames().ToList();

            Assert.Single(changedPropertyNames);
            Assert.Equal("Name", String.Join(",", changedPropertyNames));

            IEdmEntityObject originalCustomer = null;

            foreach (var customer in AlternateKeysDataSource.Customers)
            {
                object value;
                if (customer.TryGetPropertyValue("SSN", out value))
                {
                    string stringKey = (string)value;
                    if (ssnKey == stringKey)
                    {
                        originalCustomer = customer;
                    }
                }
            }

            if (originalCustomer == null)
            {
                return(NotFound());
            }

            object nameValue;

            delta.TryGetPropertyValue("Name", out nameValue);
            Assert.NotNull(nameValue);
            string  strName  = Assert.IsType <string>(nameValue);
            dynamic original = originalCustomer;

            original.Name = strName;

            return(Ok(originalCustomer));
        }
Esempio n. 8
0
        public IHttpActionResult GetColor(int key)
        {
            EdmEntityObjectCollection customers = GetCustomers();
            EdmEntityObject           customer  = customers.FirstOrDefault(e =>
            {
                object customerId;
                if (e.TryGetPropertyValue("CustomerId", out customerId))
                {
                    return((int)customerId == key);
                }

                return(false);
            }) as EdmEntityObject;

            if (customer == null)
            {
                return(NotFound());
            }

            object color;

            customer.TryGetPropertyValue("Color", out color);
            if (color == null)
            {
                return(NotFound());
            }

            // return Ok(color, color.GetType());

            EdmEnumObject enumColor = color as EdmEnumObject;

            if (enumColor == null)
            {
                return(NotFound());
            }

            return(Ok(enumColor));
        }
Esempio n. 9
0
        public IActionResult PostUntypedSimpleOpenCustomer(EdmEntityObject customer)
        {
            // Verify there is a string dynamic property in OpenEntityType
            object nameValue;

            customer.TryGetPropertyValue("Name", out nameValue);
            Type nameType;

            customer.TryGetPropertyType("Name", out nameType);

            Assert.NotNull(nameValue);
            Assert.Equal(typeof(String), nameType);
            Assert.Equal("FirstName 6", nameValue);

            // Verify there is a collection of double dynamic property in OpenEntityType
            object doubleListValue;

            customer.TryGetPropertyValue("DoubleList", out doubleListValue);
            Type doubleListType;

            customer.TryGetPropertyType("DoubleList", out doubleListType);

            Assert.NotNull(doubleListValue);
            Assert.Equal(typeof(List <Double>), doubleListType);

            // Verify there is a collection of complex type dynamic property in OpenEntityType
            object addressesValue;

            customer.TryGetPropertyValue("Addresses", out addressesValue);

            Assert.NotNull(addressesValue);

            // Verify there is a complex type dynamic property in OpenEntityType
            object addressValue;

            customer.TryGetPropertyValue("Address", out addressValue);

            Type addressType;

            customer.TryGetPropertyType("Address", out addressType);

            Assert.NotNull(addressValue);
            Assert.Equal(typeof(EdmComplexObject), addressType);

            // Verify there is a collection of enum type dynamic property in OpenEntityType
            object favoriteColorsValue;

            customer.TryGetPropertyValue("FavoriteColors", out favoriteColorsValue);
            EdmEnumObjectCollection favoriteColors = favoriteColorsValue as EdmEnumObjectCollection;

            Assert.NotNull(favoriteColorsValue);
            Assert.NotNull(favoriteColors);
            Assert.Equal(typeof(EdmEnumObject), favoriteColors[0].GetType());

            // Verify there is an enum type dynamic property in OpenEntityType
            object favoriteColorValue;

            customer.TryGetPropertyValue("FavoriteColor", out favoriteColorValue);

            Assert.NotNull(favoriteColorValue);
            Assert.Equal("Red", ((EdmEnumObject)favoriteColorValue).Value);

            Type favoriteColorType;

            customer.TryGetPropertyType("FavoriteColor", out favoriteColorType);

            Assert.Equal(typeof(EdmEnumObject), favoriteColorType);

            // Verify there is a string dynamic property in OpenComplexType
            EdmComplexObject address = addressValue as EdmComplexObject;
            object           cityValue;

            address.TryGetPropertyValue("City", out cityValue);
            Type cityType;

            address.TryGetPropertyType("City", out cityType);

            Assert.NotNull(cityValue);
            Assert.Equal(typeof(String), cityType);
            Assert.Equal("City 6", cityValue); // It reads as ODataUntypedValue, and the RawValue is the string with the ""

            return(Ok(customer));
        }
Esempio n. 10
0
        /// <summary>
        /// Построение объекта данных по сущности OData.
        /// </summary>
        /// <param name="edmEntity"> Сущность OData. </param>
        /// <param name="key"> Значение ключевого поля сущности. </param>
        /// <param name="dObjs"> Список объектов для обновления. </param>
        /// <param name="endObject"> Признак, что объект добавляется в конец списка обновления. </param>
        /// <returns> Объект данных. </returns>
        private DataObject GetDataObjectByEdmEntity(EdmEntityObject edmEntity, object key, List <DataObject> dObjs, bool endObject = false)
        {
            if (edmEntity == null)
            {
                return(null);
            }

            IEdmEntityType entityType = (IEdmEntityType)edmEntity.ActualEdmType;
            Type           objType    = _model.GetDataObjectType(_model.GetEdmEntitySet(entityType).Name);

            // Значение свойства.
            object value;

            // Получим значение ключа.
            var keyProperty = entityType.Properties().FirstOrDefault(prop => prop.Name == _model.KeyPropertyName);

            if (key != null)
            {
                value = key;
            }
            else
            {
                edmEntity.TryGetPropertyValue(keyProperty.Name, out value);
            }

            // Загрузим объект из хранилища, если он там есть (используем представление по умолчанию), или создадим, если нет, но только для POST.
            // Тем самым гарантируем загруженность свойств при необходимости обновления и установку нужного статуса.
            DataObject obj = ReturnDataObject(objType, value);

            // Добавляем объект в список для обновления, если там ещё нет объекта с таким ключом.
            var objInList = dObjs.FirstOrDefault(o => o.__PrimaryKey.ToString() == obj.__PrimaryKey.ToString());

            if (objInList == null)
            {
                if (!endObject)
                {
                    // Добавляем объект в начало списка.
                    dObjs.Insert(0, obj);
                }
                else
                {
                    // Добавляем в конец списка.
                    dObjs.Add(obj);
                }
            }

            // Все свойства объекта данных означим из пришедшей сущности, если они были там установлены(изменены).
            foreach (var prop in entityType.Properties())
            {
                string dataObjectPropName = _model.GetDataObjectProperty(entityType.FullTypeName(), prop.Name).Name;
                if (edmEntity.GetChangedPropertyNames().Contains(prop.Name))
                {
                    // Обработка мастеров и детейлов.
                    if (prop is EdmNavigationProperty)
                    {
                        EdmNavigationProperty navProp = (EdmNavigationProperty)prop;

                        edmEntity.TryGetPropertyValue(prop.Name, out value);

                        EdmMultiplicity edmMultiplicity = navProp.TargetMultiplicity();

                        // var aggregator = Information.GetAgregatePropertyName(objType);

                        // Обработка мастеров.
                        if (edmMultiplicity == EdmMultiplicity.One || edmMultiplicity == EdmMultiplicity.ZeroOrOne)
                        {
                            if (value != null && value is EdmEntityObject)
                            {
                                EdmEntityObject edmMaster = (EdmEntityObject)value;
                                DataObject      master    = GetDataObjectByEdmEntity(edmMaster, null, dObjs);

                                Information.SetPropValueByName(obj, dataObjectPropName, master);
                            }
                            else
                            {
                                Information.SetPropValueByName(obj, dataObjectPropName, null);
                            }
                        }

                        // Обработка детейлов.
                        if (edmMultiplicity == EdmMultiplicity.Many)
                        {
                            Type        detType = Information.GetPropertyType(objType, dataObjectPropName);
                            DetailArray detarr  = (DetailArray)Information.GetPropValueByName(obj, dataObjectPropName);

                            if (value != null && value is EdmEntityObjectCollection)
                            {
                                EdmEntityObjectCollection coll = (EdmEntityObjectCollection)value;
                                if (coll != null && coll.Count > 0)
                                {
                                    foreach (var edmEnt in coll)
                                    {
                                        DataObject det = GetDataObjectByEdmEntity(
                                            (EdmEntityObject)edmEnt,
                                            null,
                                            dObjs,
                                            true);

                                        if (det.__PrimaryKey == null)
                                        {
                                            detarr.AddObject(det);
                                        }
                                        else
                                        {
                                            detarr.SetByKey(det.__PrimaryKey, det);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                detarr.Clear();
                            }
                        }
                    }
                    else
                    {
                        // Обработка собственных свойств объекта (неключевых, т.к. ключ устанавливаем при начальной инициализации объекта obj).
                        if (prop.Name != keyProperty.Name)
                        {
                            Type dataObjectPropertyType = Information.GetPropertyType(objType, dataObjectPropName);
                            edmEntity.TryGetPropertyValue(prop.Name, out value);

                            // Если тип свойства относится к одному из зарегистрированных провайдеров файловых свойств,
                            // значит свойство файловое, и его нужно обработать особым образом.
                            if (FileController.HasDataObjectFileProvider(dataObjectPropertyType))
                            {
                                IDataObjectFileProvider dataObjectFileProvider = FileController.GetDataObjectFileProvider(dataObjectPropertyType);

                                // Обработка файловых свойств объектов данных.
                                string serializedFileDescription = value as string;
                                if (serializedFileDescription == null)
                                {
                                    // Файловое свойство было сброшено на клиенте.
                                    // Ассоциированный файл должен быть удален, после успешного сохранения изменений.
                                    // Для этого запоминаем метаданные ассоциированного файла, до того как свойство будет сброшено
                                    // (для получения метаданных свойство будет дочитано в объект данных).
                                    // Файловое свойство типа File хранит данные ассоциированного файла прямо в БД,
                                    // соответственно из файловой системы просто нечего удалять,
                                    // поэтому обходим его стороной, чтобы избежать лишных вычиток файлов из БД.
                                    if (dataObjectPropertyType != typeof(File))
                                    {
                                        _removingFileDescriptions.Add(dataObjectFileProvider.GetFileDescription(obj, dataObjectPropName));
                                    }

                                    // Сбрасываем файловое свойство в изменяемом объекте данных.
                                    Information.SetPropValueByName(obj, dataObjectPropName, null);
                                }
                                else
                                {
                                    // Файловое свойство было изменено, но не сброшено.
                                    // Если в метаданных файла присутствует FileUploadKey значит файл был загружен на сервер,
                                    // но еще не был ассоциирован с объектом данных, и это нужно сделать.
                                    FileDescription fileDescription = FileDescription.FromJson(serializedFileDescription);
                                    if (!(string.IsNullOrEmpty(fileDescription.FileUploadKey) || string.IsNullOrEmpty(fileDescription.FileName)))
                                    {
                                        Information.SetPropValueByName(obj, dataObjectPropName, dataObjectFileProvider.GetFileProperty(fileDescription));

                                        // Файловое свойство типа File хранит данные ассоциированного файла прямо в БД,
                                        // поэтому после успешного сохранения объекта данных, оссоциированный с ним файл должен быть удален из файловой системы.
                                        // Для этого запоминаем описание загруженного файла.
                                        if (dataObjectPropertyType == typeof(File))
                                        {
                                            _removingFileDescriptions.Add(fileDescription);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                // Преобразование типов для примитивных свойств.
                                if (value is DateTimeOffset)
                                {
                                    value = ((DateTimeOffset)value).UtcDateTime;
                                }
                                if (value is EdmEnumObject)
                                {
                                    value = ((EdmEnumObject)value).Value;
                                }

                                Information.SetPropValueByName(obj, dataObjectPropName, value);
                            }
                        }
                    }
                }
            }

            return(obj);
        }