How to intercept and change httprequests with c# - c#

I am developing one webservice using c#.It is possible intercept the client request using Filter(Using HttpModule).But how it is possible to modify the request.I can get request like this
Stream InputStrm = App.Context.Request.InputStream;
i want to decrypt the request&Set it back.How can i do this??

It depends on the web service technology you're using. If you're using Web API or MVC, you use an ActionFilter. If you're using asmx, you use a SoapExtension. If you're using WCF, you have various extension points. If it's just a web request, an HttpModule can apply a filter by saying HttpContext.Current.Response.Filter = new SomeFilter( HttpContext.Current.Response.Filter ) where SomeFilter is a class like public class SomeFilter : Stream {. Request.Filter should work the same way. http://www.15seconds.com/issue/020417.htm is an old article, but shows a bit about these Response.Filter classes.

Related

PuppeteerSharp and Page Level Proxies

I know this is possible using Puppeteer in js, but I'm wondering if anyone has figured out how to proxy on a page level in PuppeteerSharp (different proxies for different tabs)?.
it seems I can catch the request, but I'm not sure how to adjust the proxy.
page.SetRequestInterceptionAsync(true).Wait();
page.Request += (s, ev) =>
{
// what to do?
}
Edit
I am aware that I can set the proxy at the browser level like so;
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = false,
Args = new[] { "--proxy-server=host:port" }
});
var page = await browser.NewPageAsync();
await page.AuthenticateAsync(new Credentials() { Username = "username", Password = "password" });
But this is not what I'm trying to do. I'm trying to set the proxy for each page within a single browser instance. I want to test lots of proxies so spawning a new instance of the browser just to set the proxy is too much overhead.
You can use different browser instances for each logical instances. I mean instead of trying to set different proxy for each page/tab with different proxy just create new browser instance and set proxy via launch args.
If this solution doesn't fit your needs, check this question. There is library for NodeJS which give ability to use different proxy per each page/tab. You can check that library source code and implement same things inside your C# application.
That library is using very simple method. Instead of sending requests via puppeter's browser/page library send request via nodejs http tools. It can be done by using method page.setRequestInterception. So library intercept each request from page, after that gather data and send request via http tools. I used C# a long time ago. So maybe I am wrong, but you can try to use HttpWebRequest or something similar. After you get result you should use method request.respond and pass response results there. In this way you can put any kind of proxy inside your application. Check here code of library.

Choosing between accessing WCF via API Endpoint or via Dll reference

I have been contemplating on a dilemma for hours. I have a Visual Studio Solution that contains a WCF, WebForms, UWP, Xamarin and a SharedLibrary Projects.
I intend to use the WCF project as the backend which talks to the database and process Email and SMS integration and feed the other apps.
OPTION A
Currently, The WCF is hosted on an Azure App Service which makes it accessible via POST, GET, etc from the url which is: https://mywcfprojectlink.azurewebsites.net/service1.svc/GetUsers
With such arrangements, I can perform a POST request to get data from the apps:
string response = string.Empty;
string url = "https://mywcfprojectlink.azurewebsites.net/service1.svc/GetUsers";
try
{
var values = new Dictionary<string, string>
{
{ "data", Encryption.EncryptString(dat.ToString()) } //dat is incoming method param
};
string jsonString = JsonConvert.SerializeObject(values);
var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
response = cli.UploadString($"{url}", jsonString);
var result = JsonConvert.DeserializeObject<string>(response);
topic.InnerText = Encryption.DecryptString(result.ToString());
}
catch (Exception)
{
return string.Empty;
}
The method above is a simple one as I have other ones where I Deserialize with Models/Classes.
OPTION B
I equally have access to the methods defined in service1 by adding the project reference to my WebForms which surprisingly is also compatible with xamarin but not with UWP. Nevertheless, I am interested in the WebForms scenario. Below is an example method:
using BackEnd;
//Service1 service1 = new Service1();
//var send = service1.GetUsers(dat.ToString()); //dat is incoming method param
//topic.InnerText = send;
Obviously, using the Option B would eliminate the need to encrypt, decrypt, serialize or deserialize the data being sent. However, I have serious performance concerns.
I need to know the better option and if there is yet another alternative (probably an Azure Resource), you can share with me.
If you decide to use https endpoint of the Azure website, option A is secure because of SSL encryption. So you don't have to encrypt/decrypt it by yourself. The only tip is to create a proper authorization mechanism. For example use TransportWithMessageCredential. An example is provided in below article https://www.codeproject.com/Articles/1092557/WCF-Security-and-Authentication-in-Azure-WsHttpBin

Download Twilio Recordings using C#

I am working on one small utility using Twilio API which intend to download the recording of the call as soon as call ends ( can be done using webhooks ? ). I am not sure if twilio supports this kind of webhooks or not.
The second approach that i have in mind is to create nightly job that can fetch all the call details for that day and download the recordings.
Can anyone suggest me which is the best approach to follow. I checked the webhooks but i am not sure if they provide the call ended event.
I would appreciate if anyone can provide me code sample on how to get the recordings for particular date and download them using C# from twilio.
Twilio developer evangelist here.
You can get recording webhooks, but how you do so depends on how you record the call.
Using <Record>
Set a URL for the recordingStatusCallback attribute on <Record> and when the recording is ready you will receive a webhook with the link.
Using <Dial>
If you record a call from the <Dial> verb using the record attribute set to any of record-from-answer, record-from-ringing, record-from-answer-dual, record-from-ringing-dual then you can also set a recordingStatusCallback.
Using <Conference>
If you record a conference then you can also set a recordingStatusCallback.
Recording an outbound dial
If you record the call by setting Record=true on an outbound call made with the REST API then you can also set a webhook URL by setting a RecordingStatusCallback parameter in the request.
Retrieving recordings from the REST API
You can also use your second option and call the REST API to retrieve recordings. To do so, you would use the Recordings List resource. You can restrict this to the recordings before or after a date using the list filters.
Here is a quick example of how you would use the Twilio C# library to fetch recent recordings:
using System;
using Twilio;
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/user/account
string AccountSid = "AC81ebfe1c0b5c6769aa5d746121284056";
string AuthToken = "your_auth_token";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var recordings = twilio.ListRecordings(null, null, null, null);
foreach (var recording in recordings.Recordings)
{
Console.WriteLine(recording.Duration);
// Download recording.Uri here
}
}
}
Let me know if this helps at all.

Calling C# web service exposed on (soap.tcp) from Java

I found it is quite easy to create a .Net client to invoke a service with soap.tcp protocol.
Uri destinationUri = new Uri("soap.tcp://SomeHostName/SomePath");
Uri destinationUri = new Uri("http://SomeHostName/SomePath");
EndpointReference destination = new EndpointReference(destinationUri);
SoapSender sender = new SoapSender(destination);
But I need to create a Java client instead of a .Net client to the same URI (soap.tcp://SomeHostName/SomePath). Is it possible with Java with this protocol (soap.tcp) to invoke a web service.
Also I found the same question is asked
http://bytes.com/topic/java/answers/879818-calling-c-web-service-soap-tcp-java
Basically you can do that by implementing the "soap.tcp"-protocol as described by MS:
http://msdn.microsoft.com/en-us/library/cc219293.aspx
http://msdn.microsoft.com/en-us/library/cc219210.aspx
http://msdn.microsoft.com/en-us/library/cc219175.aspx
http://msdn.microsoft.com/en-us/library/cc219190.aspx
I don't know of anyone having done that... so it will be a major undertaking... "soap.tcp" is NOT made for interoperability... SOAP over HTTP is interoperable and should be used in cases like yours...

Call a webservice without proxy

I have to call a webservice from withing a C# programm. The webservice has most probably not a standard format. The interface description (wsdl and xsd) are very complicated, and using a proxy generating mechanismus results in hundreds of classes. The generated classes ar of little help since they are very generic, having mostly simple Object types as members.The best option is to build the SOAP message manually. That is also the way the webservice provider suggested to chose: Take the soap/xml messages that has to be sent and build the message according to the template. Now the question is how to build the message most efficiently. Of course hard coding the message string is an option, however I wonder if better options exists. If I have the complete message in a string, how do I best send the messages. Should I use a simple HttpRequest or can I use mechanisms of the wcf stack?
My current approach to build the message looks like this:
string msg = envelopeBegin;
RouteType rootType = new RouteType();
XmlSerializer serializer = new XmlSerializer(typeof(RouteType));
StringWriter stringWriter = new StringWriter();
serializer.Serialize(stringWriter, rootType , customNamespace);
msg += stringWriter.ToString();
msg += envelopeEnd;
// Send the message over the wire
The Soap/xml message I have to generate looks like this
<env:Envelope>xmlns:env=http://schemas.xmlsoap.org/soap/envelope/ xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns0="http://www.skanska.se/oagis/9/ws/faults">
<env:Body>
<ska:ShowSalesOrder xmlns:ska="http://www.skanska.se/oagis/9" systemEnvironmentCode="UTV" versionID="1.0" releaseID="9.0">
<!--plsql=.74s-->
<ApplicationArea xmlns="http://www.openapplications.org/oagis/9">
<!--user_name=SEBA_RAPPE-->
<ska:Sender>
<LogicalID>OEBS_SE</LogicalID>
<ComponentID>SKAIS017I</ComponentID>
<AuthorizationID>SEBA_RAPPE</AuthorizationID>
<ska:ResponsibilityID>XXOM_INTEGRATION_SVT</ska:ResponsibilityID>
</ska:Sender>
<CreationDateTime>2010-02-26T15:03:27+01:00</CreationDateTime>
<BODID>xxxxxxxxxxxxxxxxx</BODID>
</ApplicationArea>
<ska:DataArea>
<Show xmlns="http://www.openapplications.org/oagis/9">
<ResponseCriteria>
<ResponseExpression actionCode="Never" expressionLanguage="xPath">*</ResponseExpression>
</ResponseCriteria>
</Show>
<ska:SalesOrder>
<SalesOrderHeader xmlns="http://www.openapplications.org/oagis/9">
<DocumentID>
<ID>141779</ID>
</DocumentID>
<RequestedShipDateTime>2009-11-04T07:00:54+01:00</RequestedShipDateTime>
</SalesOrderHeader>
</ska:SalesOrder>
</ska:DataArea>
</ska:ShowSalesOrder>
</env:Body>
</env:Envelope>
You can definitely still use the WCF infrastructure without requiring type definitions for all of the various messages. WCF specifically supports this through the Message class. Using it is not all that difficult. Here's some more information about them but the idea is basically you would use XML readers and writers to read and write messages.
Using the Message Class
One way to do it is to create an XML skeleton template containing placeholders for the values. Read the XML and replace the values with those from your object. Post the resulting XML to the web service using HttpWebRequest.
Even that this approach might work I would strongly recommend you creating a WCF proxy class and using this instead even if the web service contains hundreds of methods and objects that are not used. As long as it is a valid WSDL, WCF will handle it. Also if there are any changes to the web service all you have to do is regenerate the proxy. To avoid the ugliness of this web service create your own infrastructure that exposes only the useful methods and classes and hides the real call.

Categories

Resources