Beispiel #1
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            var newExpression = (MethodCallExpression)base.VisitMethodCall(node);

            _queryModelVisitor.BindMethodCallExpression(
                node, (property, querySource) =>
            {
                if (querySource != null)
                {
                    DemoteQuerySource(querySource);
                }
            });

            if (AnonymousObject.IsGetValueExpression(node, out var querySourceReferenceExpression))
            {
                DemoteQuerySource(querySourceReferenceExpression.ReferencedQuerySource);
            }

            foreach (var subQueryExpression in newExpression.Arguments.OfType <SubQueryExpression>())
            {
                if (subQueryExpression.QueryModel.ResultOperators.LastOrDefault() is IQuerySource querySourceResultOperator)
                {
                    PromoteQuerySource(querySourceResultOperator);
                }
                else if (subQueryExpression.QueryModel.SelectClause.Selector is QuerySourceReferenceExpression qsre)
                {
                    PromoteQuerySource(qsre.ReferencedQuerySource);
                }
            }

            return(newExpression);
        }
        // public IActionResult Create([Bind("ParentAnonymousObjectId,Id")] AnonymousObject anonymousObject)
        public IActionResult Create([Bind("Properties, ParentAnonymousObjectId, NestedObjects")] AnonymousObject anonymousObject)
        {
            if (anonymousObject == null)
            {
                return(this.BadRequest());
            }

            if (this.ModelState.IsValid)
            {
                anonymousObject.ParentAnonymousObjectId =
                    this.ValidateAnonymousObjectId(anonymousObject.ParentAnonymousObjectId);

                for (int i = anonymousObject.Properties.Count - 1; i >= 0; i--)
                {
                    KeyValuePair pair = anonymousObject.Properties[i];
                    if (string.IsNullOrWhiteSpace(pair.Key) || string.IsNullOrWhiteSpace(pair.Value))
                    {
                        anonymousObject.Properties.Remove(pair);
                    }
                }

                this._repository.AddAnonymousObject(anonymousObject);
                return(this.RedirectToAction(nameof(this.Index)));
            }

            return(this.View(anonymousObject));
        }
Beispiel #3
0
        public void CanCastToAnyInterface()
        {
            var subject = new AnonymousObject(new ByRefValue("object@10000", Array.Empty <string>()));
            var result  = subject.UnsafeCast <IManagedInterface>();

            Assert.IsType <ManagedInterfaceProxy>(result);
        }
Beispiel #4
0
        public void DeleteAnonymousObject(AnonymousObject anonToDelete)
        {
            this._context.AnonymousObjects.Remove(anonToDelete);
            this._context.SaveChanges();

            this.UpdateIndicesWithDocumentId(anonToDelete.Id);
        }
        /// <summary>
        ///     Visits a method call expression.
        /// </summary>
        /// <param name="methodCallExpression"> The expression to visit. </param>
        /// <returns>
        ///     An Expression.
        /// </returns>
        protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
        {
            Check.NotNull(methodCallExpression, nameof(methodCallExpression));

            var operand = Visit(methodCallExpression.Object);

            if (operand != null ||
                methodCallExpression.Object == null)
            {
                var arguments
                    = methodCallExpression.Arguments
                      .Where(
                          e => !(e.RemoveConvert() is QuerySourceReferenceExpression) &&
                          !IsNonTranslatableSubquery(e.RemoveConvert()))
                      .Select(
                          e => (e.RemoveConvert() as ConstantExpression)?.Value is Array || e.RemoveConvert().Type == typeof(DbFunctions)
                                ? e
                                : Visit(e))
                      .Where(e => e != null)
                      .ToArray();

                if (arguments.Length == methodCallExpression.Arguments.Count)
                {
                    var boundExpression
                        = operand != null
                            ? Expression.Call(operand, methodCallExpression.Method, arguments)
                            : Expression.Call(methodCallExpression.Method, arguments);

                    var translatedExpression = _methodCallTranslator.Translate(boundExpression, _queryModelVisitor.QueryCompilationContext.Model);

                    if (translatedExpression != null)
                    {
                        return(translatedExpression);
                    }
                }
            }

            if (AnonymousObject.IsGetValueExpression(methodCallExpression, out var querySourceReferenceExpression))
            {
                var selectExpression
                    = _queryModelVisitor.TryGetQuery(querySourceReferenceExpression.ReferencedQuerySource);

                if (selectExpression != null)
                {
                    var projectionIndex
                        = (int)((ConstantExpression)methodCallExpression.Arguments.Single()).Value;

                    return(selectExpression.BindSubqueryProjectionIndex(
                               projectionIndex,
                               querySourceReferenceExpression.ReferencedQuerySource));
                }
            }

            return(TryBindMemberOrMethodToSelectExpression(
                       methodCallExpression, (expression, visitor, binder)
                       => visitor.BindMethodCallExpression(expression, binder))
                   ?? _queryModelVisitor.BindLocalMethodCallExpression(methodCallExpression)
                   ?? _queryModelVisitor.BindMethodToOuterQueryParameter(methodCallExpression));
        }
        public void ConvertingAnonymousObjectToDictionary()
        {
            var anonymous = new { test = "test", test2 = "test2" };
            var result    = AnonymousObject.ToDictionary(anonymous);

            result["test"].Should().Be("test");
            result["test2"].Should().Be("test2");
        }
Beispiel #7
0
        /// <summary>
        /// Converts an <see langword="object"/> into a target <see cref="Type"/>.
        /// </summary>
        /// <param name="wantedType">Target <see cref="Type"/>.</param>
        /// <param name="objectToConvert"><see langword="object"/> to convert.</param>
        /// <returns>Returns the converted <see langword="object"/>.</returns>
        public static object ConvertFromSerializable(Type wantedType, object objectToConvert)
        {
            if (objectToConvert == null)
            {
                return(null);
            }
            if (wantedType.IsIGrouping() && objectToConvert is InterLinqGroupingBase)
            {
                Type[]     genericType = objectToConvert.GetType().GetGenericArguments();
                MethodInfo method      = typeof(TypeConverter).GetMethod("ConvertFromInterLinqGrouping", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(genericType);
                return(method.Invoke(null, new[] { wantedType, objectToConvert }));
            }
            Type wantedElementType = InterLinqTypeSystem.FindIEnumerable(wantedType);

            if (wantedElementType != null && wantedElementType.GetGenericArguments()[0].IsAnonymous())
            {
                Type typeOfObject = objectToConvert.GetType();
                Type elementType  = InterLinqTypeSystem.FindIEnumerable(typeOfObject);
                if (elementType != null && elementType.GetGenericArguments()[0] == typeof(AnonymousObject))
                {
                    MethodInfo method = typeof(TypeConverter).GetMethod("ConvertFromSerializableCollection", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(wantedElementType.GetGenericArguments()[0]);
                    return(method.Invoke(null, new[] { objectToConvert }));
                }
            }
            if (wantedType.IsAnonymous() && objectToConvert is AnonymousObject)
            {
                AnonymousObject   dynamicObject = (AnonymousObject)objectToConvert;
                List <object>     properties    = new List <object>();
                ConstructorInfo[] constructors  = wantedType.GetConstructors();
                if (constructors.Length != 1)
                {
                    throw new Exception("Usualy, anonymous types have just one constructor.");
                }
                ConstructorInfo constructor = constructors[0];
                foreach (ParameterInfo parameter in constructor.GetParameters())
                {
                    object propertyValue      = null;
                    bool   propertyHasBeenSet = false;
                    foreach (AnonymousProperty dynProperty in dynamicObject.Properties)
                    {
                        if (dynProperty.Name == parameter.Name)
                        {
                            propertyValue      = dynProperty.Value;
                            propertyHasBeenSet = true;
                            break;
                        }
                    }
                    if (!propertyHasBeenSet)
                    {
                        throw new Exception(string.Format("Property {0} could not be found in the dynamic object.", parameter.Name));
                    }
                    properties.Add(ConvertFromSerializable(parameter.ParameterType, propertyValue));
                }
                return(constructor.Invoke(properties.ToArray()));
            }
            return(objectToConvert);
        }
Beispiel #8
0
        public void UpdateAnonymousObject(AnonymousObject anonToUpdate)
        {
            AnonymousObject anonToRemove =
                this._context.AnonymousObjects.FirstOrDefault(i => i.Id.Equals(anonToUpdate.Id));

            this.DeleteAnonymousObject(anonToRemove);

            this.AddAnonymousObject(anonToUpdate);
        }
        public static List <Index> CrawlAnonymousObject(this AnonymousObject anon, List <Index> currentIndices = null)
        {
            if (currentIndices == null)
            {
                currentIndices = new List <Index>();
            }

            return(anon.CrawlAnonymousObject(out _, currentIndices));
        }
Beispiel #10
0
        public static InstanceCount CreateInstanceCount(Index index, AnonymousObject anon, int count)
        {
            InstanceCount newInstanceCount = new InstanceCount()
            {
                DocumentId = anon.Id,
                Count      = count,
            };

            newInstanceCount.Id = GenerateInstanceCountId(newInstanceCount, index);
            return(newInstanceCount);
        }
        // ObjectTemplate

        private static string SpyCallback(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string templateName, DataBoundControlMode mode, object additionalViewData)
        {
            return(String.Format("Model = {0}, ModelType = {1}, PropertyName = {2}, HtmlFieldName = {3}, TemplateName = {4}, Mode = {5}, AdditionalViewData = {6}",
                                 metadata.Model ?? "(null)",
                                 metadata.ModelType == null ? "(null)" : metadata.ModelType.FullName,
                                 metadata.PropertyName ?? "(null)",
                                 htmlFieldName == String.Empty ? "(empty)" : htmlFieldName ?? "(null)",
                                 templateName ?? "(null)",
                                 mode,
                                 AnonymousObject.Inspect(additionalViewData)));
        }
Beispiel #12
0
        // CollectionTemplate

        private static string CollectionSpyCallback(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string templateName, DataBoundControlMode mode, object additionalViewData)
        {
            return(String.Format(Environment.NewLine + "Model = {0}, ModelType = {1}, PropertyName = {2}, HtmlFieldName = {3}, TemplateName = {4}, Mode = {5}, TemplateInfo.HtmlFieldPrefix = {6}, AdditionalViewData = {7}",
                                 metadata.Model ?? "(null)",
                                 metadata.ModelType == null ? "(null)" : metadata.ModelType.FullName,
                                 metadata.PropertyName ?? "(null)",
                                 htmlFieldName == String.Empty ? "(empty)" : htmlFieldName ?? "(null)",
                                 templateName ?? "(null)",
                                 mode,
                                 html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix,
                                 AnonymousObject.Inspect(additionalViewData)));
        }
Beispiel #13
0
        public IActionResult CreateAnonymousObject([FromBody] JObject anonymousObjectJson)
        {
            if (anonymousObjectJson == null)
            {
                return(this.BadRequest());
            }

            AnonymousObject anon = DeserializeAnonymousObjectJson(anonymousObjectJson);

            AnonymousObject anonToReturn = this._documentRepository.AddAnonymousObject(anon);

            return(this.Created("GetAnonymousObject", anonToReturn));
        }
        private static void CrawlAnonymousObjectForIndices(this AnonymousObject anon, List <Index> indices)
        {
            indices.AddFieldIndices(anon, "Id", anon.Id.ToString());

            foreach (KeyValuePair pair in anon.Properties)
            {
                indices.AddFieldIndices(anon, pair.Key, pair.Value);
            }

            foreach (AnonymousObject nestedObject in anon.NestedObjects)
            {
                nestedObject.CrawlAnonymousObjectForIndices(indices);
            }
        }
        public static List <Index> CrawlAnonymousObject(
            this AnonymousObject anon,
            out List <Index> indicesToUpdate,
            List <Index> currentIndices = null)
        {
            if (currentIndices == null)
            {
                currentIndices = new List <Index>();
            }

            List <Index> indicesToAdd = new List <Index>();

            anon.CrawlAnonymousObjectForIndices(indicesToAdd);

            return(CombineIndices(currentIndices, indicesToAdd, out indicesToUpdate));
        }
Beispiel #16
0
        public IActionResult GetAnonymousObject(Guid anonymousObjectId)
        {
            if (anonymousObjectId == Guid.Empty)
            {
                return(this.BadRequest());
            }

            AnonymousObject anon = this._documentRepository.GetAnonymousObject(anonymousObjectId);

            if (anon == null)
            {
                return(this.NotFound());
            }

            return(this.Ok(anon));
        }
        // GET: AnonymousObjects/Edit/5
        public IActionResult Edit(Guid?id)
        {
            if (id == null)
            {
                return(this.NotFound());
            }

            AnonymousObject anonymousObject = this._repository.GetAnonymousObject((Guid)id);

            if (anonymousObject == null)
            {
                return(this.NotFound());
            }

            return(this.View(anonymousObject));
        }
        public IActionResult Edit(Guid id, [Bind("Properties, ParentAnonymousObjectId, NestedObjects, Id")] AnonymousObject anonymousObject)
        {
            if (id != anonymousObject.Id)
            {
                return(this.NotFound());
            }

            if (this.ModelState.IsValid)
            {
                try
                {
                    if (!this._repository.AnonymousObjectExists(anonymousObject.Id))
                    {
                        return(this.NotFound());
                    }

                    anonymousObject.ParentAnonymousObjectId =
                        this.ValidateAnonymousObjectId(anonymousObject.ParentAnonymousObjectId);

                    for (int i = anonymousObject.Properties.Count - 1; i >= 0; i--)
                    {
                        KeyValuePair pair = anonymousObject.Properties[i];
                        if (string.IsNullOrWhiteSpace(pair.Key) || string.IsNullOrWhiteSpace(pair.Value))
                        {
                            anonymousObject.Properties.Remove(pair);
                        }
                    }

                    this._repository.UpdateAnonymousObject(anonymousObject);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!this._repository.AnonymousObjectExists(anonymousObject.Id))
                    {
                        return(this.NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }

                return(this.RedirectToAction(nameof(this.Index)));
            }

            return(this.View(anonymousObject));
        }
Beispiel #19
0
        public AnonymousObject AddAnonymousObject(AnonymousObject anonymousObject)
        {
            if (anonymousObject.Id == default)
            {
                anonymousObject.Id = Guid.NewGuid();
            }

            this._context.AnonymousObjects.Add(anonymousObject);

            this._context.SaveChanges();

            List <Index> indices =
                anonymousObject.CrawlAnonymousObject(out List <Index> indicesToRemove, this.GetAllIndices().ToList());

            this.RemoveIndices(indicesToRemove);
            this.AddIndices(indices);

            return(anonymousObject);
        }
Beispiel #20
0
        /// <summary>
        /// Creates the starting AnonymousObjects for the database.
        /// </summary>
        /// <returns>Returns the starting AnonymousObjects for the database.</returns>
        public static List <AnonymousObject> GenerateStartingAnons()
        {
            List <AnonymousObject> startingAnons = new List <AnonymousObject>();

            AnonymousObject anon1 = new AnonymousObject();

            startingAnons.Add(anon1);
            anon1.Properties.Add(new Entities.KeyValuePair()
            {
                Key   = "key1",
                Value = "value1",
            });
            anon1.Properties.Add(new Entities.KeyValuePair()
            {
                Key   = "name",
                Value = "anon1",
            });

            return(startingAnons);
        }
        public static AnonymousObject DeserializeAnonymousObjectJson(JObject anonymousObjectJson)
        {
            AnonymousObject anon = new AnonymousObject();

            foreach (KeyValuePair <string, JToken> pair in anonymousObjectJson)
            {
                string key = pair.Key;
                if (pair.Value.Type == JTokenType.String)
                {
                    string value = (string)((JValue)pair.Value).Value;
                    anon.Add(key, value);
                }
                else if (pair.Value.Type == JTokenType.Object)
                {
                    anon.Add(DeserializeAnonymousObjectJson((JObject)pair.Value));
                }
            }

            return(anon);
        }
Beispiel #22
0
        public static async Task PrepareAsync(this IEventPublisher eventPublisher, string routeKey, object content, object metaData, IDbConnection dbConnection, IDbTransaction dbTransaction, string exchange = "default.exchange@feiniubus", object args = null)
        {
            var message = new DefaultMessage(content);

            var anonyObj     = new AnonymousObject(metaData);
            var anonyMembers = anonyObj.GetProperties().Where(member => member.MemberType == System.Reflection.MemberTypes.Property)
                               .Select(member => new { MemberName = member.MemberName, Value = anonyObj.GetValue(member.DeclaringType, member.MemberName) });

            if (anonyMembers.Any())
            {
                var md = new MetaData();
                foreach (var member in anonyMembers)
                {
                    md.Set(member.MemberName, member.Value.ToString());
                }
                message.MetaData.Contact(md);
            }

            await eventPublisher.PrepareAsync(new EventDescriptor(routeKey, message, exchange, args), dbConnection, dbTransaction);
        }
Beispiel #23
0
        public static void AddFieldIndices(
            this List <Index> indices,
            AnonymousObject anon,
            string fieldName,
            string fieldValueString)
        {
            string[] fieldValues = fieldValueString.ParseField();

            IDictionary <string, int> fieldValueCounts = AggregateFieldValueCounts(fieldValues);

            foreach (string fieldValue in fieldValueCounts.Keys)
            {
                Index newIndexToAdd = IndexExtensions.CreateNewIndex(fieldName, fieldValue);

                fieldValueCounts.TryGetValue(fieldValue, out int fieldValueCount);
                newIndexToAdd.InstanceCounts.Add(
                    InstanceCountExtensions.CreateInstanceCount(newIndexToAdd, anon, fieldValueCount));

                indices.Add(newIndexToAdd);
            }
        }
Beispiel #24
0
        public static AnonymousObject MapDocumentToAnonymousObject(this Document document)
        {
            AnonymousObject anon = new AnonymousObject
            {
                Id = document.Id
            };

            foreach (string fieldName in FieldsToIndex.Keys)
            {
                if (fieldName != "id")
                {
                    FieldsToIndex.TryGetValue(fieldName, out Func <Document, string> accessor);
                    anon.Properties.Add(new Entities.KeyValuePair()
                    {
                        Key   = fieldName,
                        Value = accessor(document),
                    });
                }
            }

            return(anon);
        }
Beispiel #25
0
        /*private static object ConvertFromInterLinqGrouping<TKey, TElement>(Type wantedType, InterLinqGrouping<TKey, TElement> grouping)
         * {
         *  Type[] genericArguments = wantedType.GetGenericArguments();
         *  object key = ConvertFromSerializable(genericArguments[0], grouping.Key);
         *
         *  MethodInfo method = typeof(TypeConverter).GetMethod("ConvertFromSerializableCollection", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(genericArguments[1]);
         *  object elements = method.Invoke(null, new object[] { grouping });
         *
         *  //object elements = ConvertFromSerializableCollection<TElement>( typeof( IEnumerable<> ).MakeGenericType( genericArguments[1] ),  );
         *  Type elementType = InterLinqTypeSystem.FindIEnumerable(elements.GetType());
         *  if (elementType == null)
         *  {
         *      throw new Exception("ElementType could not be found.");
         *  }
         *  Type[] genericTypes = new[] { key.GetType(), elementType.GetGenericArguments()[0] };
         *  InterLinqGroupingBase newGrouping = (InterLinqGroupingBase)Activator.CreateInstance(typeof(InterLinqGrouping<,>).MakeGenericType(genericTypes));
         *  newGrouping.SetKey(key);
         *  newGrouping.SetElements(elements);
         *  return newGrouping;
         * }*/

        /* /// <summary>
         * /// Converts each element of an <see cref="IEnumerable"/>
         * /// into a target <see cref="Type"/>.
         * /// </summary>
         * /// <typeparam name="T">Target <see cref="Type"/>.</typeparam>
         * /// <param name="enumerable"><see cref="IEnumerable"/>.</param>
         * /// <returns>Returns the converted <see cref="IEnumerable"/>.</returns>
         * private static IEnumerable ConvertFromSerializableCollection<T>(IEnumerable enumerable)
         * {
         *   Type enumerableType = typeof(List<>).MakeGenericType(typeof(T));
         *   IEnumerable newList = (IEnumerable)Activator.CreateInstance(enumerableType);
         *   MethodInfo addMethod = enumerableType.GetMethod("Add");
         *   foreach (object item in enumerable)
         *   {
         *       addMethod.Invoke(newList, new[] { ConvertFromSerializable(typeof(T), item) });
         *   }
         *   return newList;
         * }*/


        #endregion

        #region Convert C# Anonymous Type to AnonymousObject

        /// <summary>
        /// Converts an object to an <see cref="AnonymousObject"/>
        /// or an <see cref="IEnumerable{AnonymousObject}"/>.
        /// </summary>
        /// <param name="objectToConvert"><see langword="object"/> to convert.</param>
        /// <returns>Returns the converted <see langword="object"/>.</returns>
        public static object ConvertToSerializable(object objectToConvert)
        {
            if (objectToConvert == null)
            {
                return(null);
            }

            Type typeOfObject = objectToConvert.GetType();
            Type elementType  = InterLinqTypeSystem.FindIEnumerable(typeOfObject);

            // Handle "IGrouping<TKey, TElement>"
            if (typeOfObject.IsIGrouping())
            {
                Type[]     genericType = typeOfObject.GetGenericArguments();
                MethodInfo method      = typeof(TypeConverter).GetMethod("ConvertToInterLinqGrouping", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(genericType);
                return(method.Invoke(null, new[] { objectToConvert }));
            }
            // Handle "IEnumerable<AnonymousType>" / "IEnumerator<T>"
            if (elementType != null && elementType.GetGenericArguments()[0].IsAnonymous() || typeOfObject.IsEnumerator())
            {
                // ReSharper disable PossibleNullReferenceException
                MethodInfo method = typeof(TypeConverter).GetMethod("ConvertToSerializableCollection", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(elementType.GetGenericArguments()[0]);
                // ReSharper restore PossibleNullReferenceException
                return(method.Invoke(null, new[] { objectToConvert }));
            }
            // Handle "AnonymousType"
            if (typeOfObject.IsAnonymous())
            {
                AnonymousObject newObject = new AnonymousObject();
                foreach (PropertyInfo property in typeOfObject.GetProperties(BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public))
                {
                    object objectValue = ConvertToSerializable(property.GetValue(objectToConvert, new object[] { }));
                    newObject.Properties.Add(new AnonymousProperty(property.Name, objectValue));
                }
                return(newObject);
            }

            return(objectToConvert);
        }
Beispiel #26
0
        private IRTRequest HandleResult <T>(Object[] args, IDictionary <String, T> requestMap, String resultKey) where T : IRTRequest
        {
            if (args == null || args.Length < 1)
            {
                Log.log(Backendless.BACKENDLESSLOG, "subscription result is null or empty");
                return(null);
            }

            AnonymousObject result = (AnonymousObject)WeborbSerializationHelper.Deserialize((byte[])args[0]);

            String id = WeborbSerializationHelper.AsString(result, "id");

            Log.log(Backendless.BACKENDLESSLOG, String.Format("Got result for subscription {0}", id));

            IRTRequest request = requestMap[id];

            if (request == null)
            {
                Log.log(Backendless.BACKENDLESSLOG, String.Format("There is no handler for subscription {0}", id));
                return(null);
            }

            Object error = WeborbSerializationHelper.AsObject(result, "error");

            if (error != null)
            {
                Log.log(Backendless.BACKENDLESSLOG, String.Format("got error {0}", error));
                BackendlessFault fault = new BackendlessFault(error.ToString());
                request.Callback.errorHandler(fault);
                return(request);
            }

            IAdaptingType data = WeborbSerializationHelper.AsAdaptingType(result, resultKey);

            request.Callback.responseHandler(data);
            return(request);
        }
        // GET: AnonymousObjects/Details/5
        public IActionResult Details(Guid?id)
        {
            if (id == null)
            {
                return(this.NotFound());
            }

            AnonymousObject anonymousObject = this._repository.GetAnonymousObject((Guid)id);

            if (anonymousObject == null)
            {
                if (this._repository.DocumentExists((Guid)id))
                {
                    return(this.RedirectToAction("Details", "Documents", new
                    {
                        Id = id,
                    }));
                }

                return(this.NotFound());
            }

            return(this.View(anonymousObject));
        }
        internal static IAdaptingType AsAdaptingType(IAdaptingType obj, String key)
        {
            AnonymousObject anonymousObject = Cast(obj);

            return((IAdaptingType)anonymousObject.Properties[key]);
        }
Beispiel #29
0
    public SearchEngineMng(string currentUserIp,
                           HttpContext context,
                           string action)
    {
        _currentUserIp = currentUserIp;
        this.context   = context;
        currentR       = context.Request;
        currentS       = context.Server;
        mngInfo        = new TimeZoneManager(currentUserIp);

        string sLangId = context.Request.QueryString["li"];

        if (string.IsNullOrEmpty(sLangId))
        {
            isValid      = false;
            errorMessage = "You forgot langid (querystring li)";
        }

        // Convert langid querystring to int32
        if (!Int32.TryParse(sLangId, out currentLangId))
        {
            isValid      = false;
            errorMessage = "Problem with converting langauge ID (querystring li)";
        }

        if (context.Session["usi"] == null || action == "1")
        {
            // Create user default information
            usi.UserID        = (Guid)ANOProfile.GetCookieValues(currentUserIp, context).UserID;
            usi.UserIpAddress = currentUserIp;

            #region Set ints data (Get data by QueryStrings)

            var dataConvertToInts = new
            {
                clanSkillID       = (string)currentR.QueryString["cs"],
                clanContinentID   = (string)currentR.QueryString["cct"],
                clanCountryID     = (string)currentR.QueryString["cc"],
                searchContinentID = (string)currentR.QueryString["sct"],
                searchCountryID   = (string)currentR.QueryString["sc"],
                searchGameID      = (string)currentR.QueryString["sg"],
                searchGameModeID  = (string)currentR.QueryString["sgt"],
                searchXvs         = (string)currentR.QueryString["sxv"],
                searchvsX         = (string)currentR.QueryString["svx"]
            }.ToAnonymousObjectCollection();

            int MaxIntValue = int.MaxValue;
            var intdata     = new
            {
                clanSkillID       = (int?)null,
                clanContinentID   = (int)MaxIntValue,
                clanCountryID     = (int)MaxIntValue,
                searchContinentID = (int)MaxIntValue,
                searchCountryID   = (int?)null,
                searchGameID      = (int)MaxIntValue,
                searchGameModeID  = (int?)null,
                searchXvs         = (int?)null,
                searchvsX         = (int?)null,
                searchYearFrom    = (int)MaxIntValue,
                searchDayFrom     = (int)MaxIntValue,
                searchMonthFrom   = (int)MaxIntValue,
                searchHourFrom    = (int)MaxIntValue,
                searchMinutesFrom = (int)MaxIntValue,
            }.ToAnonymousObjectCollection();

            #endregion

            #region validate and convert properties to ints

            for (int i = 0; i < dataConvertToInts.Count; i++)
            {
                AnonymousObject o = dataConvertToInts.GetAnonymousObject(i);

                if (!string.IsNullOrEmpty(o.GetValue <string>()))
                {
                    int result;
                    if (int.TryParse(o.GetValue <string>(), out result))
                    {
                        intdata.GetAnonymousObject(o.KeyName).SetValue(result);
                    }
                }

                if (intdata.GetAnonymousObject(o.KeyName).GetValue_UnknownObject() != null
                    &&
                    Convert.ToInt32(intdata.GetAnonymousObject(o.KeyName).GetValue_UnknownObject()) == MaxIntValue)
                {
                    isValid      = false;
                    errorMessage = "'" + o.KeyName +
                                   "' much be more than empty";
                }
            }

            #endregion

            #region Set strings data (convert to HtmlEncode strings)

            var stringData = new
            {
                ClanName  = (string)currentS.HtmlEncode(currentS.UrlDecode(currentR.QueryString["cn"])),
                SearchMap = (string)currentS.HtmlEncode(currentS.UrlDecode(currentR.QueryString["sm"])),
            };

            #endregion

            #region Set datetime data (Replace + and . (This chars is used to avoid problems))

            if (string.IsNullOrEmpty(currentR.QueryString["sfd"]))
            {
                isValid      = false;
                errorMessage = "'SearchMatchStart' much be more than empty";
            }
            else
            {
                var datetimeData = new
                {
                    SearchMatchStart = (DateTime)DateTime.ParseExact(currentS.UrlDecode(currentR.QueryString["sfd"]), "dd-MM-yyyy HH:mm:ss", new DateTimeFormatInfo())
                };

                #endregion

                // Edit/Create user search information
                usi.ClanName          = stringData.ClanName;
                usi.ClanSkillID       = intdata.GetAnonymousObject("clanSkillID").GetValue <int?>();
                usi.ClanContinentID   = intdata.GetAnonymousObject("clanContinentID").GetValue <int>();
                usi.ClanCountryID     = intdata.GetAnonymousObject("clanCountryID").GetValue <int>();
                usi.SearchContinentID = intdata.GetAnonymousObject("searchContinentID").GetValue <int>();
                usi.SearchCountryID   = intdata.GetAnonymousObject("searchCountryID").GetValue <int?>();
                usi.SearchGameID      = intdata.GetAnonymousObject("searchGameID").GetValue <int>();
                usi.SearchGameModeID  = intdata.GetAnonymousObject("searchGameModeID").GetValue <int?>();
                usi.SearchMap         = stringData.SearchMap;
                usi.SearchXvs         = intdata.GetAnonymousObject("searchXvs").GetValue <int>();
                usi.SearchvsX         = intdata.GetAnonymousObject("searchvsX").GetValue <int>();
                usi.SearchMatchStart  = new TimeZoneManager(currentUserIp).ConvertDateTimeToUtc(datetimeData.SearchMatchStart);

                userOption             = SearchWar.SearchEngine.SearchEngine.UserSearchOption.CreateUserSearch;
                context.Session["usi"] = usi;
            }
        }
        else
        {
            usi = (UserSearchInfo)context.Session["usi"];
        }

        if (isValid == true)
        {
            LangaugeSystem ls      = new LangaugeSystem();
            string         getLang = ls.GetLang(Convert.ToInt32(sLangId)).LangShortname;
            Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(getLang);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(getLang);
        }
    }
        /// <summary>
        /// Converts an object to an <see cref="AnonymousObject"/>
        /// or an <see cref="IEnumerable{AnonymousObject}"/>.
        /// </summary>
        /// <param name="objectToConvert"><see langword="object"/> to convert.</param>
        /// <returns>Returns the converted <see langword="object"/>.</returns>
        public static object ConvertToSerializable(object objectToConvert)
        {
            if (objectToConvert == null)
            {
                return(null);
            }

            Type typeOfObject = objectToConvert.GetType();
            Type elementType  = InterLinqTypeSystem.FindIEnumerable(typeOfObject);

            // Handle "IGrouping<TKey, TElement>"
            if (typeOfObject.IsIGrouping())
            {
#if !NETFX_CORE
                Type[] genericType = typeOfObject.GetGenericArguments();
#else
                Type[] genericType = typeOfObject.GetTypeInfo().GenericTypeArguments;
#endif
#if !SILVERLIGHT
                MethodInfo method = typeof(TypeConverter).GetMethod("ConvertToInterLinqGrouping", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(genericType);
#else
#if !NETFX_CORE
                MethodInfo method = typeof(TypeConverter).GetMethod("ConvertToInterLinqGrouping", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(genericType);
#else
                MethodInfo method = typeof(TypeConverter).GetTypeInfo().GetDeclaredMethod("ConvertToInterLinqGrouping").MakeGenericMethod(genericType);
#endif
#endif
                return(method.Invoke(null, new[] { objectToConvert }));
            }

            // Handle "IGrouping<TKey, TElement>[]"
            if (typeOfObject.IsIGroupingArray())
            {
#if !NETFX_CORE
                Type[] genericType = typeOfObject.GetGenericArguments();
#else
                Type[] genericType = typeOfObject.GetTypeInfo().GenericTypeArguments;
#endif
#if !SILVERLIGHT
                MethodInfo method = typeof(TypeConverter).GetMethod("ConvertToInterLinqGroupingArray", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(genericType);
#else
#if !NETFX_CORE
                MethodInfo method = typeof(TypeConverter).GetMethod("ConvertToInterLinqGroupingArray", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(genericType);
#else
                MethodInfo method = typeof(TypeConverter).GetTypeInfo().GetDeclaredMethod("ConvertToInterLinqGroupingArray").MakeGenericMethod(genericType);
#endif
#endif
                return(method.Invoke(null, new[] { objectToConvert }));
            }

            // Handle "IEnumerable<AnonymousType>" / "IEnumerator<T>"
#if !NETFX_CORE
            if (elementType != null && elementType.GetGenericArguments()[0].IsAnonymous() || typeOfObject.IsEnumerator())
#else
            if (elementType != null && elementType.GetTypeInfo().GenericTypeArguments[0].IsAnonymous() || typeOfObject.IsEnumerator())
#endif
            {
#if !SILVERLIGHT
                MethodInfo method = typeof(TypeConverter).GetMethod("ConvertToSerializableCollection", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(elementType.GetGenericArguments()[0]);
#else
#if !NETFX_CORE
                MethodInfo method = typeof(TypeConverter).GetMethod("ConvertToSerializableCollection", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType.GetGenericArguments()[0]);
#else
                MethodInfo method = typeof(TypeConverter).GetTypeInfo().GetDeclaredMethod("ConvertToSerializableCollection").MakeGenericMethod(elementType.GetTypeInfo().GenericTypeArguments[0]);
#endif
#endif
                return(method.Invoke(null, new[] { objectToConvert }));
            }
            // Handle "AnonymousType"
            if (typeOfObject.IsAnonymous())
            {
                AnonymousObject newObject = new AnonymousObject();
#if !NETFX_CORE
                foreach (PropertyInfo property in typeOfObject.GetProperties(BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public))
#else
                foreach (PropertyInfo property in typeOfObject.GetTypeInfo().DeclaredProperties)
#endif
                {
                    object objectValue = ConvertToSerializable(property.GetValue(objectToConvert, new object[] { }));
                    newObject.Properties.Add(new AnonymousProperty(property.Name, objectValue));
                }
                return(newObject);
            }

            return(objectToConvert);
        }