prestashop home category showing 404 error page - prestashop-1.6

In prestashop-1.6.1.5 after some code fixing the home category disappeared.
<?php
class CategoryController extends CategoryControllerCore
{
public function canonicalRedirection($canonicalURL = '')
{
if (Tools::getValue('live_edit'))
return ;
if (!Validate::isLoadedObject($this->category) ||
!$this->category->inShop() || !$this->category->isAssociatedToShop() ||
$this->category->id == Configuration::get('PS_ROOT_CATEGORY'))
{
$this->redirect_after = '404';
$this->redirect();
}
if (!Tools::getValue('noredirect') &&
Validate::isLoadedObject($this->category))
FrontController::canonicalRedirection(
$this->context->link->getCategoryLink($this->category));
}
}
?>

Related

ModelState validation on RedirectToAction in MVC

I want to implement ModelState.AddModelError on RedirectToAction in MVC. Currently, I am not getting error message. Can anyone please help me?
if(ModelState.IsValid)
{
var HList = hDetails.HTrackerList().Where(x => x.AccId == user.AccountID && x.UserId == user.Id).Select(y=>y.HorseId).ToList();
var datainList = HList.Contains(model.HorseId);
if(!datainList)
{
hDetails.InsertHorse(model);
}
else
{
ModelState.AddModelError("datainList", "Horse is already exist. Do you want to update it?");
}
}
return RedirectToAction("Home");
In the View:
#Html.ValidationMessage("datainList")
In your ontroller class:
public class YourController : Controller
{
[HttpPost]
public ActionResult TestMethod()
{
if(ModelState.IsValid)
{
var HList = hDetails.HTrackerList().Where(x => x.AccId == user.AccountID && x.UserId == user.Id).Select(y=>y.HorseId).ToList();
var datainList = HList.Contains(model.HorseId);
if(!datainList)
{
hDetails.InsertHorse(model);
}
else
{
TempData["datainListError"] = "Horse is already exist. Do you want to update it?";
}
}
return RedirectToAction("Home");
}
}
Then in the Home Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
if(TempData.ContainsKey("datainListError"))
{
ViewBag.ErrorMessage = TempData["datainListError"].ToString();
}
return View();
}
}
Then in the Index View:
#if(ViewBag.ErrorMessage != null)
{
<div class="alert alert-danger">#ViewBag.ErrorMessage</div>
}

Dashed routing in ASP.NET Core MVC?

Before Core, I used something like this in MVC:
public class HyphenatedRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
return base.GetHttpHandler(requestContext);
}
}
How can I in ASP.Net Core use dashes in urls? ... like http://www.example.com/my-friendly-url ... and convert it to action my_friendly_url.
I don't want to use Attribute Routes.
Thanks
Add this convention in Startup in ConfigureServices method:
options.Conventions.Add(new DashedRoutingConvention());
Routes in UseMvc will not work. They simply will not be considered by ASP.Net itself. I have created issue on GitHub... but not sure how it will go. For now you can specify routes with attributes on methods. Convention will reuse/copy original routes and update/add new dashed path in format {controller}/{action}.
public class DashedRoutingConvention : IControllerModelConvention
{
public void Apply(ControllerModel controller)
{
string parent = this.Convert(controller.ControllerName);
foreach (ActionModel action in controller.Actions)
{
string child = this.Convert(action.ActionName);
string template = $"{parent}/{child}";
if (this.Lookup(action.Selectors, template) == true)
continue;
List<SelectorModel> selectors = action.Selectors.Where(item => item.AttributeRouteModel?.Template == null).ToList();
if (selectors.Count > 0)
{
foreach (SelectorModel existing in selectors)
{
if (existing.AttributeRouteModel == null)
existing.AttributeRouteModel = new AttributeRouteModel();
existing.AttributeRouteModel.Template = template;
}
}
else
{
selectors = action.Selectors.Where(item => item.AttributeRouteModel?.Template != null).ToList();
foreach (SelectorModel existing in selectors)
{
SelectorModel selector = new SelectorModel(existing);
selector.AttributeRouteModel.Template = template;
if (action.Selectors.Any(item => this.Compare(item, selector)) == false)
action.Selectors.Add(selector);
}
}
}
}
private string Convert(string token)
{
if (token == null)
throw new ArgumentNullException(nameof(token));
if (token == string.Empty)
throw new ArgumentException("Failed to convert empty token.");
return Regex.Replace(token, "(?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])", "-$1", RegexOptions.Compiled).Trim().ToLower();
}
private bool Lookup(IEnumerable<SelectorModel> selectors, string template)
{
foreach (SelectorModel selector in selectors)
{
string current = selector.AttributeRouteModel?.Template;
if (string.Compare(current, template, StringComparison.OrdinalIgnoreCase) == 0)
return true;
}
return false;
}
private bool Compare(SelectorModel existing, SelectorModel adding)
{
if (existing.AttributeRouteModel == null && adding.AttributeRouteModel != null)
return false;
if (existing.AttributeRouteModel != null && adding.AttributeRouteModel == null)
return false;
if (existing.AttributeRouteModel != null && adding.AttributeRouteModel != null)
{
if (existing.AttributeRouteModel.Template != adding.AttributeRouteModel.Template)
return false;
if (existing.AttributeRouteModel.Order != adding.AttributeRouteModel.Order)
return false;
}
if (existing.ActionConstraints == null && adding.ActionConstraints != null)
return false;
if (existing.ActionConstraints != null && adding.ActionConstraints == null)
return false;
if (existing.ActionConstraints != null && adding.ActionConstraints != null)
{
if (existing.ActionConstraints.Count != adding.ActionConstraints.Count)
return false;
}
return true;
}
}

Showing pop up View when calling redirect in MVC

Scenario :
The scenario is if user press tab after entering AWB No. which he previously temporary saved, all ex values must populate on run time.
Problem :
Everything is working fine but view which is populated with ex values is opening as a pop up.
JavaScript for onchange
<script type="text/javascript">
$("#AWBNO").change(function () {
var AWB = $("#AWBNO").val();
var IGMa = $("#IGMa").val();
$.ajax({
url: '#Url.Content("~/IMPORTAWBs/AuthenticatingAWB")?awb=' + AWB + '&igm=' + IGMa,
async: false,
success: function (result) {
if (result == "Authenticated AWB!") {
$("input:disabled").removeAttr('disabled');
$("select:disabled").removeAttr('disabled');
$("#AWBNO").removeAttr('disabled');
$("#process").removeAttr('disabled');
$("#PAGENO").focus();
}
else {
$("#dialog").dialog({ appendTo: "#AWBNO" }).html(result);
$("input:enabled").prop('disabled', true);
$("select:enabled").prop('disabled', true);
$("#AWBNO").removeAttr('disabled');
$("#process").removeAttr('disabled');
$("#AWBNO").focus();
}
},
error: function (xhr, stats, errorMessage) {
alert(errorMessage);
}
});
});
Code for sending instance to Edit Method:
public ActionResult AuthenticatingAWB(string awb, string igm)
{
if (igm != null && awb != null)
{
string igmNO = igm;
var IgmNo = context.IMPORTAWBs.Where(f => f.IGMNO == igmNO && f.AWBNO == awb).FirstOrDefault();
var awbPart = context.IMPORTAWBs.Where(f => f.AWBNO == awb && f.IGMNO != igm && (f.SHIPMENTTYPE == "Part" || f.SHIPMENTTYPE == "Short")).FirstOrDefault();
if (awbPart == null)
{
if (awb != null)
{
if (IgmNo == null)
{
return CheckAuthenticatedAWB(awb);
}
return Content("Duplicate Airway Bill Provided against above IGM No. , please verify again.");
}
else
{
IsAuthencatedAWB = false;
return Content("Invalid Airway Bill Number Provided, Please verify it according to formula.");
}
}
else
{
return RedirectToAction("Edit", awbPart);
}
}
return Content(null);
}
Edit.cshtml
public ActionResult Edit(int? id,IMPORTAWB RunTimeImportAWBInstance)
{
var awbno = TempData["AWBNO"];
var igmno = TempData["IGMNO"];
if (awbno != null && igmno != null)
{
var importawb = context.IMPORTAWBs.Where(x => x.AWBNO == awbno && x.IGMNO == igmno).FirstOrDefault();
var deliveryInfo = context.DELIVERYINFOes.Where(f => f.AWBNO == importawb.AWBNO).FirstOrDefault();
if (deliveryInfo != null)
{
DeliveryInfo(importawb, deliveryInfo);
}
DetailSessionHandleClass = context.IMPORTAWBDETAILs.Where(f => f.AWBNO == importawb.AWBNO).ToList();
ViewBagList();
ViewBag.PossibleIGM = context.IMPORTMANIFIESTs.Where(f => f.IGMNO == importawb.IGMNO).FirstOrDefault();
CargoEntities._olderInstancea = importawb;
return View(importawb);
}
else {
var importawb = (RunTimeImportAWBInstance == null) ? context.IMPORTAWBs.Where(x => x.AWBId == id).FirstOrDefault() : RunTimeImportAWBInstance;
var deliveryInfo = context.DELIVERYINFOes.Where(f => f.AWBNO == importawb.AWBNO).FirstOrDefault();
if (deliveryInfo != null)
{
DeliveryInfo(importawb, deliveryInfo);
}
DetailSessionHandleClass = context.IMPORTAWBDETAILs.Where(f => f.AWBNO == importawb.AWBNO).ToList();
ViewBagList();
ViewBag.PossibleIGM = context.IMPORTMANIFIESTs.Where(f => f.IGMNO == importawb.IGMNO).FirstOrDefault();
CargoEntities._olderInstancea = importawb;
return View(importawb);
}
This is very simple, the pop up is being displayed because your code is written to display that:
$("#dialog").dialog({ appendTo: "#AWBNO" }).html(result);
The code above picks up #dialog element uses jQuery dialog() method appends it to element #AWBNO and then .html() method changes the mark up of that dialog to the variable result.
According to your AuthenticatingAWB Action the content that you can expect in your pop up is:
Duplicate Airway Bill Provided against above IGM No. , please
verify again
Invalid Airway Bill Number Provided, Please verify it according to formula.
RedirectToAction("Edit", awbPart);
The content you have posted screenshots for is because of the RedirectToAction("Edit", awbPart); when it returns the new page it's mark up is added to element `#dialog' hence the result is in pop up.
The official documentation:
.html()
.html( htmlString )

WWW.Post works fine in Editor, but not in WebPlayer Build

here is my post request to server:
public WWW POST(string url, string post)
{
var www = new WWW(url, Encoding.UTF8.GetBytes(post));
StartCoroutine(WaitForRequest(www));
while (!www.isDone && www.error == null)
{
Console.Write("downloading...");
Thread.Sleep(1000);
}
return www;
}
private IEnumerator WaitForRequest(WWW www)
{
while (!www.isDone && www.error == null) { yield return new WaitForSeconds(0.1f);}
// check for errors
if (www.error != null)
{
Debug.Log("WWW Error: " + www.error);
}
}
it works fine in Unity Editor, but it freeze to unlimited loop in Web Player Build version. Does anybody know why?
okay, the problem was in coroutines
public IEnumerator LoginFinished(string message)
{
string url = "URL";
Console.Write("Post on: " + url);
var response = _httpServer.POST(url, message.Substring(message.IndexOf('?') + 1));
while ( !response.isDone && response.error == null )
{
yield return new WaitForEndOfFrame();
}
Console.Write("response: " + Zlib.Unzip(response.bytes));
}
public WWW POST(string url, string post)
{
var www = new WWW(url, Encoding.UTF8.GetBytes(post));
StartCoroutine(WaitForRequest(www));
return www;
}
private IEnumerator WaitForRequest(WWW www)
{
yield return www;
if (www.error != null)
{
Debug.Log("WWW Error: " + www.error);
}
}
if i do
StartCoroutine(LoginFinished("authdata"));
it works just fine.

Domain Multiple inheritance and manyToMany relation removeFrom not working

I prepared some complex model structure due to content management businnes.
My main content model likes as following code.
class CmsContent implements Comparable<CmsContent>, Taggable, Serializable {
Set<CmsContent> contents
static hasMany = [contents:CmsContent]
}
Other Content Model extends from above
class Menu extends CmsContent {
}
class Image extends CmsContent {
}
class Video extends CmsContent {
}
On Controller side when ever add Image to Menu it is perfectly working
def addContent(){
Menu menuInstance = Menu.get(params.id)
if (menuInstance == null) {
notFound()
return
}
CmsContent content = CmsContent.get(params.contentId)
if (content == null) {
notFound()
return
}
menuInstance.addToContents(content)
menuInstance.save(flush: true)
request.withFormat {
'*'{
def result =[:] ;
result.status ='success';
render result as JSON
}
}
}
def removeContent(){
Menu menuInstance = Menu.get(params.id)
if (menuInstance == null) {
notFound()
return
}
long id = Long.valueOf(params.contentId)
CmsContent content = cmsContent.contents.find { it.id == id }
if (content == null) {
notFound()
return
}
menuInstance.removeFromContents(content)
menuInstance.save(flush: true)
request.withFormat {
'*'{
def result =[:] ;
result.status ='success';
render result as JSON
}
}
}
But when I tried to remove facing following exception.
Cannot get property 'name' on null object. Stacktrace follows:
Message: Cannot get property 'name' on null object
I tracked down in grails code in DomainClassGrailsPlugin.
I realize that addTo Method and line 368 checking prop.otherSide attribute
if (prop.bidirectional && prop.otherSide) {
}
unfortunately removeTo method not check prop.otherSide attribute, therefore name field throwing the exception.
if (prop.bidirectional) {
if (prop.manyToMany) {
String name = prop.otherSide.name
arg[name]?.remove(delegate)
} else {
arg[prop.otherSide.name] = null
}
}
What do you think ? Do you agree with me ?

Resources