Sorting Details Page MVC - asp.net-mvc

I cant figured out how perform sort in a details page. I have a classic page with list of order and for each row i have a actionlink to return details view of that order.
i try this
public ActionResult Details(int? anno,int? nr, string centro, string sortOrder)
{
ViewBag.Codice = String.IsNullOrEmpty(sortOrder) ? "Articolo_desc" : "";
if (anno == null && nr == null && string.IsNullOrEmpty(centro))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
else
{
string s = "anno=" + Request.QueryString["anno"] + "&nr=" + Request.QueryString["nr"] + "&centro=" + Request.QueryString["centro"];
ViewBag.search = s.Replace("search=", "").Replace("%3D", "=");
}
var righe = from d in db.DETAILS
where d.Anno == anno && d.Num == nr && d.Centro == centro
select new DetailsOrdersView
{
Articolo = r.Codice,
...
};
if (righe == null)
return HttpNotFound();
switch(sortOrder)
{
case "Articolo_desc":
righe = righe.OrderByDescending(i => i.Articolo);
break;
default:
righe = righe.OrderBy(i => i.Articolo);
break;
}
return View(righe);
}
}
and in details view
#Html.ActionLink("codice","Details", new { sortOrder = ViewBag.Codice, ViewBag.search })
but i on sorting I get bad request and this is the route
Orders/Details?sortOrder=Articolo_desc&search=anno%3D2017%26nr%3D6%26centro%3D1

#Html.ActionLink("codice", "Details", new { sortOrder = ViewBag.Codice, anno = ViewBag.Anno, centro = ViewBag.Centro , nr= ViewBag.Numero })
i solved as above

Related

asp.net mvc core A second operation was started on the context before the first operation is completed

I am using this code for authorization on controllers.
with [Authorize(Policy = "CustomRole")]
The thing happened that after 3 or 4 request it fails with
A second operation started on this context before a previous operation completed
public class CustomRoleRequirement : AuthorizationHandler<CustomRoleRequirement>, IAuthorizationRequirement
{
public CMSContext _context = new CMSContext();
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRoleRequirement requirement)
{
var routeobj = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;
var c = routeobj.RouteData.Values.Values.ToList();
var keys = routeobj.RouteData.Values.Keys.ToList();
string area = "";
string id = "";
string controller = "";
string action = "";
string module = "";
foreach (var item in keys)
{
if (item=="area")
{
int indexs = keys.FindIndex(cc => cc == "area");
area = c[indexs].ToString();
}
else if (item == "id")
{
int indexs = keys.FindIndex(cc => cc == "id");
id = c[indexs].ToString();
}
else if (item == "controller")
{
int indexs = keys.FindIndex(cc => cc == "controller");
controller = c[indexs].ToString();
}
else if (item == "module")
{
int indexs = keys.FindIndex(cc => cc == "module");
module = c[indexs].ToString();
}
else if (item == "action")
{
int indexs = keys.FindIndex(cc => cc == "action");
action = c[indexs].ToString();
}
}
string modulelink = controller;
if (!string.IsNullOrEmpty(module))
{
modulelink = modulelink + "/" + module;
}
List<string> Roles = new List<string>();
int UserId = Auth.UserID;
string UserName = Auth.UserName;
if (UserName == "superadmin")
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
// apparently the error occurred here
var moduleobj = _context.AppModules.FirstOrDefault(q => q.Link == modulelink);
if (moduleobj != null)
{ // 69 role is assessing news module
//60 role is accessing page module
var RolesModulesobj = _context.AppRolesModules.FirstOrDefault(q => q.ModuleId == moduleobj.ModuleId && q.RolesId == Auth.RoleId);
if (RolesModulesobj != null)
{
string permissionsobj = RolesModulesobj.Permissions;
List<string> PermissionsListobj = permissionsobj.Split(',').Select(x => x.Trim()).ToList();
var FindFullAccess = PermissionsListobj.FirstOrDefault(q => q.Contains("FullAccess:true"));
if (FindFullAccess != null)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
var abc = PermissionsListobj.FirstOrDefault(q => q.Contains(action + ":true"));
if (abc != null)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
context.Fail();
return Task.CompletedTask;
}
}
}
}
}
The error occurred at this line above
var moduleobj = _context.AppModules.FirstOrDefault(q => q.Link == modulelink);
How can I make task wait before the second operation started in the method above?
You can't use a singleton DB context. You either create one each time you need one or you pool them.

How to increase the performance for login response

I am working on one MVC application. After clicking on login button it is taking me almost 7 second to redirect on home page which is not a good response time as per performance. Please help me how to make response time better.
Below is my controller code.
public ActionResult UserLogIn(Models.LogIn user)
{
if (ModelState.IsValid)
{
if (IsValid(user.User_Id, user.User_Password))
{
using (var db = new CopaRuleContext())
{
var ApproveUsers = db.tbl_User.Where(u => u.User_Approved == "Yes" && u.User_Id == user.User_Id).ToList();
var UserDetails = db.tbl_User.FirstOrDefault(u => u.User_Id == user.User_Id);
string UserRole = UserDetails.User_Role;
if (UserRole != null)
{
Session["UserRole"] = UserDetails.User_Role;
}
var rolename = db.tbl_Roles.FirstOrDefault(u => u.Role_Name == UserRole);
if (rolename != null)
{
Session["RoleName"] = rolename.Role_Description;
}
var firstname = UserDetails.User_First_Name;
var lastname = UserDetails.User_Last_Name;
firstname = firstname.Substring(0, 1).ToUpper() + firstname.Substring(1).ToLower();
lastname = lastname.Substring(0, 1).ToUpper() + lastname.Substring(1).ToLower();
Session["UserName"] = firstname + ' ' + lastname;
Session["UserId"] = UserDetails.User_Id;
if (ApproveUsers != null && ApproveUsers.Count() > 0)
{
if (UserDetails.User_Is_Deleted != 1)
{
Session["Process"] = "PP";
if (UserRole == "Role-1")
{
FormsAuthentication.SetAuthCookie(user.User_Id, false);
return RedirectToAction("Notification", "Inbox");
}
else if (UserRole == "Role-2")
{
FormsAuthentication.SetAuthCookie(user.User_Id, false);
return RedirectToAction("Clear", "Clear");
}
if (UserRole == "Role-3")
{
FormsAuthentication.SetAuthCookie(user.User_Id, false);
return RedirectToAction("Notification", "Inbox");
}
if (UserRole == "Role-4")
{
FormsAuthentication.SetAuthCookie(user.User_Id, false);
return RedirectToAction("Notification", "Inbox");
}
}
}
}
}
}
return View(user);
}
I was having problem with password encryption. I was using salt hash technique to encrypt the password which was affecting the performance of login. I have changed it with SHA1 encryption and performance has became incredibly fast.

Return null When Using DropDownList

I want to add news in database. When I use this code for Select Category return
Me Null . How can I resolve this?
<select name="category">
#{
foreach (var item in RCat.MainCategory().Where(a=>a.ParentID==1))
{
<option value="#item.ID">#item.Title</option>
}
}
</select>
My Controller :
[HttpPost]
[ValidateInput(false)]
public ActionResult CreateNews(Tbl_News t, HttpPostedFileBase pic, int Category)
{
try
{
if (Session["Username"] == null)
return RedirectToAction("Register", "Home");
if (pic == null)
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . باید عکسی را برای خبر انتخاب کنید";
return View();
}
if (Category == 0)
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . باید یکی از دسته ها را انتخاب کنید";
return View();
}
t.Date = DateTime.Now.Date;
t.Dislike = 0;
t.Like = 0;
t.Visit = 0;
t.Username = Session["Username"].ToString();
if (t.Type != "iran" && t.Type != "world" && t.Type != "sport" && t.Type != "art" && t.Type != "knowledge" && t.Type != "economic" && t.Type != "memo" && t.Type != "you" && t.Type != "pic" && t.Type != "video")
t.Type = null;
if (ModelState.IsValid)
{
if (pic != null)
{
if (pic.ContentLength <= 512000)
{
if (pic.ContentType == "image/jpeg")
{
Random rnd = new Random();
string picname = rnd.Next().ToString();
string path = System.IO.Path.Combine(Server.MapPath("~/Content/img/NewsPic/"));
pic.SaveAs(path + picname);
t.Image = picname;
db.Tbl_News.Add(t);
if (Convert.ToBoolean(db.SaveChanges()))
{
var q = (from a in db.Tbl_News
orderby a.Date descending
select a).FirstOrDefault();
Tbl_Cat_News TCN = new Tbl_Cat_News();
TCN.NewsID = q.ID;
TCN.CatID = Category;
db.Tbl_Cat_News.Add(TCN);
if (Convert.ToBoolean(db.SaveChanges()))
{
ViewBag.Style = "color:green";
ViewBag.Message = "با موفقیت ثبت شد";
return View();
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . خبر ثبت نشد";
return View();
}
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . خبر ثبت نشد";
return View();
}
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . فرمت تصویر باید jpg باشد";
return View();
}
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . حجم تصویر باید بیشتر کمتر از 515 کیلو بایت باشد";
return View();
}
}
else
{
return RedirectToAction("Logout", "Admin");
}
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . تمامی فیلدها باید پر شوند";
return View();
}
}
catch (Exception)
{
return Content("خطا");
}
}
You have all OR condition, so if any type not match with any condition it fires "t.Type = null;" and because of that you always get "NULL" value.

MVC 4 Paging Searching

I have applied search method in my project but , I have also Action index()
and getting erorr. (The current request for action 'Index' on controller type 'AdultLiteracyTeachersController' is ambiguous between the following action methods:)
public ViewResult Index(string searchstring, string currentFilter, int? page)
{
if (searchstring != null)
{
page = 1;
}
else
{
searchstring = currentFilter;
}
ViewBag.CurrentFilter = searchstring;
var teachers = from r in db.AdulLiteracyTeachers select r;
if (!string.IsNullOrEmpty(searchstring))
{
teachers = teachers.Where(r => r.ALTName.ToUpper().Contains(searchstring.ToUpper()));
}
teachers = teachers.OrderBy(r => r.ALTName);
int pagesize = 10;
int pageNo = (page ?? 1);
return View(teachers.ToPagedList(pageNo, pagesize));
}
The other ActionResult.index()
public ActionResult Index()
{
var adulliteracyteachers = db.AdulLiteracyTeachers.Include(a => a.District);
return View(adulliteracyteachers.ToList());
}
Action result is used for calling all data how can I aplly in single index ?
Combine them:
public ViewResult Index(string searchstring, string currentFilter, int? page)
{
if (searchString == null && currentFilter == null && !page.HasValue)
{
// No parameters
var adulliteracyteachers = db.AdulLiteracyTeachers.Include(a => a.District);
return View(adulliteracyteachers.ToList());
}
// Regular code here down
if (searchstring != null)
{
page = 1;
}
else
{
searchstring = currentFilter;
}
ViewBag.CurrentFilter = searchstring;
var teachers = from r in db.AdulLiteracyTeachers select r;
if (!string.IsNullOrEmpty(searchstring))
{
teachers = teachers.Where(r => r.ALTName.ToUpper().Contains(searchstring.ToUpper()));
}
teachers = teachers.OrderBy(r => r.ALTName);
int pagesize = 10;
int pageNo = (page ?? 1);
return View(teachers.ToPagedList(pageNo, pagesize));
}

uBlogsy (webforms) PostService showing no posts on landing page

I'm using uBlogsy WebForms 3.0.2 on Umbraco 6.1.5...
And the posts on the landing page are not showing up.
The function PostService.Instance.GetPosts is returning 0 posts, even though there are posts in the correct location.
I still get 0 posts when I try to substitute this:
var posts = PostService.Instance
.GetPosts(
IPublishedContentHelper.GetNode((int)Model.Id)
).ToIPublishedContent(true);
int postCount = posts.Count();
Would anyone know why the PostService isn't working? Or, what is going on?
I had same problem couple of times with Ublogsy. So I decided to write my own codes as below:
(Its a bit long)
// get tag, label, or author from query string
var tag = Request.QueryString["tag"] ?? "";
var label = Request.QueryString["label"] ?? "";
var author = Request.QueryString["author"] ?? "";
var searchTerm = Request.QueryString["search"] ?? "";
var commenter = Request.QueryString["commenter"] ?? "";
int page = int.TryParse(Request.QueryString["page"], out page) ? page : 1;
var year = Request.QueryString["year"] ?? "";
var month = Request.QueryString["month"] ?? "";
var day = Request.QueryString["day"] ?? "";
int postCount;
IEnumerable<IPublishedContent> posts = new BlockingCollection<IPublishedContent>();
var filterResults = this.FilterAgainstPosts(this.Model.Content, tag, label, author, searchTerm, commenter, year, month);
if (filterResults != null)
{
posts = Enumerable.Take(filterResults.Skip((page - 1) * itemsPerPage), itemsPerPage);
}
#RenderForLanding(posts)
And my FilterAgainstPosts method is as follow:
#functions
{
private IEnumerable<IPublishedContent> FilterAgainstPosts(IPublishedContent landing, string tag, string label, string author, string searchTerm, string commenter, string year, string month)
{
IEnumerable<IPublishedContent> filteredPosts = landing.DescendantsOrSelf("uBlogsyPost").Where(x => x.GetProperty("umbracoNaviHide").Value.ToString() != "1");
if (!String.IsNullOrEmpty(searchTerm))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterAgainstTerm(i, searchTerm));
}
if (!String.IsNullOrEmpty(tag))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponTag(i, i.GetProperty("uBlogsyPostTags").Value.ToString(), tag));
}
if (!String.IsNullOrEmpty(label))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponLabel(i, i.GetProperty("uBlogsyPostLabels").Value.ToString(), label));
}
if (!String.IsNullOrEmpty(author))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponAuthor(i, i.GetProperty("uBlogsyPostAuthor").Value.ToString(), author));
}
//
//TODO: Coomenter search needs to added
//
if (!string.IsNullOrEmpty(year))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponYear(i, i.GetProperty("uBlogsyPostDate").Value.ToString(), year));
}
if (!string.IsNullOrEmpty(month))
{
filteredPosts = filteredPosts.ForEach(i => this.FilterUponMonth(i, i.GetProperty("uBlogsyPostDate").Value.ToString(), month));
}
return filteredPosts.WhereNotNull();
}
private IPublishedContent FilterUponMonth(IPublishedContent currentNode, string postDate, string month)
{
DateTime postedDate;
if (DateTime.TryParse(postDate, out postedDate) && postedDate.Month.ToString() == month) return currentNode;
return null;
}
private IPublishedContent FilterUponYear(IPublishedContent currentNode, string postDate, string year)
{
DateTime postedDate;
if (DateTime.TryParse(postDate, out postedDate) && postedDate.Year.ToString() == year) return currentNode;
return null;
}
private IPublishedContent FilterUponAuthor(IPublishedContent currentNode, string authorId, string author)
{
if (String.IsNullOrEmpty(authorId)) return null;
//Loads relevant node
int authorNodeId = -1;
if (!Int32.TryParse(authorId, out authorNodeId)) return null;
Node authorNode = new Node(authorNodeId);
//Trims the author name and search for given name
if (authorNode.GetProperty("uBlogsyAuthorName") != null && authorNode.GetProperty("uBlogsyAuthorName").Value.ToUpper().Trim().Contains(author.ToUpper())) return currentNode;
return null;
}
private Boolean FilterUponAuthor(string authorId, string author)
{
if (String.IsNullOrEmpty(authorId)) return false;
int authorNodeId = -1;
if (!Int32.TryParse(authorId, out authorNodeId)) return false;
Node authorNode = new Node(authorNodeId);
if (authorNode.GetProperty("uBlogsyAuthorName") != null && authorNode.GetProperty("uBlogsyAuthorName").Value.ToUpper().Trim().Contains(author.ToUpper())) return true;
return false;
}
private Boolean FilterUponCategories(string categoryIds, string category)
{
if (String.IsNullOrEmpty(categoryIds)) return false;
int categoryNodeID = -1;
foreach (string catID in categoryIds.Split(','))
{
if (!Int32.TryParse(catID, out categoryNodeID)) continue;
Node categoryNode = new Node(categoryNodeID);
if (categoryNode.GetProperty("uBlogsyLabelName") != null && categoryNode.GetProperty("uBlogsyLabelName").Value.ToUpper().Trim().Contains(category.ToUpper())) return true;
}
return false;
}
private Boolean FilterUponTags(string tagIds, string tag)
{
if (String.IsNullOrEmpty(tagIds)) return false;
int tagNodeID = -1;
foreach (string tagID in tagIds.Split(','))
{
if (!Int32.TryParse(tagID, out tagNodeID)) continue;
Node tagNode = new Node(tagNodeID);
if (tagNode.GetProperty("uTagsyTagName") != null && tagNode.GetProperty("uTagsyTagName").Value.ToUpper().Trim().Contains(tag.ToUpper())) return true;
}
return false;
}
private IPublishedContent FilterUponLabel(IPublishedContent currentNode, string nodeIDs, string label)
{
if (String.IsNullOrEmpty(nodeIDs)) return null;
foreach (string nodeId in nodeIDs.Split(','))
{
int labelNodeId = -1;
if (!Int32.TryParse(nodeId, out labelNodeId))
continue;
//Loads relevant node
Node labelNode = new Node(labelNodeId);
if (labelNode.GetProperty("uBlogsyLabelName") != null && labelNode.GetProperty("uBlogsyLabelName").Value.ToUpper().Trim().Contains(label.ToUpper())) return currentNode;
}
return null;
}
private IPublishedContent FilterAgainstTerm(IPublishedContent currentNode, string searchTerm)
{
if (String.IsNullOrEmpty(searchTerm)) return currentNode;
if (currentNode.GetProperty("uBlogsyContentTitle").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsyContentSummary").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsyContentBody").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsySeoKeywords").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsySeoDescription").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
currentNode.GetProperty("uBlogsyNavigationTitle").Value.ToString().ToUpper().Contains(searchTerm.ToUpper()) ||
FilterUponAuthor(currentNode.GetProperty("uBlogsyPostAuthor").Value.ToString(), searchTerm.ToUpper()) ||
FilterUponCategories(currentNode.GetProperty("uBlogsyPostLabels").Value.ToString(), searchTerm.ToUpper()) ||
FilterUponTags(currentNode.GetProperty("uBlogsyPostTags").Value.ToString(), searchTerm.ToUpper())
)
return currentNode;
return null;
}
private IPublishedContent FilterUponTag(IPublishedContent currentNode, string nodeIDs, string tag)
{
if (String.IsNullOrEmpty(nodeIDs)) return null;
foreach (string nodeId in nodeIDs.Split(','))
{
int tagNodeId = -1;
if (!Int32.TryParse(nodeId, out tagNodeId))
continue;
// Loads relevant TagNode
Node tagNode = new Node(tagNodeId);
if (tagNode.GetProperty("uTagsyTagName") != null && tagNode.GetProperty("uTagsyTagName").Value.ToUpper().Contains(tag.ToUpper())) return currentNode;
}
return null;
}
}

Resources