how to get current session in onRouteRequest - session

Hi i am using play framework 2.3(java)
I would like to handle session in onRouteRequest
public play.api.mvc.Handler onRouteRequest(RequestHeader request) {
/*
for eaxmple. I want to like this.
Is possilbe?
if (!session.get("userId")) {
redirect("loginPage.html");
}
*/
}
please help me.

you can simply do
if(session("userId")==null){
redirect("page url to redirect");
}

Related

How to use Spring method DELETE

I have some customers in ArrayList and when I want through Postman delete (with id) it is not working : 500 - Internal Error. Please Could someone help me ?
Delete customer
DELETE http://localhost:8080/api/customers/{customerId}
#DeleteMapping("/api/customers{customerId}")
public void deleteCustomer(#PathVariable Long customerId) {
customers.remove(this.customers.get(Math.toIntExact(customerId)));
}
try like this you did not add "/" in delete mapping.
#DeleteMapping("/api/customers/{customerId}")
public void deleteCustomer(#PathVariable Long customerId) {
customers.remove(this.customers.get(Math.toIntExact(customerId)));
}
Is this how you send the request?
http://localhost:8080/api/customers/{customerId}
If you are sending like this, it won't work because you gave path like this:
/api/customers{customerId}
In my opinion, either change the path like this:
/api/customers/{customerId}
Or send the request like this:
http://localhost:8080/api/customers{customerId}

Persistent Storage using Application.Current.Properties not working

I'm trying to achieve a persistent storage in Xamarin.Forms. After researching in Xamarin.Forms, I decided to use Application.Current.Properties property.
It looks like it is working just only if the app still remains alive. If I close the app and start it again the Application.Current.Properties is empty.
Does anyone know if I'm doing something wrong? Can I achieve this feature in another way?
As usual, thanks guys.
I have had a ton of problems with Application.Current.Properties on Android. I highly suggest using Xamarin Settings plugin instead which I have never had any issues with. It is persistent even when the app is closed.
That being said Application.Current.Properties is supposed to work even when you close the app. Not sure why it wouldn't but it does not surprise me either.
*Edit: To use once it is installed, basically CrossSettings.Current is the plugin class that will do the work but the example just creates a separate property to access it. So create a new file, lets call it SettingsImplementation:
public static class SettingsImplementation {
#region Instance
private static Lazy<ISettings> _appSettings;
public static ISettings AppSettings {
get {
if(_appSettings == null) {
_appSettings = new Lazy<ISettings>(() => CrossSettings.Current, LazyThreadSafetyMode.PublicationOnly);
}
return _appSettings.Value;
}
set {
_appSettings = new Lazy<ISettings>(() => value, LazyThreadSafetyMode.PublicationOnly);
}
}
#endregion
private const string UserNameKey = "username_key"; //Key used to get your property
private static readonly string UserNameDefault = string.Empty; //Default value for your property if the key-value pair has not been created yet
public static string UserName {
get { return AppSettings.GetValueOrDefault<string>(UserNameKey, UserNameDefault); }
set { AppSettings.AddOrUpdateValue<string>(UserNameKey, value); }
}
}
Then to use that you would do this anywhere in your app:
SettingsImplementation.UserName = "something";
OR
string username = SettingsImplementation.UserName;
My own problem regarding this issue was due to me not explicitly saving the properties with the following line of code:
Application.Current.SavePropertiesAsync();
you can use Xamarin essentials "Preferences" instead:
Preferences.Set("Key", "Value");
Preferences.Get("Key", "Default");
I ran into the same issue.
The problem:
I was trying to throw complex objects into the Application Properties.
It turns out that the Properties can only take primitive data typs.
This Blog was very helpfull.
https://codemilltech.com/persist-whatever-you-want-with-xamarin-forms/

Restricting auto Help Page contents when using Attribute Routing in Web API 2

I'm currently implementing a Web API using Web API 2's attribute routing (http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2). I am also using the Help Pages module in order to automatically generate documentation from XML comments (http://www.asp.net/web-api/overview/creating-web-apis/creating-api-help-pages).
For this API I am providing support for optional return format extensions, so that every API method has a pair of routes defined on it like so:
[HttpGet]
[Route("Path/Foo")]
[Route("Path/Foo.{ext}")]
public HttpResponseMessage DoFoo()
{
// Some API function.
}
This allows a user to hit any of these and get a result:
www.example.com/api/Controller/Path/Foo
www.example.com/api/Controller/Path/Foo.json
www.example.com/api/Controller/Path/Foo.xml
My issue is that when Help Pages uses MapHttpAttributeRoutes() to generate documentation, it is picking up both routes for each method. So right now I see help for:
api/Controller/Foo
api/Controller/Foo.{ext}
But I want to only see:
api/Controller/Foo.{ext}
I would prefer to hide the non-extension route on each method, so that every method only shows a single Help Page entry.
Has anyone else tried something similar? Is there a work around that I am missing?
My question would be is that, would consumers of your api figure out easily that the {ext} is optional?...personally, I would prefer the default behavior...but anyways following are some workarounds that I can think of:
A quick and dirty workaround. Split the DoFoo into 2 actions like DoFoo() and DoFooWithExt maybe. Notice that I am using an attribute called ApiExplorerSettings, which is for HelpPage purposes. Example below:
[HttpGet]
[Route("Path/Foo")]
[ApiExplorerSettings(IgnoreApi=true)]
public HttpResponseMessage DoFoo()
{
return DoFooHelper();
}
[HttpGet]
[Route("Path/Foo.{ext}")]
public HttpResponseMessage DoFooWithExt()
{
return DoFooHelper();
}
private HttpResponseMessage DoFooHelper()
{
//do something
}
Create a custom ApiExplorer (which HelpPage feature uses internally) and check for specific routes like the following and can decide whether to show the action or not for that particular route.
// update the config with this custom implementation
config.Services.Replace(typeof(IApiExplorer), new CustomApiExplorer(config));
public class CustomApiExplorer : ApiExplorer
{
public CustomApiExplorer(HttpConfiguration config) : base(config)
{
}
public override bool ShouldExploreAction(string actionVariableValue, HttpActionDescriptor actionDescriptor, IHttpRoute route)
{
if (route.RouteTemplate.EndsWith("Path/Foo", StringComparison.OrdinalIgnoreCase))
{
return false;
}
return base.ShouldExploreAction(actionVariableValue, actionDescriptor, route);
}
}
Get list of all ApiDescription from the default ApiExplorer and then filter out the descriptions which you do not like. Example:
Configuration.Services.GetApiExplorer().ApiDescriptions.Where((apiDesc) => !apiDesc.RelativePath.EndsWith("Path/Foo", StringComparison.OrdinalIgnoreCase))

HttpRoutes - how do they work?

I´m struggling with URLs for ajax-reader/JSON. Each time I think I understand it, it seems that I haven´t.
Please, can anybody explain the logic behind this???
I got this Controller:
public class ServiceController : DnnApiController
{
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage GetAllItems(int moduleId)
{
MyProjectController controller = new MyProjectController();
IEnumerable<ItemInfo> items = controller.GetAllItems(moduleId);
return Request.CreateResponse(HttpStatusCode.OK, items);
}
}
I got this Routemapper:
public class RouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapHttpRoute("MyProject",
"default",
"{controller}/{action}",
new[] { "MyCompany.MyProject.Services" });
}
}
At what URL can I read the data with $.ajax() and what is the URL showing me the data in a browser?
Thanx in Advance!
Asle :)
This is how I do it (Note: this will only work with DNN6.2 and above);
In the View.ascx.cs add
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
ServicesFramework.Instance.RequestAjaxScriptSupport();
ServicesFramework.Instance.RequestAjaxAntiForgerySupport();
jQuery.RequestDnnPluginsRegistration();
}
This ensures that jquery and the required DNN ajax plugins are added.
Initiate the services framework jquery plugin in the View.ascx like this inside javascript script tags (S.O. wouldn't allow me to include them)
var modId = <%=ModuleId %>;
var sf = $.ServicesFramework(modId);
Now in a separate javascript file or in the view.ascx control add the ajax function
function getAllItems(){
$.ajax({
type:"GET",
url:sf.getServiceRoot("MyProject")+"Service/GetAllItems",
beforeSend:sf.setModuleHeaders,
data:{moduleId:modId},
cache:false
}).done(function(data){
alert("Success!");
}).fail(function(){
alert("Crashed!");
}).always(function(){
//something you want done whether passed or failed
//like hide progress bar, ajax spinner etc.
});
}
The DNN jquery plugin will build the url which will look similar to this (Note: 142 is just for illustration purpose and will be replace with actual module id)
/DesktopModules/MyProject/API/Service/GetAllItems?moduleId=142
The URL will be something like
/desktopmodules/SlidePresentation/API/SlidePresetnation.ashx/ListOfSlides
I have examples at
https://slidepresentation.codeplex.com/SourceControl/latest
but they were for DNN6, they might require a few updates due to the API changes for DNN 7
you can see a DNN7 module that has a service layer at https://dnnsimplearticle.codeplex.com/SourceControl/latest#cs/services/

Checking requests that come in through SNMP

So I'm still in the process of learning SNMP, please go easy. I'm using snmp4j, not just the libraries but I've loaded the source code and I'm not against modifying the source if it gets me what I need. I've programmed an agent and a test client. What I want to do is be able to check the requests coming in from the test client and specifically listening for a "set" request to a specific OID.
The current way I'm thinking about doing it is catching the request right after it runs the snmp4j method fireProcessMessage (located in the package org.snmp4j.transport.DefaultUdpTranportMapping) but I don't know how an agent queries its own mib for an oid. Is there a method that the agent uses to get OID values from its mib?
Or Is there a better way to catch a specific SET request? Is it even possible to do what I want? Basically what I want to do is run another process if the client sets a certain OID value to 1(true).
It can be done by extending the CommandProcessor
and implementing RequestHandler
like i have done
public class SNMPRequestProcessor extends CommandProcessor
{
SetHandler setHandler = new SetHandler ();
public SNMPRequestProcessor()
{
//Your code
}
#Override
protected void processRequest(CommandResponderEvent command, CoexistenceInfo cinfo, RequestHandler handler)
{
synchronized (command) {
if (command.getPDU().getType() == PDU.SET) {
super.processRequest(command, cinfo, setHandler);
}
super.processRequest(command, cinfo, handler);
}
}
/**
* Handler for process set request which update to the database
*
*/
class SetHandler implements RequestHandler
{
#Override
public boolean isSupported(int mode)
{
return mode == PDU.SET;
}
#Override
public void processPdu(Request request, MOServer server)
{
//your code
}
}
}
I have no experience with the agent side of snmp4j, but I recommend to pose this question on the official mailing list: http://lists.agentpp.org/pipermail/snmp4j/. It is quite active, you'll have a good answer in a few hours.

Resources