Форум программистов, компьютерный форум, киберфорум
C# .NET
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
Другие темы раздела
C# Предлагаю создать группу для изучения .NET технологий Список рассматриваемых технологий: ADO.NET, Entity Framework, LINQ, WPF, ASP.NET. Изучение и применение паттернов проектирования. Список еще будет корректироваться. Как это будет проходить: Всё общение будет происходить по скайпу или на https://www.cyberforum.ru/. В скайпе будет 1 общая группа и отдельные группы по конкретным технологиям. Группа создается для того что бы можно было быстро... https://www.cyberforum.ru/ csharp-net/ thread1374076.html C# "Вшить" в файл имя файла. Или как из string перевести в byte[]
Здравствуйте. Считываю файл, получаю массив байтов. Сохраняю его имя, расширение, хеш в переменные. Делаю различные операции с массивом байтов, и снова записываю в файл (File.WriteAllBytes(path, ByteFile)); Но мне помимо самого файла надо "вшить" в него имя, расширение, хеш. Как это правильно делать чтобы потом можно было легко их считать из файла и использовать в дальнейшем? Проблема в том, что...
C# В NetWorkSteam отправляются болше данных чем доходят https://www.cyberforum.ru/ csharp-net/ thread1374041.html
Собственно Отправляю bytes = System.Text.Encoding.UTF8.GetBytes("Ok"); stream.Flush(); stream.Write(bytes, 0, bytes.Length); Принимаю byte msg;
C# Тестировщик: Не засчитывается последнее нажатие на кнопку Здравствуйте,помогите пожалуйста. Читается все с txt файла ответы заносятся тоже в txt, и выводятся в сообщении под исключение. Когда индекс за пределами диапазона, но проблема заключается в том чтобы сделать правильный адекватный рандом. И почему-то не засчитывается последнее нажатие на кнопку, пример: вопросов 24, а правильных и не правильных 13 и 10. А рандом не адекватно выдает правильный и... https://www.cyberforum.ru/ csharp-net/ thread1373734.html
Как получить методы с определённым атрибутом? C#
Подскажите пожалуйста как из сборки(длл) вытянуть методы с атрибутом «тест» ? Методы я достал, а как дальше не раздупляю.. Вот скрин. Вот полная схема: Надо получить список тестов, которые входят в определенную категорию Категория Selenium называется Этой категорией отмечаются и сами тесты и классы, в которых сидят тесты и их наследники Допустим Category(“Selenium”) атрибут указан в...
C# Синхронизация баз данных и dropbox Не так давно я уже открывал подобную тему здесь. Значит в чём прбема. У нас на дропбоксе лежит база данных. На рабочих пк лежит общая папка дропбокса. Изменения вносятся в базу и дропбокс синхронизирует базу благополучно на всех машинах. И появляются 2 проблемы. 1. Если одновременно внести изменения в бд на разных машинах, то дропбокс создаёт 2 файла усебя. 1 из них - обновлённая база с... https://www.cyberforum.ru/ csharp-net/ thread1373478.html
C# Прослушивать порт (или сразу все порты) на исходящий с компьютера трафик Доброго времени суток! Мне необходимо прослушивать порт(или сразу все порты) на исходящий с компьютера трафик. Т.е. есть некое приложение на самом компьютере, которое слушает порт(или порты) и записывает пакеты, проходящие через этот порт и адрес, на который они посланы. Подскажите пожалуйста, как мне слушать порт на исходящий трафик? И как получить адрес, на который направлен пакет? https://www.cyberforum.ru/ csharp-net/ thread1373462.html EmguCV. На другом компьютере не открывается видео файлы C#
Доброго времени суток. Проблема: написал прогу по обработке видео с использованием EmguCV. На моём компе работает всё отлично, открывает любые видео с почти любыми кодеками (xvid, h264 без проблем). Как только переношу прогу на другой комп, там не открывается вообще ни одно видео. Все нужные dll лежат вместе с exe, ffmpeg тоже там. На другой компьютера ставил такой же набор кодеков как и на...
C# Потоки Thread: Необработанное исключение типа "System.NullReferenceException" https://www.cyberforum.ru/ csharp-net/ thread1372929.html
Такова проблема thrListener = new Thread(KeepListening); thrListener.Start(); ... public void KeepListening() { while (ServRunning == true) {
C# Webclient, gzip - приходит только два запроса https://www.cyberforum.ru/ csharp-net/ thread1372791.html
Добрый день. Я не могу понять где я запутался и когда. Суть в чем. Разбираю сайт, странички возвращаются в gzip. Gzip разбираю, в отладчике видел хороший html. Но вот беда, когда разбираю, я получаю только 2 ответа от сервера. Если же не работаю с gzip, то я получаю ответов столько, сколько мне нужно. Собсно код: Когда пытаюсь разобрать: string AuctionsCount =...
Плагин для Internet Explorer C#
подскажите с чего начать написание плагина для браузера? мне нужно самое простое, управление вкладками, открытие закрытие, переход по определённому адресу
C# Параллельный Regex не работает вот отрывок кода: Regex newReg = new Regex(pattern, option); MatchCollection matches = newReg.Matches(text); Parallel.ForEach (matches, Match mat => { Console.WriteLine("Значение найденного обьекта {0}", mat.Groups); myBigList.Add(mat.Groups.ToString());
Master of Orion
Эксперт .NET
6098 / 4954 / 905
Регистрация: 10.07.2011
Сообщений: 14,522
Записей в блоге: 5
16.02.2015, 13:16 0

Гибкая фильтрация данных запроса - C# - Ответ 7233764

16.02.2015, 13:16. Показов 1849. Ответов 14
Метки (Все метки)

Ответ

sigmov, Да это не секрет, гуглите по T4 template Например

Добавлено через 40 минут
Очень мощная штука. В моем случае вот ЭТО
Кликните здесь для просмотра всего текста
<#@ template language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Reflection" #>
<#@ assembly name="$(TargetDir)$(TargetFileName)"

#>using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using Lanit.Audit.Models;

<#var props = typeof (Lanit.Audit.Models.AuditEntry).GetProperties(System.Reflection.BindingFlags.Ins tance | System.Reflection.BindingFlags.Public); #>

public static class AuditHelper
{
public static IOrderedEnumerable<AuditEntry> OrderBy(this IEnumerable<AuditEntry> collection, string property)
{
switch(property)
{
<# foreach (var prop in props) {
#>case "<#=prop.Name#>":
return collection.OrderBy(x=>x.<#=prop.Name#>);
<# }
#>}
throw new NotImplementedException();
}

public static IOrderedEnumerable<AuditEntry> OrderByDescending(this IEnumerable<AuditEntry> collection, string property)
{
switch(property)
{
<# foreach (var prop in props) {
#>case "<#=prop.Name#>":
return collection.OrderByDescending(x=>x.<#=prop.Name#>);
<# }
#>}
throw new NotImplementedException();
}

public static IOrderedEnumerable<AuditEntry> OrderBy(this IEnumerable<AuditEntry> collection, string property, SortDirection directon)
{
return directon == SortDirection.Ascending ? collection.OrderBy(property) : collection.OrderByDescending(property);
}

public static IComparer<AuditEntry> GetComparer(string property, SortDirection directon)
{
switch(property)
{
<#foreach (var prop in props) {
#>case "<#=prop.Name#>":
return directon == SortDirection.Ascending ? (IComparer<AuditEntry>) new <#=prop.Name#>Comparer() : new <#=prop.Name#>ComparerDescendant();
<# }
#>}
throw new NotImplementedException();
}

public static bool RegexIsMatch(this AuditEntry entry, string pattern, string property)
{
var regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
switch(property)
{
<# foreach (var prop in props) {
#>case "<#=prop.Name#>":
return regex.IsMatch(entry.<#= prop.Name + (prop.PropertyType == typeof (string) ? "" : ".ToString()")#>);
<# }
#>}
throw new NotImplementedException();
}

public static IEnumerable<AuditEntry> WhereRegexIsMatch(this IEnumerable<AuditEntry> collection, string pattern, string property)
{
var regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
switch(property)
{
<# foreach (var prop in props) {
#>case "<#=prop.Name#>":
return collection.Where(x => regex.IsMatch(x.<#= prop.Name + (prop.PropertyType == typeof (string) ? "" : ".ToString()")#>));
<# }
#>}
throw new NotImplementedException();
}
}


<# foreach (var prop in props) { #>

public class <#=prop.Name#>Comparer : IComparer<AuditEntry>
{
public int Compare(AuditEntry x, AuditEntry y)
{
return x.<#=prop.Name#>.CompareTo(y.<#=prop.Name#>);
}
}

public class <#=prop.Name#>ComparerDescendant : IComparer<AuditEntry>
{
public int Compare(AuditEntry x, AuditEntry y)
{
return y.<#=prop.Name#>.CompareTo(x.<#=prop.Name#>);
}
}

<# } #>


превращается в
Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using Lanit.Audit.Models;
 
 
public static class AuditHelper
{
    public static IOrderedEnumerable<AuditEntry> OrderBy(this IEnumerable<AuditEntry> collection, string property)
    {   
        switch(property)
        {
            case "ItemId":          
                return collection.OrderBy(x=>x.ItemId);
            case "ItemType":            
                return collection.OrderBy(x=>x.ItemType);
            case "DocLocation":             
                return collection.OrderBy(x=>x.DocLocation);
            case "Event":           
                return collection.OrderBy(x=>x.Event);
            case "UserId":          
                return collection.OrderBy(x=>x.UserId);
            case "Occurred":            
                return collection.OrderBy(x=>x.Occurred);
            }
        throw new NotImplementedException();
    }
 
    public static IOrderedEnumerable<AuditEntry> OrderByDescending(this IEnumerable<AuditEntry> collection, string property)
    {  
        switch(property)
        {
            case "ItemId":          
                return collection.OrderByDescending(x=>x.ItemId);
            case "ItemType":            
                return collection.OrderByDescending(x=>x.ItemType);
            case "DocLocation":             
                return collection.OrderByDescending(x=>x.DocLocation);
            case "Event":           
                return collection.OrderByDescending(x=>x.Event);
            case "UserId":          
                return collection.OrderByDescending(x=>x.UserId);
            case "Occurred":            
                return collection.OrderByDescending(x=>x.Occurred);
            }
        throw new NotImplementedException();
    }
 
    public static IOrderedEnumerable<AuditEntry> OrderBy(this IEnumerable<AuditEntry> collection, string property, SortDirection directon)
    {
      return directon == SortDirection.Ascending ? collection.OrderBy(property) : collection.OrderByDescending(property); 
    }
 
    public static IComparer<AuditEntry> GetComparer(string property, SortDirection directon)
    {
      switch(property)
      {
         case "ItemId":
            return directon == SortDirection.Ascending ? (IComparer<AuditEntry>) new ItemIdComparer() : new ItemIdComparerDescendant();   
         case "ItemType":
            return directon == SortDirection.Ascending ? (IComparer<AuditEntry>) new ItemTypeComparer() : new ItemTypeComparerDescendant();   
         case "DocLocation":
            return directon == SortDirection.Ascending ? (IComparer<AuditEntry>) new DocLocationComparer() : new DocLocationComparerDescendant();   
         case "Event":
            return directon == SortDirection.Ascending ? (IComparer<AuditEntry>) new EventComparer() : new EventComparerDescendant();   
         case "UserId":
            return directon == SortDirection.Ascending ? (IComparer<AuditEntry>) new UserIdComparer() : new UserIdComparerDescendant();   
         case "Occurred":
            return directon == SortDirection.Ascending ? (IComparer<AuditEntry>) new OccurredComparer() : new OccurredComparerDescendant();   
         }
        throw new NotImplementedException();
    }
 
    public static bool RegexIsMatch(this AuditEntry entry, string pattern, string property)
    {
        var regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        switch(property)
        {
            case "ItemId":          
                return regex.IsMatch(entry.ItemId.ToString());
            case "ItemType":            
                return regex.IsMatch(entry.ItemType);
            case "DocLocation":             
                return regex.IsMatch(entry.DocLocation);
            case "Event":           
                return regex.IsMatch(entry.Event);
            case "UserId":          
                return regex.IsMatch(entry.UserId.ToString());
            case "Occurred":            
                return regex.IsMatch(entry.Occurred.ToString());
            }        
        throw new NotImplementedException();
    }
 
    public static IEnumerable<AuditEntry> WhereRegexIsMatch(this IEnumerable<AuditEntry> collection, string pattern, string property)
    {
        var regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        switch(property)
        {
            case "ItemId":          
                return collection.Where(x => regex.IsMatch(x.ItemId.ToString()));
            case "ItemType":            
                return collection.Where(x => regex.IsMatch(x.ItemType));
            case "DocLocation":             
                return collection.Where(x => regex.IsMatch(x.DocLocation));
            case "Event":           
                return collection.Where(x => regex.IsMatch(x.Event));
            case "UserId":          
                return collection.Where(x => regex.IsMatch(x.UserId.ToString()));
            case "Occurred":            
                return collection.Where(x => regex.IsMatch(x.Occurred.ToString()));
            }          
        throw new NotImplementedException();
    }
}
 
 
 
public class ItemIdComparer : IComparer<AuditEntry>
{
    public int Compare(AuditEntry x, AuditEntry y)
    {
        return x.ItemId.CompareTo(y.ItemId);
    }
}
 
public class ItemIdComparerDescendant : IComparer<AuditEntry>
{
    public int Compare(AuditEntry x, AuditEntry y)
    {
        return y.ItemId.CompareTo(x.ItemId);
    }
}
 
 
public class ItemTypeComparer : IComparer<AuditEntry>
{
    public int Compare(AuditEntry x, AuditEntry y)
    {
        return x.ItemType.CompareTo(y.ItemType);
    }
}
 
public class ItemTypeComparerDescendant : IComparer<AuditEntry>
{
    public int Compare(AuditEntry x, AuditEntry y)
    {
        return y.ItemType.CompareTo(x.ItemType);
    }
}
 
 
public class DocLocationComparer : IComparer<AuditEntry>
{
    public int Compare(AuditEntry x, AuditEntry y)
    {
        return x.DocLocation.CompareTo(y.DocLocation);
    }
}
 
public class DocLocationComparerDescendant : IComparer<AuditEntry>
{
    public int Compare(AuditEntry x, AuditEntry y)
    {
        return y.DocLocation.CompareTo(x.DocLocation);
    }
}
 
 
public class EventComparer : IComparer<AuditEntry>
{
    public int Compare(AuditEntry x, AuditEntry y)
    {
        return x.Event.CompareTo(y.Event);
    }
}
 
public class EventComparerDescendant : IComparer<AuditEntry>
{
    public int Compare(AuditEntry x, AuditEntry y)
    {
        return y.Event.CompareTo(x.Event);
    }
}
 
 
public class UserIdComparer : IComparer<AuditEntry>
{
    public int Compare(AuditEntry x, AuditEntry y)
    {
        return x.UserId.CompareTo(y.UserId);
    }
}
 
public class UserIdComparerDescendant : IComparer<AuditEntry>
{
    public int Compare(AuditEntry x, AuditEntry y)
    {
        return y.UserId.CompareTo(x.UserId);
    }
}
 
 
public class OccurredComparer : IComparer<AuditEntry>
{
    public int Compare(AuditEntry x, AuditEntry y)
    {
        return x.Occurred.CompareTo(y.Occurred);
    }
}
 
public class OccurredComparerDescendant : IComparer<AuditEntry>
{
    public int Compare(AuditEntry x, AuditEntry y)
    {
        return y.Occurred.CompareTo(x.Occurred);
    }
}


Мне норм

Вернуться к обсуждению:
Гибкая фильтрация данных запроса C#
1
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
16.02.2015, 13:16
Готовые ответы и решения:

Фильтрация данных
Здравствуйте, есть datagridview для вывода данных и два ComboBox с помощью которых требуется...

Фильтрация данных
Есть у меня две таблицы в БД: Sotrudniki (id_sotr(pk), id_ot(fk) name_sotr) -&gt; Otdely (id_ot(pk),...

Гибкая последовательная сортировка
Всем привет! Столкнулся с проблемой, имеется таблица - Table3, с полями - Field1, Field2, Field3,...

Фильтрация данных из БД Access
Помогите пожалуйста с поиском и выводом данных в поле поиска вводим пин-код и вывести нужную...

14
16.02.2015, 13:16
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
16.02.2015, 13:16
Помогаю со студенческими работами здесь

Фильтрация выводимых в datagridview данных
Здравствуйте. Есть два datagridview, связанные по полю ID. Во тором gride есть колонка содержащая...

Динамичная фильтрация данных из списка
Здравствуйте. Нашел на форуме интересный метод фильтрации списка данных для textbox. Подскажите,...

Фильтрация данных в зависимости от выбора в ComboBox
Помогите организовать поиск(фильтрацию)во второй вкладке Combobox результат вывести в...

Фильтрация данных через BindingSource.Filter
Необходимо произвести поиск сразу по нескольким столбцам типа int и string. Данный запрос работает...

0
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru