Winforms server side consumed by ASP.NET, WCF? - asp.net

Where can I find a tutorial/sample of asp.net page consuming a WCF service that uses a winforms application server side?
Thanks

You are mentioning two separate and independent operations:
Consuming a WCF service from an ASP .Net application
Creating a WCF service that uses a win forms application
Which of them is the actual problem? Exposing functionality as a service separates the service consumer from the service provider. The service consumer (the ASP .Net application in your case) will never need to know the service provider (the WCF application) is implementing its functionality behind the scenes. All it needs to know is the public interface exposed by the service.
Update
If you are new to WCF, the video tutorials available here might be a good starting point. They present you the basic knowledge of exposing as well as consuming a service with WCF.
Now, related to "that uses a winforms application server side". I assume that what you are trying to do is expose in the service some of the functionality available in the win forms application. If that is the case all you have to do is reference the exe of the forms app (with Add reference in Visual Studio) inside the WCF app and call all the needed methods from there.
Even cleaner from an architectural perspective would be to separate the user interface (UI) and business logic (BL) of your win forms application in separate projects, which will result in separate binary files after compilation (an exe file corresponding to the UI and a dll for the BL). Then you will only need to reference the BL corresponding dll in the WCF service.

OK, This is what you need to do:
Create a Solution with a ASP.Net project in it. (Project A)
Go to File > Add > New Project and add a Windows Forms application. (Project B)
So, now you have two projects in your solution,
Add a reference from project B to project A.
Add a method that returns the main form of project B in Program.cs, here is an example:
public static class Program
{
public static MainForm mainForm;
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
mainForm = new MainForm();
Application.Run(mainForm);
}
public static MainForm RunForm()
{
Main();
return mainForm;
}
}
Define a new Thread in Global.asax > Application_Start to call the RunForm method and store the result in a static variable. example:
public static MainForm mainForm;
public void Application_Start()
{
new Thread(
() => { mainForm = Program.RunForm(); }
).Start();
}
(Don't forget to use using B;)
(If you don't run the form application in another thread, your website doesn't load.)
So, now you can access the main form using Global.mainForm
You can define some methods for showing MessageBox in MainForm class, and call them from the website! (The form doesn't need to be shown at all)

Related

Get current owin context in self host mode

I need to run my application which provides some ASP.NET Web API services on both IIS and .NET CLR self host modes.
I developed my ASP.NET Web API services based on OWIN and it is working fine on both hosts.
For now I need something like this:
public class OwinContextInfrastructure
{
public static IOwinContext Current
{
get
{
if (HttpContext.Current != null)
{
return HttpContext.Current.GetOwinContext();
}
else
{
// What should I do here ?
return null;
}
}
}
}
to get current owin context whenever I need in my application.
My code is working fine on IIS, but what should I do in .NET Self Host mode ?
You can use Request.GetOwinContext() for both web-hosting and self-hosting. GetOwinContext is an extension method for HttpRequestMessage and is defined in the System.Web.Http.Owin.dll assembly.
UPDATE
I have answered your original question, which is how to get OWIN context in both web-hosting and self-hosting. Now, through your additional question in the comment, you have significantly broadened the scope of your question. There is a fundamental problem though. IOwinContext is not a OWIN thing, it is a Katana thing. You cannot expect any framework hosted on OWIN to provide a context in the form of IOwinContext. ASP.NET Web API does but not every framework is supposed to. IOwinContext is an abstraction over OWIN environment dictionary and this dictionary will be available to any OWIN middleware. However, by working on top of a framework, you no longer can access the OWIN environment directly but only through how that specific framework has decided to expose the context.
For Nancy, you have to use NancyContext to get to the Items dictionary and look for the value corresponding to the key "OWIN_REQUEST_ENVIRONMENT". For SignalR, Environment property of IRequest gives you access to OWIN environment. Once you have the OWIN environment, you can create a new OwinContext using the environment.
First, I've to correct my question.
HttpContext.Current is available in applications which are based on ASP.NET and integrated IIS pipeline.But We can't use this class without asp.net anywhere, even on IIS integrated pipeline.
Answer:
1- Anywhere you need IOwinContext, you've to get it, using dependency injection, for example by constructor injection.
2- Configure everything to work based on Owin, SignalR is Owin based only, but use Web Api & owin together, and use nancy for server side views if any. Instead of writting IIS or ASP.NET handlers and modules, develop owin middlewares.
3- Using Autofac.Owin & AutoFac.WebApi & AutoFac.WebApi.Owin & Autofac.SignalR, you can setup dependency injection working across all owin middlewares you've in your application.
4- Autofac will instantiate web api controllers, signalr hubs and owin middlewares, and it will pass IOwinContext instance to classes you want using constructor injection.
My tests are ok on Owin IIS/Helios (without asp.net) , Owin SelfHost and even Owin Test Server.
This approach is similar to asp.net vNext. You can easily migrate your app to asp.net vNext, when it is production ready.

how to call webapi function from codebehind in webforms

I added a web api in my asp.net web forms project. I want to call this web api directly from my code behind. Both my code behind and web api are in the same project. Both are in same namespaces.
Is it the right way to instantiate the controller class and directly call the method in it(in webforms project - in button click). like:
SampleController obj = new SampleController();
Dictionary<String,String> values = obj.MyMethod();
Please suggest an alternative way, if this method is incorrect.
(This web-api is also consumed by another windows service using httpclient)
Thanks in advance.

Using WCF http web service in ASP.NET application

We have web application written in ASP.NET webforms with some asmx web services. Now we want to add some toher web services, which will serve different purpose than the old ones. We decided to use WCF framework.
My colleague created a new project in our solution, where he implemented the web service. Unfortunatelly he did not use the WCF* project templates, but normal console application with the following method for starting the WS:
public static void StartWS() {
if (_selfHost!=null)
StopWS();
Uri baseAdress = new Uri(WSIntegrationService.ServerUrl);
_selfHost = new ServiceHost(typeof(WSIntegrationService), baseAdress);
_selfHost.AddServiceEndpoint(typeof(IWSIntegrationService), new WSHttpBinding(SecurityMode.None), WSIntegrationService.EndPointName);
_selfHost.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });
_selfHost.Open();
logger.Info("Integration WS started on adress " + baseAdress);
}
Now I have to integrate the project to our web application (another project in solution).
What is the easiest way to do it?
How can I ensure that both - the old asmx service as well as the new WCF service is operational?
In the end the solution was not that hard:
In web app project choose Add New Item -> WCF Service. This should create Service.svc, Service.svc.cs and IService.cs. It also modifies your web config. Now you can try if it works, with the auto generated method DoWork. Simply use something like SoapUI app to do that. ALso you can try to browse to the svc file and check the wsdl (e.g.http://localhost:2753/WSIntegration/Service1.svc?wsdl)
Delete the files IService.cs and Service.csv.cs. Modify the Service.svc file, so it contains just the reference to the class implementing the WS, e.g. like this:
That's all. I haven't deploy the solution to the IIS yet, but I don't expect any problems there. As soon as I will do that. I will update the unswer if any additional steps will be needed.

What is the advantage of using web API over web method in ASP.NET

I am familiar with web method. Now I got a suggestion to use web API instead of web method. I had done a demo of ASP.NET web API it's more closer to a MVC architecture am using the classical asp.net web development. I don't like to mess up the controller (MVC concept) with classical development.
My web Method :
[WebMethod]
public static string GetName(int id)
{
return "testName";
}
My Web API controller:
public class MyController : ApiController
{
[HttpGet]
public string GetName(int id)
{
return "testName";
}
}
am really confused on this issue any one have a better idea on the same.
What is your suggestion on the same which is the better option?
How can i compare, if both having same piece of code?
The classic ASP.NET WebServices (what you call WebMethod) are a deprecated technology. There is no longer any active development. The ASP.NET Web API is a complete rewrite of the web stack from Microsoft in which you have far greater control for creating RESTful web services. This doesn't mean that you should choose between one or the other. There's also ServiceStack. If you are starting a new project you should stay away from classic webservices. If they are still present in the .NET framework it is for compatibility reasons with legacy code.
Complementing Darin's answer, if you want to test your method from ApiController, you can inject the object's dependencies using an DI container (http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver). The dependency injection is done automatically.
However, with webmethods, you can't use DI in that way because webmethods must be static. If you insist in using DI, you need to instantiate and call the container directly in each of the webmethods to get the dependencies to work on.

call web methods directly from other project

I am working with .NET solution project and there are a couple projects in side of the solution. One of projects has asmx file. Now, my question is that is it possible to call web methods in the asmx file directly from other projects in same solution instead of adding web reference of it?
Thanks.
ASMX files are usually placed in ASP.NET projects which are not suitable to be referenced by other projects. For this reason I would recommend you refactoring the functionality into a class library that will be referenced from the web service and from other projects where you directly call the methods:
var result = new SomeClass().SomeMethod();
and in the web service:
[WebMethod]
public string SomeMethod()
{
return new SomeClass().SomeMethod();
}

Resources