I'm using pageList (the one made by troy goode), on his example he has
// in this case we return IEnumerable<string>, but in most
// - DB situations you'll want to return IQueryable<string>
private IEnumerable<string> GetStuffFromDatabase()
{
var sampleData = new StreamReader(Server.MapPath("~/App_Data/Names.txt")).ReadToEnd();
return sampleData.Split('\n');
}
Since i'm using a database i changed to IQueryable, but, i don't know what to write inside to return the data from the database, i tried changing the path to ~/App_Data/DatabaseName.sdf but i get that sampleData.Split('\n');
cannot implicitly convert type string to system.linq.iqueryable<string>
How i can change that?
return sampleData.Split('\n').AsQueryable();
The return type of your method is IEnumerable and requires to return as Enumeration
so please do this way
return sampleData.Split('\n').AsEnumerable();
Related
I have an object called PostMapDB and a method which retrieves a list of those objects. I would like to be able to pass this list and retrieve the data using webapi.
The code bellow gets me an error:{"":["The input was not valid."]}
[HttpGet]
public string Get(PostMapDB list)
{
IEnumerable<PostMapDB> dataOfPosts = list.getAllPosts().OrderBy(x => x.Date);
var data = JsonConvert.SerializeObject(dataOfPosts, new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableAttribute = false
}
});
return data;
}
How does your request to server looks like?
What's the definition on PostMapDB?
Make sure you're passing data in a right way.
Probably the attribute FromBody would help:
public string Get([FromBody] PostMapDB list)
Reference: https://learn.microsoft.com/en-gb/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
i am working on an asp.net mvc web application. and i have the following repository method,, where i will be passing the .Include() dynamically :-
public async Task<SecurityRole> FindSecurityRole(int id,string path="")
{
return await context.SecurityRoles.Include(path).SingleOrDefaultAsync(a2 => a2.SecurityRoleID == id);
}
now inside my controller i want to call the above method as follow:-
await uniteofwork.SecurityRoleRepository.FindSecurityRole(id.Value,)
but i am not sure what are the apporachies i can follow to pass the properties ?
Thanks
You can chain calls to things like Include over multiple lines by storing the result in a variable. Nothing will actually hit your database until you call an evaluating expression like SingleOrDefaultAsync here.
var query = context.SecurityRoles;
foreach (var include in path.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(include);
}
return await query.SingleOrDefaultAsync(a2 => a2.SecurityRoleID == id);
Splitting the string allows you to pass multiple include hierarchies at once, comma-delimited.
I have few empty route values I want in the query string:
var routeValues = new RouteValueDictionary();
routeValues.Add("one", "");
routeValues.Add("two", null);
routeValues.Add("three", string.Empty);
If I then pass it to UrlHelper.RouteUrl() it ignores all the values and the generated query string is empty. However, urls like /?one=&two=&three= are perfectly valid. How can I do that?
This behavior is built into the default Route class. It calls into the ParsedRoute.Bind() method where it does this check:
if (IsRoutePartNonEmpty(obj2))
{
acceptedValues.Add(key, obj2);
}
Which does this:
private static bool IsRoutePartNonEmpty(object routePart)
{
string str = routePart as string;
if (str != null)
{
return (str.Length > 0);
}
return (routePart != null);
}
This effectively prevents any query string values from being output if they are empty. Everything it does is private, static, internal, and otherwise impossible to override. So, there are really only 2 options to override this behavior.
Subclass Route and override GetVirtualPath(), replacing ParsedRoute.Bind() with a custom implementation.
Subclass RouteBase and create a custom route implementation.
I guess the 3rd option is to leave it alone, as others have pointed out this isn't really a problem since having an empty parameter in the query string has little or no value.
I want to show the images stored in my database in my View.
I have a field "deliverable_image" from the type "longblob" in my mysql database.
In my controller:
public ActionResult Show( int id )
{
var imageData = repository.GetAllImages();
return File( imageData, "image/jpg" );
}
Repository:
public IQueryable<byte[]> GetAllImages()
{
return from deliverable in entities.deliverables
orderby deliverable.deliverable_image
select deliverable.deliverable_image;
}
View:
<img src='<%= Url.Action( "Show", "Deliverable", new { id = ViewData["DeliverableID"] } ) %>' />
But in my controller I get the error:
cannot convert from 'System.Linq.IQueryable' to 'string'
Does anybody knows how I can fix this?
In your action method, the very first line gets a collection of images (specifically, an IQueryable<byte[]>:
var imageData = repository.GetAllImages();
Then you try to send all of the images as a single file:
return File(imageData, "image/jpg");
imageData is a collection of files. You need to select one of them and return just that. To do that, you'll probably need to modify your GetAllImages function or use a different function. The action method is being passed an id, but you can't use that on the results of that function because all you have are byte arrays. You need to filter for the id specified and then use the resulting byte array.
So I'd like to write a new set of evaluators in Share based on the result of some repository webscripts.
The current existing Share evaluators are usable through some XML configuration and are related to Alfresco usual meta-data.
But, I'd like to know how to write my own Java evaluator while re using most of the logic already here (BaseEvaluator).
Suppose I have a repository webscript that returns some JSON like {"result" : "true"}:
How do I access it from my custom Evaluator? Mainly how do I access the proxy URL to alfresco webapp from the Spring context?
Do I need to write my own async call in Java?
Where do I find this JSONObject parameter of the required evaluate method?
thanks for your help
See if this helps. This goes into a class that extends BaseEvaluator. Wire the bean in through Spring, then set the evaluator on your actions.
public boolean evaluate(JSONObject jsonObject) {
boolean result = false;
final RequestContext rc = ThreadLocalRequestContext.getRequestContext();
final String userId = rc.getUserId();
try {
final Connector conn = rc.getServiceRegistry().getConnectorService().getConnector("alfresco", userId, ServletUtil.getSession());
final Response response = conn.call("/someco/example?echo=false");
if (response.getStatus().getCode() == Status.STATUS_OK) {
System.out.println(response.getResponse());
try {
org.json.JSONObject json = new org.json.JSONObject(response.getResponse());
result = Boolean.parseBoolean(((String) json.get("result")));
} catch (JSONException je) {
je.printStackTrace();
return false;
}
} else {
System.out.println("Call failed, code:" + response.getStatus().getCode());
return false;
}
} catch (ConnectorServiceException cse) {
cse.printStackTrace();
return false;
}
return result;
}
In this example I am using a simple example web script that echoes back your JSON and switches the result based on the value of the "echo" argument. So when it is called with "false", the JSON returns false and the evaluator returns false.
I should probably point out the name collision between the org.json.simple.JSONObject that the evaluate method expects and the org.json.JSONObject I am using to snag the result from the response JSON.