how to solve MvxIoCResolveException - android-fragments

protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
RegisterForDetailsRequests(bundle);
}
{
RegisterFragment<HomeFragment,HomeFragmentViewModel>(typeof(HomeFragmentViewModel).Name, bundle, new HomeFragmentViewModel());
}
public void RegisterFragment<TFragment, TViewModel>(string tag, Bundle args, IMvxViewModel viewModel = null)
where TFragment : IMvxFragmentView
where TViewModel : IMvxViewModel
{
var customPresenter = Mvx.Resolve<IMvxFragmentsPresenter>();
customPresenter.RegisterViewModelAtHost<TViewModel>(this);
}
This is my code and I am getting this error:
Caused by: md52ce486a14f4bcd95899665e9d932190b.JavaProxyThrowable: Cirrious.CrossCore.Exceptions.MvxIoCResolveException: Failed to resolve type Cirrious.MvvmCross.Droid.Fragging.Presenter.IMvxFragmentsPresenter

Related

Dependency Service and passing values between droid and standard project

i have a method that need to use native droid functions. I am using Dependency services to achieve that which is fine, however i also need to send a value that gets filled in my standard project.When debugging i see the value in the standard however once i enter droid the value is null i have also tried to make the list Static but not help
My Service
public interface INavigationService
{
void PushDictionary(List<Word> allWordsOfUserForAutomat);
}
My Implementation
public class NavigationImplementation : Activities.INavigationService
{
public void PushDictionary(List<Word> allWordsOfUserForAutomat) //HERE I SEE THE VALUE
{
Intent intent = new Intent(MainActivity.Instance,typeof(LockScreenDictionary));
MainActivity.Instance.StartActivity(intent);
}
}
My standard
protected void LockScreen()
{
if (!viewDisabled)
{
DependencyService.Get<INavigationService>().PushDictionary(_allWordsOfUserForAutomat); //HERE I SEE THE VALUE
}
else
{
NotificationService.ShowToast("Nothing to play");
}
}
My droid project
[Activity(Label = "LockScreenDictionary", Theme = "#style/Theme.Splash")]
public class LockScreenDictionary : FormsAppCompatActivity
{
private List<Word> _allWordsOfUserForAutomat; //HERE ITS NULL
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
LangUpDictionaryPlayer.PlayAutomat(_allWordsOfUserForAutomat); //HERE ITS NULL
}
}
You should pass the allWordsOfUserForAutomat to Intent:
In your Implementation:
public class NavigationImplementation : INavigationService
{
public void PushDictionary(List<Word> allWordsOfUserForAutomat) //HERE I SEE THE VALUE
{
Intent intent = new Intent(MainActivity.Instance, typeof(LockScreenDictionary));
//pass data
intent.PutExtra("myData", allWordsOfUserForAutomat);
MainActivity.Instance.StartActivity(intent);
}
}
In your droid project:
public class LockScreenDictionary : FormsAppCompatActivity
{
private List<Word> _allWordsOfUserForAutomat; //HERE ITS NULL
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
_allWordsOfUserForAutomat = Intent.Extras.GetInt("myData");
LangUpDictionaryPlayer.PlayAutomat(_allWordsOfUserForAutomat); //HERE ITS NULL
}
}

Catching HttpRequestValidationException with ExceptionHandler

Using ASP.NET WebApi 2,
Why can't I catch HttpRequestValidationException in my Global ExceptionHandler or Global ExceptionLogger?
Error is: [HttpRequestValidationException (0x80004005): A potentially dangerous Request.QueryString value was detected from the client...]
Using Application_Error works fine, HttpRequestValidationException can be caught fine.
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
//...stuffs
//Global exception handler
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
//add global error logger
config.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());
}
public class GlobalExceptionLogger : ExceptionLogger
{
public override void Log(ExceptionLoggerContext context)
{
//This does not handle HttpRequestValidationException
Exception exception = context.ExceptionContext.Exception;
//.....
}
}
public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
//This does not handle HttpRequestValidationException either ...
var result = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An unexpected error occured. Please notify your administrator"),
ReasonPhrase = "Unexpected Error"
};
context.Result = new UnhandledExceptionResult(context.Request, result);
}
public class UnhandledExceptionResult : IHttpActionResult
{
private HttpRequestMessage _request;
private HttpResponseMessage _httpResponseMessage;
public UnhandledExceptionResult(HttpRequestMessage request, HttpResponseMessage httpResponseMessage)
{
_request = request;
_httpResponseMessage = httpResponseMessage;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(_httpResponseMessage);
}
}
}

getting error on createObject

i am getting
StartSensor Attempt to invoke virtual method 'void io.realm.ProxyState.setConstructionFinished()' on a null object reference
i try to create a new object with primarykey inside application class.
primarykeyFactory works it set the new key to "1" the database is empty at this moment.
public class SensorRecord extends MainApplication {
private final static String TAG = SensorRecord.class.getSimpleName();
private Realm mRealm;
public SensorRecord() {
Realm.init(this);
mRealm = getInstance(getRealmConfig());
}
public void StartSensor(long startTime) {
long newprimekey = PrimaryKeyFactory.getInstance().nextKey(SensorData.class);
try {
mRealm.beginTransaction();
SensorData mSensorData = mRealm.createObject(SensorData.class, newprimekey);
mSensorData.setstarted_at(startTime);
mRealm.commitTransaction();
mRealm.close();
} catch (Exception e) {
Log.v(TAG, "StartSensor " + e.getMessage());
}
}}
my main application class which init the realm config
public class MainApplication extends RealmBaseApplication {
private final static String TAG = MainApplication.class.getSimpleName();
Realm mRealm;
#Override
public void onCreate() {
super.onCreate();
Realm.init(this);
mRealm = getInstance(getRealmConfig());
initializePrimaryKeyFactory();
}
public void initializePrimaryKeyFactory() {
try {
Log.v(TAG, "Start PrimaryKeyFactory ");
PrimaryKeyFactory.getInstance().initialize(mRealm);
} catch (Exception e) {
Log.v(TAG, "initializePrimaryKeyFactory " + e.getMessage());
}
}}
and my realm config class
public abstract class RealmBaseApplication extends Application {
private RealmConfiguration realmConfiguration;
protected RealmConfiguration getRealmConfig() {
if (realmConfiguration == null) {
realmConfiguration = new RealmConfiguration
.Builder()
.deleteRealmIfMigrationNeeded()
.build();
}
Realm.setDefaultConfiguration(realmConfiguration);
return realmConfiguration;
}
protected void resetRealm() {
Realm.deleteRealm(getRealmConfig());
}}
kind regards
viktoria
ok fixed by myself. had add butterknife tonight. and with that i add apt to my build.gradle... i removed
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
apply plugin: 'com.neenbedankt.android-apt'
and replaced
apt 'com.jakewharton:butterknife-compiler:8.5.1'
with
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'

How to use Exception filters in MVC 5

How i can implement Exception Filters in MVC5.
I want to throw the exception to NLog and redirect the page to a default error page which displays "Something is gone wrong"
I have a Filter class as follows
using System;
using System.Diagnostics;
using System.Security.Policy;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Web.Routing;
using System.Web.UI.WebControls;
using Delivros.UI.Controllers;
using Delivros.UI.Areas.User.ViewModel;
using System.Web;
namespace Delivros.UI.Filters
{
public class CustomAuthenticationFilter : IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
Debug.WriteLine("OnAuthenticationChallenge : MyAuthenticationFilter");
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MyAuthorizationFilter : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.Cookies[System.Configuration.ConfigurationManager.AppSettings[Convert.ToString(CookieField.cookieName)]] == null)
{
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "controller", "User" },
{ "action", "UserRegistration" } ,
{"Area","User"}
});
}
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CustomActionFilter : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
base.OnResultExecuted(filterContext);
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "controller", "User" },
{ "action", "UserRegistration" } ,
{"Area","User"}
});
// ActionResult home = new HomeController().Index();
}
}
public class MyResultFilter : IResultFilter
{
public void OnResultExecuting(ResultExecutingContext filterContext)
{
}
public void OnResultExecuted(ResultExecutedContext filterContext)
{
}
}
public class MyExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "controller", "User" },
{ "action", "UserLogOut" } ,
{"Area","User"}
});
}
}
}
But nothing is redirecting to the page...
You could derive your own HandleErrorAttribute
public class NLogExceptionHandlerAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
// log error to NLog
base.OnException(filterContext);
}
}
Then register it globally
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new NLogExceptionHandlerAttribute());
...
}
By default, the HandleErrorAttribute will display the Error view located in the ~/Views/Shared folder but if you wanted to display a specific view you can set the View property of the attribute.
I believe it should be this code:
public class MyExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {
action = "UserLogOut",
controller = "User",
area = "User"
}));
}
}
You may add an additional "if (!filterContext.ExceptionHandled)" statement before logging the values inside the result to make sure that the exception's unhandled for the moment.
Exception filters are run only when unhandled exception has been thrown inside an action method. As you asked, here is an example to redirect to another page upon exception:
public class MyExceptionAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if(!filterContext.ExceptionHandled)
{
filterContext.Result = new RedirectResult("~/Content/ErrorPage.html");
filterContext.ExceptionHandled = true;
}
}
}
Now, to apply this filter to either controllers or individual actions, put [MyException] on them.
You may need to check the occurence of an specific Exception inside the if clause.
e.g.:
if(... && filterContext.Excaption is ArgumentOutOfRangeException)
To return a View as Exception Response:
filterContext.Result = new RedirectResult("/Home/ErrorAction");
other alternatives you might use to redirect are:
new RedirectToRouteResult{ ... }
new ViewResult{ ... }
Below worked for me. A few things to note 1) RedirectResult points to a controller action, not a view 2) you need to set filterContext.ExceptionHandled = true; or your exception view / page will not display.
public class ErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
Log.Logger.Error(filterContext.Exception, "An Unhandled exeption occured durring the execution of a request");
filterContext.Result = new RedirectResult("~/MyControler/MyErrorAction");
filterContext.ExceptionHandled = true;
}
}
Ofcourse you will also need to register the Error attribute using the GlobalFilters object from your Global.asax as shown below.
protected void Application_Start()
{
GlobalFilters.Filters.Add(new ErrorAttribute());
...
}

How do I get my EntitySetController to be visible to my route?

I created an EntitySetController that looks like this:
public class OrdersController : EntitySetController<Order,Guid>
{
private readonly PizzaCompanyEntities _context = Factories.DataFactory.GetPizzaContext();
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
public override IQueryable<Order> Get()
{
return _context.Orders;
}
protected override Order GetEntityByKey(Guid key)
{
var result = _context.Orders.FirstOrDefault(o => o.Id == key);
if (result == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return result;
}
}
In an existing MVC 4 web application.
I configure the route as follows:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapODataRoute("PizzaApi", "odata", GetImplicitEdm());
}
private static IEdmModel GetImplicitEdm()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<Order>("Orders");
builder.EntitySet<Pizza>("Pizzas");
builder.EntitySet<Pizzas_To_Orders>("PizzasToOrders");
builder.EntitySet<Size>("Sizes");
builder.EntitySet<Status>("Statuses");
builder.EntitySet<Pizzas_To_Toppings>("PizzasToToppings");
return builder.GetEdmModel();
}
}
And execute the configuration as follows:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
But when I execute my route at http://localhost:29064/odata/Orders I am getting a 404 and a message "The controller for path /odata/Orders was not found or does not implement IController.
I cannot figure out what I am missing to get the route registered and the controller running. I have done a similar application from scratch and have not had this trouble.
How do I get my OData route working?

Resources