Raw strings into HttpRequest/HttpResponse using ASP.NET 5? - c#

We're manipulating raw requests and responses. We're looking to read the raw HTTP message from the socket, and convert it to an Microsoft.AspNet.Http.HttpRequest object. We want the same for responses, that is converting raw text into in a Microsoft.AspNet.Http.HttpResponse object that can be manipulated as needed.
The question:
How can I convert raw strings into HttpRequest/HttpResponse objects, using the new classes in ASP.NET 5?
Edit:
Ok, so the above is, apparently, not clear enough. Here's a code snippet that gets to the meat of what we're after:
static void Main()
{
string http = #"CONNECT www.google.com:443 HTTP/1.0" + "\r\n" +
"Host: www.google.com:443" + "\r\n" +
"Content-Length: 0" + "\r\n" +
"Proxy-Connection: Keep-Alive" + "\r\n" +
"Pragma: no-cache" + "\r\n" +
"\r\n\r\n";
Microsoft.AspNet.Http.HttpRequest request = ParseHttp(http);
}
static Microsoft.AspNet.Http.HttpRequest ParseHttp(string http)
{
//Magic goes here
}

First create a new DefaultHttpContext(). That will get all the collections set up for you. Then you can just set the properties as needed. https://github.com/aspnet/HttpAbstractions/blob/dev/src/Microsoft.AspNet.Http/DefaultHttpContext.cs#L34
I don't have a simple example for you to actually parse the request, but I can show you one where I did something very similar with HttpRequestMessage & HttpResponseMessage from the client side: https://github.com/Tratcher/HttpClient/blob/dev/src/Microsoft.Net.Http.Client/HttpConnection.cs#L29-L41

Have you looked at the Proxy implementation in the aspnet repo on GitHub?
https://github.com/aspnet/Proxy
You might get some ideas from there. I'm guessing you want to do something like this:
https://github.com/aspnet/Proxy/blob/dev/src/Microsoft.AspNetCore.Proxy/ProxyMiddleware.cs#L70

Related

Sending CTCP action to an IRC server using C#

I have encountered a problem that others seem to have also encountered, but their solutions don't seem to work for me:
Using \x01 send the message as "ACTION wave" with nothing else.
The solutions I've found but haven't worked are:
Using \001: message is interpret as "01ACTION waves" but I get a "No
text to send" error.
Using \0001: same issue. Using \u0001: only
sends "ACTION waves" but prints an unknown symbol before action.
Apparently the issue is the '\0' part where it interprets it as an escape character, is there a way to avoid this? I have tried the following three methods already:
writer.WriteLine("PRIVMSG " + CHANNEL + " :" + CONTROL + "ACTION " +
message.Remove(0, 3) + CONTROL);
writer.WriteLine("PRIVMSG " + CHANNEL + " :" + "\u0001" + "ACTION " +
message.Remove(0, 3) + "\u0001");
writer.Write(string.Format("PRIVMSG {0} :{1} ACTION {2}{1}", CHANNEL,
CONTROL, message.Remove(0,3)));
Where CONTROL = either one of the values before mentioned.
A better more simple way will be using hex character \x01.
Code:
writer.WriteLine("PRIVMSG {0} :{1}ACTION {2}{1}", CHANNEL, '\x01', message.Remove(0, 3))

SSDP Search in Windows Phone 8

I'm new at SSDP/UPNP/Sockets and all that jazz. I'm playing around with it a bit and I just want to see what a generic SSDP search on my network will bring up.
Using this SSDP Sniffer app, I get a lot of results so I'm attempting to recreate this.
I'm using the following code, which I've found various versions of, but all the tweaking I do doesn't appear to bring back any results. I pretty much at a loss here and would appreciate any guidance.
thanks!
private const string SSDP_IP = "239.255.255.250";
private const string SSDP_PORT = "1900";
private const string SSDP_QUERY = "M-SEARCH * HTTP/1.1\r\n" +
"Host: " + SSDP_IP + ":" + SSDP_PORT + "\r\n" +
"Man: ssdp:discover\r\n" +
"ST: ssdp:all\r\n";
DataGramSocket socket;
async public void SsdpQueryAsync()
{
var remoteIP = new Windows.Networking.HostName(SSDP_IP);
var reqBuff = Encoding.UTF8.GetBytes(SSDP_QUERY);
socket = new DatagramSocket();
socket.MessageReceived += (sender, args) =>
{
// This is invoked for each device that responds to the query...
Task.Run(() =>
{
// do something useful
});
};
await socket.BindEndpointAsync(null, "");
socket.JoinMulticastGroup(remoteIP);
using (var stream = await socket.GetOutputStreamAsync(remoteIP, SSDP_PORT))
{
await stream.WriteAsync(reqBuff.AsBuffer());
}
await Task.Delay(5000);
}
I'm not familiar with C# or dotnet APIs, but I can see some details wrong with the M-SEARCH message:
MAN header must be enclosed in double quotes, so MAN: "ssdp:discover"\r\n
MX header is missing (required for multicast)
USER-AGENT header is missing
missing an empty line in the end
Header names are supposedly case insensitive, but I'd use upper case just in case...
See the Device Architecture reference pdf for more details

best way to calculate statistics from a file in c#

I have around 300k image files in a remote location. I download (have to) and write the details of these files to a text file (with some additional info). Due to the nature of the info I'm getting, I have to process each file as they arrive (Also I write each file info to a file line) to get some form of statistics for example, I have a list of objects with attributes size and count to see how many images of certain sizes I have.
I have also thought about getting everything read and written to a file without keeping any statistics info where I could just open the file again to add the statistics. But I can't think of a way to process a 250k line multi attribute file for statistics info.
I know the lists (yeah I have 2 of them) and the constant loop for each item is bugging the application down but is there another way? Right now it's been 2 hours and the application is still on 26k. For each image item, I do something like this to keep count where I check if an image comes with a certain size that did come before, I add it to that List item.
public void AddSizeTokens(Token token)
{
int index = tokenList.FindIndex(item => item.size== token.size);
if (index >= 0)
tokenList[index].count+=1;
else
tokenList.Add(token);
}
What a single line from the file I write to looks like
Hits Size Downloads Local Loc Virtual ID
204 88.3 4212 .../someImage.jpg f-dd-edb2-4a64-b42
I'm downloading the files like below;
try
{
using (WebClient client = new WebClient())
{
if (File.Exists(filePath + "/" + fileName + "." + ext))
{
return "File Exists: " + filePath + "/" + fileName + "." + ext;
}
client.DownloadFile(virtualPath, filePath + "/" + fileName + "." + ext);
return "Downloaded: " + filePath + "/" + fileName + "." + ext;
}
}
catch (Exception e) {
return"Problem Downloading " + fileName + ": " + e.Message;
}
You should be changing your tokenList from List<Token> to Dictionary<long, Token>.
The key is the size.
Your code would look like this:
Dictionary<long, Token> tokens = new Dictionary<long, Token>();
public void AddSizeTokens(Token token)
{
Token existingToken;
if(!tokens.TryGetValue(token.size, out existingToken))
tokens.Add(token.size, token);
else
existingToken.count += 1;
}
That will change it from an O(n) operation to a O(1) operation.
Another point to consider is Destrictor's comment. Your internet connection speed is very possibly the bottle neck here.
Well, I thought perhaps the coding was the issue. Some of the problem was indeed so. As per Daniel Hilgarth's instructions, changing to dictionary helped a lot, but only the first 30 minutes. Then It was getting worse by every minute.
The problem was apparently the innocent looking UI elements that I've fed information. They ate away so much cpu that it killed the application eventually. Minimizing UI info feed helped (1.5k per minute to at slowest 1.3k). Unbelievable! Hope it helps others who have similar problems.

Emailing in C# why isn't the information sending correctly?

I have a form that the users for my website will fill out. Once they click submit the information they filled out is supposed to be sent to my email. For some reason the information they fill out is not being sent. I am posting the code below. For a while it was working, but I must have changed something simple when I was trying to get other parts of the code to work and now I can't figure it out.
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
string strMessage = "Bug Name: " + txtBugName.Text.Trim()
+ "<br/>" + "Module Name: " + ddlModule.SelectedValue
+ "<br/>" + "Page Name: " + ddlPage.SelectedValue
+ "<br/>" + "Description: " + txtComments.Text.Trim()
+ "<br/>" + "Email is" + " " + txtemail.Text.Trim()
+ "<br/>" + "The request was sent at" +
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, "", "");
}
catch
{
}
}
As you can see I have this code pulling the information they fill out and then also I am formatting it for the email that will be sent to myself. But now I just get a blank email or actually the subject line will have something, but the email will be blank.
Also at the bottom of the code you can see i put this email was sent at + dandt I am trying to have the date and time sent in that part is there any code I can just put there to send the date and time the email was sent at? Like is there any syntax specifically just for date and time?
Thank you all
You're swallowing the exception. Remove the try/catch to see any errors that may occur as you change your code; only apply exception handling after testing.
Verify your method signature (params) here because that's where the mistake lies:
UPDATE:
You need to pass the parameters in the following order (read the link below):
public void Send(
string from,
string to,
string subject,
string body
)
SmtpClient.Send Method (String, String, String, String)
Your wrote the following, with extra strings snipped:
string strMessage = "..." + ... + SendMessage(..., strMessage, ...);
You're calling SendMessage() before assigning strMessage.

Java to C# code converter [duplicate]

This question already has answers here:
Tool to convert java to c# code [closed]
(4 answers)
Closed 6 years ago.
Are there any converters available that converts Java code to C#?
I need to convert the below code into C#
String token = new String("");
URL url1 =new URL( "http", domain, Integer.valueOf(portnum), "/Workplace/setCredentials?op=getUserToken&userId="+username+"&password="+password +"&verify=true");
URLConnection conn1=url1.openConnection();
((HttpURLConnection)conn1).setRequestMethod("POST");
InputStream contentFileUrlStream = conn1.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(contentFileUrlStream));
token=br.readLine();
String encodedAPIToken = URLEncoder.encode(token);
String doubleEncodedAPIToken ="ut=" + encodedAPIToken;//.substring(0, encodedAPIToken.length()-1);
//String doubleEncodedAPIToken ="ut=" + URLEncoder.encode(encodedAPIToken);
//String userToken = "ut=" + URLEncoder.encode(token, "UTF-8"); //URLEncoder.encode(token);
String vsId = "vsId=" + URLEncoder.encode(docId.substring(5, docId.length()), "UTF-8");
url="http://" + domain + ":" + portnum + "/Workplace/getContent?objectStoreName=RMROS&objectType=document&" + vsId + "&" +doubleEncodedAPIToken;
String vsId = "vsId=" + URLEncoder.encode(docId.substring(5, docId.length()), "UTF-8");
url="http://" + domain + ":" + portnum + "/Workplace/getContent?objectStoreName=RMROS&objectType=document&" + vsId + "&" +doubleEncodedAPIToken;
Thanks in advance
The below links might help:
Microsoft Launches Java-to-C# Converter;
Tangible Software Solutions inc..
The code is not very complicated, but if you don't have the time to translate it, you can use a tool like JLCA(Java Language Conversion Assistant 2.0).
You can try VaryCode Domain no longer exists and no valid snapshots in the Wayback Machine
But you used classes like URLEncoder, BufferedReader etc. that are hard to convert to C# without losing some Java-specific features. For this particular part of code it is insignificant but in prospect you can get some unpredicted behavior of the whole converted program.

Categories

Resources