: Controller
17 | where TD : DbContext, ICustomDbContext
18 | where T : class
19 | {
20 |
21 | [HttpGet]
22 | [Route("{id}")]
23 | public IActionResult Get(long id)
24 | {
25 | using (var uow = new UnitOfWork())
26 | {
27 | var repository = uow.GetRepository();
28 | T item = repository.GetAll(id.GetIdentifierExpression())
29 | .Include(repository.GetDbContext().GetIncludePaths(typeof(T))).FirstOrDefault();
30 |
31 | if (item == null)
32 | return StatusCode(404);
33 | return Json(item);
34 | }
35 | }
36 |
37 | [HttpPost]
38 | [Route("DynamicQuery")]
39 | public IActionResult DynamicQuery([FromBody] SelectDto selectDto)
40 | {
41 | using (var uow = new UnitOfWork())
42 | {
43 | var repository = uow.GetRepository();
44 | return Json(repository.GetAll(selectDto.GetExpression())
45 | .Include(repository.GetDbContext().GetIncludePaths(typeof(T))).ToList());
46 | }
47 | }
48 |
49 |
50 | [HttpPut]
51 | public IActionResult Put([FromBody]T item)
52 | {
53 | using (var uow = new UnitOfWork())
54 | {
55 | uow.GetRepository().Add(item);
56 | if (uow.SaveChanges() > 0)
57 | return Json(item);
58 | return StatusCode(500);
59 | }
60 | }
61 |
62 | [HttpDelete]
63 | [Route("{id}")]
64 | public IActionResult Delete(long id)
65 | {
66 | using (var uow = new UnitOfWork())
67 | {
68 | T item = uow.GetRepository().Get(id.GetIdentifierExpression());
69 | if (item == null)
70 | return StatusCode(404);
71 |
72 | uow.GetRepository().Delete(item);
73 | return StatusCode(uow.SaveChanges() > 0 ? 200 : 500);
74 | }
75 | }
76 |
77 | [HttpPost]
78 | [Route("{id}")]
79 | public IActionResult Update(long id, [FromBody] T updateItem)
80 | {
81 | using (var uow = new UnitOfWork())
82 | {
83 | T item = uow.GetRepository().Get(id.GetIdentifierExpression());
84 | if (item == null)
85 | return StatusCode(404);
86 |
87 | ObjectMapper.MapExclude(item, updateItem, new string[] { typeof(T).GetIdentifierColumnName() });
88 | uow.GetRepository().Update(item);
89 | return StatusCode(uow.SaveChanges() > 0 ? 200 : 500);
90 | }
91 | }
92 |
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/DMicroservices/Base/Identity/IdentityFilter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using Microsoft.AspNetCore.Mvc.Filters;
5 |
6 | namespace DMicroservices.Base.Identity
7 | {
8 | public abstract class IdentityFilter : ActionFilterAttribute, IAuthorizationFilter
9 | {
10 | public virtual void OnAuthorization(AuthorizationFilterContext context)
11 | {
12 |
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/DMicroservices/DMicroservices.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 | true
6 | https://github.com/detayteknoloji/dmicroservices
7 | Serhat Boyraz
8 | Detaysoft
9 | 3.1.102
10 | LICENSE
11 | Library
12 | true
13 | 3.1.102
14 | 3.1.102
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 | True
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 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/Cache/MemoryCacheManager.cs:
--------------------------------------------------------------------------------
1 | using DMicroservices.Utils.Logger;
2 | using MessagePack;
3 | using Microsoft.Extensions.Caching.Memory;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Text.RegularExpressions;
8 | using System.Threading;
9 | using Microsoft.Extensions.Options;
10 | using System.Collections;
11 | using System.Reflection;
12 |
13 | namespace DMicroservices.DataAccess.Cache
14 | {
15 | public class MemoryCacheManager
16 | {
17 | private IMemoryCache _memoryCache;
18 | private bool _memoryCacheDisabled = false;
19 | #region Singleton Section
20 |
21 | private static readonly Lazy _instance = new Lazy(() => new MemoryCacheManager());
22 |
23 | protected MemoryCacheManager()
24 | {
25 |
26 | _memoryCache = new MemoryCache(new MemoryDistributedCacheOptions()
27 | {
28 | SizeLimit = null
29 | });
30 | }
31 |
32 | public static MemoryCacheManager Instance => _instance.Value;
33 | #endregion
34 |
35 | ///
36 | /// Bellekte tutulan veriyi getirir.
37 | ///
38 | ///
39 | ///
40 | public string Get(string key)
41 | {
42 | if (_memoryCacheDisabled)
43 | return null;
44 | return _memoryCache.Get(key)?.ToString();
45 | }
46 |
47 | ///
48 | /// Önbellekte tutulan veriyi siler.
49 | ///
50 | ///
51 | public bool DeleteByKey(string key)
52 | {
53 | if (_memoryCacheDisabled)
54 | return true;
55 |
56 | _memoryCache.Remove(key);
57 | return true;
58 | }
59 |
60 | ///
61 | /// Önbellekte tutulan verileri key benzerliğine göre siler.
62 | ///
63 | ///
64 | public bool DeleteByKeyLike(string key)
65 | {
66 |
67 | if (_memoryCacheDisabled)
68 | return true;
69 |
70 | foreach (var keyItem in GetAllKeys())
71 | {
72 | if (keyItem.StartsWith(key))
73 | _memoryCache.Remove(keyItem);
74 | }
75 |
76 | return true;
77 | }
78 |
79 | ///
80 | /// Tüm listeyi temizler
81 | ///
82 | public bool Clear()
83 | {
84 | if (_memoryCacheDisabled)
85 | return true;
86 |
87 | foreach (var key in GetAllKeys())
88 | {
89 | _memoryCache.Remove(key);
90 | }
91 |
92 | return true;
93 | }
94 |
95 | ///
96 | /// Önbellekte veriyi, verilmişse istenilen süre kadar tutar
97 | ///
98 | ///
99 | ///
100 | ///
101 | public bool Set(string key, string value, TimeSpan? expireTime = null)
102 | {
103 | if (_memoryCacheDisabled)
104 | return true;
105 |
106 | if (expireTime.HasValue)
107 | _memoryCache.Set(key, value, expireTime.Value);
108 | else
109 | _memoryCache.Set(key, value);
110 |
111 | return true;
112 | }
113 |
114 | ///
115 | /// Önbellekte veriyi, verilmişse istenilen süre kadar tutar
116 | ///
117 | ///
118 | ///
119 | ///
120 | public bool Set(Dictionary bulkInsertList)
121 | {
122 | if (_memoryCacheDisabled)
123 | return true;
124 |
125 | foreach (var (key, value) in bulkInsertList)
126 | {
127 | _memoryCache.Set(key, value);
128 | }
129 |
130 | return true;
131 | }
132 |
133 | ///
134 | /// Önbellekte byte[] tipinde veriyi tutar.
135 | ///
136 | ///
137 | ///
138 | public bool SetSerializeBytes(string key, T value, TimeSpan? expireTime = null)
139 | {
140 | if (_memoryCacheDisabled)
141 | return true;
142 |
143 | if (expireTime.HasValue)
144 | _memoryCache.Set(key, value, expireTime.Value);
145 | else
146 | _memoryCache.Set(key, value);
147 |
148 |
149 | return false;
150 | }
151 |
152 | ///
153 | /// Önbellekte tutulan byte[] tipinde veriyi döner.
154 | ///
155 | ///
156 | public T GetDeserializeBytes(string key)
157 | {
158 | if (_memoryCacheDisabled)
159 | return default;
160 |
161 | return _memoryCache.Get(key);
162 | }
163 |
164 | ///
165 | /// Anahtara göre var olup olmadığını döner
166 | ///
167 | ///
168 | public bool Exists(string key)
169 | {
170 | if (_memoryCacheDisabled)
171 | return false;
172 |
173 | return _memoryCache.Get(key) != null;
174 | }
175 |
176 | ///
177 | /// Anahtara göre var olun önbelleği döner
178 | ///
179 | ///
180 | public bool GetIfExists(string key, out string obj)
181 | {
182 | if (_memoryCacheDisabled)
183 | {
184 | obj = null;
185 | return false;
186 | }
187 |
188 | obj = _memoryCache.Get(key)?.ToString();
189 | return obj != null;
190 | }
191 |
192 | ///
193 | /// Anahtara göre var olun önbelleği döner
194 | ///
195 | ///
196 | public bool GetIfExists(string key, out T obj) where T : class
197 | {
198 | if (_memoryCacheDisabled)
199 | {
200 | obj = null;
201 | return false;
202 | }
203 |
204 | var memoryCacheData = _memoryCache.Get(key);
205 |
206 | obj = (T)memoryCacheData;
207 | return memoryCacheData != null;
208 | }
209 |
210 | public List GetAllKeys()
211 | {
212 | if (_memoryCacheDisabled)
213 | {
214 | return null;
215 | }
216 |
217 | var field = typeof(MemoryCache).GetProperty("EntriesCollection", BindingFlags.NonPublic | BindingFlags.Instance);
218 | var collection = field.GetValue(_memoryCache) as ICollection;
219 | var items = new List();
220 | if (collection != null)
221 | foreach (var item in collection)
222 | {
223 | var methodInfo = item.GetType().GetProperty("Key");
224 | var val = methodInfo.GetValue(item);
225 | items.Add(val.ToString());
226 | }
227 |
228 | return items;
229 | }
230 |
231 | public void DisableCache()
232 | {
233 | _memoryCacheDisabled = true;
234 | }
235 | public void EnableCache()
236 | {
237 | _memoryCacheDisabled = false;
238 | }
239 | }
240 | }
241 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/DynamicQuery/Enum/SortTypeEnum.cs:
--------------------------------------------------------------------------------
1 | namespace DMicroservices.DataAccess.DynamicQuery.Enum
2 | {
3 | ///
4 | /// Sıralama tipi
5 | ///
6 | public enum SortTypeEnum
7 | {
8 | ///
9 | /// Artan
10 | ///
11 | ASC,
12 |
13 | ///
14 | /// Azalan
15 | ///
16 | DESC
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/DynamicQuery/Enum/TypePropertyEnum.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 |
6 | namespace DMicroservices.DataAccess.DynamicQuery.Enum
7 | {
8 | public enum TypePropertyEnum
9 | {
10 | Byte =0,
11 | Sbyte =1,
12 | Short = 2,
13 | Ushort = 3,
14 | Int32 = 4,
15 | Uint = 5,
16 | Long = 6,
17 | Ulong = 7,
18 | Float = 8,
19 | Double = 9,
20 | Decimal = 10,
21 | Char = 11,
22 | Boolean = 12,
23 | Object = 13,
24 | String = 14,
25 | DateTime =15,
26 | DateTimeNullable= 16,
27 | Int32Nullable= 17,
28 | ByteNullable= 18
29 |
30 |
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/DynamicQuery/FilterCompareTypesItem.cs:
--------------------------------------------------------------------------------
1 | namespace DMicroservices.DataAccess.DynamicQuery
2 | {
3 | public class FilterCompareTypesItem
4 | {
5 | ///
6 | /// Mantıksal grup ismi.
7 | ///
8 | public string Group { get; set; }
9 |
10 | ///
11 | /// Grubun AND/OR şeklinde birleştirilmesi için AND ve ya OR bağlacı
12 | /// AND/OR
13 | ///
14 | public string Type { get; set; }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/DynamicQuery/FilterItemDto.cs:
--------------------------------------------------------------------------------
1 | namespace DMicroservices.DataAccess.DynamicQuery
2 | {
3 | ///
4 | /// Filtreleme yapmak için rest tarafından gönderilen veri ögesi
5 | ///
6 | public class FilterItemDto
7 | {
8 | ///
9 | /// Filtreleme yapılması için özellik adı.
10 | ///
11 | public string PropertyName { get; set; }
12 |
13 | ///
14 | /// Filtreleme yapılacak işlem
15 | /// "EQ" ->equals
16 | /// "IN" ->in
17 | /// "CT" ->contains
18 | /// "LT" ->less than
19 | /// "GT" ->grater than
20 | ///
21 | public string Operation { get; set; }
22 |
23 | ///
24 | /// Filtreleme yapılacak value
25 | ///
26 | public string PropertyValue { get; set; }
27 |
28 | ///
29 | /// Karşılaştırma yapılırken PropertyName tarafında uygulanacak olan metod.
30 | /// "ToLower" -> PropertyName.ToLower()
31 | /// "ToUpper" -> PropertyName.ToUpper()
32 | ///
33 | public string ConversionMethodName { get; set; }
34 |
35 | ///
36 | /// Mantıksal grup ismi.
37 | /// Gruplamak / AND or işlemini gruba uygulamak için kullanılır.
38 | ///
39 | public string Group { get; set; }
40 |
41 | ///
42 | /// Bir kolon birden fazla tabloda kullanılıyorsa ve bu kolonun iki tabloda birden aynı filtre ile sorgu çekilmesi gerekmiyorsa bu alan
43 | /// BNT_<TABLO ADI> şeklinde belirtilir.
44 | ///
45 | public string TableObject { get; set; }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/DynamicQuery/OrderItemDto.cs:
--------------------------------------------------------------------------------
1 |
2 | namespace DMicroservices.DataAccess.DynamicQuery
3 | {
4 | ///
5 | /// Sıralama yapmak için gerekli nesne
6 | ///
7 | public class OrderItemDto
8 | {
9 | ///
10 | /// Filtreleme yapılması için özellik adı.
11 | ///
12 | public string Column { get; set; }
13 |
14 | ///
15 | /// Descending olarak sırala?
16 | ///
17 | public bool Descending { get; set; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/DynamicQuery/SortItemDto.cs:
--------------------------------------------------------------------------------
1 | using DMicroservices.DataAccess.DynamicQuery.Enum;
2 |
3 | namespace DMicroservices.DataAccess.DynamicQuery
4 | {
5 | public class SortItemDto
6 | {
7 | ///
8 | /// Sıralama yapılacak olan özellik.
9 | ///
10 | public string PropertyName { get; set; }
11 |
12 | ///
13 | /// Sıralama Türü
14 | ///
15 | public SortTypeEnum SortType { get; set; }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/ElasticSearch/ElasticHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Nest;
6 |
7 | namespace DMicroservices.DataAccess.ElasticSearch
8 | {
9 | public class ElasticHelper : IElasticRepository where T : class
10 | {
11 | #region Singleton Section
12 |
13 | private static readonly Lazy> _instance = new Lazy>(() => new ElasticHelper());
14 |
15 | private ElasticHelper()
16 | {
17 | }
18 |
19 | public static ElasticHelper Instance => _instance.Value;
20 |
21 | #endregion
22 |
23 | #region Members
24 |
25 | private ConnectionSettings _connectionSettings;
26 |
27 | private ElasticClient _elasticClient;
28 |
29 | #endregion
30 |
31 | #region Property
32 | private ConnectionSettings ConnectionSettings
33 | {
34 | get
35 | {
36 | if (_connectionSettings == null)
37 | {
38 | string elasticUri = Environment.GetEnvironmentVariable("ELASTIC_URI");
39 |
40 | if (string.IsNullOrEmpty(elasticUri))
41 | throw new ArgumentNullException($"ELASTIC_URI environment variable can not be empty");
42 |
43 | _connectionSettings = new ConnectionSettings(new Uri(elasticUri));
44 | }
45 |
46 | return _connectionSettings;
47 | }
48 | }
49 |
50 | private ElasticClient ElasticClient
51 | {
52 | get
53 | {
54 | if (_elasticClient == null)
55 | _elasticClient = new ElasticClient(ConnectionSettings);
56 | return _elasticClient;
57 | }
58 | }
59 |
60 | #endregion
61 |
62 | #region Methods
63 |
64 | ///
65 | /// Elasticsearch'e verilen modeli indexler.
66 | ///
67 | ///
68 | ///
69 | ///
70 | public IndexResponse AddIndex(T model, string indexName = null)
71 | {
72 | return ElasticClient.Index(model, p => p.Index(indexName?.ToLower() ?? typeof(T).Name.ToLower()));
73 | }
74 |
75 | ///
76 | /// Elasticsearch'e verilen modeli asenkron olarak indexler.
77 | ///
78 | ///
79 | ///
80 | ///
81 | public Task AddIndexAsync(T model, string indexName = null)
82 | {
83 | return ElasticClient.IndexAsync(model, p => p.Index(indexName?.ToLower() ?? typeof(T).Name.ToLower()));
84 | }
85 |
86 | ///
87 | /// Elasticsearch'e verilen model listesini ekler.
88 | ///
89 | ///
90 | ///
91 | ///
92 | public BulkResponse BulkIndexList(List model, string indexName = null)
93 | {
94 | if (!model.Any())
95 | throw new ArgumentNullException($"model cannot be null!");
96 |
97 | return ElasticClient.Bulk(p => p
98 | .Index(indexName?.ToLower() ?? typeof(T).Name.ToLower())
99 | .IndexMany(model)
100 | );
101 | }
102 |
103 | ///
104 | /// Elasticsearch'e verilen model listesini asenkron olarak ekler.
105 | ///
106 | ///
107 | ///
108 | ///
109 | public Task BulkIndexListAsync(List model, string indexName = null)
110 | {
111 | if (!model.Any())
112 | throw new ArgumentNullException($"model cannot be null!");
113 |
114 | return ElasticClient.BulkAsync(p => p
115 | .Index(indexName?.ToLower() ?? typeof(T).Name.ToLower())
116 | .IndexMany(model)
117 | );
118 | }
119 |
120 | ///
121 | /// Elasticsearch'e verilen model listesini ekler.
122 | ///
123 | ///
124 | /// Yeniden denemeden önce beklenilecek süre
125 | /// Hata alındığında deneme sayısı
126 | /// Toplu istek başı gönderilecek öge sayısı
127 | ///
128 | ///
129 | public BulkAllObservable BulkAllObservable(List model, int backOffTime, int backOffRetries, int size, string indexName = null)
130 | {
131 | if (!model.Any())
132 | throw new ArgumentNullException($"model cannot be null!");
133 |
134 | return ElasticClient.BulkAll(model, b => b
135 | .Index(indexName?.ToLower() ?? typeof(T).Name.ToLower())
136 | .BackOffTime(backOffTime)
137 | .BackOffRetries(backOffRetries)
138 | .MaxDegreeOfParallelism(Environment.ProcessorCount)
139 | .Size(size)
140 | );
141 | }
142 |
143 | ///
144 | /// Verilen index ismine göre gönderilen idyi siler.
145 | ///
146 | ///
147 | ///
148 | ///
149 | public DeleteResponse DeleteIndex(string indexName, string id)
150 | {
151 | if (string.IsNullOrEmpty(indexName) || id == null)
152 | {
153 | throw new ArgumentNullException($"indexName and id cannot be null!");
154 | }
155 |
156 | return ElasticClient.Delete(new DeleteRequest(indexName, id));
157 | }
158 |
159 | ///
160 | /// Elasticsearchün kendi querysi ile gönderilen search querysi ile arama yapar.
161 | ///
162 | ///
163 | ///
164 | ///
165 | public ISearchResponse Search(Func, QueryContainer> searchTerms, string indexName = null)
166 | {
167 | if (indexName == null)
168 | indexName = typeof(T).Name;
169 |
170 | return ElasticClient.Search(p => p
171 | .Query(searchTerms)
172 | .Index(indexName.ToLower())
173 | .Size(20)
174 | );
175 | }
176 |
177 | #endregion
178 | }
179 | }
180 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/ElasticSearch/IElasticRepository.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Threading.Tasks;
4 | using Nest;
5 |
6 | namespace DMicroservices.DataAccess.ElasticSearch
7 | {
8 | public interface IElasticRepository where T : class
9 | {
10 | IndexResponse AddIndex(T model, string indexName = null);
11 |
12 | Task AddIndexAsync(T model, string indexName = null);
13 |
14 | BulkResponse BulkIndexList(List model, string indexName = null);
15 |
16 | Task BulkIndexListAsync(List model, string indexName = null);
17 |
18 | BulkAllObservable BulkAllObservable(List model, int backOffTime, int backOffRetries, int size, string indexName = null);
19 |
20 | DeleteResponse DeleteIndex(string indexName, string id);
21 |
22 | ISearchResponse Search(Func, QueryContainer> searchTerms, string indexName = null);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/HealthCheck/DatabaseHealthCheck.cs:
--------------------------------------------------------------------------------
1 | using DMicroservices.DataAccess.Redis;
2 | using DMicroservices.DataAccess.UnitOfWork;
3 | using DMicroservices.Utils.Logger;
4 | using Microsoft.EntityFrameworkCore;
5 | using Microsoft.Extensions.Diagnostics.HealthChecks;
6 | using System;
7 | using System.Threading;
8 | using System.Threading.Tasks;
9 |
10 | namespace DMicroservices.RabbitMq.Base
11 | {
12 | public class DatabaseHealthCheck : IHealthCheck
13 | {
14 | Type _dbContextType = null;
15 | public DatabaseHealthCheck(Type dbContextType)
16 | {
17 | _dbContextType = dbContextType;
18 | }
19 |
20 | public Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
21 | {
22 | try
23 | {
24 | UnitOfWorkFactory.CreateUnitOfWork(_dbContextType).GetDbContext().Database.ExecuteSqlRaw("SELECT 1");
25 | }
26 | catch (Exception e)
27 | {
28 | ElasticLogger.Instance.Error(e, $"Mysql Connection Lost");
29 | return Task.FromResult(HealthCheckResult.Unhealthy("Mysql Connection Lost"));
30 |
31 | }
32 |
33 | return Task.FromResult(HealthCheckResult.Healthy());
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/HealthCheck/RedisHealthCheck.cs:
--------------------------------------------------------------------------------
1 | using DMicroservices.DataAccess.Redis;
2 | using DMicroservices.DataAccess.UnitOfWork;
3 | using DMicroservices.Utils.Logger;
4 | using Microsoft.EntityFrameworkCore;
5 | using Microsoft.Extensions.Diagnostics.HealthChecks;
6 | using System;
7 | using System.Threading;
8 | using System.Threading.Tasks;
9 |
10 | namespace DMicroservices.RabbitMq.Base
11 | {
12 | public class RedisHealthCheck : IHealthCheck
13 | {
14 |
15 | public Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
16 | {
17 | try
18 | {
19 | RedisManager.Instance.Get("test");
20 | }
21 | catch (Exception e)
22 | {
23 | ElasticLogger.Instance.Error(e, $"Redis Connection Lost");
24 | return Task.FromResult(HealthCheckResult.Unhealthy("Redis Connection Lost"));
25 |
26 | }
27 |
28 | return Task.FromResult(HealthCheckResult.Healthy());
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/History/HistoryCollectionModel.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 |
6 | namespace DMicroservices.DataAccess.History
7 | {
8 | public class HistoryCollectionModel
9 | {
10 | public string DatabaseName { get; set; }
11 | public string ObjectName { get; set; }
12 | public string ChangeType { get; set; }
13 | public string ChangedUser { get; set; }
14 | public object RowId { get; set; }
15 | public List Columns { get; set; }
16 | public string Hash { get; set; }
17 | public DateTime DateTime { get; set; }
18 | }
19 |
20 | public class HistoryTableColumnsModel
21 | {
22 | public string Name { get; set; }
23 | public object OldValue { get; set; }
24 | public object NewValue { get; set; }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/MongoRepository/Base/MongoBaseModel.cs:
--------------------------------------------------------------------------------
1 | using MongoDB.Bson;
2 | using MongoDB.Bson.Serialization.Attributes;
3 |
4 | namespace DMicroservices.DataAccess.MongoRepository.Base
5 | {
6 | public abstract class MongoBaseModel
7 | {
8 | [BsonId]
9 | public ObjectId Id { get; set; }
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/MongoRepository/Interfaces/IDatabaseSettings.cs:
--------------------------------------------------------------------------------
1 | namespace DMicroservices.DataAccess.MongoRepository.Interfaces
2 | {
3 | public interface IDatabaseSettings
4 | {
5 | string ConnectionString { get; set; }
6 |
7 | string DatabaseName { get; set; }
8 |
9 | string CollectionName { get; set; }
10 |
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/MongoRepository/Interfaces/IMongoRepository.cs:
--------------------------------------------------------------------------------
1 | using DMicroservices.DataAccess.DynamicQuery.Enum;
2 | using MongoDB.Driver;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Linq.Expressions;
7 |
8 | namespace DMicroservices.DataAccess.MongoRepository.Interfaces
9 | {
10 | ///
11 | /// Model katmanımızda bulunan her T tipi için aşağıda tanımladığımız fonksiyonları gerçekleştirebilecek generic bir repository tanımlıyoruz.
12 | ///
13 | ///
14 | public interface IMongoRepository where T : class
15 | {
16 | ///
17 | /// Tüm veriyi getir.
18 | ///
19 | ///
20 | IQueryable GetAll();
21 |
22 | ///
23 | /// Veriyi Where metodu ile getir.
24 | ///
25 | ///
26 | ///
27 | IQueryable GetAll(Expression> predicate);
28 |
29 | ///
30 | /// Verilen sorguya göre tablodaki sayıyı gönderir.
31 | ///
32 | ///
33 | ///
34 | int Count();
35 |
36 | ///
37 | /// Verilen sorguya göre tablodaki sayıyı gönderir.
38 | ///
39 | ///
40 | ///
41 | int Count(Expression> predicate);
42 |
43 | ///
44 | /// İstenilen veriyi single olarak getirir.
45 | ///
46 | ///
47 | ///
48 | T Get(Expression> predicate);
49 |
50 | ///
51 | /// Getirilen veri üzerinde veri gelmeden kolonları seç.
52 | ///
53 | /// Veri kısıtlamaları
54 | /// Seçilecek kolonlar
55 | ///
56 | IQueryable SelectList(Expression> @where, Expression> @select);
57 |
58 | ///
59 | /// Verinin bir bölümünü getirir.
60 | ///
61 | /// neye gore gelsin?
62 | /// Veri nerden baslasin?
63 | /// Kac veri gelsin
64 | /// Neye gore sortlansin
65 | /// A|D (A->ascending | D->descending)
66 | ///
67 | IQueryable GetDataPart(Expression> where, Expression> sort, SortTypeEnum sortType, int skipCount, int takeCount);
68 |
69 | ///
70 | /// Entity ile sql sorgusu göndermek için kullanılır.
71 | ///
72 | /// Gönderilecek sql
73 | ///
74 | List SendSql(string sqlQuery);
75 |
76 | ///
77 | /// Verilen entityi ekle.
78 | ///
79 | ///
80 | bool Add(T entity);
81 |
82 | ///
83 | /// Verilen entity i güncelle.
84 | ///
85 | ///
86 | bool Update(T entity);
87 |
88 | ///
89 | /// predicate göre veriler düzenlenir.
90 | ///
91 | ///
92 | ///
93 | bool Update(Expression> predicate, T entity);
94 |
95 | ///
96 | /// Verilen entityi sil.
97 | ///
98 | ///
99 | bool Delete(T entity, bool forceDelete = false);
100 |
101 | ///
102 | /// predicate göre veriler silinir.
103 | ///
104 | ///
105 | ///
106 | bool Delete(Expression> predicate, bool forceDelete = false);
107 |
108 | bool Delete(FieldDefinition field, TField date);
109 |
110 | ///
111 | /// Aynı kayıt eklememek için objeyi kontrol ederek true veya false dönderir.
112 | ///
113 | ///
114 | ///
115 | ///
116 | bool Any(Expression> predicate);
117 |
118 |
119 | bool Truncate();
120 |
121 | bool BulkInsert(List entityList);
122 |
123 | bool BulkDelete(Expression> predicate);
124 |
125 | bool AddAsync(T entity);
126 |
127 | bool UpdateAsync(Expression> predicate, T entity);
128 |
129 | bool BulkInsertAsync(List entityList);
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/MongoRepository/MongoRepositoryFactory.cs:
--------------------------------------------------------------------------------
1 | using DMicroservices.DataAccess.MongoRepository.Settings;
2 |
3 | namespace DMicroservices.DataAccess.MongoRepository
4 | {
5 | public static class MongoRepositoryFactory
6 | {
7 | public static MongoRepository CreateMongoRepository() where T : class
8 | {
9 | return new MongoRepository();
10 | }
11 |
12 | public static MongoRepository CreateMongoRepository(DatabaseSettings databaseSettings) where T : class
13 | {
14 | return new MongoRepository(databaseSettings);
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/MongoRepository/Settings/DatabaseSettings.cs:
--------------------------------------------------------------------------------
1 | using DMicroservices.DataAccess.MongoRepository.Interfaces;
2 |
3 | namespace DMicroservices.DataAccess.MongoRepository.Settings
4 | {
5 | public class DatabaseSettings : IDatabaseSettings
6 | {
7 | public string ConnectionString { get; set; }
8 |
9 | public string DatabaseName { get; set; }
10 |
11 | public string CollectionName { get; set; }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/Redis/RedisList.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using StackExchange.Redis;
6 |
7 | namespace DMicroservices.DataAccess.Redis
8 | {
9 |
10 | public class RedisList : IList
11 | {
12 | private static readonly string Domain = Environment.GetEnvironmentVariable("REDIS_URL");
13 | private ConnectionMultiplexer Connection { get; set; }
14 | private IDatabase RedisDatabase { get; set; }
15 |
16 | private string _key;
17 | public RedisList(string key)
18 | {
19 | _key = key;
20 |
21 | ConfigurationOptions options = ConfigurationOptions.Parse(Domain);
22 | Connection = ConnectionMultiplexer.Connect(options);
23 | RedisDatabase = Connection.GetDatabase();
24 | }
25 | private IDatabase GetRedisDb()
26 | {
27 | return Connection.GetDatabase();
28 | }
29 | private byte[] Serialize(object obj)
30 | {
31 | return MessagePack.MessagePackSerializer.Serialize(obj, MessagePack.MessagePackSerializer.DefaultOptions.WithResolver(MessagePack.Resolvers.ContractlessStandardResolver.Instance));
32 | }
33 | private T Deserialize(byte[] serialized)
34 | {
35 | return MessagePack.MessagePackSerializer.Deserialize(serialized, MessagePack.MessagePackSerializer.DefaultOptions.WithResolver(MessagePack.Resolvers.ContractlessStandardResolver.Instance));
36 | }
37 | public void Insert(int index, T item)
38 | {
39 | var db = GetRedisDb();
40 | var before = db.ListGetByIndex(_key, index);
41 | db.ListInsertBefore(_key, before, Serialize(item));
42 | }
43 | public void RemoveAt(int index)
44 | {
45 | var db = GetRedisDb();
46 | var value = db.ListGetByIndex(_key, index);
47 | if (!value.IsNull)
48 | {
49 | db.ListRemove(_key, value);
50 | }
51 | }
52 | public T this[int index]
53 | {
54 | get
55 | {
56 | var value = GetRedisDb().ListGetByIndex(_key, index);
57 | return Deserialize(value);
58 | }
59 | set
60 | {
61 | Insert(index, value);
62 | }
63 | }
64 | public void Add(T item)
65 | {
66 | GetRedisDb().ListRightPush(_key, Serialize(item));
67 | }
68 | public void Add(T item, TimeSpan expireTime)
69 | {
70 | GetRedisDb().ListRightPush(_key, Serialize(item));
71 |
72 | GetRedisDb().KeyExpire(_key, expireTime);
73 | }
74 |
75 | public void AddRange(IEnumerable collection, TimeSpan? expireTime = null)
76 | {
77 | GetRedisDb().ListRightPush(_key, collection.Select(x => (RedisValue)Serialize(x)).ToArray());
78 |
79 | if (expireTime == null)
80 | expireTime = new TimeSpan(0, 10, 0);
81 |
82 | GetRedisDb().KeyExpire(_key, expireTime);
83 | }
84 |
85 | public void AddRange(IEnumerable collection)
86 | {
87 | GetRedisDb().ListRightPush(_key, collection.Select(x => (RedisValue)Serialize(x)).ToArray());
88 | }
89 |
90 | public void Clear()
91 | {
92 | GetRedisDb().KeyDelete(_key);
93 | }
94 | public bool Contains(T item)
95 | {
96 | for (int i = 0; i < Count; i++)
97 | {
98 | if (GetRedisDb().ListGetByIndex(_key, i).ToString().Equals(Serialize(item)))
99 | {
100 | return true;
101 | }
102 | }
103 | return false;
104 | }
105 | public void CopyTo(T[] array, int arrayIndex)
106 | {
107 | var range = GetRedisDb().ListRange(_key);
108 | for (var i = 0; i < range.Length; i++)
109 | {
110 | array[i] = Deserialize(range[i]);
111 | }
112 | }
113 | public int IndexOf(T item)
114 | {
115 | for (int i = 0; i < Count; i++)
116 | {
117 | if (GetRedisDb().ListGetByIndex(_key, i).ToString().Equals(Serialize(item)))
118 | {
119 | return i;
120 | }
121 | }
122 | return -1;
123 | }
124 | public int Count
125 | {
126 | get { return (int)GetRedisDb().ListLength(_key); }
127 | }
128 | public bool IsReadOnly
129 | {
130 | get { return false; }
131 | }
132 | public bool Remove(T item)
133 | {
134 | return GetRedisDb().ListRemove(_key, Serialize(item)) > 0;
135 | }
136 | public IEnumerator GetEnumerator()
137 | {
138 | for (int i = 0; i < this.Count; i++)
139 | {
140 | yield return Deserialize(GetRedisDb().ListGetByIndex(_key, i));
141 | }
142 | }
143 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
144 | {
145 | for (int i = 0; i < this.Count; i++)
146 | {
147 | yield return Deserialize(GetRedisDb().ListGetByIndex(_key, i));
148 | }
149 | }
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/Repository/FilteredReadonlyRepository.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Linq.Expressions;
5 | using System.Reflection;
6 | using DMicroservices.DataAccess.History;
7 | using DMicroservices.Utils.Extensions;
8 | using Microsoft.EntityFrameworkCore;
9 | using Microsoft.EntityFrameworkCore.ChangeTracking;
10 |
11 | namespace DMicroservices.DataAccess.Repository
12 | {
13 | ///
14 | /// EntityFramework için hazırlıyor olduğumuz bu repositoriyi daha önceden tasarladığımız generic repositorimiz olan IRepository arayüzünü implemente ederek tasarladık.
15 | /// Bu şekilde tasarlamamızın ana sebebi ise veritabanına independent(bağımsız) bir durumda kalabilmek.
16 | ///
17 | ///
18 | public class FilteredReadonlyRepository : IRepository where T : class
19 | {
20 | private readonly DbContext DbContext;
21 | private readonly DbSet DbSet;
22 |
23 | public string FilterColumnName { get; set; }
24 | public object FilterColumnValue { get; set; }
25 |
26 | private PropertyInfo FilterProperty;
27 | ///
28 | /// Repository instance ı başlatırç
29 | ///
30 | /// Veritabanı bağlantı nesnesi
31 | ///
32 | ///
33 | public FilteredReadonlyRepository(DbContext dbContext, string filterColumnName, object filterValue)
34 | {
35 | DbContext = dbContext;
36 | DbSet = dbContext.Set();
37 | FilterColumnName = filterColumnName;
38 | FilterColumnValue = filterValue;
39 | FilterProperty = typeof(T).GetProperty(FilterColumnName);
40 | }
41 |
42 | public void Add(T entity)
43 | {
44 | throw new NotImplementedException("This repository is read-only.");
45 | }
46 |
47 | public void BulkInsert(List entityList)
48 | {
49 | throw new NotImplementedException("This repository is read-only.");
50 | }
51 |
52 | ///
53 | /// Aynı kayıt eklememek için objeyi kontrol ederek true veya false dönderir.
54 | ///
55 | ///
56 | ///
57 | ///
58 | public bool Any(Expression> predicate)
59 | {
60 | return DbSet.Where(GetFilterExpression()).Any(predicate);
61 | }
62 |
63 | public DbContext GetDbContext()
64 | {
65 | return DbContext;
66 | }
67 |
68 | public List GetIncludePaths()
69 | {
70 | return DbContext.GetIncludePaths(typeof(T)).ToList();
71 | }
72 |
73 | public int Count()
74 | {
75 | return Count(arg => true);
76 | }
77 |
78 | public int Count(Expression> predicate)
79 | {
80 | IQueryable iQueryable = DbSet.Where(GetFilterExpression())
81 | .Where(predicate);
82 | return iQueryable.Count();
83 | }
84 |
85 | public void Delete(T entity, bool forceDelete = false)
86 | {
87 | throw new NotImplementedException("This repository is read-only.");
88 | }
89 |
90 | public void Delete(Expression> predicate, bool forceDelete = false)
91 | {
92 | throw new NotImplementedException("This repository is read-only.");
93 | }
94 |
95 | public void BulkDelete(List entityList)
96 | {
97 | throw new NotImplementedException("This repository is read-only.");
98 | }
99 |
100 | public T Get(Expression> predicate)
101 | {
102 | IQueryable iQueryable = DbSet.Where(GetFilterExpression())
103 | .Where(predicate);
104 | return iQueryable.ToList().FirstOrDefault();
105 | }
106 |
107 | public TResult Get(Expression> predicate, Expression> @select)
108 | {
109 | IQueryable iQueryable = DbSet.Where(GetFilterExpression())
110 | .Where(predicate);
111 | return iQueryable.Select(@select).FirstOrDefault();
112 | }
113 |
114 | public T Get(Expression> predicate, List includePaths)
115 | {
116 | IQueryable iQueryable = DbSet
117 | .Where(predicate).Where(GetFilterExpression()).Include(includePaths);
118 | return iQueryable.ToList().FirstOrDefault();
119 | }
120 |
121 | public IQueryable GetAll()
122 | {
123 | IQueryable iQueryable = DbSet.Where(GetFilterExpression()).Where(x => x != null);
124 | return iQueryable;
125 | }
126 |
127 | public IQueryable GetAll(System.Linq.Expressions.Expression> predicate)
128 | {
129 | IQueryable iQueryable = DbSet.Where(GetFilterExpression())
130 | .Where(predicate);
131 | return iQueryable;
132 | }
133 |
134 | public IQueryable GetAll(System.Linq.Expressions.Expression> predicate, List includePaths)
135 | {
136 | IQueryable iQueryable = DbSet
137 | .Where(GetFilterExpression()).Where(predicate).Include(includePaths);
138 | return iQueryable;
139 | }
140 |
141 | public IQueryable SelectList(Expression> where, Expression> select)
142 | {
143 | throw new NotImplementedException();
144 | }
145 |
146 | public IQueryable SelectList(Expression> @where, Expression> @select)
147 | {
148 | IQueryable iQueryable = DbSet
149 | .Where(GetFilterExpression()).Where(@where).Select(@select);
150 | return iQueryable;
151 | }
152 |
153 | public List SendSql(string sqlQuery)
154 | {
155 | throw new NotImplementedException();
156 | }
157 |
158 |
159 | ///
160 | /// Clid ile yalıtabilmek için CLID ile ilgili expression oluşturur.
161 | ///
162 | ///
163 | private Expression> GetFilterExpression()
164 | {
165 | if (FilterProperty != null)
166 | {
167 | ParameterExpression argParams = Expression.Parameter(typeof(T), "x");
168 | Expression filterProp = Expression.Property(argParams, FilterColumnName);
169 | ConstantExpression filterValue = Expression.Constant(FilterColumnValue);
170 |
171 | BinaryExpression filterExpression = Expression.Equal(filterProp, filterValue);
172 | return Expression.Lambda>(filterExpression, argParams);
173 | }
174 |
175 | return x => true;
176 | }
177 |
178 |
179 | ///
180 | /// Verilen veriyi context üzerinde günceller.
181 | ///
182 | /// Güncellenecek entity
183 | public void Update(T entity)
184 | {
185 | throw new NotImplementedException("This repository is read-only.");
186 | }
187 |
188 | public void UpdateProperties(T entity, params string[] changeProperties)
189 | {
190 | throw new NotImplementedException("This repository is read-only.");
191 | }
192 |
193 | public void Update(Expression> predicate, T entity)
194 | {
195 | throw new NotImplementedException("This repository is read-only.");
196 | }
197 |
198 |
199 |
200 | public int SendSqlScalar(string sqlQuery)
201 | {
202 | throw new NotImplementedException("This repository is read-only.");
203 | }
204 | }
205 | }
206 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/Repository/IRepository.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.EntityFrameworkCore;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Linq.Expressions;
6 | using DMicroservices.DataAccess.History;
7 |
8 | namespace DMicroservices.DataAccess.Repository
9 | {
10 | public interface IRepository where T : class
11 | {
12 |
13 | ///
14 | /// Tüm veriyi getir.
15 | ///
16 | ///
17 | IQueryable GetAll();
18 |
19 | ///
20 | /// Veriyi Where metodu ile getir.
21 | ///
22 | ///
23 | ///
24 | IQueryable GetAll(Expression> predicate);
25 |
26 | ///
27 | /// Veriyi Where metodu ile getir.
28 | ///
29 | ///
30 | ///
31 | ///
32 | IQueryable GetAll(Expression> predicate, List includePaths);
33 |
34 | ///
35 | /// Verilen sorguya göre tablodaki sayıyı gönderir.
36 | ///
37 | ///
38 | ///
39 | int Count();
40 | ///
41 | /// Verilen sorguya göre tablodaki sayıyı gönderir.
42 | ///
43 | ///
44 | ///
45 | int Count(Expression> predicate);
46 |
47 | ///
48 | /// İstenilen veriyi single olarak getirir.
49 | ///
50 | ///
51 | ///
52 | T Get(Expression> predicate);
53 |
54 | ///
55 | /// İstenilen veriyi single olarak getirir.
56 | ///
57 | ///
58 | ///
59 | TResult Get(Expression> predicate, Expression> @select);
60 |
61 | ///
62 | /// İstenilen veriyi single olarak getirir.
63 | ///
64 | ///
65 | T Get(Expression> predicate, List includePaths);
66 |
67 | ///
68 | /// Getirilen veri üzerinde veri gelmeden kolonları seç.
69 | ///
70 | /// Veri kısıtlamaları
71 | /// Seçilecek kolonlar
72 | ///
73 | IQueryable SelectList(Expression> @where, Expression> @select);
74 |
75 | ///
76 | /// Getirilen veri üzerinde veri gelmeden kolonları seç.
77 | ///
78 | /// Veri kısıtlamaları
79 | /// Seçilecek kolonlar
80 | ///
81 | IQueryable SelectList(Expression> @where, Expression> @select);
82 |
83 | ///
84 | /// Entity ile sql sorgusu göndermek için kullanılır.
85 | ///
86 | /// Gönderilecek sql
87 | ///
88 | List SendSql(string sqlQuery);
89 |
90 | ///
91 | /// Execute sql query. Return affected rows.
92 | ///
93 | ///
94 | ///
95 | int SendSqlScalar(string sqlQuery);
96 |
97 | ///
98 | /// Verilen entityi ekle.
99 | ///
100 | ///
101 | void Add(T entity);
102 |
103 | ///
104 | /// Verilen entityi ekle.
105 | ///
106 | ///
107 | void BulkInsert(List entityList);
108 |
109 | ///
110 | /// Verilen entity i güncelle.
111 | ///
112 | ///
113 | void Update(T entity);
114 |
115 | ///
116 | /// Verilen entity i güncelle.
117 | ///
118 | ///
119 | void UpdateProperties(T entity,params string[] changeProperties);
120 |
121 | ///
122 | /// predicate göre veriler düzenlenir.
123 | ///
124 | ///
125 | ///
126 | void Update(Expression> predicate, T entity);
127 |
128 | ///
129 | /// Verilen entityi sil.
130 | ///
131 | ///
132 | void Delete(T entity, bool forceDelete = false);
133 |
134 | ///
135 | /// predicate göre veriler silinir.
136 | ///
137 | ///
138 | void Delete(Expression> predicate, bool forceDelete = false);
139 |
140 | ///
141 | /// Verilen entityi sil.
142 | ///
143 | ///
144 | void BulkDelete(List entityList);
145 |
146 | ///
147 | /// Aynı kayıt eklememek için objeyi kontrol ederek true veya false dönderir.
148 | ///
149 | ///
150 | ///
151 | ///
152 | bool Any(Expression> predicate);
153 |
154 | ///
155 | /// DbContext i verir.
156 | ///
157 | ///
158 | DbContext GetDbContext();
159 |
160 | List GetIncludePaths();
161 |
162 |
163 |
164 | }
165 | }
166 |
167 |
168 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/Repository/ReadonlyRepository.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Linq;
5 | using System.Linq.Expressions;
6 | using DMicroservices.DataAccess.History;
7 | using DMicroservices.Utils.Extensions;
8 | using Microsoft.EntityFrameworkCore;
9 | using Microsoft.EntityFrameworkCore.ChangeTracking;
10 |
11 | namespace DMicroservices.DataAccess.Repository
12 | {
13 | ///
14 | /// EntityFramework için hazırlıyor olduğumuz bu repositoriyi daha önceden tasarladığımız generic repositorimiz olan IRepository arayüzünü implemente ederek tasarladık.
15 | /// Bu şekilde tasarlamamızın ana sebebi ise veritabanına independent(bağımsız) bir durumda kalabilmek.
16 | ///
17 | ///
18 | public class ReadonlyRepository : IRepository where T : class
19 | {
20 | private readonly DbContext DbContext;
21 | private readonly DbSet DbSet;
22 |
23 | ///
24 | /// Repository instance ı başlatırç
25 | ///
26 | /// Veritabanı bağlantı nesnesi
27 | public ReadonlyRepository(DbContext dbContext)
28 | {
29 | DbContext = dbContext;
30 | DbSet = dbContext.Set();
31 | }
32 |
33 | public void Add(T entity)
34 | {
35 | throw new NotImplementedException("This repository is read-only.");
36 | }
37 |
38 | public void BulkInsert(List entityList)
39 | {
40 | throw new NotImplementedException("This repository is read-only.");
41 | }
42 |
43 | ///
44 | /// Aynı kayıt eklememek için objeyi kontrol ederek true veya false dönderir.
45 | ///
46 | ///
47 | ///
48 | ///
49 | public bool Any(Expression> predicate)
50 | {
51 | return DbSet.Any(predicate);
52 | }
53 |
54 | public DbContext GetDbContext()
55 | {
56 | return DbContext;
57 | }
58 |
59 | public List GetIncludePaths()
60 | {
61 | return DbContext.GetIncludePaths(typeof(T)).ToList();
62 | }
63 |
64 | public int Count()
65 | {
66 | return Count(arg => true);
67 | }
68 |
69 | public int Count(Expression> predicate)
70 | {
71 | IQueryable iQueryable = DbSet
72 | .Where(predicate);
73 | return iQueryable.Count();
74 | }
75 |
76 | public void Delete(T entity, bool forceDelete = false)
77 | {
78 | throw new NotImplementedException("This repository is read-only.");
79 | }
80 |
81 | public void Delete(Expression> predicate, bool forceDelete = false)
82 | {
83 | throw new NotImplementedException("This repository is read-only.");
84 | }
85 | public void BulkDelete(List entityList)
86 | {
87 | throw new NotImplementedException("This repository is read-only.");
88 | }
89 |
90 | public T Get(Expression> predicate)
91 | {
92 | IQueryable iQueryable = DbSet
93 | .Where(predicate);
94 | return iQueryable.ToList().FirstOrDefault();
95 | }
96 |
97 | public TResult Get(Expression> predicate, Expression> @select)
98 | {
99 | IQueryable iQueryable = DbSet
100 | .Where(predicate);
101 | return iQueryable.Select(@select).FirstOrDefault();
102 | }
103 |
104 | public T Get(Expression> predicate, List includePaths)
105 | {
106 | IQueryable iQueryable = DbSet
107 | .Where(predicate).Include(includePaths);
108 | return iQueryable.ToList().FirstOrDefault();
109 | }
110 |
111 | public IQueryable GetAll()
112 | {
113 | IQueryable iQueryable = DbSet.Where(x => x != null);
114 | return iQueryable;
115 | }
116 |
117 | public IQueryable GetAll(System.Linq.Expressions.Expression> predicate)
118 | {
119 | IQueryable iQueryable = DbSet
120 | .Where(predicate);
121 | return iQueryable;
122 | }
123 |
124 | public IQueryable GetAll(System.Linq.Expressions.Expression> predicate, List includePaths)
125 | {
126 | IQueryable iQueryable = DbSet
127 | .Where(predicate).Include(includePaths);
128 | return iQueryable;
129 | }
130 |
131 | public IQueryable SelectList(Expression> where, Expression> select)
132 | {
133 | throw new NotImplementedException();
134 | }
135 |
136 | public IQueryable SelectList(Expression> @where, Expression> @select)
137 | {
138 | IQueryable iQueryable = DbSet
139 | .Where(@where).Select(@select);
140 | return iQueryable;
141 | }
142 |
143 | public List SendSql(string sqlQuery)
144 | {
145 | throw new NotImplementedException();
146 | }
147 |
148 |
149 | ///
150 | /// Verilen veriyi context üzerinde günceller.
151 | ///
152 | /// Güncellenecek entity
153 | public void Update(T entity)
154 | {
155 | throw new NotImplementedException("This repository is read-only.");
156 | }
157 |
158 | public void UpdateProperties(T entity, params string[] changeProperties)
159 | {
160 | throw new NotImplementedException("This repository is read-only.");
161 | }
162 |
163 | public void Update(Expression> predicate, T entity)
164 | {
165 | throw new NotImplementedException("This repository is read-only.");
166 | }
167 |
168 | public int SendSqlScalar(string sqlQuery)
169 | {
170 | throw new NotImplementedException("This repository is read-only.");
171 | }
172 |
173 | }
174 | }
175 |
--------------------------------------------------------------------------------
/DMicroservices/DataAccess/Repository/Repository.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Linq.Expressions;
5 | using System.Reflection;
6 | using DMicroservices.Base.Attributes;
7 | using DMicroservices.DataAccess.History;
8 | using DMicroservices.Utils.Extensions;
9 | using Microsoft.EntityFrameworkCore;
10 | using Microsoft.EntityFrameworkCore.ChangeTracking;
11 | using Microsoft.EntityFrameworkCore.Metadata.Internal;
12 |
13 | namespace DMicroservices.DataAccess.Repository
14 | {
15 | ///
16 | /// EntityFramework için hazırlıyor olduğumuz bu repositoriyi daha önceden tasarladığımız generic repositorimiz olan IRepository arayüzünü implemente ederek tasarladık.
17 | /// Bu şekilde tasarlamamızın ana sebebi ise veritabanına independent(bağımsız) bir durumda kalabilmek.
18 | ///
19 | ///
20 | public class Repository : IRepository where T : class
21 | {
22 | private readonly DbContext DbContext;
23 | private readonly DbSet DbSet;
24 |
25 | ///
26 | /// Repository instance ı başlatırç
27 | ///
28 | /// Veritabanı bağlantı nesnesi
29 | public Repository(DbContext dbContext)
30 | {
31 | DbContext = dbContext;
32 | DbSet = dbContext.Set();
33 | }
34 |
35 | public void Add(T entity)
36 | {
37 | DbSet.Add(entity);
38 | }
39 |
40 | public void BulkInsert(List entityList)
41 | {
42 | foreach (var entity in entityList)
43 | {
44 | DbSet.Add(entity);
45 | }
46 | }
47 |
48 | ///
49 | /// Aynı kayıt eklememek için objeyi kontrol ederek true veya false dönderir.
50 | ///
51 | ///
52 | ///
53 | ///
54 | public bool Any(Expression> predicate)
55 | {
56 | return DbSet.Any(predicate);
57 | }
58 |
59 | ///
60 | /// Aynı kayıt eklememek için objeyi varsa alt ilişkisiyle birlikte kontrol ederek true veya false dönderir.
61 | ///
62 | ///
63 | /// Sorgu
64 | /// Join nesnelerinin classı
65 | ///
66 | public bool Any(Expression> predicate, List includePaths)
67 | {
68 | return DbSet.Include(includePaths).Any(predicate);
69 | }
70 |
71 | public DbContext GetDbContext()
72 | {
73 | return DbContext;
74 | }
75 |
76 | public List GetIncludePaths()
77 | {
78 | return DbContext.GetIncludePaths(typeof(T)).ToList();
79 | }
80 |
81 | public int Count()
82 | {
83 | return Count(arg => true);
84 | }
85 |
86 | public int Count(Expression> predicate)
87 | {
88 | IQueryable iQueryable = DbSet
89 | .Where(predicate);
90 | return iQueryable.Count();
91 | }
92 |
93 | public int Count(Expression> predicate, List includePaths)
94 | {
95 | IQueryable iQueryable = DbSet.Include(includePaths)
96 | .Where(predicate);
97 | return iQueryable.Count();
98 | }
99 |
100 | public void Delete(T entity, bool forceDelete = false)
101 | {
102 | // Önce entity'nin state'ini kontrol etmeliyiz.
103 | EntityEntry dbEntityEntry = DbContext.Entry(entity);
104 |
105 | if (dbEntityEntry.State != EntityState.Deleted)
106 | {
107 | dbEntityEntry.State = EntityState.Deleted;
108 | }
109 | else
110 | {
111 | DbSet.Attach(entity);
112 | DbSet.Remove(entity);
113 | }
114 | }
115 |
116 | public void Delete(Expression> predicate, bool forceDelete = false)
117 | {
118 | T model = DbSet.FirstOrDefault(predicate);
119 |
120 | if (model != null)
121 | Delete(model, forceDelete);
122 | }
123 | public void BulkDelete(List entityList)
124 | {
125 | foreach (var entity in entityList)
126 | {
127 | DbSet.Remove(entity);
128 | }
129 | }
130 |
131 | public T Get(Expression> predicate)
132 | {
133 | IQueryable iQueryable = DbSet
134 | .Where(predicate);
135 | return iQueryable.ToList().FirstOrDefault();
136 | }
137 |
138 | public TResult Get(Expression> predicate, Expression> @select)
139 | {
140 | IQueryable iQueryable = DbSet
141 | .Where(predicate);
142 | return iQueryable.Select(@select).FirstOrDefault();
143 | }
144 |
145 | public T Get(Expression> predicate, List includePaths)
146 | {
147 | IQueryable iQueryable = DbSet
148 | .Where(predicate).Include(includePaths);
149 | return iQueryable.ToList().FirstOrDefault();
150 | }
151 |
152 | public IQueryable GetAll()
153 | {
154 | IQueryable iQueryable = DbSet.Where(x => x != null);
155 | return iQueryable;
156 | }
157 |
158 | public IQueryable GetAll(System.Linq.Expressions.Expression> predicate)
159 | {
160 | IQueryable iQueryable = DbSet
161 | .Where(predicate);
162 | return iQueryable;
163 | }
164 |
165 | public IQueryable GetAll(System.Linq.Expressions.Expression> predicate, List includePaths)
166 | {
167 | IQueryable iQueryable = DbSet
168 | .Where(predicate).Include(includePaths);
169 | return iQueryable;
170 | }
171 |
172 | public IQueryable SelectList(Expression> where, Expression | | | | |