source: PostgreSqlDotnetCore/Controllers/BlogController.cs

main
Last change on this file was e90ba32, checked in by ElenaMoskova <elena.moskova99@…>, 4 weeks ago

fix issues

fix bugs with nested tables
fix delete nested fk items

  • Property mode set to 100644
File size: 13.4 KB
Line 
1using Microsoft.AspNetCore.Identity;
2using Microsoft.AspNetCore.Mvc;
3using Microsoft.EntityFrameworkCore;
4using PostgreSqlDotnetCore.Data;
5using PostgreSqlDotnetCore.Models;
6using System.Net;
7
8namespace PostgreSqlDotnetCore.Controllers
9{
10 public class BlogController : BaseController
11 {
12 public BlogController(UserManager<IdentityUser> userManager) : base(userManager)
13
14 {
15
16 }
17
18 // GET: Customer
19 /* public async Task<ActionResult> IndexAsync()
20 {
21 // check for permission
22 bool isAuthenticated = User.Identity.IsAuthenticated;
23 if (!isAuthenticated)
24 {
25 return RedirectToAction("AccessDenied", "Error");
26 }
27 //return View(Enumerable.Empty<UsersClass>());
28 return View(db.BlogPostControllerObj.ToList());
29 }
30 */
31
32 /* public async Task<ActionResult> Index()
33 {
34 // Проверка за автентикација
35 bool isAuthenticated = User.Identity.IsAuthenticated;
36
37 if (!isAuthenticated)
38 {
39 return RedirectToAction("AccessDenied", "Error");
40 }
41
42 // Список на блог постови
43 var blogPosts = await db.BlogPostControllerObj.ToListAsync();
44
45 // Предавање на ViewBag за проверка на автентикација
46 ViewBag.isAuthenticated = isAuthenticated;
47
48 return View(blogPosts);
49 }*/
50
51 public async Task<ActionResult> Index()
52 {
53 // Проверка за автентикација
54 bool isAuthenticated = User.Identity.IsAuthenticated;
55
56 if (!isAuthenticated)
57 {
58 return RedirectToAction("AccessDenied", "Error");
59 }
60
61 // Список на блог постови
62 var blogPosts = await db.BlogUsers.ToListAsync();
63
64 // Вземи тековниот корисник
65 var currentUser = await _userManager.GetUserAsync(User);
66 var customerClass = await db.CustomerObj.SingleOrDefaultAsync(x => x.email == currentUser.Email);
67
68 // Предавање на ViewBag за проверка на автентикација и корисничкиот ID
69 ViewBag.isAuthenticated = isAuthenticated;
70 // no access for standard user
71 ViewBag.OnlyAdminManager = await checkAuthorizationSpecificRoleAsync(RoleConstants.Admin) ?? await checkAuthorizationSpecificRoleAsync(RoleConstants.Manager);
72
73 ViewBag.CurrentUserId = customerClass?.id;
74
75 return View(blogPosts);
76 }
77
78
79
80
81
82 // GET: Customer/Details/5
83 public async Task<ActionResult> DetailsAsync(int? id)
84 {
85 if (id == null)
86 {
87 return View(null);
88 //return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
89 }
90 BlogPostConsultation blogClass = db.BlogPostControllerObj.Find(id);
91 UsersClass customerClass = await getCrrentUser();
92 ViewBag.isAuthenticated = customerClass;
93 if (blogClass == null)
94 {
95 return RedirectToAction("NotExist", "Error");
96 }
97 // get answers
98
99 // query
100 var query = from st in db.BlogPostAnswersObj
101 where st.BlogPostConsultationid == blogClass.id
102 select st;
103 //elenaaa
104 var blogAnswers = query.ToList();
105 blogClass.BlogPostAnswers = blogAnswers;
106 ViewBag.OnlyAdminManager = await checkAuthorizationSpecificRoleAsync(RoleConstants.Admin) ?? await checkAuthorizationSpecificRoleAsync(RoleConstants.Manager);
107 ViewBag.CurrentUserId = customerClass?.id;
108 return View(blogClass);
109 }
110
111 // GET: Customer/Create
112 //public ActionResult Create()
113 //{
114 // return View();
115 //}
116
117 /* public ActionResult Create()
118 {
119 var model = new BlogPostConsultation();
120 return View(model);
121 }*/
122
123 public async Task<ActionResult> CreateAsync()
124 {
125
126 // check for permission
127 //UsersClass customerClass = await checkAuthorizationAsync();
128 // ViewBag.isAuthenticated = await getCrrentUser();
129 UsersClass customerClass = await getCrrentUser();
130 // set if is authenticated
131 ViewBag.isAuthenticated = customerClass;
132 ViewBag.OnlyAdminManager = await checkAuthorizationSpecificRoleAsync(RoleConstants.Admin) ?? await checkAuthorizationSpecificRoleAsync(RoleConstants.Manager);
133
134 return View();
135 }
136
137 // POST: Customer/Create
138 // To protect from overposting attacks, enable the specific properties you want to bind to, for
139 // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
140 [HttpPost]
141 [ValidateAntiForgeryToken]
142 public async Task<ActionResult> CreateAsync([Bind(include: "id,date_askes,title,description,users_id")] BlogPostConsultation blogClass)
143 {
144 if (ModelState.IsValid)
145 {
146 bool isAuthenticated = User.Identity.IsAuthenticated;
147 if (isAuthenticated)
148 {
149 var user = await _userManager.GetUserAsync(User);
150 var customerClass = db.CustomerObj.SingleOrDefault(x => x.email == user.Email);
151 //dodadeno na 25.08
152 ViewBag.isAuthenticated = await getCrrentUser();
153 if (customerClass != null)
154 {
155 // Поставете users_id на идентификаторот на корисникот
156 blogClass.users_id = customerClass.id;
157 //blogClass.date_askes = DateOnly.FromDateTime(DateTime.UtcNow);
158 blogClass.date_askes = DateOnly.FromDateTime(DateTime.Now); // Ова ќе стави локално време
159
160 db.BlogPostControllerObj.Add(blogClass);
161 await db.SaveChangesAsync();
162 return RedirectToAction("Index");
163 }
164 }
165 else
166 {
167 return RedirectToAction("AccessDenied", "Error");
168 }
169 }
170
171 return View(blogClass);
172 }
173
174
175
176
177
178
179
180 // GET: Customer/Edit/5
181 public async Task<ActionResult> EditAsync(int? id)
182 {
183 if (id == null)
184 {
185 return View(null);
186 //return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
187 }
188 BlogPostConsultation blogClass = db.BlogPostControllerObj.Find(id);
189 if (blogClass == null)
190 {
191 return RedirectToAction("NotExist", "Error");
192 }
193
194 // izbriseno na 26.08
195 UsersClass customerClass = await checkAuthorizationAsync();
196 //dodadeno na 26.08
197 // UsersClass customerClass = await checkAuthorizationSpecificRoleAsync(RoleConstants.Admin);
198 ViewBag.isAuthenticated = await getCrrentUser();
199 if (customerClass == null)
200 {
201
202 bool isAuthenticated = User.Identity.IsAuthenticated;
203 if (isAuthenticated)
204 {
205 var user = await _userManager.GetUserAsync(User);
206 customerClass = db.CustomerObj.SingleOrDefault(x => x.email == user.Email);
207 if (blogClass.users_id != customerClass.id)
208 {
209 return RedirectToAction("AccessDenied", "Error");
210 }
211 }
212 }
213 // no access for standard user
214 ViewBag.OnlyAdminManager = await checkAuthorizationSpecificRoleAsync(RoleConstants.Admin) ?? await checkAuthorizationSpecificRoleAsync(RoleConstants.Manager);
215 ViewBag.OnlyAdminManager1 = await checkAuthorizationSpecificRoleAsync(RoleConstants.Admin) ?? await checkAuthorizationSpecificRoleAsync(RoleConstants.Manager);
216
217
218 return View(blogClass);
219 }
220
221 // POST: Customer/Edit/5
222 // To protect from overposting attacks, enable the specific properties you want to bind to, for
223 // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
224 [HttpPost]
225 [ValidateAntiForgeryToken]
226 /* public ActionResult Edit([Bind(include: "id,date_askes,title,description,users_id")] BlogPostConsultation blogClass)
227 {
228 if (ModelState.IsValid)
229 {
230 db.Entry(blogClass).State = EntityState.Modified;
231 db.SaveChanges();
232 return RedirectToAction("Index");
233 }
234 return View(blogClass);
235 }*/
236
237
238 public async Task<ActionResult> EditAsync(int id, [Bind(include: "id,date_askes,title,description")] BlogPostConsultation blogClass)
239 {
240 if (ModelState.IsValid)
241 {
242 var existingBlogClass = await db.BlogPostControllerObj.FindAsync(id);
243 if (existingBlogClass != null)
244 {
245
246
247 // Запамтете ја старата вредност на users_id
248 blogClass.users_id = existingBlogClass.users_id;
249
250 db.Entry(existingBlogClass).CurrentValues.SetValues(blogClass);
251 await db.SaveChangesAsync();
252 return RedirectToAction("Index");
253 }
254 }
255 return View(blogClass);
256 }
257
258
259
260 // GET: Customer/Delete/5
261
262 public async Task<ActionResult> DeleteAsync(int? id)
263 {
264 // UsersClass customerClass = await checkAuthorizationAsync();
265
266 ViewBag.isAuthenticated = await getCrrentUser();
267
268 if (id == null)
269 {
270 return View(null);
271 //return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
272 }
273 BlogPostConsultation blogClass = db.BlogPostControllerObj.Find(id);
274 if (blogClass == null)
275 {
276 return View(null);
277 //return HttpNotFound();
278 }
279 // check for permission
280 UsersClass customerClass = await checkAuthorizationAsync();
281 if (customerClass == null)
282 {
283
284 bool isAuthenticated = User.Identity.IsAuthenticated;
285 if (isAuthenticated)
286 {
287 var user = await _userManager.GetUserAsync(User);
288 customerClass = db.CustomerObj.SingleOrDefault(x => x.email == user.Email);
289 if (blogClass.users_id != customerClass.id)
290 {
291 return RedirectToAction("AccessDenied", "Error");
292 }
293 }
294 }
295 // no access for standard user
296 ViewBag.OnlyAdminManager = await checkAuthorizationSpecificRoleAsync(RoleConstants.Admin) ?? await checkAuthorizationSpecificRoleAsync(RoleConstants.Manager);
297
298 return View(blogClass);
299 }
300
301
302 // POST: Customer/Delete/5
303
304 /*
305 [HttpPost, ActionName("Delete")]
306 [ValidateAntiForgeryToken]
307 public ActionResult DeleteConfirmed(int id)
308 {
309 BlogPostConsultation blogClass = db.BlogPostControllerObj.Find(id);
310 db.BlogPostControllerObj.Remove(blogClass);
311 db.SaveChanges();
312 return RedirectToAction("Index");
313 }
314 */
315
316 [HttpPost, ActionName("Delete")]
317 [ValidateAntiForgeryToken]
318 public ActionResult DeleteConfirmed(int id)
319 {
320 // Наоѓање на објектот по ID
321 BlogPostConsultation blogClass = db.BlogPostControllerObj.Find(id);
322
323 // Проверка дали објектот е пронајден
324 if (blogClass == null)
325 {
326 // Ако објектот не е пронајден, враќаме 404 Not Found или друга соодветна акција
327 return View(null);
328 }
329 // prvo izbrisi gi site odgovori po sot BlogId e primaren kluc vo drugata tabela
330
331 // query
332 var query = from st in db.BlogPostAnswersObj
333 where st.BlogPostConsultationid == blogClass.id
334 select st;
335 //elenaaa
336 var blogAnswers = query.ToList();
337 foreach (BlogPostAnswers answerClass in blogAnswers)
338 {
339 db.BlogPostAnswersObj.Remove(answerClass);
340 db.SaveChanges();
341
342 }
343
344 // Отстранување на објектот ако е пронајден
345 db.BlogPostControllerObj.Remove(blogClass);
346 db.SaveChanges();
347
348 // Пренасочување на корисникот кон Index страницата
349 return RedirectToAction("Index");
350 }
351
352 // GET: Customer/Delete/5
353 // GET: Customer/Delete/5
354 // GET: Customer/Delete/5
355
356
357
358 protected override void Dispose(bool disposing)
359 {
360 if (disposing)
361 {
362 db.Dispose();
363 }
364 base.Dispose(disposing);
365 }
366 }
367}
Note: See TracBrowser for help on using the repository browser.