Exemplo n.º 1
0
        public async Task <IList <PermissionRoleModel> > GetAllUserPermissionsWithRolesAsync(long userId)
        {
            var user = await SmartHomeAppDbContext.SingleAsync <User>(userId);

            var userPermissions = await SmartHomeAppDbContext.Query <UserPermission>()
                                  .Where(x => x.UserId == userId)
                                  .ProjectTo <PermissionRoleModel>(Mapper.ConfigurationProvider)
                                  .ToListAsync();

            var rolesStrings = (List <string>) await userManager.GetRolesAsync(user);

            var rolePermissions = await SmartHomeAppDbContext.Query <RolePermission>()
                                  .Where(x => rolesStrings.Contains(x.Role.Name))
                                  .ProjectTo <PermissionRoleModel>(Mapper.ConfigurationProvider)
                                  .ToListAsync();

            var comparer = EqualityComparerFactory.Create <PermissionRoleModel>(
                x => (int)x.PermissionId,
                (x, y) => x.PermissionId == y.PermissionId && string.Equals(x.RoleName, y.RoleName));
            var resultPermissions = userPermissions.Union(rolePermissions, comparer);

            resultPermissions = resultPermissions.OrderBy(x => x.PermissionName);

            return(resultPermissions.ToList());
        }
Exemplo n.º 2
0
        public bool Exists(User user)
        {
            //Get(user.Id);
            IEqualityComparer <User> userComparer = EqualityComparerFactory <User> .Create((user_a, user_b) => user_a.Username == user_b.Username, (_user) => _user.GetHashCode());

            return(dbset.ToList().Contains(user, userComparer));
        }
Exemplo n.º 3
0
        private static IList <T> MergeLists <T, TE>(IEnumerable <T> first, IEnumerable <T> second, Func <T, TE> selection)
        {
            var comparer = EqualityComparerFactory <T>
                           .CreateComparer(x => selection(x).GetHashCode(), (x, y) => x != null && x.Equals(y));

            var list = new List <T>();



            if (second != null && first != null)
            {
                list.AddRange(first.Where(x => !second.Contains(x, comparer)));
                list.AddRange(second);
            }
            else
            {
                if (first != null)
                {
                    list.AddRange(first);
                }
                if (second != null)
                {
                    list.AddRange(second);
                }
            }

            return(list);
        }
 private Transformation(IQuery query)
 {
     _query = query;
     _repositoryFactory = new VerifiableRepositoryFactory();
     _metadataSource = new AggregateConstructionMetadataSource();
     _comparerFactory = new EqualityComparerFactory(new LinqToDbPropertyProvider(Schema.Erm, Schema.Facts, Schema.CustomerIntelligence));
 }
Exemplo n.º 5
0
        /// <summary>
        /// Probes working directory for all available metadata providers
        /// </summary>
        /// <returns>List of UWP XAML metadata providers</returns>
        internal static IEnumerable <WUX.Markup.IXamlMetadataProvider> DiscoverMetadataProviders()
        {
            // Get all assemblies loaded in app domain and placed side-by-side from all DLL and EXE
            var loadedAssemblies = GetAssemblies();

#if NET462
            var uniqueAssemblies = new HashSet <Assembly>(loadedAssemblies, EqualityComparerFactory <Assembly> .CreateComparer(
                                                              a => a.GetName().FullName.GetHashCode(),
                                                              (a, b) => a.GetName().FullName.Equals(b.GetName().FullName, StringComparison.OrdinalIgnoreCase)));
#else
            var uniqueAssemblies = new HashSet <Assembly>(loadedAssemblies, EqualityComparerFactory <Assembly> .CreateComparer(
                                                              a => a.GetName().FullName.GetHashCode(StringComparison.InvariantCulture),
                                                              (a, b) => a.GetName().FullName.Equals(b.GetName().FullName, StringComparison.OrdinalIgnoreCase)));
#endif

            // Load all types loadable from the assembly, ignoring any types that could not be resolved due to an issue in the dependency chain
            foreach (var assembly in uniqueAssemblies)
            {
                foreach (var provider in LoadTypesFromAssembly(assembly))
                {
                    yield return(provider);

                    if (typeof(WUX.Application).IsAssignableFrom(provider.GetType()))
                    {
                        System.Diagnostics.Debug.WriteLine("Xaml application has been created");
                        yield break;
                    }
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Probes working directory for all available metadata providers
        /// </summary>
        /// <returns>List of UWP XAML metadata providers</returns>
        internal static List <WUX.Markup.IXamlMetadataProvider> DiscoverMetadataProviders()
        {
            var filteredTypes = FilteredTypes;

            // List of discovered UWP XAML metadata providers
            var metadataProviders = new List <WUX.Markup.IXamlMetadataProvider>();

            // Get all assemblies loaded in app domain and placed side-by-side from all DLL and EXE
            var loadedAssemblies = GetAssemblies();

#if NET462
            var uniqueAssemblies = new HashSet <Assembly>(loadedAssemblies, EqualityComparerFactory <Assembly> .CreateComparer(
                                                              a => a.GetName().FullName.GetHashCode(),
                                                              (a, b) => a.GetName().FullName.Equals(b.GetName().FullName, StringComparison.OrdinalIgnoreCase)));
#else
            var uniqueAssemblies = new HashSet <Assembly>(loadedAssemblies, EqualityComparerFactory <Assembly> .CreateComparer(
                                                              a => a.GetName().FullName.GetHashCode(StringComparison.InvariantCulture),
                                                              (a, b) => a.GetName().FullName.Equals(b.GetName().FullName, StringComparison.OrdinalIgnoreCase)));
#endif

            // Load all types loadable from the assembly, ignoring any types that could not be resolved due to an issue in the dependency chain
            foreach (var assembly in uniqueAssemblies)
            {
                try
                {
                    LoadTypesFromAssembly(assembly, ref metadataProviders, ref filteredTypes);
                }
                catch (FileLoadException)
                {
                    // These exceptions are expected
                }
            }

            return(metadataProviders);
        }
        public DatabaseEntity CreateEmptyEntity(DatabaseTableDefinitionJson definition, DatabaseKey key, bool phantomEntity)
        {
            Dictionary <string, IDatabaseField> columns = new(StringComparer.InvariantCultureIgnoreCase);

            foreach (var column in definition.Groups.SelectMany(t => t.Fields)
                     .Distinct(
                         EqualityComparerFactory.Create <DatabaseColumnJson>(
                             f => f.DbColumnName.GetHashCode(),
                             (a, b) => a !.DbColumnName.Equals(b !.DbColumnName))))
            {
                IValueHolder valueHolder;
                var          type = column.ValueType;

                if (parameterFactory.IsRegisteredLong(type))
                {
                    type = "uint";
                }
                else if (parameterFactory.IsRegisteredString(type))
                {
                    type = "string";
                }
                else if (type.EndsWith("Parameter"))
                {
                    type = "uint";
                }

                if (type == "float")
                {
                    valueHolder = new ValueHolder <float>(column.Default is float f ? f : 0.0f, column.CanBeNull && column.Default == null);
                }
                else if (type is "int" or "uint" or "long")
                {
                    valueHolder = new ValueHolder <long>(column.Default is long f ? f : 0, column.CanBeNull && column.Default == null);
                }
 public static IImmutableSession WithRegexComparer(this IImmutableSession context)
 {
     return(context.WithComparer(GetComparerNameFromCaller(), EqualityComparerFactory <object> .Create
                                 (
                                     equals: (left, right) => Regex.IsMatch((string)right, (string)left, RegexOptions.None),
                                     getHashCode: (obj) => 0
                                 )));
 }
Exemplo n.º 9
0
 private Transformation(IQuery query, IRepositoryFactory repositoryFactory)
 {
     _query             = query;
     _repositoryFactory = repositoryFactory;
     _operations        = new List <IOperation>();
     _metadataSource    = new FactsReplicationMetadataSource();
     _comparerFactory   = new EqualityComparerFactory(new LinqToDbPropertyProvider(Schema.Erm, Schema.Facts, Schema.CustomerIntelligence));
 }
Exemplo n.º 10
0
 public static IImmutableSession WithSoftStringComparer(this IImmutableSession context)
 {
     return(context.WithComparer(GetComparerNameFromCaller(), EqualityComparerFactory <object> .Create
                                 (
                                     equals: (left, right) => SoftString.Comparer.Equals((string)left, (string)right),
                                     getHashCode: (obj) => SoftString.Comparer.GetHashCode((string)obj)
                                 )));
 }
        private ProjectionGatewayConfigurationBuilder(ILocator locator)
        {
            _locator = locator;
            var stringEqComparer = EqualityComparerFactory.Create <string>(
                (x, y) => x.ToLower() == y.ToLower(),
                s => s.GetHashCode());

            Subscriptions = new MultiValueDictionary <string, Subscription>(stringEqComparer);
        }
Exemplo n.º 12
0
        private bool ProcessMultipartData(ref IDictionary <string, string> postVars, ref IDictionary <string, IFile> files)
        {
            bool?result = null;

            try
            {
                var match = _REGEX_MULTIPART_BOUNDARY.Match(this.ContentType ?? string.Empty);
                if (match.Success)
                {
                    postVars = new ConcurrentDictionary <string, string>(EqualityComparerFactory.CreateHttpKeyComparer());
                    files    = new ConcurrentDictionary <string, IFile>(EqualityComparerFactory.CreateHttpKeyComparer());

                    var parser = new HttpMultipartContentParser(this.GetBodyData(),
                                                                Encoding.ASCII.GetBytes("--" + match.Groups[9].Value));

                    foreach (var part in parser.PARTS
                             .Where(p => !string.IsNullOrWhiteSpace(p.NAME)))
                    {
                        try
                        {
                            var data = part.DATA ?? new byte[0];

                            if (string.IsNullOrWhiteSpace(part.FILE_NAME))
                            {
                                // POST data

                                postVars[part.NAME] = Encoding.ASCII.GetString(data);
                            }
                            else
                            {
                                // uploaded file
                                var newFile = new SimpleFile();
                                newFile.SetContentType(string.IsNullOrWhiteSpace(part.CONTENT_TYPE) ? "application/octet-stream" : part.CONTENT_TYPE.ToLower().Trim());
                                newFile.Name = part.FILE_NAME.Trim();
                                newFile.SetData(data);

                                files[part.NAME] = newFile;
                            }
                        }
                        catch
                        {
                            // ignore
                        }
                    }

                    parser = null;
                    result = true;
                }
            }
            catch
            {
                // ignore
            }

            return(result ?? false);
        }
Exemplo n.º 13
0
        public Store()
        {
            var data = new HashSet <object>();

            EqualityComparerFactory = new EqualityComparerFactory(new LinqToDbPropertyProvider(Schema.Erm, Schema.Facts, Schema.Aggregates));

            Query             = new StoreQuery(data);
            Builder           = new StoreBuilder(data);
            RepositoryFactory = new StoreRepositoryFactory(data, EqualityComparerFactory);
        }
        private static IStatisticsProcessor StatisticsProcessor <T>(object[] data, out Mock <IRepository <T> > repository)
            where T : class
        {
            var metadataSource = new StatisticsRecalculationMetadataSource();
            var metadata       = metadataSource.Metadata.Values.SelectMany(x => x.Elements).OfType <StatisticsRecalculationMetadata <T, StatisticsKey> >().Single();

            repository = new Mock <IRepository <T> >();
            var comparerFactory = new EqualityComparerFactory(new LinqToDbPropertyProvider(Schema.Erm, Schema.Facts, Schema.CustomerIntelligence));

            return(new StatisticsProcessor <T>(metadata, new MemoryMockQuery(data), new BulkRepository <T>(repository.Object), comparerFactory));
        }
Exemplo n.º 15
0
 public XMerge(IEnumerable <KeyValuePair <string, string> > keyMap)
 {
     _keyMap = keyMap.ToDictionary(
         x => x.Key.Split('/'),
         x => new Func <XElement, string>(e => e.Attribute(x.Value).Value),
         EqualityComparerFactory <IEnumerable <string> > .Create(
             (left, right) => left.SequenceEqual(right),
             (obj) => obj.CalcHashCode()
             )
         );
 }
Exemplo n.º 16
0
        public static void AddUserSkillIfDoesNotExist(User dbUser, Skill userSkill)
        {
            // Update user if programming skill is missing
            IEqualityComparer <Skill> compareSkills = EqualityComparerFactory <Skill> .Create((s1, s2) => s1.Type == s2.Type, s => s.GetHashCode());

            if (!dbUser.Skill.ToList().Contains(userSkill, compareSkills))
            {
                Console.WriteLine($"dbUser does not contain skill: { userSkill }");
                dbUser.Skill.Add(userSkill);
            }
        }
        public DatabaseEntity CreateEmptyEntity(DatabaseTableDefinitionJson definition, uint key)
        {
            Dictionary <string, IDatabaseField> columns = new();

            foreach (var column in definition.Groups.SelectMany(t => t.Fields)
                     .Distinct(
                         EqualityComparerFactory.Create <DatabaseColumnJson>(
                             f => f.DbColumnName.GetHashCode(),
                             (a, b) => a !.DbColumnName.Equals(b !.DbColumnName))))
            {
                IValueHolder valueHolder;
                var          type = column.ValueType;

                if (parameterFactory.IsRegisteredLong(type))
                {
                    type = "uint";
                }
                else if (parameterFactory.IsRegisteredString(type))
                {
                    type = "string";
                }
                else if (type.EndsWith("Parameter"))
                {
                    type = "uint";
                }

                if (type == "float")
                {
                    valueHolder = new ValueHolder <float>(column.Default is float f ? f : 0.0f, column.CanBeNull && column.Default == null);
                }
                else if (type == "int" || type == "uint")
                {
                    if (column.DbColumnName == definition.TablePrimaryKeyColumnName)
                    {
                        valueHolder = new ValueHolder <long>(key, false);
                    }
                    else
                    {
                        valueHolder = new ValueHolder <long>(column.Default is long f ? f : 0, column.CanBeNull && column.Default == null);
                    }
                }
                else
                {
                    valueHolder = new ValueHolder <string>(column.Default is string f ? f : "", column.CanBeNull && column.Default == null);
                }


                columns[column.DbColumnName] = databaseFieldFactory.CreateField(column.DbColumnName, valueHolder);
            }

            return(new DatabaseEntity(false, key, columns, null));
        }
Exemplo n.º 18
0
        public Wallet(IEnumerable <Coin> coins)
        {
            Contract.Requires(coins != null);

            var coinEqualityComparer = EqualityComparerFactory.Create <Coin>(
                (c1, c2) => c1.ParValue == c2.ParValue,
                c => c.ParValue.GetHashCode());

            _coins = coins
                     .GroupBy(c => c.ParValue)
                     .Select(c => c.Aggregate(0, (i, coin) => i + coin.Count, count => new Coin(c.Key, count)))
                     .ToImmutableHashSet(coinEqualityComparer);
        }
        public void GetHashCodeShouldBeEqaulToResharperGenerated(int id, int? nullable, string name)
        {
            var provider = new Mock<IObjectPropertyProvider>();
            var props = typeof(SampleEntity).GetProperties();
            provider.Setup(x => x.GetProperties<SampleEntity>()).Returns(props);
            provider.Setup(x => x.GetPrimaryKeyProperties<SampleEntity>()).Returns(new List<PropertyInfo>());

            var factory = new EqualityComparerFactory(provider.Object);
            var comparer = factory.CreateCompleteComparer<SampleEntity>();

            var left = new SampleEntity { Id = id, NullableId = nullable, Name = name };

            Assert.That(comparer.GetHashCode(left), Is.EqualTo(left.GetHashCode()));
        }
Exemplo n.º 20
0
        public void GetHashCodeShouldBeEqaulToResharperGenerated(int id, int?nullable, string name)
        {
            var provider = new Mock <IObjectPropertyProvider>();
            var props    = typeof(SampleEntity).GetProperties();

            provider.Setup(x => x.GetProperties <SampleEntity>()).Returns(props);
            provider.Setup(x => x.GetPrimaryKeyProperties <SampleEntity>()).Returns(new List <PropertyInfo>());

            var factory  = new EqualityComparerFactory(provider.Object);
            var comparer = factory.CreateCompleteComparer <SampleEntity>();

            var left = new SampleEntity {
                Id = id, NullableId = nullable, Name = name
            };

            Assert.That(comparer.GetHashCode(left), Is.EqualTo(left.GetHashCode()));
        }
Exemplo n.º 21
0
        public BagOfGoods(IEnumerable <Goods> goods)
        {
            Contract.Requires(goods != null);

            var goodsEqualityComparer = EqualityComparerFactory.Create <Goods>(
                (g1, g2) => g1.Identity.Equals(g2.Identity) && g1.Price == g2.Price,
                g => g.Identity.GetHashCode()
                );

            _bag = goods
                   .GroupBy(g => new { g.Identity, g.Price })
                   .Select(g => g.Aggregate(
                               default(int),
                               (count, nextGoods) => count + nextGoods.Count,
                               c => new Goods(g.Key.Identity, g.Key.Price, c)))
                   .ToHashSet(goodsEqualityComparer);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Handles a job item.
        /// </summary>
        /// <param name="ctx">The underlying item context.</param>
        protected virtual void HandleJobItem(IForAllItemExecutionContext <IJob, DateTimeOffset> ctx)
        {
            List <Exception> occuredErrors = new List <Exception>();

            DateTimeOffset      completedAt;
            JobExecutionContext execCtx = new JobExecutionContext();

            try
            {
                execCtx.Job        = ctx.Item;
                execCtx.ResultVars = new Dictionary <string, object>(EqualityComparerFactory.CreateCaseInsensitiveStringComparer(true, true));
                execCtx.SyncRoot   = new object();
                execCtx.Time       = ctx.State;

                execCtx.Job
                .Execute(execCtx);

                completedAt = AppTime.Now;
            }
            catch (Exception ex)
            {
                completedAt = AppTime.Now;

                AggregateException aggEx = ex as AggregateException;
                if (aggEx != null)
                {
                    occuredErrors.AddRange(CollectionHelper.OfType <Exception>(aggEx.InnerExceptions));
                }
                else
                {
                    occuredErrors.Add(ex);
                }
            }

            JobExecutionResult result = new JobExecutionResult();

            result.Context = execCtx;
            result.Errors  = occuredErrors.ToArray();
            result.Vars    = new TMReadOnlyDictionary <string, object>(execCtx.ResultVars);
            result.Time    = completedAt;

            this.RaiseEventHandler(this.Executed,
                                   new JobExecutionResultEventArgs(result));
        }
Exemplo n.º 23
0
        // Private Methods (3) 

        private static IDictionary <string, string> ExtractVarsFromQueryString(IEnumerable <char> queryStr)
        {
            var result = new ConcurrentDictionary <string, string>(EqualityComparerFactory.CreateHttpKeyComparer());

            try
            {
                var coll = BclHttpUtility.ParseQueryString(queryStr.AsString() ?? string.Empty);
                foreach (var key in coll.AllKeys)
                {
                    result[key ?? string.Empty] = coll[key];
                }
            }
            catch
            {
                // ignore
            }

            return(result);
        }
        public void EqualityShouldRespectProvidedComparers(int idLeft, int idRight, bool expected)
        {
            var provider = new Mock <IObjectPropertyProvider>();
            var props    = typeof(SampleEntity).GetProperties();

            provider.Setup(x => x.GetProperties <SampleEntity>()).Returns(props);
            provider.Setup(x => x.GetPrimaryKeyProperties <SampleEntity>()).Returns(new List <PropertyInfo>());

            var factory  = new EqualityComparerFactory(provider.Object, new CustomIntegerComparer());
            var comparer = factory.CreateCompleteComparer <SampleEntity>();

            var left = new SampleEntity {
                Id = idLeft
            };
            var right = new SampleEntity {
                Id = idRight
            };

            Assert.AreEqual(expected, comparer.GetHashCode(left) == comparer.GetHashCode(right));
            Assert.AreEqual(expected, comparer.Equals(left, right));
        }
Exemplo n.º 25
0
 /// <summary>
 /// Creates an empty collection for parameters.
 /// </summary>
 /// <returns>The created collection.</returns>
 protected virtual IDictionary <string, object> CreateEmptyParameterCollection()
 {
     return(new Dictionary <string, object>(EqualityComparerFactory.CreateCaseInsensitiveStringComparer(true, true)));
 }
Exemplo n.º 26
0
        /// <summary>
        /// Adds, removes and updates contacts, groups, masages
        /// </summary>
        /// <param name="syncData"></param>
        public static async Task SyncData()
        {
            if (!ServerConnected)
            {
                return;
            }

            await Task.Run(() =>
            {
                var res = commandChain.MakeRequest(CommandType.Synchronize, null, User);

                if (res == null)
                {
                    return;
                }

                //Update user
                if (User.LastTimeUpdated != res.UserData.LastTimeUpdated)
                {
                    User = res.UserData;
                }

                var syncData = (object[])res.RequestData;

                var groupsInfo   = (List <Group>)syncData[0];
                var contactsInfo = (List <Contact>)syncData[1];
                var messagesInfo = (List <Message>)syncData[2];

                //Find differences in Last Time Update and update if necessary
                foreach (var group in groupsInfo)
                {
                    var foundGroup = Database.GroupsTableRepo.FindFirst(GroupsTableFields.Id.ToString(), group.Id.ToString());

                    if (foundGroup == null)
                    {
                        Database.GroupsTableRepo.Add(group);
                        continue;
                    }


                    if (foundGroup.LastTimeUpdated != group.LastTimeUpdated)
                    {
                        Database.GroupsTableRepo.Update(GroupsTableFields.Id.ToString(), group.Id.ToString(), group);
                    }
                }

                foreach (var contact in contactsInfo)
                {
                    var foundContact = Database.ContactsTableRepo.FindFirst(ContactsTableFields.Id.ToString(), contact.Id.ToString());

                    if (foundContact == null)
                    {
                        Database.ContactsTableRepo.Add(contact);
                        continue;
                    }

                    if (foundContact.LastTimeUpdated != contact.LastTimeUpdated)
                    {
                        Database.ContactsTableRepo.Update(ContactsTableFields.Id.ToString(), contact.Id.ToString(), contact);
                    }
                }

                foreach (var message in messagesInfo)
                {
                    var foundMessage = Database.MessagesTableRepo.FindFirst(MessagesTableFields.Id.ToString(), message.Id.ToString());

                    if (foundMessage == null)
                    {
                        Database.MessagesTableRepo.Add(message);
                        continue;
                    }

                    if (foundMessage.LastTimeUpdated != message.LastTimeUpdated)
                    {
                        Database.MessagesTableRepo.Update(MessagesTableFields.Id.ToString(), message.Id.ToString(), message);
                    }
                }

                #region Create custom comparers

                //Create comparers
                var groupsComparer = EqualityComparerFactory.Create <Group>(
                    (Group a) => a.Id.GetHashCode(),
                    (Group a, Group b) => a.Id == b.Id
                    );

                var contactsComparer = EqualityComparerFactory.Create <Contact>(
                    (Contact a) => a.Id.GetHashCode(),
                    (Contact a, Contact b) => a.Id == b.Id
                    );
                var messagesComparer = EqualityComparerFactory.Create <Message>(
                    (Message a) => a.Id.GetHashCode(),
                    (Message a, Message b) => a.Id == b.Id
                    );

                #endregion

                //Delete
                var deletedGroups   = Database.GroupsTableRepo.GetAll()?.Except(groupsInfo, groupsComparer);
                var deletedContacts = Database.ContactsTableRepo.GetAll()?.Except(contactsInfo, contactsComparer);
                var deletedMessages = Database.MessagesTableRepo.GetAll()?.Except(messagesInfo, messagesComparer);

                if (deletedGroups != null)
                {
                    foreach (var group in deletedGroups)
                    {
                        Database.GroupsTableRepo.Remove(GroupsTableFields.Id.ToString(), group.Id.ToString());
                    }
                }

                if (deletedContacts != null)
                {
                    foreach (var contact in deletedContacts)
                    {
                        Database.ContactsTableRepo.Remove(GroupsTableFields.Id.ToString(), contact.Id.ToString());
                    }
                }

                if (deletedMessages != null)
                {
                    foreach (var message in deletedMessages)
                    {
                        Database.MessagesTableRepo.Remove(GroupsTableFields.Id.ToString(), message.Id.ToString());
                    }
                }
            });
        }
Exemplo n.º 27
0
        internal HttpRequest(DateTimeOffset time,
                             HttpRequestMessageProperty property,
                             Message message,
                             WcfHttpServer server)
        {
            this._TIME     = time;
            this._PROPERTY = property;
            this._MESSAGE  = message;
            this._SERVER   = server;

            this._METHOD = (this._PROPERTY.Method ?? string.Empty).ToUpper().Trim();
            if (this._METHOD == string.Empty)
            {
                this._METHOD = null;
            }

            this._BODY = new Lazy <byte[]>(valueFactory: this.GetBodyDataInner,
                                           isThreadSafe: true);

            //  address of remote client
            try
            {
                var messageProperties = OperationContext.Current.IncomingMessageProperties;
                var endpointProperty  = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

                this._REMOTE_ADDRESS = new SimpleTcpAddress()
                {
                    Address = endpointProperty.Address,
                    Port    = endpointProperty.Port,
                };
            }
            catch
            {
                // ignore here
            }

            // requesting user
            try
            {
                ServiceSecurityContext context = ServiceSecurityContext.Current;
                if (context != null)
                {
                    var finder = this._SERVER.PrincipalFinder;
                    if (finder != null)
                    {
                        this._USER = finder(context.PrimaryIdentity);
                    }
                }
            }
            catch
            {
                // ignore here
            }

            // request headers
            {
                var headers = new ConcurrentDictionary <string, string>(EqualityComparerFactory.CreateHttpKeyComparer());
                foreach (var key in this._PROPERTY.Headers.AllKeys)
                {
                    headers[key] = this._PROPERTY.Headers[key];
                }

                this._HEADERS = new TMReadOnlyDictionary <string, string>(headers);
            }

            // content type
            this._HEADERS
            .TryGetValue("content-type",
                         out this._CONTENT_TYPE);
            if (string.IsNullOrWhiteSpace(this._CONTENT_TYPE))
            {
                this._CONTENT_TYPE = null;
            }
            else
            {
                this._CONTENT_TYPE = this._CONTENT_TYPE.ToLower().Trim();
            }

            // GET
            this._GET = new TMReadOnlyDictionary <string, string>(ExtractVarsFromQueryString(this._PROPERTY.QueryString));

            // POST
            {
                IDictionary <string, string> postVars = null;
                IDictionary <string, IFile>  files    = null;

                if (this.TryGetKnownMethod() == HttpMethod.POST)
                {
                    try
                    {
                        if (!this.ProcessMultipartData(ref postVars, ref files))
                        {
                            // no uploaded files, handle complete
                            // request body as variables

                            using (var reader = new StreamReader(this.GetBody(), Encoding.ASCII))
                            {
                                postVars = ExtractVarsFromQueryString(reader.ReadToEnd());
                            }
                        }
                    }
                    catch
                    {
                        // ignore
                    }
                }

                this._POST = new TMReadOnlyDictionary <string, string>(postVars ??
                                                                       new ConcurrentDictionary <string, string>(EqualityComparerFactory.CreateHttpKeyComparer()));

                this._FILES = new TMReadOnlyDictionary <string, IFile>(files ??
                                                                       new ConcurrentDictionary <string, IFile>(EqualityComparerFactory.CreateHttpKeyComparer()));
            }

            // REQUEST
            {
                var vars = new ConcurrentDictionary <string, string>(EqualityComparerFactory.CreateHttpKeyComparer());

                // first copy GET
                foreach (var g in this._GET)
                {
                    vars[g.Key] = g.Value;
                }

                // then set POST vars and overwrite existing ones
                foreach (var p in this._POST)
                {
                    vars[p.Key] = p.Value;
                }

                this._REQUEST = new TMReadOnlyDictionary <string, string>(vars);
            }
        }
Exemplo n.º 28
0
 public static bool SequenceEqual <T>(IEnumerable <T> first, IEnumerable <T> second, Func <T?, T?, bool> equalizer)
 {
     return(Enumerable.SequenceEqual(first, second, EqualityComparerFactory.Create <T>((t) => t?.GetHashCode() ?? 0, equalizer)));
 }
 public Factory(IQuery query, IRepositoryFactory repositoryFactory, EqualityComparerFactory comparerFactory)
 {
     _query = query;
     _repositoryFactory = repositoryFactory;
     _comparerFactory = comparerFactory;
 }
Exemplo n.º 30
0
 /// <summary>
 /// Initializes the <see cref="TMApplication" /> class.
 /// </summary>
 static TMApplication()
 {
     _VARS = new SynchronizedDictionary <string, object>(EqualityComparerFactory.CreateCaseInsensitiveStringComparer(true, true));
 }
Exemplo n.º 31
0
 public Factory(IQuery query, IBulkRepository <TFact> repository, EqualityComparerFactory comparerFactory)
 {
     _query           = query;
     _repository      = repository;
     _comparerFactory = comparerFactory;
 }