Good day!
I try to learn ASP MVC vNext (6?) , so i use this tutorial, but when i type this code:
[HttpPost]
public void CreateTodoItem([FromBody] TodoItem item)
{
item.Id = 1 + _items.Max(x => (int?)x.Id) ?? 0;
_items.Add(item);
string url = Url.RouteUrl("GetByIdRoute", new { id = item.Id },
Request.Scheme, Request.Host.ToUriComponent());
Context.Response.StatusCode = 201;
Context.Response.Headers["Location"] = url;
}
I have the error message:'Url' does not contain a definition for 'RouteUrl'.
I add this usings, but it does no help:
using Microsoft.AspNet.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Net.Http.Server;
using System.Runtime.Remoting.Contexts;
using System.Security.Policy;
Please, help me to fix this errors!
Url.RouteUrl is in the System.Web.Mvc.dll so add using System.Web.Mvc;
looking back at this Url.RouteUrl is in the Microsoft.AspNet.Mvc namespace in MVC6. you seem to have that so I'm not 100% sure. could be missing reference files or other compile errors.
Related
I want to log .net WEB API request-response to newly created file. So, I have implemented NLog mechanism in my project which works great. but still below code's .ToJSON() line doesn't get resolved. I can't figure out which namespace is required to use it. is there anything missing out?
I'm referring these two articles but still can't figure out.
1) http://www.codeproject.com/Articles/1028416/RESTful-Day-sharp-Request-logging-and-Exception-ha
2) http://www.strathweb.com/2012/06/using-nlog-to-provide-custom-tracing-for-your-asp-net-web-api/
.net namespaces
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Tracing;
using System.Net.Http;
using System.Text;
if (level != TraceLevel.Off)
{
if (traceAction != null && traceAction.Target != null)
{
category = category + Environment.NewLine + "Action Parameters : " + traceAction.Target.ToJSON(); //this ToJSON doesn't get resolved. which namespace should I include?
}
var record = new TraceRecord(request, category, level);
if (traceAction != null) traceAction(record);
Log(record);
}
There is no such method. The example from codeproject.com shows you how to make it yourself:
using System.Web.Script.Serialization;
using System.Data;
using System.Collections.Generic;
using System;
namespace WebApi.Helpers
{
public static class JSONHelper
{
/// <summary>
/// Extened method of object class, Converts an object to a json string.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJSON(this object obj)
{
var serializer = new JavaScriptSerializer();
try
{
return serializer.Serialize(obj);
}
catch(Exception ex)
{
return "";
}
}
}
}
A better way is to use JSON.Net. It is most likely already referenced in your project and System.Web.Extensions.dll is ancient nowadays (its performance is terrible):
public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
{
if (level != TraceLevel.Off)
{
if (traceAction != null && traceAction.Target != null)
{
category = category + Environment.NewLine + "Action Parameters : " + JsonConvert.SerializeObject(traceAction.Target);
}
var record = new TraceRecord(request, category, level);
if (traceAction != null) traceAction(record);
Log(record);
}
}
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!
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();
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();
}
}