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).
Related
I have basic knowledge to create a web service using asmx.cs
and consume from any client application.
I want to create a Web Service using asmx.cs in .NET 3.5 using Visual Studio 2010.
For the following program,By default it gives textBox to take input from user.
But I want to use comboBox to take input from the user.
The result will be displayed as xml output.
I want to do a Web Service program where one city from ComboBox will be taken as input
and the temperature will be shown as xml output.
This code gives only textBox as input.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebService1
{
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string GetCityByZip(int Zip)
{
return "City Name = XYZ, Temperature = 30 Degree";
}
}
}
I think, what you're talking about is this html to test your web service methods, right?
http://3.bp.blogspot.com/_nuQwSyDoLk8/RvWnnpahW8I/AAAAAAAAAJw/UTFuJmCx5M0/s1600-h/WS3.bmp
This test ui is generated automatically based upon your service's WSDL.
The input types are based on the methods your service exposes. So if there's a method like CityInfo GetCityInfo(string cityName) in your service, there will be a textbox with input type string (as you already noticed). If you're exposing a method like CityInfo GetCityInfo(int cityId) the input type will be an int.
What's not possible, is to put a combobox there, as the service is autogenerated and has no knowledge which cities are selectable.
What you can do, is expose several methods and build a ui yourself (which you should do anyway).
public interface IYourServiceInterface
{
City[] GetCities(); // returns all possible cities
CityInfo GetCityInfo(City city); // returns detail Infos about a concrete city
}
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 am following this tutorial on how to send a SOAP message via C#, and have reached this stage:
Program
using System;
using System.Xml;
using Microsoft.Web.Services3;
using Microsoft.Web.Services3.Addressing;
using Microsoft.Web.Services3.Messaging;
namespace SOAP
{
class Program
{
static void Main(string[] args)
{
Uri strEpr = new Uri("http://www.webservicex.com/globalweather.asmx?WSDL");
EndpointReference epr = new EndpointReference(strEpr);
TcpClient client = new TcpClient(epr);
}
}
}
TcpClient
using System.Xml;
using Microsoft.Web.Services3;
using Microsoft.Web.Services3.Addressing;
using Microsoft.Web.Services3.Messaging;
namespace SOAP
{
class TcpClient : SoapClient
{
public TcpClient(EndpointReference endpointreference)
{
SoapClient();
}
[SoapMethod("RequestResponseMethod")]
public SoapEnvelope RequestResponseMethod(SoapEnvelope envelope)
{
return base.SendRequestResponse("RequestResponseMethod", envelope);
}
}
}
However, in the constructor in my TcpClient class I am seeing this error:
Non-invocable member 'SoapClient' cannot be used like a method.
I can see why this is, because the SoapClient class is abstract and its constructors are all protected. Does this mean that the MSDN documentation is out of date, or am I missing something here?
All I need to do is send a SOAP message to a web service and get the response - surely this should be quite easy in C#?
Although you now use a different approach, the problem with your posted code is that you didn't call the base classes constructor.
You should have done it like so
public TcpClient(EndpointReference endpointreference)
: base(endpointreference)
{}
As per Kosala W's recommendation, I found a solution to this without using SOAP messaging.
Right click the project in the Solution Explorer and select Add -> Service Reference.
In the dialog, type in the WSDL address and give it a name . This generates some tags in the app.config file with details about the Endpoint entered.
The service reference can now be called in the code. For example, if I created a Service Reference called Darwin, I can now call the methods associated with this web service like this:
Darwin.LDBServiceSoapClient client = new Darwin.LDBServiceSoapClient();
Darwin.StationBoard myBoard = client.GetDepartureBoard(params, go, here);
Where the client is used to send the message, and the GetDepartureBoard performs some operation on the web server (In this case, the method retrieves data about the specified Train Times Departure Board and returns it in SOAP message format).
Thanks Kosala w!
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.
The below code throws an error of "Object reference not set to an instance of an object" When calling mycache.Get("products"). Im using a WCF application. Im not 100% im using caching correctly. Any advice?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;
namespace DataLayer {
public class Products
{
public List<Product> Current()
{
Cache mycache = new Cache();
if (mycache.Get("products")== null)
{
using (DataLayer.AccessDataContext db = new AccessDataContext())
{
var products = from p in db.fldt_product_to_supp_parts
where p.Current
select new Product
{
WholesaleCode = p.WholesaleCode,
ProductCode = p.Product_Code
};
mycache["products"] = products.ToList();
}
}
return mycache["products"] as List<Product>;
}
} }
EDIT : I'm using .net 3.5
I'm not sure what is wrong with your code, because I don't know off-hand how Cache is implemented, but a little searching uncovered the following Walkthrough from MSDN:
http://msdn.microsoft.com/en-us/library/dd997362.aspx
Caching Application Data in a WPF Application
And the following link gives an overview:
http://msdn.microsoft.com/en-us/library/dd997357.aspx
In summary, it appears that for .NET v4 onwards, caching has been moved into System.Runtime.Caching from System.Web.Caching.
From the look of the documentation you shouldn't be creating your own instance of the Cache class (it says the constructor is for framework use only). Try using Cache.Get instead?
EDIT (in response to comment)...
From the MSDN docs here:
One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. Information about an instance of this class is available through the Cache property of the HttpContext object or the Cache property of the Page object.
So, it looks like Cache.Get is available when you're within a Page; otherwise you can call HttpContext.Cache to get the active cache. Either way, there's a single Cache object for your entire application and you definitely shouldn't be creating one of your own.
For non ASP.NET applications use caching from System.Runtime.Caching.
Your code throws System.NullReferenceException because internal cache CacheInternal of System.Web.Caching.Cache isn't initialized using internal void SetCacheInternal(CacheInternal cacheInternal) method. It initializes by ASP.NET infrastructure in System.Web.HttpRuntime class.
Unless I'm missing something, you're trying to use the ASP .NET cache within your WCF service. In order for this to work, you need to turn on ASP .NET compatibility using the AspNetCompatibilityRequirementsMode Enumeration. If you're self-hosting you'll have to roll your own.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class CalculatorService : ICalculatorSession
{
}