Without any Linq or Entity Framework, I would like to see an example of using ADO.NET with Oracle in WCF. I have seen the ABC's and the different contracts, but with say consuming a Restful WCF service sending in 1 to several parameters I would like to see an example of using this type of code:
connection = new OracleConnection(EnvironmentSettings.connectionString);
connection.Open();
command = new OracleCommand("H16.WEB_FACILITY.get_facility_info", connection);
command.CommandType = CommandType.StoredProcedure;
// Input Parameters
command.Parameters.Add("pfcode", OracleDbType.Varchar2, facilityCode, ParameterDirection.Input);
// Output Parameters
command.Parameters.Add("pfacility", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
adapter = new OracleDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
So that I can do CRUD operations will a WCF good practice design. Fault Contracts / Data Contracts etc... I see many examples, but not specific to something that seems so simple. I guess that it why so many people are still doing asmx ... I'm wanting to convert a project I am on and I see tons of asmx web services everywhere and wish for an expert or someone who has done this to point my in the right direction or even better show me how to write that ADO code into WCF ... Thanks in advance.
Slightly confusted as to exactly what you mean, but Linq and EntityFramework have nothing to do with WCF, and the paradigm doesn't change one bit in using them. You could do something as simple as:
[ServiceContract]
public class MyService
{
[OperationContract]
public DataSet LoadData(string facilityCode)
{
command = new OracleCommand("H16.WEB_FACILITY.get_facility_info", connection);
command.CommandType = CommandType.StoredProcedure;
// Input Parameters
command.Parameters.Add("pfcode", OracleDbType.Varchar2, facilityCode, ParameterDirection.Input);
// Output Parameters
command.Parameters.Add("pfacility", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
adapter = new OracleDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds;
}
}
In practice you would probably want to use a [DataContract] class, and return that instead of a DataSet, but the only real change would be reading your results into a real class instead of a DataSet, something like:
[DataContract]
public class MyData
{
[DataMember]
public string Facility { get; set; }
}
Then your service method returns that instead of DataSet:
[OperationContract]
public MyData LoadData(string facilityCode)
{
MyData data;
// read from Oracle into data object...
return data;
}
You can also look at WCF Transaction Flow to control your database transaction scope. It is a nice way to have every WCF service operation be trapped in its own transaction scope, or even control the transaction from the WCF client if needed.
[FaultContract]s are a subject on their own, but you can find some good examples if you google for it. Basically you would set up your own exception type, and then add that to the service like:
[ServiceContract]
[FaultContract(typeof(MyException))]
public class MyService
and that tells WCF to add the serialization info for MyException to the WSDL, so then your operations can throw new MyException(); and that will serialize back to the clients, so they will get your exception.
Related
I need to build a Web API from ASP.NET Core without Entity Framework. It's an existing database that has some custom stored procedures and we do not want to use EF.
I searched this topic and can't find anything about it, is this even possible?
This is possible.
The first problem you will run into is getting the database connection string. You will want to import the configuration to do so. In a controller, it might look like this:
private readonly IConfiguration _configuration;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
Add using System.Data and using System.Data.SqlClient (you'll need NuGet for SqlClient) as well as using Microsoft.Extensions.Configuration. With access to the database, you are writing code "old style", for example:
[HttpGet]
[Route("[controller]/movies")]
public IEnumerable<Movie> GetMovies()
{
List<Movie> movies = new List<Movie>();
string connString = ConfigurationExtensions.GetConnectionString(_configuration, "RazorPagesMovieContext");
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Movie", conn);
DataSet ds = new DataSet();
sda.Fill(ds);
DataTable dt = ds.Tables[0];
sda.Dispose();
foreach (DataRow dr in dt.Rows)
{
Movie m = new Movie
{
ID = (int)dr["ID"],
Title = dr["Title"].ToString(),
ReleaseDate = (DateTime)dr["ReleaseDate"],
Genre = dr["Genre"].ToString(),
Price = (decimal)dr["Price"],
Rating = dr["Rating"].ToString()
};
movies.Add(m);
}
conn.Close();
return movies.ToArray();
}
The connection string name is in appsettings.json.
"ConnectionStrings": {
"RazorPagesMovieContext": "Server=localhost;Database=Movies;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Yes it is possible. Just implement the API by yourself. Or here is also sample for the identity scaffold, without EF.
https://markjohnson.io/articles/asp-net-core-identity-without-entity-framework/
Just used Dapper as our ORM in a project rather than EF.
https://dapper-tutorial.net/
It is similar to ADO.Net, but it has some additionally features that we leveraged and it was really clean to implement.
I realize this is an old question, but it came up in a search I ran so I figured I'd add to the answers given.
First, if the custom stored procedures are your concern, you can still run them using Entity Framework's .FromSql method (see here for reference: https://www.entityframeworktutorial.net/efcore/working-with-stored-procedure-in-ef-core.aspx)
The relevant info is found at the top of the page:
EF Core provides the following methods to execute a stored procedure:
1. DbSet<TEntity>.FromSql(<sqlcommand>)
2. DbContext.Database.ExecuteSqlCommand(<sqlcommand>)
If you are avoiding Entity Framework for other reasons, it's definitely possible to use any database connection method you want in ASP.NET Core. Just implement your database connection methods using whatever library is relevant to your database and set up your controller to return the data in whatever format you want. Most, if not all, of Microsoft's examples return Entity Framework entities, but you can easily return any data format you want.
As an example, this controller method returns a MemoryStream object after running a query against an MS SQL server (note, in most cases where you want data returned it's my understanding that it should be a "GET" method, not "POST" as is done here, but I needed to send and use information in the HttpPost body)
[HttpPost]
[Route("Query")]
public ActionResult<Stream> Query([FromBody]SqlDto content)
{
return Ok(_msSqlGenericService.Query(content.SqlCommand, content.SqlParameters));
}
Instead of a MemoryStream, you could return a generic DataTable or a List of any custom class you want. Note that you'll also need to determine how you are going to serialize/deserialize your data.
Is there a way to create an async client for a synchronous WCF service without adding a service reference? This is for a .NET 4 client.
A service reference in Visual Studio is nothing else than a code generator that creates a proxy class with corresponding data elements necessary to call your web service. Of course you can hand build a proxy if you really want to go over tedious and boring work.
Maybe start by decompiling System.ServiceModel.ClientBase using .net reflector?
Do some research on ChannelFactory: http://msdn.microsoft.com/en-us/library/system.servicemodel.channelfactory.aspx
Even when implementing my own client by wrapping a ChannelFactory, I am still using the Add Service reference in another project to create the class definitions and move them into the real project. That's a good compromise.
Here's a simple async service interface:
[ServiceContract(Name = "IService")]
public interface IServiceAsync
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginGetStuff(string someData, AsyncCallback callback, object state);
IEnumerable<Stuff> EndGetStuff(IAsyncResult result);
}
The .NET contract might look like this:
[ServiceContract]
public interface IService
{
[OperationContract]
IEnumerable<Stuff> GetStuff(string someData);
}
Then in code, assuming you use HTTP, No security and binary message encoding, something like this (Sorry I haven't compiled any of this, just typed it using some of the code I have written for projects):
//Create a binding for the proxy to use
HttpTransportBindingElement httpTransportBindingElement;
httpTransportBindingElement = new HttpTransportBindingElement();
absoluteServiceUri = new Uri(absoluteServiceUri.OriginalString + BinaryEndpointUri, UriKind.Absolute);
}
//Create the message encoding binding element - we'll specify binary encoding
var binaryMessageEncoding = new BinaryMessageEncodingBindingElement();
//Add the binding elements into a Custom Binding
var customBinding = new CustomBinding(binaryMessageEncoding, httpTransportBindingElement);
// Set send timeout
customBinding.SendTimeout = this.SendTimeout;
var factory = new ChannelFactory<IServiceAsync>(customBinding, new EndpointAddress(absoluteServiceUri, new AddressHeader[0]));
var channel = factory.CreateChannel();
channel.BeginGetStuff(Bla, results => { // Do something }, null);
I decided to open a new question about this matter, maybe expanding this question, not having found a precise answer about the issue anywhere on the Internet.
I want to use protobuf-net to serialize/deserialize messages exchanged between my WCF client and service. The service is self-hosted in a Windows Service. Both client and service are configured programmatically, using a custom binding very similar to wsHttpBinding. Service reference code is generated using "Add Service Reference" option in Visual Studio. The ORM used on the WCF service is EntityFramework 4 and it's code is generated using EF 4.x POCO Generator. More info about my service configuration can be found in a question I started here (that's where I described that my current serializer is DataContractSerialzizer).
I have only tested protobuf-net with one service operation which returns a list of custom DTOs.
Here is the operation (be advised that I just did a copy-paste of my code to here, there might be some fields named in my domestic language, not English):
public static List<OsobaView> GetListOsobas()
{
Database DB = new Database(); // EF object context
var retValue = DB.Baza.Osoba
.Select(x => new OsobaView
{
ID = x.ID,
Prezime = x.Prezime,
Ime = x.Ime,
Adresa = x.Adresa,
DatumRodjenja = x.DatumRodjenja,
JMBG = x.JMBG
});
return retValue.ToList();
}
Here is the definition of OsobaView class:
[ProtoContract]
public class OsobaView
{
[ProtoMember(1)]
public int ID;
[ProtoMember(2)]
public string Prezime;
[ProtoMember(3)]
public string Ime;
[ProtoMember(4)]
public string Adresa;
[ProtoMember(5)]
public DateTime DatumRodjenja;
[ProtoMember(6)]
public string JMBG;
}
As I am using "Add Service Reference" to generate the reference code, I had to use one of the two work-arounds in order to have my client recognize ProtoContracts and members:
using a shared assembly for DTOs (which is not an ideal solution in my case except for custom DTOs, due to the fact that I pass EF-generated POCOs to the client)
using ProtoPartialMember approach
I used both of them and I used both v1 and v2 of protobuf-net, all solutions yielded similar results which led me to believe my client is not deserializing at all. Read on.
Let's consider cases where I used the ProtoPartialMember approach. At first I used v2. I love the way ProtoOperationBehavior can be used. Here is the service operation to be invoked:
[ProtoBuf.ServiceModel.ProtoBehavior]
public List<OsobaView> GetListOsobas()
{
return OsobaQueries.GetListOsobas();
}
Here is how I replaced DataContractSerializerOperationBehavior with ProtoOperationBehavior for the needed service operation on client side:
OperationDescription op = Service.Proxy.Endpoint.Contract.Operations.Find("GetListOsobas");
if (op != null)
{
DataContractSerializerOperationBehavior dcsBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>();
if (dcsBehavior != null)
op.Behaviors.Remove(dcsBehavior);
op.Behaviors.Add(new ProtoBuf.ServiceModel.ProtoOperationBehavior(op));
}
And of course, here is the above mentioned work-around implementation for DTO:
[ProtoPartialMember(1, "ID")]
[ProtoPartialMember(2, "Prezime")]
[ProtoPartialMember(3, "Ime")]
[ProtoPartialMember(4, "Adresa")]
[ProtoPartialMember(5, "DatumRodjenja")]
[ProtoPartialMember(6, "JMBG")]
[ProtoContract]
public partial class OsobaView
{
}
Now when I call this service operation from my client, I get null. But Fiddler disagrees. It clearly says, in response header:
Content-Length: 1301963
Content-Type: application/soap+xml; charset=utf-8
...and in the message body:
<s:Body>
<GetListOsobasResponse xmlns="http://tempuri.org/">
<proto>CkMIpHES .../* REALLY LONG RESPONSE */... IyMDAxOA==</proto>
</GetListOsobasResponse>
</s:Body>
Then I thought, let's try with v1. On the service side, I haven't changed much. I just removed the reference to v2 .DLL and replaced it with a reference to v1 .DLL. On the client side, I had to remove the code to add ProtoOperationBehavior to my service operation behaviors and added the following line instead:
Service.Proxy.Endpoint.Behaviors
.Add(new ProtoBuf.ServiceModel.ProtoEndpointBehavior());
I fired it up, invoked the operation, and this time the result is not null. This time it is a list of blank fields. Again, Fiddler couldn't agree because it again said the same what it said before. The same content length and the same message body.
What's going on here?
P.S. If it's worth anything, here is the WCF configuration:
CustomBinding customBinding = new CustomBinding();
customBinding.CloseTimeout = TimeSpan.FromMinutes(10);
customBinding.OpenTimeout = TimeSpan.FromMinutes(10);
customBinding.ReceiveTimeout = TimeSpan.FromMinutes(10);
customBinding.SendTimeout = TimeSpan.FromMinutes(10);
HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
httpsBindingElement.AllowCookies = false;
httpsBindingElement.BypassProxyOnLocal = false;
httpsBindingElement.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
httpsBindingElement.MaxBufferPoolSize = 20480000;
httpsBindingElement.MaxBufferSize = 20480000;
httpsBindingElement.MaxReceivedMessageSize = 20480000;
httpsBindingElement.RequireClientCertificate = true;
httpsBindingElement.UseDefaultWebProxy = true;
TransportSecurityBindingElement transportSecurityElement = new TransportSecurityBindingElement();
transportSecurityElement.EndpointSupportingTokenParameters.SignedEncrypted.Add(new UserNameSecurityTokenParameters());
transportSecurityElement.EndpointSupportingTokenParameters.SetKeyDerivation(false);
TransactionFlowBindingElement transactionFlowElement = new TransactionFlowBindingElement();
TextMessageEncodingBindingElement textMessageEncoding = new TextMessageEncodingBindingElement();
textMessageEncoding.MaxReadPoolSize = 20480000;
textMessageEncoding.MaxWritePoolSize = 20480000;
textMessageEncoding.ReaderQuotas = XmlDictionaryReaderQuotas.Max;
ReliableSessionBindingElement reliableSessionElement = new ReliableSessionBindingElement();
reliableSessionElement.ReliableMessagingVersion = ReliableMessagingVersion.WSReliableMessagingFebruary2005;
customBinding.Elements.Add(transportSecurityElement);
customBinding.Elements.Add(transactionFlowElement);
customBinding.Elements.Add(textMessageEncoding);
customBinding.Elements.Add(reliableSessionElement);
customBinding.Elements.Add(httpsBindingElement);
EndpointAddress endpoint = new EndpointAddress(new Uri(ServiceAddress));
Service.Proxy = new BazaService.BazaClient(customBinding, endpoint);
Service.Proxy.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, CertificateSubject);
CustomBehavior behavior = Service.Proxy.Endpoint.Behaviors.Find<CustomBehavior>();
if (behavior == null)
{
Service.Proxy.Endpoint.Behaviors.Add(new CustomBehavior()); // message inspector
}
Service.Proxy.Endpoint.Contract.Behaviors.Add(new CyclicReferencesAwareContractBehavior(true));
Service.Proxy.Endpoint.Behaviors.Add(new ProtoBuf.ServiceModel.ProtoEndpointBehavior());
/* code used for protobuf-net v2
OperationDescription op = Service.Proxy.Endpoint.Contract.Operations.Find("GetListOsobas");
if (op != null)
{
DataContractSerializerOperationBehavior dcsBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>();
if (dcsBehavior != null)
op.Behaviors.Remove(dcsBehavior);
op.Behaviors.Add(new ProtoBuf.ServiceModel.ProtoOperationBehavior(op));
} */
Service.Proxy.ClientCredentials.UserName.UserName = LogOn.UserName;
Service.Proxy.ClientCredentials.UserName.Password = LogOn.Password;
Service.Proxy.Open();
EDIT
To provide even more information, I have read what's written there but it didn't help. I have deleted the service reference generated by Visual Studio and created my own, sharing the whole service contract, but nothing has changed.
After concentrating a bit better, I decided to restart the solution from scratch. I created one class library for the EDMX with it's POCOs, one for ServiceContract and DataContracts and one for the actual WCF service implementation. Then I shared those two libraries containing ServiceContract and DataContracts, and POCOs with the WCF client and tried again, which yielded the same results as before. After trying some other operations which didn't use protobuf-net for serialization, turned out they behaved the same as the first one, resulting in empty fields (!).
The thing was that, I screwed my WCF client's .datasource files while refactoring after I decided to use the assembly sharing technique. So this was a typical PEBKAC, it of course works fine when done properly. Great work with protobuf-net, Marc Gravell!
I have a requirement by which I need to retrieve data from SSAS cubes and send it over to OData. How can that be done? Any help will be greatly appreciated. Any pointers to sample code will also be greatly appreciated.
Thanks and regards,
Venkatesh. S
you can use ADOMD.Net to execute the query and send the result with wcf. Below is the class that I usually use.
class MDXQueryEngine : IMDXQueryEngine
{
private readonly string _serverName;
private readonly string _initalCatalog;
public MDXQueryEngine(string serverName, string initalCatalog)
{
_serverName = serverName;
_initalCatalog = initalCatalog;
}
public TResult Execute<TResult>(MDXQuery query, Func<IDataReader, TResult> work)
{
var connectionString = string.Format("Data Source={0}; Initial Catalog={1}", _serverName, _initalCatalog);
TResult result;
using (var conn = new AdomdConnection(connectionString))
{
conn.Open();
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = query.Expression;
using (var reader = cmd.ExecuteReader())
{
result = work(reader);
}
}
}
return result;
}
}
You can query SSAS cubes using LINQ and ADO.NET Entity Framework.
You will need SSAS Entity Framework Provider in order to be able to do that:
http://agiledesignllc.com/products
This option makes building WCF Data Services straightforward and trivial.
I assume it is SSAS cubes. Not sure about specific frameworks as such to do this.
But one possible solution:
Wrap the Cube (MDX) with a store procedure. (Access SSAS with MDX from SP)
You can create WCF data service, add an EM and specify stored procedure for EM. You should be able to expose them as oData.
How can I implement one way WCF operations?
I just tried using IsOneWay attribute as:
[OperationContract(IsOneWay=true)]
void MethodName(string param1, int param2)
Is there any other change I need to make or any specific change in app.config?
FYI, my WCF service implements netTcpBinding, though I think that shouldn't make any difference.
As shown, your code looks ok. There should be no problem with doing one-way calls with netTcpBinding.
If you're interested, chapter 5 in Juval Lowy's awesome Programming WCF Services 2nd Edition contains a good bit of information about one-way services.
From what you've shown, so far though I don't see anything wrong. Please give us some more details.
We had a problem with one-way calls not returning immediately using the NetTcpBinding. This blog post identifies the problem and provides a solution.
http://blogs.msdn.com/b/distributedservices/archive/2009/02/12/client-proxy-close-method-call-does-not-finish-immediately-in-one-way-wcf-calls.aspx
From the article:
Problem: Clients calling a one-way method in WCF Service and then close method on proxy does not return until the call is actually finished or call times out. Ever wonder why this happens?
Cause: When you specify “One-Way” on your interface, the underlying channel operation is still two-way since the one way binding element is not in the channel stack. Thus, the close operation gets blocked until the one way operation completes.
This is by design and the development team is working to change it in future versions of .Net framework.
...
Solution (Work around):
Layer the OneWayBindingElement on top of netTcpBinding as shown in the below code. This way, close call on proxy will return immediately and eventually the one-way call will return in fire and forget fashion.
[ServiceContract]
public interface IService1
{
[OperationContract(IsOneWay = true)]
void SetData(int value);
}
public class Service1 : IService1
{
public void SetData(int value)
{
//Application specific code
}
}
Service Host code:
Form1ServiceHost = new ServiceHost(this, new Uri("net.tcp://localhost:8091/WindowsFormApp/Form1/"), new Uri("http://localhost:8090/WindowsFormApp/Form1/"));
Binding binding = new NetTcpBinding();
BindingElementCollection oldBindingElements = binding.CreateBindingElements();
BindingElementCollection bindingElements = new BindingElementCollection();
bindingElements.Add(new OneWayBindingElement());
foreach (BindingElement bindingElement in oldBindingElements)
{
bindingElements.Add(bindingElement);
}
binding = new CustomBinding(bindingElements);
Form1ServiceHost.AddServiceEndpoint("WCFServiceLibrary.IService1", binding, "");
Form1ServiceHost.Open();
Client Code:
Binding binding = new NetTcpBinding();
BindingElementCollection oldBindingElements = binding.CreateBindingElements();
BindingElementCollection bindingElements = new BindingElementCollection();
bindingElements.Add(new OneWayBindingElement());
foreach (BindingElement bindingElement in oldBindingElements)
{
bindingElements.Add(bindingElement);
}
binding = new CustomBinding(bindingElements);
Service1Client client = new Service1Client(binding, new EndpointAddress("net.tcp://localhost:8091/WindowsFormApp/Form1/"));
client.SetData(10);
Console.WriteLine("set data");
Console.WriteLine("Now closing the channel,Before close, current time is {0}", DateTime.Now.ToString() + " " + DateTime.Now.Millisecond.ToString());
client.Close();
Console.WriteLine("Now closing the channel,After close, current time is {0}", DateTime.Now.ToString() + " " + DateTime.Now.Millisecond.ToString());`