Hi this should be a really simple problem with actual LINQ knowledge unlike me! I want to return only the last 20 records and normally .Take(20) when ordered by descending works but because I'm returning an instance of the model.CPU I don't know where to put the statement.
Help would be greatly appreciated, have been Googling for the past hour or so.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace hello_services.Controllers
{
public class cpuController : ApiController
{
private Data.ResourceDataModelDataContext _context = new Data.ResourceDataModelDataContext();
//WebAPI will respond to an HTTP GET with this method
public List<Models.CPU> Get()
{
//get all of the records from the Counter_CPU table
var cpuRecords = from e in _context.Counter_CPUs
select new Models.CPU
{
Counter_CPU_ID = e.Counter_CPU_ID,
//Counter_CPU_Time = e.Counter_CPU_Time,
Counter_CPU_Percentage = e.Counter_CPU_Percentage
};
return cpuRecords.ToList();
}
}
}
You can
Order the query (desc) and then select your Models.CPU class with take(20) as last statement
Order your result before using the .ToList() (before executing the query on the db)
e.g.
return cpuRecords.OrderByDesc(o => o.Counter_CPU_ID).Take(20).ToList();
Related
So i have two functions that return a customer, which get feeded by two different parameters. One being the ID of the customer and the other being his customer number.
My controller:
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.OData;
using System.Web.OData.Routing;
using Models;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using System.Web.OData.Extensions;
using Importing;
using Objects;
using Microsoft.OData;
namespace Controllers
{
public class CustomersController : ODataController
{
// GET: CustomerByCNO(5)
[HttpGet]
[ODataRoute("CustomerByCNO({key})")]
[EnableQuery]
public SingleResult<CustomerDTO> GetCustomerByCNO([FromODataUri]string key)
{
Import i = new Import();
var customer = i.GetCustomer(key).ProjectTo<CustomerDTO>().AsQueryable();
return SingleResult.Create(customer);
}
// GET: Customer(5)
[HttpGet]
[ODataRoute("Customer({id})")]
[EnableQuery]
public SingleResult<CustomerDTO> Get([FromODataUri]int id)
{
Import i = new Import();
var customer = i.GetCustomer(id).ProjectTo<CustomerDTO>().AsQueryable();
return SingleResult.Create(customer);
}
}
}
Initialization:
using AutoMapper;
using Models;
using Objects;
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using Microsoft.OData.Edm;
namespace API
{
public static class WebApiConfig
{
public static void ConfigureAPI(HttpConfiguration config)
{
config.MapODataServiceRoute(
routeName: "odata",
routePrefix: "",
model: GetEdmModel()
);
config.EnsureInitialized();
}
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder
{
Namespace = "Controllers",
ContainerName = "DefaultContainer"
};
builder.EntitySet<CustomerDTO>("Customer")
.EntityType.HasKey(c => c.Id)
.CollectionProperty(c => c.CustomFields);
var edmModel = builder.GetEdmModel();
return edmModel;
}
}
}
While the second functions works as intended the first functions does not and the EnsureInitialized() function throws an InvalidOperationException saying, that it is no valid OData path template and that no resource has been found. How can i get this to work? Not quite sure what i am missing here.
UPDATE 1:
Changing the Controller method to this:
[HttpGet]
[ODataRoute("CustomerByNo(No={no})")]
public SingleResult<CustomerDTO> CustomerByNo([FromODataUri] int no)
{
Import i = new Import();
var customer = i.GetCustomer(no.ToString()).ProjectTo<CustomerDTO>().AsQueryable();
return SingleResult.Create(customer);
}
with this additional line in the config:
builder.Function("CustomerByNo").Returns<SingleResult<CustomerDTO>>().Parameter<int>("No");
Made it so i can access the functions at least. I had to change the parameter to an int as well, seems like it doesnt like strings? However the return value is not deserialized and shown as usual. Also if i leave the [EnableQuery] line in the method declaration, the call will crash saying that it doesnt know how to deserialize since it is not bound to the entityset of Customer i guess.
Trying it this way however, leads to the original error message, that the resource could not be found:
builder.EntityType<CustomerDTO>().Collection.Function("CustomerByNo").Returns<SingleResult<CustomerDTO>>().Parameter<int>("No");
You have to declare your custom odata functions in the convention model:
FunctionConfiguration customerByCNOFunction = builder.Function("CustomerByCNO");
customerByCNOFunction.Returns<CustomerDTO>();
customerByCNOFunction.Parameter<string>("key");
Update :
My first answer was for declaring a functions that returns a type not queryable in odata.
To enable query, the function needs to return an odata entity from an entity set :
builder.Function("CustomerByNo").ReturnsFromEntitySet<CustomerDTO>("Customer").Parameter<int>("No")
I'm new to MVC working on 3-tier MVC project and i am using a ready database.
now i need to write a query using linq in Business Layer to bring list of doctors like this :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DoctorsSheet.DataAccess;
namespace DoctorsSheet.Business
{
class Doctor : IDoctor
{
DoctorsSheetDBEntities db = new DoctorsSheetDBEntities();
public IQueryable<Doctors> GetDoctors()
{
var doctors = from d in db.Doctors
select d;
return doctors.AsQueryable<Doctors>();
}
}
}
and when i call GetDoctors() from DoctorsController
it tell me Object reference not set to an instance of an object
this is the Controller :
public ActionResult Index()
{
var doctors = obj.GetDoctors().AsQueryable<Doctors>();
return View(doctors);
}
please help me how to fix it.
Make your class public -
public class Doctor : IDoctor
And then initiate obj variable as shown below and then use obj.
IDoctor obj = new Doctor();
NOTE: As #Sippy explained there is no need for you to use GetDoctors().AsQueryable<Doctors>();.
I have an asp.net web application, now i am trying to convert it to ASP.NET MVC. The problem is my old project has some .cs classes i, Example one class that handle all user data operations , one handle database operations , one will handle some priority properties like... I had included those classes in mvc Project , i had created a new Folder named Project_Class and copy all of my classes to it, my problem is how to access these classes in mvc controller class, how can i call a function of this class in mvc controller class.
I had include a sample .cs class structure below
**class1.cs**
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.SqlClient;
using System.Xml;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace xyz.abc
{
public class AssignValues:SSS
{
Process Objdb;
SqlCommand sqlcom;
SqlConnection sqlcon;
private int _EId;
private int _CId;
XmlDocument PXML, OutputXML;
XmlElement Root, ParameterElement, InputParamIdNode, OperatorIdNode, OutputParamIdNode, OutputParamValueNode, ConditionStatusNode, ModeNode, InputTypeNode, OutputTypeNode, InputRegisterIdNode, InputRegisterHeaderIdNode, OutputRegisterIdNode, OutputRegisterHeaderIdNode, UIdNode, orderNode;
public int iCount = 0;
public int EId
{
set
{
_EId = value;
}
get
{
return _EId;
}
}
public int CId
{
set
{
_CId = value;
}
get
{
return _CId;
}
}
public AssignValues()
{
}
public AssignValues(SqlCommand SqlComm,SqlConnection SqlConn)
{
Objdb = new Process();
sqlcom=SqlComm;
sqlcon = SqlConn;
}
public string check()
{
string x="hai";
return x
}
}
}
my Controller class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XYZ.ABC.Controllers;
using XYZ.ABC;
namespace XYZ.ABC.Controllers
{
public class XYZ_Controller :Controller
{
public ActionResult XYZ_Checklist()
{
return View();
}
}
}
i want to call "public string check()" method in my controller class,is it possible? ,i am newbie in mvc, please help me to solve this.
You can simply call that in your MVC controller class
Follow the steps
1) Include the namespace of the class in MVC controller class
2) Inherit old class in Your MVC Controller
Public Class MVCCOntrollerclassname: Class1
3) Create object of the .cs class
like
class1 c=new class1();
4) Create a constructor of MVC controller class
like
MVCCOntrollerclassname()
{
c.methodname();
}
Note : You say you are migrating asp.net to MVC , so if you have any asp.net dll then must change it as MVC Compitable dll
The MVC Framework just instantiates your Controller class and invokes an action method using some defined configuration or convention. So with that in mind ask yourself the question how would I invoke this method if you instantiated the controller yourself and called XYZ_Checklist().
The answer may look something like this:
public ActionResult XYZ_Checklist()
{
var assignValues = new AssignValues();
var result = assignValues.check();
// Do something here with the result ...
return View();
}
That's the short and simple answer. Once you start to understand that the framework isn't magic and is simply calling your code, you can start to delve into better ways to arrange your code (IoC/DI, etc.).
Hope this helps!
I'm new to EPiServer, and am attempting to retrieve child news article pages from a news list that I created. Examples that I've found online used the Locate() method, but when I attempt to apply Locate to my code, it's not being found.
This is one of the articles that I looked at.
http://world.episerver.com/Blogs/Johan-Bjornfot/Dates1/2012/8/EPiServer7-Working-with-IContentRepositoryDataFactory/
Essentially, I just need to return a list of child articles for a list of news items, so it's possible that the approach that I'm attempting is not right in the first place.
At any rate, this is my current model with the using statements.
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using EPiServer.ServiceLocation;
using EPiServer.SpecializedProperties;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace EPiServerExercise.Models.Pages
{
[ContentType(DisplayName = "News List", GUID = "ac3287b1-4d78-4eb3-bad2-6b5c43530b33", Description = "")]
public class NewsList : BasePage
{
private IEnumerable<NewsArticle> getNewsArticles(NewsList currentPage)
{
//var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>
//IEnumerable<NewsArticle> newsArticles = new List<NewsArticle>();
//PageReference pageLink = currentPage.ParentLink;
//IEnumerable<NewsArticle> newsArticles = Locate.ContentRepository().GetChildren<IContent>(pageLink);
//IEnumerable<NewsArticle> newsArticles = ServiceLocationHelperExtensions.
//var serviceLocationHelper = ServiceLocator.Current.GetInstance();
//serviceLocationHelper.ContentLoader
}
}
}
What reference am I missing to get the Locate() method to resolve? We are using EPiServer 7 and MVC. Thanks for your help.
Update on 11/18/2014
This is the eventual solution that I put into the model. It's almost identical to what Vsevolod Goloviznin suggested. Thanks.
public string showNewsArticles()
{
IEnumerable<NewsArticle> newsArticles = getNewsArticles(this);
// Code to loop through the articles
}
private IEnumerable<NewsArticle> getNewsArticles(NewsList currentPage)
{
var repository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
IEnumerable<NewsArticle> newsArticles = repository.GetChildren<NewsArticle>(currentPage.ContentLink);
return newsArticles;
}
Looks like he just uses a factory to get IContentRepository and forgot to mention to. So to just get the same functionality you can use the ServiceLocator to get the IContentRepository and then get all children for your page:
var service = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
var pages = service.GetChildren<NewsArticle>(currentPage.ParentLink).ToList();
I am trying to query a customer in qbo with a name that has an ' for example (Joe's Shop) and getting the above error.
here is the code.
IEnumerable<Customer> customers = customerQueryService.Where(c => c.DisplayName =="Joe's Shop");
if (customers.Count()!=0 )
{
customer = customers.First();
}
return customer;
Please use backslash to escape the single quote.
"Joe\'s Shop"
Thanks
using Intuit.Ipp.Core;
using Intuit.Ipp.Data;
using Intuit.Ipp.LinqExtender;
using Intuit.Ipp.QueryFilter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
static class SampleCalls
{
public static Customer QueryCustomerByDisplayName(ServiceContext context, string displayName) {
displayName = displayName.Replace("'", "\\'"); //Escape special characters
QueryService<Customer> customerQueryService = new QueryService<Customer>(context);
return customerQueryService.Where(m => m.DisplayName == displayName).FirstOrDefault();
}
}