It doesn't look like there's any built in function for getting the day of week using a function based on the documentation here:
http://docs.oasis-open.org/odata/odata/v4.0/odata-v4.0-part2-url-conventions.html
What I want is a Web Api 2.2 OData V4 implementation that can service a url request like this:
/meeting?$filter=dayofweek(StartDate) eq 'Wednesday'
or something similar. But it seems like a pipe dream at this moment. Can someone show how this could be done? Would it have to be done using something like this?
builder.EntityType<Meeting>().Collection
.Function("DayOfWeek")
.Returns<IEnumerable<Meeting>>();
then
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.OData;
namespace Test.Controllers
{
public class MeetingsController : ODataController
{
private EntityContext db = new EntityContext();
[EnableQuery]
public IQueryable<Meeting> GetMeetings()
{
return db.Meetings;
}
[HttpGet]
public IHttpActionResult DayOfWeek(DateTime dayofweek)
{
//calculate day of week and return string
}
}
}
You are correct about there being no build-in functions for getting day of week. From the protocol perspective, defining custom function to be used in query clauses should resolve the problem.
Unfortunately, although you can follow this blog post to define your own DayOfWeek as an unbound function, the current version of Web API OData V4 only supports such functions being called at the service root. Thus can't be used for your scenario.
The good news is, that such support of defining custom unbound function to be used in query clauses is prioritized for the release after the next. (next will be in December, the one after next will be in February/March). You can use it then.
Related
I'm working with C# xamarin forms android and I'm trying to get the IMEI number. I've been searching about it and everything I found doesn't works. Now I'm trying with this code but again, Doesn't works.
Errors:
The name settings does not exist in the current context.
The name Forms does not exist in the current context.
C# code:
[assembly: Xamarin.Forms.Dependency(typeof(UniqueIdAndroid))]
namespace AppMobile.Models
{
public class UniqueIdAndroid
{
public string GetIdentifier()
{
return Settings.Secure.GetString(Forms.Context.ContentResolver, Settings.Secure.AndroidId);
}
}
}
Somebody knows how could I resolve this or knows other solution? Thank you very much!
UPDATE 1
c# code:
using Android.OS;
using AppMobile.Models;
using System;
using System.Collections.Generic;
using System.Text;
using static Android.Provider.Settings;
using Android.Provider;
using Xamarin.Forms;
[assembly: Xamarin.Forms.Dependency(typeof(UniqueIdAndroid))]
namespace AppMobile.Models
{
public class UniqueIdAndroid : IDevice
{
public string GetIdentifier()
{
return Settings.Secure.GetString(Forms.Context.ContentResolver, Settings.Secure.AndroidId);
}
}
}
I have added the IDevice interface that I don't know really what it should be and I fixed the settings problem with using Android.Provider;.
this link shows that I have to call with this:
string deviceIdentifier = DependencyService.Get<IDevice>().GetIdentifier();
But i don't understand how to implement IDevice interface.
Someone can help me? Thank you very much!
UPDATE 2
so, now I can use the function.
C# code:
using Android.OS;
using AppMobile.Models;
using System;
using System.Collections.Generic;
using System.Text;
using static Android.Provider.Settings;
using Android.Provider;
using Xamarin.Forms;
using Android.Content;
[assembly: Xamarin.Forms.Dependency(typeof(UniqueIdAndroid))]
namespace AppMobile.Models
{
public class UniqueIdAndroid
{
public string GetIdentifier()
{
//return Settings.Secure.GetString(Forms.Context.ContentResolver, Settings.Secure.AndroidId);
return Settings.Secure.GetString(Android.App.Application.Context.ContentResolver, Settings.Secure.AndroidId);
}
}
}
My problem is that this doesn't give me the IMEI. Insted it gives me the ID of the phone, ¿is there some way to get the IMEI string? Thank you very much!
You can try the following code:
Android.Telephony.TelephonyManager mTelephonyMgr;
mTelephonyMgr = (Android.Telephony.TelephonyManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.TelephonyService);
string imei = mTelephonyMgr.GetMeid(0);
And from android document getMeid, we know that :
Starting with API level 29, persistent device identifiers are guarded
behind additional restrictions, and apps are recommended to use
resettable identifiers (see Best practices for unique identifiers).
This method can be invoked if one of the following requirements is
met:
If the calling app has been granted the READ_PRIVILEGED_PHONE_STATE permission; this is a privileged permission that can only be granted
to apps preloaded on the device.
If the calling app is the device owner of a fully-managed device, a profile owner of an organization-owned device, or their delegates
(see DevicePolicyManager.getEnrollmentSpecificId()).
If the calling app has carrier privileges (see hasCarrierPrivileges()) on any active subscription.
If the calling app is the default SMS role holder
Note:
In general, you can't get READ_PRIVILEGED_PHONE_STATE permission. It's only available to privileged system apps. Unless this is a personal app and you have a rooted device so you can make your app a privileged system app.
For more information, you can check document getMeid.
I'm new in web api and I wrote a code in which I return a datatable in an IHttpActionResult and I want to know what is the difference between return a datatable and a list or dictionary.
this is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication2.BLL;
namespace WebApplication2.Controllers
{
public class HomeController : ApiController
{
public IHttpActionResult getpro()
{
var tabla= new Conexion().table();
tabla.TableName = "tablilla";
return Ok(tabla);
}
}
}
I am testing this in post man and is runing well, but I want to know if should I sent a list in the response or another object.
There might not be an apparent difference right now, but as your application grows, you might run into maintainability issues.
The issue is that right now, the signature of your API endpoint (i.e. what data it returns) is hard coupled to your database, so if you change your database, so does the result returned by your endpoint. That's usually a bad thing for anything but the smallest/simplest applications, since it might break consumers of your API.
What you'd do instead, is create models specifically for returning from your API endpoints and then convert (also called map) your datatable to a list of these "view"-models. This way, you can change the backend of your web API without it (immediately) having an impact on your frontend (or other consumers of your API).
I try to make a class with NancyModules and GET string on URL but method 'Get' tells that:
"Error CS0021 Cannot apply indexing with [] to an expression of type
'method group' ...."
My Code:
using System; using System.Collections.Generic; using System.Linq;
using System.Web; using Nancy; using System.Text;
namespace SinglePageApp1 {
public class BloodPresureNancy : NancyModule
{
public BloodPresureNancy()
{
// Get dasn't work
Get["/"] = _ => "Heloooo";
}
}
}
I add references: Nancy, Nancy.Hosting.asp and it isn't working.
What version of Nancy are you currently using? That syntax should work on versions 1.x. However, I think that Nancy recently made a change to the way that you register routes for their upcoming 2.0 release. If you take a look at the samples they have on github https://github.com/NancyFx/Nancy/blob/master/samples/Nancy.Demo.Hosting.Self/TestModule.cs. You will see that you don't index into the different verbs anymore like you are doing above, you actually reference them like you would a Method. Try changing your code to be
Get("/", _ => {
//do work here
});
instead and see if that works for you.
See https://github.com/NancyFx/Nancy/pull/2441
Specifically:
the wiki will not be updates as the 2.0 packages comes out of pre-release, until then all changes are considered as being pending =)
Ie. The magic custom indexer syntax that allowed you to do this:
Get["/"] = ...
Is gone in the Nancy 2.x releases.
However, all the documentation currently still refers to the current (ie. 1.4.x versions); so...
tldr; That syntax is old and gone in the new version of Nancy. Use Get(...), Post(...), etc if you're using the new version of Nancy.
While this is most likely not the right way of doing it, it does work:
Get("/test/{category}", parameters => { return "My category is " + (Nancy.DynamicDictionaryValue)parameters.category; });
Going to http://localhost/test/hello will return "My category is hello"
There is an application which is used for taking surveys. I want to use REST api and add some questions to the survey. So basically I want to update some pages of the survey. Here are the links of that application.
My surveys name is trial and the page number that I want to update is 2.
fields#updateobject
Here is my code to do. But i think the http call I have used is not correct. and I am not able to figure out how to make the request.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
namespace ConsoleApplication1
{
class Program
{
private static object post;
private static object response;
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
string webReq = "https://restapi.survey.com/v4/survey/trial/surveypage/2?_method=POST?api_token="/*token goes here*/;
// $.post{webReq};
}
}
}
Use System.Net.Http.HttpClient class for sending requests to any API. Tutorial and examples on sending various requests (GET, POST, etc.) can be found here.
I'm trying to do a search on my Web API URL, as follows:
http://localhost:8000/api/trips/World Trip/stops
In this case, "World Trip" is the word. But when the call arrives on the server, it arrives as follows:
"World%20Trip" with code %20 to replace the empty space!
IS there some setting that has to be made to prevent substituting the space with code? I remember <httpRuntime relaxedUrlToFileSystemMapping="true" /> in previous versions.
I do not want to use any method for conversion within the server: Such as HttpServerUtility.UrlEncode().
My Data Annotation route:
[Route("api/trips/{tripName}/stops")]
My StopController.cs
using AutoMapper;
using Microsoft.AspNet.Mvc;
using Microsoft.Framework.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using TheWorld.Models;
using TheWorld.ViewModels;
namespace TheWorld.Controllers.Api
{
[Route("api/trips/{tripName}/stops")]
public class StopController : Controller
{
private ILogger<StopController> _logger;
private IWorldRepository _repository;
public StopController(IWorldRepository repository, ILogger<StopController> logger)
{
_repository = repository;
_logger = logger;
}
[HttpGet("")]
public JsonResult Get(string tripName)
{
try
{
var results = _repository.GetTripByName(tripName);
if (results == null)
{
return Json(null);
}
return Json(Mapper.Map<IEnumerable<StopViewModel>>(results.Stops.OrderBy(s => s.Order)));
}
catch (Exception ex)
{
_logger.LogError($"Failed to get stops for trip {tripName}", ex);
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Error occurred finding trip name");
}
}
}
}
You can just use HttpUtility.UrlDecode(yourstring) and you will have a more secure application.
I have had the same problem when walking through the pluralsight tutorial "Building a Web App with ASP.net 5, MVC 6, EF7 and AngularJS".
I solved the issue by using the code below,
tripName = WebUtility.UrlDecode(tripName);
This appears to be a bug in beta-8. Upgrade to rc1 and your problem should be solved.
I agree with user1919597 an upgrade all your packages and install the newest ASP version to rc1-update1 (this is the newest as of 11/30 up to this post date). See Shawn's Blog Post to perform all the updates you will need
Afterwards, you can test that the code is picking up the tripName in the URL bypassing it into the error message as follows
return Json($"Error occurred finding trip name {tripName}");
If the code returns an error it will pass in the tripName string from the url - for example: http://localhost:5151/api/trips/World%20Trip/stops will return "Error occurred finding trip name World Trip".
Now if your only getting an error message, instead of data, then something else may be going on...which happens to be the issue I am currently facing with this part of the course...its been 2 days of searching with no true fix...
All and All - Start with updating everything according to Shawn's Blog and then test this out again. Good Luck and I am interested to know how it turns out.