How to host duplex wcf service on a VPS - asp.net

i am trying to host a wcf service which has a following attribute;
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
and i am creating host class like this;
var uri = new Uri("net.tcp://localhost:7951");
var binding = new NetTcpBinding();
host = new ServiceHost(typeof(ChatService), uri);
ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null) host.Description.Behaviors.Add(new ServiceMetadataBehavior());
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
host.AddServiceEndpoint(typeof(IChat), new NetTcpBinding(), "");
host.Open();
So, on developer computer and dedicated server this is working. However, what i need to do is, host this on a VPS (vitual private server).
I thought making a web project and adding this code block to global.asax application start method. but this failed. I suspect problem that the port is closed from firewall maybe.
What solution should I follow?

Related

Using an asp web api in wpf

So i have got a simple question, when using our cms we can attach a driver as an executable.
The driver we want to make is an httpreceiver or just an api endpoint. SO i tought lets use asp.net web api for it -> using version .net 4.6.1. altough asp.net application requires a webserver and is not an executable, But i read on google you can use it inside a wpf application since our cms is wpf in the first place.
So my question is is there a way i can use my mvc web api project inside a wpf application? and if not what would be the best bet to have an httpreceiver or httppost receiver into an executable?
Main reason is we want to send httppost requests to the server as a desktop application. I know it's complicated but thats how it needs to be as far as I know.
In the case where asp is not an option, what the best way to make a postreqst/ httpreceiver as a desktop application?
EDit:
the resource guide from microsoft beneath was perfectly however i still have a question:
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpClient and make a request to api/values
HttpClient client = new HttpClient();
string username = "test".ToUpper().Trim();
string password = "test123";
//Mock data
var body = new PostTemplate1();
body.Description = "test";
body.StateDesc = "httpdriver/username";
body.TimeStamp = DateTime.Now;
body.Message = "This is a post test";
var json = JsonConvert.SerializeObject(body);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var authToken = Encoding.ASCII.GetBytes($"{username}:{password}");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
var response = await client.PostAsync(baseAddress + #"api/Post", data);
var result = response.StatusCode;
}
As the guide says you post to url with port 9000
is there a possibility to use another port and use https?
if yes where to manage certificates for handling https?

Load balance with thrift and nginx

I have the following thrift server (socket), listening for connections on a specific host/port.
final TProtocolFactory factory = new TBinaryProtocol.Factory();
TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(serverPort);
final SignatureService.Processor theProcessor = new SignatureService.Processor(new SignatureServiceFacade());
TServer server = new THsHaServer(new THsHaServer.Args(serverTransport).processor(theProcessor).
protocolFactory(factory).
minWorkerThreads(minThreads).
maxWorkerThreads(maxThreads));
And following client connection:
clientTransport = new TFramedTransport(new TSocket(signatureHost, signaturePort));
final TProtocol theProtocol = new TBinaryProtocol(clientTransport);
client = new SignatureService.Client(theProtocol);
clientTransport.open();
//call the business specific method
client.doStuff(param1, param2, param3);
As we can see in the code above I need to provide the host and port in order to open a connection with the server.
But I want to use a service discovery with load balance support, because I'll have multiple instances of my service running.
Anybody has an example of this using nginx? All the examples is using regular http rest based applications.
Tks in advance.

add a host header to a website on IIS 7 programmatically

I want to add a host header to a website which is working on IIS7 through a web application (asp.net 4.0 / C#).There are some examples in internet,but i guess most of them dont work on iis7.
(note:the web application is being hosted in same server so i guess there wont be a security problem while changing iis configurations)
Any help is appreciated,thanks
I found this solution and it works for me.This is a little function with couple parameters,just you have to find the id of yourwebsite in your iss configuration.After that you have to give the ip adress of the server (iis),and port number,and hostname to the function and it will add a hostheader by using the parameters you entered.For example
AddHostHeader(2, "127.0.0.1:81", 81, "newsHostHeader");
static void AddHostHeader(int? websiteID, string ipAddress, int? port, string hostname)
{
using (var directoryEntry = new DirectoryEntry("IIS://localhost/w3svc/" + websiteID.ToString()))
{
var bindings = directoryEntry.Properties["ServerBindings"];
var header = string.Format("{0}:{1}:{2}", ipAddress, port, hostname);
if (bindings.Contains(header))
throw new InvalidOperationException("Host Header already exists!");
bindings.Add(header);
directoryEntry.CommitChanges();
}
}
(note:do not forget to add to the page using
System.DirectoryServices; using Microsoft.Web.Administration; )
The above solution didn't quite work with IIS7.5 for me.
I eventually had to do this
http://www.iis.net/configreference/system.applicationhost/sites/site/bindings/binding

Set up dummy proxy server on a dev environment

There is a proxy server on the clients site that all external request must go through. I am calling an external web service that needs the proxy settings.
The code I am using to set up the proxy for the web request can be seen below.
How would I go about setting up a test proxy server on my developer environment to verify that my code works?
string url = String.Format("http://currencyconverter.kowabunga.net/converter.asmx/GetConversionAmount?CurrencyFrom={0}&CurrencyTo={1}&RateDate={2}&Amount={3}", CurrencyFrom.Text, CurrencyTo.Text, formattedDate, amount);
WebRequest request = WebRequest.Create(url);
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["proxyLogin"]))
{
WebProxy proxy = new WebProxy();
string proxyUrl = ConfigurationManager.AppSettings["proxyUrl"];
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["proxyPort"]))
{
proxyUrl += ":" +ConfigurationManager.AppSettings["proxyPort"];
}
// Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
proxy.Address = new Uri(proxyUrl);
// Create a NetworkCredential object and associate it with the
// Proxy property of request object.
proxy.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["proxyLogin"], ConfigurationManager.AppSettings["proxyPassword"]);
request.Proxy = proxy;
}
WebResponse response = request.GetResponse();
You can install a proxy server in your development environment and configure the machines in such a way that the service is deployed beyond the firewall and you need to connect to the service through the proxy server only.

Return large data from WCF Service to ASP.NET Web Service

So we have console-hosted WCF Service and ASP.NET WEB Service (on IIS).
After some tough operation WCF Service must return some (large) data to ASP.NET Web Service for next processing. I tested on small results and everything is ok.
But after testing on real data that is a serialized result object that is near 4.5 MB, an error occurs on ASP.NET Web Service, which is the client in wcf-client-server communication.
This is the error I got:
The socket connection was aborted. This could be caused by an error
processing your message or a receive timeout being exceeded by the
remote host, or an underlying network resource issue. Local socket
timeout was '04:00:00'. Inner Exception: SocketException:"An existing
connection was forcibly closed by the remote host" ErrorCode = 10054
Messages size are configured by next binding (on server and client):
NetTcpBinding netTcpBinding = new NetTcpBinding();
netTcpBinding.TransactionFlow = true;
netTcpBinding.SendTimeout = new TimeSpan(0, 4,0, 0);
netTcpBinding.Security.Mode = SecurityMode.None;
netTcpBinding.Security.Message.ClientCredentialType = MessageCredentialType.None;
netTcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
netTcpBinding.Security.Transport.ProtectionLevel = ProtectionLevel.None;
netTcpBinding.MaxReceivedMessageSize = 2147483647;
netTcpBinding.MaxBufferSize = 2147483647;
netTcpBinding.MaxBufferPoolSize = 0;
netTcpBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
netTcpBinding.ReaderQuotas.MaxArrayLength = int.MaxValue;
netTcpBinding.ReaderQuotas.MaxBytesPerRead = int.MaxValue;
netTcpBinding.ReaderQuotas.MaxDepth = 32;
netTcpBinding.ReaderQuotas.MaxNameTableCharCount = 16384;
MaxObjectsInGraph property is configured in a config file.
What can you advise me? And also I need example how programmatically set MaxObjectsInGraph property on client and server.
Thanks for answers.
Problem is fixed by setting programmatically MaxObjectsInGraph(for serializer) as a service attribute.

Resources