Web services and client DLL - c#

I have a web service and a client DLL. The web service uses an Oracle database.
For testing the client DLL, I copied the web service and made it point to a test database. Then I copied the client DLL and added this test web service using "Add web reference".
What I would like to do is to use one web service and one client DLL but be able to tell the client DLL to use either use the test or production database rather than two identical web serivces and client DLLs.
Edit
I mis-stated the issue. What I need to do is use one client DLL and two web services (one production version, one development/test version) and be able to, somehow, tell the client DLL which web services to use.
This is a sample of how the web service, client DLL and client app are used:
public class DSSService : System.Web.Services.WebService
{
public DSSService()
{
}
[WebMethod(MessageName = "GetFacility", BufferResponse=true, Description = "blah.")]
public Facility GetFacility(string sFDBID, string sZip, string sFinNo)
{
Facility oFacility = ...;
...
return oFacility;
}
....
}
Client DLL:
namespace DSSConfig
{
string sWSURL;
public class Config
{
public Config()
{
}
public void SetWSURL(string sURL)
{
sWSURL = sURL;
}
public Facility GetFacility(string sFDBID, string sZip, string sFinNo)
{
DSSService Proxy = new DSSService();
proxy.Url = sWSURL;
Facility oFacility = Proxy.GetFacility(sFDBID, sZip, sFinNo);
return oFacility;
}
In client application, having DSSConfig DLL as reference:
DSSConfig oConfig = new DSSConfig();
oConfig.SetWSURL("http://myserver/WebService1/service.asmx");
oConfig.GetFacility("blah", "blah", "blah");

What you need to do is change the WEB Service to take a parameter that it will use to construct the connection string to the DB.
Then change client DLL to pass that parameter as part of the call or connection.
Then you can configure the Client DLL to using any technique you like to pass the parameter. My suggestion is perhaps derive a class from the generated proxy in the client DLL and use this in the client code.
Without specific implementation details I can't be more precise.

Related

REST Web Service in C# class library

I'm trying to create a REST Webservice, not sure to create a separate WebAPI or just add a WCF Service.
public class FirstService : Reactor, IFirstService
{
const string StateFilename = "DetectedEvent.bin";
public string Reset()
{
string stateFile = Path.Combine(App.StoragePath, StateFilename);
if (File.Exists(stateFile))
{
File.Delete(stateFile);
}
return "Reset Completed";
}
}
I am trying to write a webservice for deleting a file and that call I would be doing using Powershell Invoke-RestMethod
The DetectedEvent.bin is located in remote server.
I have already created a C# class library i.e. custom Seq.App.FirstOfType but now I want to create a REST webservice by which wen called can delete a file.
I am using Seq App, Seq has a storagePath which it stores all data, which I want to delete it.
Please someone can let me know how should I go forward i.e should I create new project i.e. WEBAPI and attach it to current solution or I should create a WCF service application.

Exposing lookup interface for MemoryCache in a windows service

Using .net 4.6, I have a windows service which has a timer that wakes up everyday at a configured time, connects to a remote database and caches some data in memory using the MemoryCache class:
string id = rec.ID;
string surname = rec.Surname;
string dateOfBirth = rec.DateOfBirth;
string agreement = rec.Agreement;
CachedData cd = new CachedData(id, surname, dateOfBirth, agreement);
MemoryCache.Default.Set(id, cd, new DateTimeOffset(DateTime.Now.AddDays(1)));
I need to expose a lookup interface on this MemoryCache. I have a separate WCF service which exposes a lookup interface but I don't know how to communicate the lookup request/result between the WCf service and windows service so if I get an id in the WCf service:
string id = HttpContext.Current.Request.QueryString.Get("id");
I could pass it on to the windows service which would look it up in memory cache and return a result.
I followed https://msdn.microsoft.com/en-us/library/ff649818.aspx to host a wcf service in a windows service. At the end I just added the following to the OnStart() method of the Service1.cs class of my WindowsService:
MemoryCache.Default.Set("K", "Hello World", new DateTimeOffset(DateTime.Now.AddDays(1)));
and assuming that because the WCF service (also called Service1.cs) is now hosted by the windows service and will share the same app domain, I modified the default GetData method in the WCF as follows:
public string GetData(int value)
{
var kv = MemoryCache.Default["K"] as string;
if (kv != null)
{
return kv;
}
else
{
return string.Format("Entered: {0}", value);
}
}
However when I use the test client and call the GetData it can't find the cached item in the MemoryCache.
You cannot get to MemoryCache instance from another process that hosts your WCF service.
Can you host WCF service inside Windows Service? In that case it won't be any issue to use MemoryCahce instance updated by timer in WCF service.
I would go for a (persistent) cache outside your application, that way you can have multiple instance, make deploys and so on without losing your cached data (what happens if your windows services goes tits up within those 24h today?). Memcached and Redis are the first ones that I think of.

Proxy for interacting with WCF services on client

Please, Help me !
I've some problems with my project (WPF with WCF).
My project its client-server interaction. In server I've EF that interaction with PatternRepository . On server it`s a wcf interaction I have services.
Each service its repository. In each service I have a set of commands for communication between server and client . Between client and server data transfer occurs via Json . Example, it's service:
public class ProductRepositoryService : IProductRepositoryService
{
public void AddProduct(string json)
{
_productRepository.Add(wrapperProduct.DeserializeProduct(json));
_productRepository.Save();
}
public void DeleteProduct(string json)
{ productRepository.Delete(_productRepository.GetById(wrapperProduct.DeserializeProduct(json).Id));
_productRepository.Save();
}
}
Example, its ProductSeviceLogics that interaction with ProductService :
ProductRepositoryServiceClient _service1Client;
public ProductSeviceLogics()
{
this._service1Client = new ProductRepositoryServiceClient();
}
public void AddProduct(string json)
{
_service1Client.AddProduct(json);
}
public void DeleteProduct(string json)
{
_service1Client.DeleteProduct(json);
}
It's mean that if I'll create services. I'll be create those methods for each service on the server and the client. I think that it's very bad .
So my question, How can i do so that these methods will be for all services ?
That is, I want not to create this methods for each service and for each client.
I recommend you to have a look into this ASP.NET MVC Solution Architecture article. Download the code and have a look into that, how they maintain the Repositories/Services/Models in separate class library and make use in User interface or WCF or WebAPI.
Here I will provide some sample solution pattern.
Create a new blank solution : File -> New Project -> Other Project Type -> Blank Solution and name it as MyProject.
Create new class library listed below
MyProject.Model
Create POCO class like Product, Sale
MyProject.Data
Add a reference of Model.
Contains EF(DbSet and DbContext) and Repositories like ProductRepository, SalesRepository.
MyProject.Service
Add reference Model and Data.
Make a call to your repositories from this project.
Create User Interface and WCF services
MyProject.Web
MyProject.WCF
Add a reference of Model and Service.
Your work flow like this WCF or Web Calls --> Service --> Repositories --> EF, So you can avoid creating multiple service for client and server.
Hope this helps you.
I solved this issue.
Generate proxy for WCF Service
Generate Proxy by implementing ClientBase class*
Generating proxy by using ClientBase class option has an advantage that it creates proxy at run time, so it will accommodate service implementation changes. Let’s follow the steps to generate proxy.
Add a Client Project to solution named as “ClientApp2″ that is
basically a Console Application.
enter image description here
Add reference of StudentService Project to ClientApp2. Add following
proxy class using ClientBase as:
public class StudentServiceProxy : ClientBase<IStudentService>, IStudentService
{
public string GetStudentInfo(int studentId)
{
return base.Channel.GetStudentInfo(studentId);
}
}
Note: Don’t forget to add “using StudentService” to class.
Following is the code for program.cs class in ClientApp2. We are using above created proxy class to communicate with WCF Service
“StudentService“.
class Program
{
static void Main(string[] args)
{
StudentServiceProxy myclient;
myclient = new StudentServiceProxy();
int studentId = 1;
Console.WriteLine(“Calling StudentService with StudentId =1…..”);
Console.WriteLine(“Student Name = {0}”, myclient.GetStudentInfo(studentId));
Console.ReadLine();
}
}
Note: Don’t forget to add “using System.ServiceModel” to class.
App.Config file will have following configuration:
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name=”WSHttpBinding_IStudentService” />
</wsHttpBinding>
</bindings>
<client>
<endpoint address=”http://localhost:4321/StudentService”
binding=”wsHttpBinding”
bindingConfiguration=”WSHttpBinding_IStudentService”
contract=”StudentService.IStudentService”
name=”WSHttpBinding_IStudentService”>
</endpoint>
</client>
Now, when we run the client application, we will receive the following same output as we get in earlier option “Adding Service Reference”.

Do I need to change web service path everytime when I call it?

I am developing on Windows application in c# and I am using web server's web service in this Windows application.
The web service should be dynamic and I need to change it in the application.
I managed to do it by this code :
CallWebService.MyWS ws = new CallWebService.MyWS();
ws.Url = "new url";
This new url will be set as per client's web server url.
I am calling this web service (I mean web service functions) 20 to 25 times in my application.
Do I need to change this path everytime when I call it or for the first time will be ok ?
Use a fixed port number for your service and configure this url in your app/web.config file and use it in your code.
Create a helper class and use that. Make it configurable by using an app setting or better store in config table in database if you are using one.
If you are using WCF client, you can pass URL in client constructor. Otherwise create a partial class for your webservice to create that constructor.
public class MyWebServiceHelper
{
private string _url = null;
public MyWebServiceHelper()
{
this._url = GetWsUrlFromDbOrAppConfig();
}
public CallWebService.MyWS GetMyWebServiceProxy()
{
return new CallWebService.MyWS("WcfBindingConfig", _url);
}
}

I can't seem to call my web service from C# Forms app

I have a web site which has a simple web service. I can call the web service successfully from javascript on the page. I need to be able to call the same web service from a C# forms application.
The web service code is very simple:
[WebService(Namespace = "http://myurl.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class IDCService : System.Web.Services.WebService {
public IDCService () {
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
My javascript works:
function HelloWorld() {
var yourName = $get('txtYourName').value;
alert(yourName);
IDCService.HelloWorld(HelloWorldCalback, failureCB);
}
function HelloWorldCalback(result) {
alert(result);
}
function failureCB(result) {
alert("Failed");
}
However, when I try to set a reference to the WS in my C# code what I expect to see is an object with a method "HelloWorld", what I in fact see is an object with properties like "HelloWorldRequest", "HelloWorldResponse", "HelloWorldRequestBody" and so forth.
I am new to web services, and am very confused. Any help would be appreciated.
Depends on how you added your reference :-)
If you added it by clicking "Add Web Reference", you specified the location of the service, and you gave it a namespace - let's assume it would be called "MySVC".
In that case, you should be able to do this in your Winforms program:
MySVC.MyTestService svc = new MySVC.MyTestService();
string message = svc.HelloWorld();
and thus retrieve the output of the HelloWorld method.
On the other hand, if you clicked on "Add Service Reference" (which is not the same - this will add a WCF client side proxy to your web service), then you'd get those request and response object classes. You should also get a xxxxClient class, and that's what you'll use:
MyWCFService.MyTestServiceSoapClient client =
new MyWCFService.MyTestServiceSoapClient();
string message = client.HelloWorld()
That way, you should be able to access all your methods on your web service, too.
Marc

Categories

Resources