I am Developing one Windows Smart Phone - 6 Application using C# in .Net 3.5 Framework. And I have created one Webservice project using ASP.Net Web Service Application 3.5. Into this Webservice project I have define Service1.asmx. Now I would like to call Webmethod "HelloWorld" on Button Click. Here is code.
Service1.asmx
using System.Web.Services;
namespace WebService1
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
And Button Click Event
private void button1_Click(object sender, EventArgs e)
{
WebService1.Service1 myService = new WebService1.Service1();
string str = myService.HelloWorld();
}
I am Getting Error On This Line
WebService1.Service1 myService = new WebService1.Service1();
Please Give Me Guidance As I am Very New In This.
Thanks In Advance
Pratik Bhatt
Use the add web reference dialog from visual studio and point them to your hosted service. The dialog creates the consuming client based on the generated WSDL.
Your approach doesn't work because hosting a webservice and consuming one uses a different set of classes.
Problem Solved.
Error Was Occurring Because The Smart Device Emulator has No Access Permission for internet(network)so you have to install Microsoft Active Sync to connect emulator to network
Thanks Ralf Ehlert For Suggesting.....
Related
I'm trying to create a new Web API based on the ASP.Net 5 Web API template in VS2015, with DryIoc at container.
I've created a new Web API project and installed the DryIoc using package-manager
Install-Package DryIoc.Dnx.DependencyInjection -Pre
but I'm not sure how to wire up the container... haven't been able to find any 'Web API' samples showing that....
Any help would be greatly appreciated
I've figured it out now...
The default startup.cs file contains:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
}
but it has to be replace with:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var container = new Container().WithDependencyInjectionAdapter(services);
container.Register<IRepository, Repository>(Reuse.Singleton);
var serviceProvider = container.Resolve<IServiceProvider>();
return serviceProvider;
}
also the ' System.Runtime.Extensions >= 4.0.11-rc2-23706' error can just be ignored
I don't have a specific WebApi sample at the moment. But WebApi and Mvc are "unified" in AspNetCore, and I do have primitive Mvc sample. Hope it helps.
Btw, I am open for ideas / PRs how to improve it further.
I have a WCF Web Service sitting on a client's IIS server secured with NTLM authentication - I have no control over the authentication configuration on that server.
I need to integrate my WSO2 ESB server with this service, but I can't find a way to get the ESB to authenticate automatically. I have successfully pushed requests through the ESB to the service with web applications, but I was prompted to provide my Windows credentials during that process - I would like for this to not happen.
I have attempted to set up an NTLM proxy on my server, but couldn't figure this out either.
Any guidance would be much appreciated.
Strainy
Ok, i found your answer. As you know, WSO2 ESB uses Axis2 for web services. You must add NTLM configuration in Axis2 config file (ESB_HOME/repository/conf/axis2/axis2.xml).
This links, describes the configuration.
http://wso2.com/library/161/
http://axis.apache.org/axis2/java/core/docs/http-transport.html
There were a few components to getting this working correctly. It's hard to find it all written down in one place, so I'll attempt to provide an end-to-end overview here.
I first had to use a class mediator within my WSO2 ESB in-sequence to handle the sending and the NTLM authentication. The class mediator references a custom class which takes the message context from the mediation flow (called the Synapse message context) and extracts the SOAP envelope. I then loaded the Synapse SOAP envelope into an Axis2 message context object. I then used an Axis2 client along with the message context to submit my authenticated request to the server. The authentication for NTLM through Axis2 comes from the JCIFS_NTLMScheme class, which you can reference here.
Note: you'll have to play with the logging configuration in that class to make it work with WSO2. I just removed the " org.sac.crosspather.common.util* " libraries and altered any logging I saw to use the Apache Commons logging capability
Create a Custom Mediator Project in WSO2 Developer Studio
Create a new project in Developer studio. Right click the project node in the project explorer and select "New > Mediator Project".
This will generate a bit of boilerplate code for you - that is, a class which extends AbstractMediator and which implements an "mediate()" method which Synapse will call when it comes to executing the logic defined within your sequence.
public class NTLMAuthorisation extends AbstractMediator {
public boolean mediate(MessageContext context){
//Mediation Logic
return true;
}
}
Expose Some Variables/Properties to the User
The class mediator looks for variables which are publicly accessible and exposes them in the WSO2 configuration. This is helpful before you can create a re-usable mediator which adapts itself to properties or values defined in the WSO2 Carbon Web UI. Here we need to expose seven variables: soapAction, SoapEndpoint, domain, host, port, username, and password. Expose the variables by defining your instance variables, along with their accessors and mutators.
This is all really quite useful for using the WSO2 Secure Vault to store your NTLM password and fetching other configuration from a system registry with properties.
public class NTLMAuthorisation extends AbstractMediator {
private String soapAction;
private String soapEndpoint;
private String domain;
private String host;
private int port;
private String username;
private String password;
public boolean mediate(MessageContext context) {
//Mediation Logic
return true;
}
public void setSoapAction(String _soapAction){
soapAction = _soapAction;
}
public String getSoapAction(){
return soapAction;
}
public void setSoapEndpoint(String _soapEndpoint){
soapEndpoint = _soapEndpoint;
}
public String getSoapEndpoint(){
return soapEndpoint;
}
public void setDomain(String _domain){
domain = _domain;
}
public String getDomain(){
return domain;
}
public void setHost(String _host){
host = _host;
}
public String getHost(){
return host;
}
public void setPort(int _port){
port = _port;
}
public int getPort(){
return port;
}
public void setUsername(String _username){
username = _username;
}
public String getUsername(){
return username;
}
public void setPassword(String _password){
password = _password;
}
public String getPassword(){
return password;
}
}
The Custom Mediation Logic
Make sure you created an JCIFS_NTLMScheme class from here and have added the org.samba.jcifs dependency to your Maven dependencies like so:
<dependency>
<groupId>org.samba.jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>1.3.17</version>
</dependency>
Now you can use the following mediate method in your custom mediator class:
public boolean mediate(MessageContext context) {
//Build NTLM Authentication Scheme
AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, JCIFS_NTLMScheme.class);
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername(username);
auth.setPassword(password);
auth.setDomain(domain);
auth.setHost(host);
auth.setPort(port);
ArrayList<String> authPrefs = new ArrayList<String>();
authPrefs.add(AuthPolicy.NTLM);
auth.setAuthSchemes(authPrefs);
//Force Authentication - failures will get caught in the catch block
try {
//Build ServiceClient and set Authorization Options
ServiceClient serviceClient = new ServiceClient();
Options options = new Options();
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
options.setTo(new EndpointReference(soapEndpoint));
options.setAction(soapAction);
serviceClient.setOptions(options);
//Generate an OperationClient from the ServiceClient to execute the request
OperationClient opClient = serviceClient.createClient(ServiceClient.ANON_OUT_IN_OP);
//Have to translate MsgCtx from Synapse to Axis2
org.apache.axis2.context.MessageContext axisMsgCtx = new org.apache.axis2.context.MessageContext();
axisMsgCtx.setEnvelope(context.getEnvelope());
opClient.addMessageContext(axisMsgCtx);
//Send the request to the server
opClient.execute(true);
//Retrieve Result and replace mediation (synapse) context
SOAPEnvelope result = opClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE).getEnvelope();
context.setEnvelope(result);
} catch (AxisFault e) {
context.setProperty("ResponseCode", e.getFaultCodeElement().getText());
return false; //This stops the mediation flow, so I think it executes the fault sequence?
}
return true;
}
Package as an OSGi Bundle and Deploy to the Server
At this stage you should be able to your custom mediator project within the project explorer in WSO2 Developer Studio and from the context menu select Export Project as Deployable Archive. Follow the prompts to save the JAR file somewhere on your system. After generating the JAR file, locate it and transfer it to the [ESB_HOME]/repository/components/dropins directory. You may need to restart the server for it to detect the new external library.
Using the Custom Mediator
In your sequence, you should now be able to add a class mediator and reference your custom class using the package name and class name together, for example: org.strainy.ntlmauthorisation.
The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.
We're getting this exception frequently when using .Net 4.0 web service client to communicate with an ONVIF network device.
Looking at the packet captures, this seems to be a device that is non compliant with the HTTP spec and closing a connection after sending the response, against the HTTP/1.1 default of keeping it alive.
This results in the client (WCF) trying to reuse the connection while the server has just closed it,
Until the manufacturer can fix this, is there any way I can tell the web service/SOAP client NOT to use persistent connections?
Note that modifying the header to use Connection: Close won't help unless as it's being closed anyway, but the SOAP client is expecting it to stay open.
but is there any way I can tell the web service/SOAP client NOT to use persistent connections?
Yes, you can set InstanceContextMode to PerCall, it will create new InstanceContext object is created prior to and recycled subsequent to each call.
In other words, When we configure a WCF service as per call, new service instances are created for every method call you make via a WCF proxy client.
You can use it like :
setting in ServiceBehavior over Contract Interface implementation like:
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public class CalculatorService : ICalculator
{
...
}
UPDATE --
As per your comment, it seems the solution is to explicitly set the KeepAlive property to FALSE.
It can be done in multiple ways:
Code
IIS Settings
Web.config
Code
I actually don't know how much control you have over code.But at the client end where you are consuming service, we can change this behavior like:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)base.GetWebRequest(uri);
webRequest.KeepAlive = false;
return webRequest;
}
Or
namespace YourNamespace
{
using System.Diagnostics;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Xml.Serialization;
/// <summary>
/// This partial class makes it so all requests specify
/// "Connection: Close" instead of "Connection: KeepAlive" in the HTTP headers.
/// </summary>
public partial class YourServiceNameWse : Microsoft.Web.Services3.WebServicesClientProtocol
{
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)base.GetWebRequest(uri);
webRequest.KeepAlive = false;
return webRequest;
}
}
}
IIS Settings
Open Internet Information Services (IIS) Manager:
If you are using Windows Server 2008 or Windows Server 2008 R2:
On the taskbar, click Start, point to Administrative Tools, and then click Internet Information Services (IIS) Manager.
If you are using Windows Vista or Windows 7:
On the taskbar, click Start, and then click Control Panel.
Double-click Administrative Tools, and then double-click Internet Information Services (IIS) Manager.
In the Connections pane, go to the site, application, or directory for which you want to enable HTTP keep-alives.
In the Home pane, double-click HTTP Response Headers.
In the HTTP Response Headers pane, click Set Common Headers... in the Actions pane.
In the Set Common HTTP Response Headers dialog box, uncheck the box to disable HTTP keep-alives, and then click OK.
Additionally you can set for particular website on IIS using CommandLine like:
appcmd.exe set config "<Your Web Site Here>" -section:system.webServer/httpProtocol /allowKeepAlive:"False"
Web.Config
<configuration>
<system.webServer>
<httpProtocol allowKeepAlive="false" />
</system.webServer>
</configuration>
I hope it can help you in some way.
The underlying HttpWebRequests are created in the HttpChannelFactory used by the generated client classes.
This is created from the HttpTransportBindingElement which exposes a KeepAliveEnabled property.
The binding element is created internally in the WSHttpBinding class, and can be changed by overriding GetTransport().
private class WSHttpBindingNoKeepAlive : WSHttpBinding {
public WSHttpBindingNoKeepAlive(SecurityMode securityMode)
: base(securityMode) {
}
protected override TransportBindingElement GetTransport() {
TransportBindingElement transport = base.GetTransport();
if (transport is HttpTransportBindingElement) {
((HttpTransportBindingElement)transport).KeepAliveEnabled = false;
}
return transport;
}
}
This overriden ...Binding class can then be used like:
WSHttpBindingNoKeepAlive clientBinding = new WSHttpBindingNoKeepAlive(SecurityMode.None);
EndpointAddress address = new EndpointAddress(this.deviceUrl);
WSNameSpace.WSClient client = new WSNameSpace.WSClient(clientBinding, address);
As I am new to web service and WCF too I don't know where to create web service (or WCF) for accessing SQL Server 2012 data.
Is there any tool to create web service like Visual Studio 2010 (maybe but I don't know)? If yes then how to create it in Visual Studio suggest any solution.
If there is any code of web service or WCF service to access SQL Server 2012 data then please post or link it or if possible send the zip of it
You can try to use this framework Nelibur. Just modify an example according to your needs.
Official site: Nelibur.org
Here is an idea to get you started
public sealed class ClientProcessor : IPostWithResponse<CreateClientRequest>,
IGetWithResponse<GetClientRequest>,
IDelete<DeleteClientRequest>,
IPutWithResponse<UpdateClientRequest>
{
public object GetWithResponse(GetClientRequest request)
{
string connectionString = "Data Source=.;Initial Catalog=MyDatabase;Integrated Security=SSPI;";
using (SqlConnection connection = new SqlConnection(connectionString)) {
using (SqlCommand command = new SqlCommand("SELECT * FROM Clients WHERE Id=request.Id", connection)) {
connection.Open();
Client client = ...read from database here...
}
}
return client;
}
... other methods ...
}
Here is a simplet example to learn WCF step by step with backend,
WCF Service to Insert,Delete and Update
I created web service :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
namespace MemberWebService
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public DataSet GetMemberData(string memberId, string thirdName)
{
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=Healthy;Integrated Security=TRUE");
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = new SqlCommand("SELECT * FROM MemberMaster WHERE MemberId=#MemberId and ThirdName=#ThirdName", cn);
da.SelectCommand.Parameters.Add("#MemberId", SqlDbType.NVarChar).Value = memberId;
da.SelectCommand.Parameters.Add("#ThirdName", SqlDbType.NVarChar).Value = thirdName;
ds.Clear();
da.Fill(ds);
return ds;
}
}
}
and when i run it this is the link :
http://localhost:19722/Service1.asmx
and it work OK.
if i call it in asp.net as a web reference it work correctly till the server port is open if i close the port the asp.net page cannot see the web service so
how can i solve the problem and if i want to make this web service work on another device how can i do it ?
That port is specifically used for Visual Studio - it's either Cassini or IIS Express, and is only used for debugging purposes, not for live production work. When you're ready to publish your service, it will likely go into IIS in a regular permanent port (probably 80). Once it's there, it will always be available for your client to call.
After you publish the service to IIS, you'll just need to update the config file for the client to point to the real permanent URL.