RedirectToAction inside a method doesn't work - actionresult

Hello i have this method
private ActionResult CheckResult(ReactivationResponse result, GlobalObject globalInfo)
{
if (result == null)
{
return RedirectToAction("Failed", "Redirect", new { errorCode = 1014 });
}
else if (!result.IsReactivationSuccess && !result.IsOrderImported && !globalInfo.MemberInfo.IsWinbackAplicable)
{
return RedirectToAction("Failed", "Redirect", new { errorCode = 201 });
}
else if (!result.IsReactivationSuccess && result.Errors.Any())
{
if (result.Errors.Any(e => e.Message == "ApprovalPending"))
{
return View("Pending");
}
return RedirectToAction("Failed", "Redirect", new { errorCode = result.Errors.FirstOrDefault().StackTrace });
}
return null;
}
inside another Action Result
public ActionResult OtherMethod()
{
CheckResult(result, globalInfo);
//More code
return View()
}
I'm trying to redirect the code according to the result, and in case it doesn't apply, that the app continue and return the normal view.
But it doesn't work, if any of the if statements applies it doesn't redirect to anywhere, it continues with the normal viw.
I also tried to put a return before the method
return CheckResult(result, globalInfo);
and it works except if my method returns null, then it doesn't continue with the app.
I want to evaluate if it needs to redirect or if it should continue

Related

IPageRetriever not working with Ajax calls

I have the following API call to retrieve page data
List<VillageNewsItem> newsList = pageRetriever.RetrieveAsync<VillageNewsItem>(
query => query
.Path("/Home/Village-News", PathTypeEnum.Children)
.Published(true)
.OnSite(SiteContext.CurrentSiteName)
.OrderByDescending(x => x.DocumentCreatedWhen)
)?.Result?.ToList();
It works fine and return 2 records if I run the query on page load. Inside Index action of the controller.
public VillageNewsListController(IPageDataContextRetriever dataRetriever, VillageNewsListRepository villageNewsListRepository,
IPageRetriever pagesRetriever, IPageDataContextRetriever pageDataContextRetriever, IPageUrlRetriever pageUrlRetriever)
{
this._dataRetriever = dataRetriever;
this._villageNewsListRepository = villageNewsListRepository;
this._pagesRetriever = pagesRetriever;
this.pageDataContextRetriever = pageDataContextRetriever;
this.pageUrlRetriever = pageUrlRetriever;
}
public async Task<ActionResult> Index(CancellationToken cancellationToken)
{
try
{
List<VillageNewsItem> newsList = pagesRetriever.RetrieveAsync<VillageNewsItem>(
query => query
.Path("/Home/Village-News", PathTypeEnum.Children)
.Published(true)
.OnSite(SiteContext.CurrentSiteName)
.OrderByDescending(x => x.DocumentCreatedWhen)
)?.Result?.ToList();
newsItems.VillageNewsItems = newsList;
return View(newsItems);
}
catch (Exception ex)
{
ErrorHandler.EventLog.LogError(ex.Source, ex.Message, ex.StackTrace);
return RedirectToAction("ErrorPage", "Error");
}
}
However, if I try to make the same API call via a client side AJAX call, it doesn't work and return 0 records. Why it's not working with Ajax calls?
Ajax call
function loadMoreNews() {
$.ajax({
url: '/VillageNewsList/VillageNewsItemList',
//data: { "term": request.term },
type: "POST",
success: function (data) {
response($.map(data,
function (item) {
console.log(data);
}));
},
error: function (response) {
//alert(response.responseText);
},
failure: function (response) {
// alert(response.responseText);
}
});
}
Server side method.
[HttpPost]
[Route("VillageNewsList/VillageNewsItemList")]
public VillageNewsListViewModel VillageNewsItemList(string NodeAliasPath = "", int villageId = 0, string state = "", int page = 1, int pageSize = 4)
{
try
{
List<VillageNewsItem> newsList = pagesRetriever.RetrieveAsync<VillageNewsItem>(
query => query
.Path("/Home/Village-News", PathTypeEnum.Children)
.Published(true)
.OnSite(SiteContext.CurrentSiteName)
.OrderByDescending(x => x.DocumentCreatedWhen)
)?.Result?.ToList();
var model = new VillageNewsListViewModel
{
VillageNewsItems = newsList, // returns 0 records
};
return model;
}
catch (Exception ex)
{
ErrorHandler.EventLog.LogError(ex.Source, ex.Message, ex.StackTrace);
//return RedirectToAction("ErrorPage", "Error");
}
return null;
}
Couple things I see.
You're calling IPageRetriever.RetrieveAsync, but you aren't putting an await before it. There may be some odd behavior due to this. Get rid of the ?.Result?.ToList() and instead just put await before it, it will return an IEnumerable of the specified type.
You don't need ".Published" nor "OnSite" with IPageRetriever, this API automatically uses the Current Site Context, the current culture, and either Published or not / Latest Version or not based on if it's in edit/preview mode or not.
See if those things fix the issue!
I also asume it is caused by async context here...
You can try to use a document query instead.
Would be something like this:
var items = new DocumentQuery<VillageNewsItem>(
.Path("/Home/Village-News", PathTypeEnum.Children)
.PublishedVersion()
.Published()
.OnCurrentSite()
.OrderByDescending(x => x.DocumentCreatedWhen))
?.Result
?.ToList();
If you have multiple cultures, add the culture to your query, too.
.Culture(LocalizationContext.CurrentCulture.CultureCode)

Unexpected double WHERE clause in Servicestack OrmLite

We have an issue that occurs at every method call for limited periods of time. Then it works as expected. The issue is that the code produces double WHERE clauses.
We're using Servicestack 4.5.14
The method we have:
protected static void InsertOrUpdate<T>(
IDbConnection connection,
T item,
Expression<Func<T, bool>> singleItemPredicate,
Expression<Func<T, object>> updateOnlyFields = null)
{
var type = item.GetType();
var idProperty = type.GetProperty("Id");
if (idProperty == null)
{
throw new Exception("Cannot insert or update on a class with no ID property");
}
var currentId = (int)idProperty.GetValue(item);
if (currentId != 0)
{
throw new Exception("Cannot insert or update with non-zero ID");
}
var query = connection.From<T>().Where(singleItemPredicate).WithSqlFilter(WithUpdateLock);
T existingItem;
try
{
existingItem = connection.Select(query).SingleOrDefault();
Log.Verbose(connection.GetLastSql);
}
catch (SqlException)
{
Log.Verbose(connection.GetLastSql);
throw;
}
if (existingItem == null)
{
Insert(connection, item);
return;
}
var existingId = (int)idProperty.GetValue(existingItem);
idProperty.SetValue(item, existingId);
try
{
var affectedRowCount = connection.UpdateOnly(item, onlyFields: updateOnlyFields, where: singleItemPredicate);
Log.Verbose(connection.GetLastSql);
if (affectedRowCount != 1)
{
throw new SwToolsException("Update failed");
}
}
catch (SqlException)
{
Log.Verbose(connection.GetLastSql);
throw;
}
}
When it all works, an example output from the logs could be:
SELECT "Id", "Application", "Hostname", "LastContact", "Version", "ToolState", "ServerState"
FROM "ca"."ExecutionHost"
WITH (UPDLOCK) WHERE ("Hostname" = #0)
UPDATE "ca"."ExecutionHost" SET "LastContact"=#LastContact, "Version"=#Version, "ToolState"=#ToolState, "ServerState"=#ServerState WHERE ("Hostname" = #0)
When it fails, the output (same session, only seconds later) was:
SELECT "Id", "Application", "Hostname", "LastContact", "Version", "ToolState", "ServerState"
FROM "ca"."ExecutionHost"
WITH (UPDLOCK) WHERE ("Hostname" = #0)
UPDATE "ca"."ExecutionHost" SET "LastContact"=#LastContact, "Version"=#Version, "ToolState"=#ToolState, "ServerState"=#ServerState WHERE "LastContact"=#LastContact, "Version"=#Version, "ToolState"=#ToolState, "ServerState"=#ServerState WHERE ("Hostname" = #0)
Marked in bold is the addition to the SQL that makes the call to fail. It seems that it adds an additional WHERE clause with the content from the SET clause.
We've been debugging this for a while and don't really know if the issue is on "our" side or in Servicestack.
Any ideas on where to continue?

local variable stays uninitialized

The private array $list_of_files stays uninitialized. How can I update it from the while loop?
class listOfFiles {
private $list_of_files = [];
function __construct() {
if ($handle = opendir(WEB_STORAGE_DIR)) {
while (false !== ($entry = readdir($handle))) {
$this->list_of_files[$entry] = filesize(WEB_STORAGE_DIR.DIRECTORY_SEPARATOR.$entry);
}
closedir($handle);
// Remove . and .. from the list
unset($list_of_files['.']);
unset($list_of_files['..']);
}
}
function is_empty() {
return empty($list_of_files);
}
}
$list_of_files is referring to a variable, which is not the same as a property which would be $this->list_of_files.
Variables declared/referenced in a function are only available in that function (unless you use global - but this is generally considered 'evil' and should be avoided)
Properties are available from all methods in the class (unless they are static) and persist for the life of the object.
<?php
//lets show all error so we can see if anything else is going on..
error_reporting(E_ALL & ~E_NOTICE);
class listOfFiles {
private $list_of_files = [];
function __construct() {
if ($handle = opendir(WEB_STORAGE_DIR)) {
while (false !== ($entry = readdir($handle))) {
$this->list_of_files[$entry] = filesize(WEB_STORAGE_DIR.DIRECTORY_SEPARATOR.$entry);
}
closedir($handle);
// Remove . and .. from the list
unset($this->list_of_files['.']);
unset($this->list_of_files['..']);
}
}
function is_empty() {
return empty($this->list_of_files);
}
}
Is the issue that the directory doesn't exist? It would be better to check this before trying to open, and also allow for what to do when it does exist but you cant actually read it:
<?php
//lets show all error so we can see if anything else is going on..
error_reporting(E_ALL & ~E_NOTICE);
class listOfFiles {
private $list_of_files = [];
function __construct() {
if(!is_dir(WEB_STORAGE_DIR)){
throw new Exception("Missing Web Storage Directory");
}
$handle = opendir(WEB_STORAGE_DIR);
if (!$handle) {
throw new Exception("Could not read Web Storage Directory");
}
else{
while (false !== ($entry = readdir($handle))) {
$this->list_of_files[$entry] = filesize(WEB_STORAGE_DIR.DIRECTORY_SEPARATOR.$entry);
}
closedir($handle);
// Remove . and .. from the list
unset($this->list_of_files['.']);
unset($this->list_of_files['..']);
}
}
function is_empty() {
return empty($this->list_of_files);
}
}
I have added error_reporting(E_ALL & ~E_NOTICE); to the examples as this would make sure that you see any errors and may help debug your issue. More info on this here: http://php.net/manual/en/function.error-reporting.php
The access a property, you need to use $this, otherwise you are making a local variable. You do this at one place, but e.g. not here
return empty($list_of_files);
As that variable is never set, this will always return the same thing.
return empty($this->list_of_files);
The same goes for other references to that property, making the complete code (this is untested of course, as you didn't provide anything testable) look something like this
class listOfFiles {
private $list_of_files = [];
function __construct() {
if ($handle = opendir(WEB_STORAGE_DIR)) {
while (false !== ($entry = readdir($handle))) {
$this->list_of_files[$entry] = filesize(WEB_STORAGE_DIR.DIRECTORY_SEPARATOR.$entry);
}
closedir($handle);
// Remove . and .. from the list
unset( $this->list_of_files['.']);
unset( $this->list_of_files['..']);
}
}
function is_empty() {
return empty( $this->list_of_files);
}
}

primefaces remoteCommand action is not getting called

I have the following code:
<p:remoteCommand name="navigateTo" actionListener="#{searchControllerHelper.dummyActionListener}"
action="#{searchControllerHelper.navigateTo}" update="searchPanelForm"
onstart="plsWaitDlg.show()" onsuccess="plsWaitDlg.hide()"/>
Controller Code as under:
Thank you Lars. Code of the bean as under:
public String navigateTo() throws FetchException {
if (null == this.getSelectedMenuLink()) {
return null;
}
if (this.getSelectedMenuLink().longValue() == 1L) {
this.prevSelectedMenuLink = this.selectedMenuLink;
this.location = null;
return searchCRE();
}
else if (this.getSelectedMenuLink().longValue() == 2L) {
this.prevSelectedMenuLink = this.selectedMenuLink;
this.selectedLoanType=null;
return searchLoans();
}
else if (this.getSelectedMenuLink().longValue() == 3L) {
this.prevSelectedMenuLink = this.selectedMenuLink;
this.selectedLoanType=null;
return searchLoans();
}
else if (this.getSelectedMenuLink().longValue() == 4L) {
this.prevSelectedMenuLink = this.selectedMenuLink;
return otherOpportunities();
}
else if (this.getSelectedMenuLink().longValue() == 5L) {
//The link needs to be 'activated' once a service provider is selected.
this.prevSelectedMenuLink= this.selectedMenuLink;
return this.navigateToHome();
}
return null;
}
I added the actionlistener to check if the controller was getting fired or not, and it is.
What is happening is the following: The page loads, and before it is completely done loading if the user clicks the button that calls this remoteCommand then strangely the actionListener gets called, but the action method does not.
Any ideas what I could do to alleviate this issue?
Thank you
Karthik

E_SCN_READINCOMPATIBLE Notification error thrown while scanning bar code on MC9090G

I'm using EMDK 2.5 (VS2008 and VC# and .NetCF3.5) Barcode2 class from the library to write a sample application to scan bar codes. I followed the samples available in EMDK namely CS_Barcode2Sample1 project.Every time I hardware trigger the scan the notification "E_SCN_READINCOMPATIBLE" is thrown and not able to retrieve the scanned data. The documentation doesn't say much about the cause of E_SCN_READINCOMPATIBLE notification and no luck from Google search. I tried several options including making use of Symbol.Barcode and the outcome is same.
I also tried EMDK 2.3 but the result is same.
I've pasted the whole code here....
public partial class Form1 : Form
{
private Barcode2 myBarcode2 = null;
public Form1()
{
InitializeComponent();
InitBarcode();
}
public bool InitBarcode()
{
// If the Barcode2 object is already initialized then fail the initialization.
if (myBarcode2 != null)
{
return false;
}
else // Else initialize the reader.
{
try
{
Symbol.Barcode2.Device[] AvailableDevices = Symbol.Barcode2.Devices.SupportedDevices;
if (AvailableDevices.Length == 0)
{
return false;
}
if (AvailableDevices.Length == 1)
{
//get the first available scanner in the list
Symbol.Barcode2.Device MyDevice = AvailableDevices[0];
// Create the reader, based on selected device.
myBarcode2 = new Barcode2(MyDevice);
// Attach a scan notification handler.
//this.myScanNotifyHandler = new Barcode2.OnScanHandler(myBarcode2_ScanNotify);
myBarcode2.OnScan += myBarcode2_ScanNotify;
// Attach a status notification handler.
//this.myStatusNotifyHandler = new Barcode2.OnStatusHandler(myBarcode2_StatusNotify);
myBarcode2.OnStatus += myBarcode2_StatusNotify;
myBarcode2.Config.TriggerMode = TRIGGERMODES.HARD;
// Submit a scan.
myBarcode2.Scan(5000);
}
}
catch (OperationFailureException ex)
{
MessageBox.Show("Exception Raised 1");
return false;
}
catch (InvalidRequestException ex)
{
MessageBox.Show("Exception Raised 2");
return false;
}
catch (InvalidIndexerException ex)
{
MessageBox.Show("Exception Raised 3");
return false;
}
}
return false;
}
private void myBarcode2_ScanNotify(ScanDataCollection scanDataCollection)
{
// Checks if the BeginInvoke method is required because the OnScan delegate is called by a different thread
if (this.InvokeRequired)
{
// Executes the OnScan delegate asynchronously on the main thread
this.BeginInvoke(new Barcode2.OnScanHandler(myBarcode2_ScanNotify), new object[] { scanDataCollection });
}
else
{
// Get ScanData
ScanData scanData = scanDataCollection.GetFirst;
int i;
switch (scanData.Result)
{
case Symbol.Barcode2.Results.SUCCESS:
String str = scanData.Text;
myBarcode2.Config.TriggerMode = TRIGGERMODES.HARD;
myBarcode2.Scan(5000);
break;
case Symbol.Barcode2.Results.E_SCN_READTIMEOUT:
break;
case Symbol.Barcode2.Results.CANCELED:
break;
case Symbol.Barcode2.Results.E_SCN_DEVICEFAILURE:
i = 93;
break;
default:
if (scanData.Result == Symbol.Barcode2.Results.E_SCN_READINCOMPATIBLE)
{
// If the failure is E_SCN_READINCOMPATIBLE, exit the application.
MessageBox.Show("Fatal Error");
this.Close();
return;
}
break;
}
}
}
private void myBarcode2_StatusNotify(StatusData statusData)
{
// Checks if the Invoke method is required because the OnStatus delegate is called by a different thread
if (this.InvokeRequired)
{
// Executes the OnStatus delegate on the main thread
this.Invoke(new Barcode2.OnStatusHandler(myBarcode2_StatusNotify), new object[] { statusData });
}
else
{
int i;
switch (statusData.State)
{
case States.IDLE:
break;
case States.READY:
break;
default:
break;
}
}
}
}
}
I've went thru this recently also, as I observed, it probably due to the scanner device is occupied by other application, where the scan request has been queued already, you can go to memory management, and kill the suspect app, and try your app again.
Refer to the Symbol FAQ

Resources