JS: Call API from server side - c#

The following JavaScript code is working fine on old i9 browser but not on the latest one. Now I want to call API from server side as this code is not working due to cross domain cores issue.
var xmlHttpDevice = new XMLHttpRequest();
xmlHttpDevice.open("DEVICEINFO", "http://127.0.0.1:" + PortNumber + "/getDeviceInfo", true);
xmlHttpDevice.onload = function (e) {
if (xmlHttpDevice.readyState === 4) {
if (xmlHttpDevice.status === 200) {
alert(xmlHttpDevice.responseText);
} else {
alert(xmlHttpDevice.statusText);
}
}
};
xmlHttpDevice.onerror = function (e) {
console.error(xmlHttpDevice.statusText);
};
var params = "rdverb=DEVICEINFO&URL=''";
xmlHttpDevice.send(params);
my server side code :
TcpClient socket = new TcpClient();
try
{
// Call EndGetContext to complete the asynchronous operation.
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
string strPortNumber = string.Empty;
string strRDVerb = "";
int PortNumberStartRange = 11099;
result.AsyncWaitHandle.WaitOne();
if (context.Request.InputStream != null)
{
var body = new StreamReader(context.Request.InputStream).ReadToEnd();
GetPostedData(ref strPortNumber, ref strRDVerb, body);
}
else
{
strPortNumber = "12345";
strRDVerb = "RDSERVICE";
}
if (strRDVerb != "RDSERVICE" && strRDVerb != "DEVICEINFO")
{
strRDVerb = "CAPTURE";
}
//var body = new StreamReader(context.Request.InputStream).ReadToEnd();
string response = string.Empty;
//Get the stream that will be used to send/receive data
ExecuteRecoveryCode(ref socket, PortNumberStartRange);
NetworkStream ns = socket.GetStream();
//Write the HTTP Header info to the stream
StreamWriter sw = new StreamWriter(ns);
if (strRDVerb == "DEVICEINFO")
{
var message = "rdverb=DEVICEINFO&URL=''";
//var data = System.Text.Encoding.ASCII.GetBytes(message);
sw.Write(message, 0, message.Length);
sw.WriteLine(string.Format(strRDVerb + " /getDeviceInfo HTTP/1.1"));
sw.WriteLine(string.Format("HOST:127.0.0.1:11100"));
}
sw.Flush();
//Save the data that lives in the stream
string packet = string.Empty;
StreamReader sr = new StreamReader(ns);
int count = 0;
string EndString = string.Empty;
GetServiceMethod(strRDVerb, ref count, ref EndString);
for (int i = 0; i < count; i++)
{
packet = sr.ReadLine();
response += packet;
}
HttpListenerResponse resp = context.Response;
//byte[] buffer = System.Text.Encoding.UTF8.GetBytes("<HTML><BODY> " + response + EndString + "</BODY></HTML>");
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(response + EndString);
resp.StatusDescription = response;
resp.ContentLength64 = buffer.Length;
System.IO.Stream output = resp.OutputStream;
resp.StatusCode = (int)HttpStatusCode.OK;
output.Write(buffer, 0, buffer.Length);
output.Close();
resp.Close();
}
catch (Exception ex)
{
//throw ex;
}
finally
{
socket.Close();
listener.BeginGetContext(new AsyncCallback(OnRequestReceive), listener);
}

Related

Why Sending Apple Push Notifications, and Android using TcpClient cause application to hang?

I have searched the web and I could not find a solution to my problem.
I have a project targeting .net Framework 4.0.
I have two methods. One to push notification to ios devices, the other one to push notification to android devices.
Here is my first method :
public void SendAplePushNotificationMessage(string body, int Participant_ID, int Trainer_ID)
{
var componentSetup = new ComponentSetup();
var odsDevicesToken = componentSetup.getDevicesToken(Participant_ID, Trainer_ID, 1);
if (odsDevicesToken.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in odsDevicesToken.Tables[0].Rows)
{
try
{
var deviceToken = HexStringToByteArray(dr["DeviceToken"].ToString());
var memoryStream = new MemoryStream();
var writer = new BinaryWriter(memoryStream);
writer.Write((byte)0); //The command
writer.Write((byte)0); //The first byte of the deviceId length (big-endian first byte)
writer.Write((byte)32); //The deviceId length (big-endian second byte)
writer.Write(deviceToken);
writer.Write((byte)0); //First byte of payload length; (big-endian first byte)
var payload = "{\"aps\":{\"alert\":\"" + body + "\",\"badge\":1,\"sound\":\"default\"}}";
var b1 = Encoding.UTF8.GetBytes(payload);
if (b1.Length > 256)
{
body = body.Substring(0, 106) + "...";
payload = "{\"aps\":{\"alert\":\"" + body + "\",\"badge\":1,\"sound\":\"default\"}}";
b1 = Encoding.UTF8.GetBytes(payload);
}
writer.Write((byte)b1.Length);
writer.Write(b1);
writer.Flush();
var array = memoryStream.ToArray();
memoryStream.Write(Encoding.ASCII.GetBytes(body), 0, body.Length);
var port = Convert.ToInt32(ConfigurationManager.AppSettings["APNPortNo"]);
var hostname = ConfigurationManager.AppSettings["APNHostName"];
var certificatePath = Server.MapPath("~") + ConfigurationManager.AppSettings["APNCertificatePath"].Replace("/", "\\");
Logger.LogInfoMessage("certificatePath: " + certificatePath);
var clientCertificate = new X509Certificate2(File.ReadAllBytes(certificatePath), "");
var certificatesCollection = new X509Certificate2Collection(clientCertificate);
var client = new TcpClient(hostname, port);
var sslStream = new SslStream(client.GetStream(), false,
new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
sslStream.Write(array);
sslStream.Flush();
client.Close();
}
catch (AuthenticationException ex)
{
client.Close();
var setupObj = new ComponentSetup();
setupObj.AddErrorLog(ex.Message, CamelRaceContext.UserSettings.User.USER_NAME, null,
Participant_ID, dr["DeviceToken"].ToString());
if (ex.InnerException != null)
Logger.LogErrorMessage(ex.InnerException, ex.InnerException.Message);
throw new CamelRaceApplicationException<MobileAdmin_ManageNotifications>(ex.Message, ex);
}
catch (CamelRaceApplicationException<MobileAdmin_ManageNotifications> ex)
{
throw new CamelRaceApplicationException<MobileAdmin_ManageNotifications>(ex.Message,ex);
}
catch (Exception e)
{
client.Close();
var setupObj = new ComponentSetup();
setupObj.AddErrorLog(e.Message, CamelRaceContext.UserSettings.User.USER_NAME, null, Participant_ID, dr["DeviceToken"].ToString());
}
}
catch (CamelRaceApplicationException<MobileAdmin_ManageNotifications> ex)
{
throw new CamelRaceApplicationException<MobileAdmin_ManageNotifications>(ex.Message, ex);
}
catch (Exception exMain)
{
var setupObj = new ComponentSetup();
setupObj.AddErrorLog(exMain.Message, CamelRaceContext.UserSettings.User.USER_NAME, null, Participant_ID, dr["DeviceToken"].ToString());
if (exMain.InnerException != null)
Logger.LogErrorMessage(exMain.InnerException, exMain.InnerException.Message);
}
}
}
}
The second Method is :
private void SendGCMPushNotificationMessage(string body, int Participant_ID, int Trainer_ID)
{
var _ComponentSetup = new ComponentSetup();
var odsDevicesToken = _ComponentSetup.getDevicesToken(Participant_ID, Trainer_ID , 2);
if (odsDevicesToken.Tables[0].Rows.Count > 0)
{
var registration_ids = new string[odsDevicesToken.Tables[0].Rows.Count];
var index = 0;
foreach (DataRow dr in odsDevicesToken.Tables[0].Rows)
{
registration_ids[index] = dr["DeviceToken"].ToString();
index = index + 1;
}
if (registration_ids.Length > 0)
{
var GcmHttpUrl = ConfigurationManager.AppSettings["GcmHttpUrl"];
var GcmApiKey = ConfigurationManager.AppSettings["GcmApiKey"];
var notificationData = new JObject(
new JProperty("registration_ids", new JArray(registration_ids)),
new JProperty("notification", new JObject(
new JProperty("title", ConfigurationManager.AppSettings["title"]),
new JProperty("body", body),
new JProperty("icon", "myicon"),
new JProperty("sound", "default")
)),
new JProperty("data", new JObject(
new JProperty("state", ConfigurationManager.AppSettings["state"])
)
)
);
var contentText = notificationData.ToString(Formatting.None);
var content = Encoding.UTF8.GetBytes(contentText);
try
{
var req = (HttpWebRequest)WebRequest.Create(GcmHttpUrl);
req.Method = "POST";
// Disable expect-100 to improve latency
req.ServicePoint.Expect100Continue = false;
req.ContentType = "application/json";
req.ContentLength = content.Length;
req.Headers.Add("Authorization", "key=" + GcmApiKey);
using (var s =req.GetRequestStream())
{
s.Write(content, 0, content.Length);
s.Close();
}
// Receive the HTTP response.
string response;
using (var res = (HttpWebResponse) req.GetResponse())
{
// Read the request body
using (TextReader r = new StreamReader(res.GetResponseStream(), Encoding.UTF8, true))
{
response = r.ReadToEnd();
}
}
Console.WriteLine("Response: " + response);
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.ToString());
var setupObj = new ComponentSetup();
setupObj.AddErrorLog("Exception: " + ex.ToString(), CamelRaceContext.UserSettings.User.USER_NAME, null, Participant_ID,null);
if (ex is WebException)
{
var webex = (WebException)ex;
if (webex.Response != null)
{
var status = ((HttpWebResponse)webex.Response).StatusCode;
setupObj.AddErrorLog("Exception: " + status.ToString(), CamelRaceContext.UserSettings.User.USER_NAME, null, Participant_ID, null);
// Check the status code here...
}
}
}
}
}
}
Now, this code is working fine when number of devices is 3 or 4.
When this number increase. Like 8423.
It causes the application to hang.
Currently I am calling this code on button click.
I was wondering will putting this code using task class will make it work ?
var task1 = Task.Factory.StartNew(() =>SendAplePushNotificationMessage(txtNotification.Text, Participant_ID, Trainer_ID) , TaskCreationOptions.LongRunning);
var task2 = Task.Factory.StartNew(() => SendGCMPushNotificationMessage(txtNotification.Text, Participant_ID, Trainer_ID), TaskCreationOptions.LongRunning);
Task.WaitAll(task1, task2);
I know some of you will propose to use pushsharp.
I was thinking of doing so.
However push sharp targets 4.5.
My project target 4.0.
Upgrade is not an option.
Will my solution work ?
If not, how can I solve my problem then.
Thanks.

Wants to receive total bytes from the client along with the data and how I have to handle it from other code

I am using a c# application that sends data to my server.
I want to send bytes along with the data so that I can handle at server code if the data size is large it can break there only.
I am not getting how to send bytes value along with the data.
The below is my client side sending part and my server side responding part to client.
Client Code :-
public bool sendData(StringBuilder QueryVal)
{
TcpClient clientSocket = new System.Net.Sockets.TcpClient();
try
{
clientSocket.Client.Connect(Serverip, 8888);
var connect = clientSocket.Connected;// it can be ? clientSocket.Client.Connected
if (connect == true)
{
try
{
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(QueryVal + "$");
serverStream.Write(outStream, 0, outStream.Length);
String decodedString = System.Text.Encoding.ASCII.GetString(outStream);
decodedData(decodedString.ToString());
serverStream.Flush();
byte[] inStream = new byte[clientSocket.ReceiveBufferSize];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
//MessageBox.Show("Receive data is: " + returndata);
int SendByte = outStream.Count();
int ReceivedByte = Convert.ToInt32(returndata);
try
{
clientSocket.Client.Shutdown(SocketShutdown.Both);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
bool chk = clientSocket.Connected;// this line should be comment
if (SendByte == ReceivedByte) { return true; }
else { return false; }
}
catch (Exception ex)
{
StackFrame objtrack = new StackFrame();
var methodinfo = objtrack.GetMethod();
string calssName = methodinfo.DeclaringType.Name;
string methoname = methodinfo.Name;
string Lineno = Convert.ToString(ex.LineNumber());
log(ex.Message, calssName, methoname, Lineno);
return false;
}
}
else
{
return false;
}
}
catch (Exception ex)
{
StackFrame objtrack = new StackFrame();
var methodinfo = objtrack.GetMethod();
string calssName = methodinfo.DeclaringType.Name;
string methoname = methodinfo.Name;
string Lineno = Convert.ToString(ex.LineNumber());
log(ex.Message, calssName, methoname, Lineno);
return false;
}
}
Server Code :-
Byte[] sendBytesAA = Encoding.ASCII.GetBytes(ReceiveSize.ToString());
ReceiveSize = 0;
networkStream.Write(sendBytesAA, 0, sendBytesAA.Length);
Don't convert data to string in can mess up the data and adds unnecessary processing time. Try following code :
TcpClient clientSocket = new TcpClient();
NetworkStream serverStream = clientSocket.GetStream();
List<byte> inStream = new List<byte>();
serverStream.Read(inStream.ToArray(), 0, (int)clientSocket.ReceiveBufferSize);
long length = inStream.Count;
byte[] byteLength = BitConverter.GetBytes(length);
inStream.InsertRange(0, byteLength.ToList());

async/await ftpupload damages uploaded file

I am trying to ftpupload a zipfile with async/await pattern:
private async void button2_Click(object sender, RoutedEventArgs e)
{
await processFtp();
}
async Task processFtp()
{
string result = "";
string ftpHost = "ftp://mysite/mysubdir";
string ftpUser = "itsme";
string ftpPassword = "mypw";
string ftpfullpath = ftpHost + "/" + "OutdoorTest.zip";
string fileToUpload = #"c:\temp\Outdoorbilder.zip";
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpfullpath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUser,ftpPassword);
request.UseBinary = true;
request.KeepAlive = false;
request.ReadWriteTimeout = 1000000;
request.Timeout = 1000000;
using (Stream requestStream = request.GetRequestStream())
{
using (FileStream fs = File.OpenRead(fileToUpload))
{
byte[] b = new byte[10 * 1024];
int readLength = 0;
int sentLength = 0;
while ((readLength = fs.Read(b, 0, b.Length)) > 0)
{
await requestStream.WriteAsync(b, 0, b.Length);
int percentComplete = (int)((float)(sentLength += readLength) / (float)fs.Length * 100);
ftpprogress.Value = percentComplete;
}
requestStream.Close();
requestStream.Flush();
}
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
result = response.StatusDescription;
}
catch (WebException e)
{
result = e.Message;
if (e.Status == WebExceptionStatus.ProtocolError)
{
result = result + "Status Code : " +
((FtpWebResponse)e.Response).StatusCode;
result = result + "\nStatus Description : " +
((FtpWebResponse)e.Response).StatusDescription;
}
}
catch (Exception e)
{
result = e.Message;
}
MessageBox.Show(result);
}
}
The code seems to work fine and I get a 226 response. But the zip file on the ftp server is arround 1000bytes biger than the original and after download to a mobile android device cannot be opend/extracted.
When I upload without async/await pattern the uploaded file has the same size on ftp server as the local original.
How/where does this happen?
This has nothing to do with async/await.
Your problem is that you are not telling the correct size to upload. Look at these two lines:
while ((readLength = fs.Read(b, 0, b.Length)) > 0)
{
await requestStream.WriteAsync(b, 0, b.Length);
You need to specify that the WriteAsyc writes the read amount and not the amount allocated for the byte buffer. At least the last read will return less than the buffer size.
So the correct code is:
while ((bytesRead = fs.Read(b, 0, b.Length)) > 0)
{
await requestStream.WriteAsync(b, 0, bytesRead);

Http post method hanging before getting response using c# [duplicate]

Failed to get response for large file HTTP put create file using c#
I am using file watcher service service monitor, when user created file or folder we are uploading to cloud
if file size more than 512 MB it is taking too much time to get the response
here I am confusing here the issue with my code or server
and reason for this error
if any changes on my code suggest me.
{
var fileFolderObj1 = new FileFolder();
var postURL = apiBaseUri + "/filefolder/create/file/user/" + userId; // +"?type=file";
code = HttpStatusCode.OK;
HttpWebResponse response = null;
FileInfo f = new FileInfo(filePath);
long filesizeF = f.Length;
try
{
string selectedFile = null;
selectedFile = filePath;
var fi = System.IO.Path.GetFileName(filePath);
////commented for some reason
var postParameters = new Dictionary<string, object>();
postParameters.Add("file", new FileParameter(filePath, ""));
postParameters.Add("parentId", parentId);
postParameters.Add("newName", fi);
postParameters.Add("cloudId", cloudId);
postParameters.Add("isSecure", isSecure);
//postParameters.Add("fileSize", fi.Length);
postParameters.Add("fileSize", filesizeF);
var userAgent = "Desktop";
var formDataBoundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
var uri = new Uri(postURL);
var createFileRequest = WebRequest.Create(uri) as HttpWebRequest;
this.SetBasicAuthHeader(createFileRequest, userId, password);
createFileRequest.ContentType = "multipart/form-data";
createFileRequest.Method = "PUT";
createFileRequest.Timeout = System.Threading.Timeout.Infinite;
createFileRequest.KeepAlive = false;/*true;*/
createFileRequest.UserAgent = userAgent;
createFileRequest.CookieContainer = new CookieContainer();
try
{
using (var requestStream = createFileRequest.GetRequestStream())
{
}
using (response = (HttpWebResponse)createFileRequest.GetResponse())
{
StreamReader(response.GetResponseStream()).ReadToEnd();
fileFolderObj1 = JsonConvert.DeserializeObject<FileFolder>(reslut);
}
}
catch (Exception exc)
{
if (response != null)
{
code = response.StatusCode;
}
}
}
catch (Exception exc)
{
}
}
}
private static readonly Encoding encoding = Encoding.UTF8;
private void WriteMultipartFormData(Dictionary<string, object> postParameters, string boundary, Stream requestStream, ILogService logService = null)
{
var needsCLRF = false;
foreach (var param in postParameters)
{
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
{
requestStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
}
needsCLRF = true;
if (param.Value is FileParameter)
{
var fileToUpload = (FileParameter)param.Value;
// Add just the first part of this param, since we will write the file data directly to the Stream
var header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
fileToUpload.FileName ?? param.Key,
fileToUpload.ContentType ?? "application/octet-stream");
requestStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
// Write the file data directly to the Stream, rather than serializing it to a string.
FileStream fileStream = new FileStream(fileToUpload.FileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0,buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
logService.Debug("WRITEMULTIPART FORM DATA Bufferlent Running :{0}", bytesRead);
}
fileStream.Close();
}
else
{
var postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
requestStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
var footer = "\r\n--" + boundary + "--\r\n";
requestStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
}
}

How to Relay SSL(HTTPS) response through Proxy?

I have to trace the HTTP traffic .It work without Https. I try for the https, it successfully get the response via Sslstream through the certificate. When i forward ssl response for the relay but it doesn’t getting the response.
Please let me how to relay SSL response?
Please check the following code for the same.
Thanks
public void ThreadHandleHTTPClient(object o)
{
try{
Socket client = (Socket)o;
Stream ns = new NetworkStream(client);
//Stream outStrem = ns;
//RECEIVE CLIENT DATA
byte[] buffer = new byte[2048];
int rec = 0, sent = 0, transferred = 0, rport = 0;
string data = "";
do
{
rec = ns.Read(buffer, 0, buffer.Length);
data += Encoding.ASCII.GetString(buffer, 0, rec);
} while (rec == buffer.Length);
//PARSE DESTINATION AND SEND REQUEST
string line = data.Replace("\r\n", "\n").Split(new string[] { "\n" }, StringSplitOptions.None)[0];
string e=line.Split(new string[] { " " }, StringSplitOptions.None)[1];
Uri uri = new Uri(e);
if (uri.Scheme == "https" || line.Contains("CONNECT"))
{
rport = 443;
//Make tunnel for the HTTPS which is authentic host.
SslStream sslStream = sslTunnel(ns, uri.OriginalString, "1.0");
ns = sslStream;
string remoteUri = "https://" + uri.Scheme;
StreamReader clientStreamReader = new StreamReader(sslStream);
string httpCmd = clientStreamReader.ReadLine();
string[] splitBuffer = httpCmd.Split(_spaceSplit, 3);
remoteUri = remoteUri + splitBuffer[1];
myQuery = string.Empty;
//Read the SSL Stream save command in myQuery variable.
readRequestHeadersEx(clientStreamReader);
data = myQuery;
data = splitBuffer[0]+" ";
data += remoteUri;
data += " ";
data += splitBuffer[2];
data += "\r\n";
data += myQuery;
data += "\r\n";
line = data.Replace("\r\n", "\n").Split(new string[] { "\n" }, StringSplitOptions.None)[0];
uri = new Uri(line.Split(new string[] { " " }, StringSplitOptions.None)[1]);
}
else
{
rport = 80;
}
IPHostEntry rh = Dns.GetHostEntry(uri.Host);
Socket remoteserver = new Socket(rh.AddressList[0].AddressFamily, SocketType.Stream, ProtocolType.IP);
remoteserver.Connect(new IPEndPoint(rh.AddressList[0], rport));
byte[] databytes = Encoding.ASCII.GetBytes(data);
remoteserver.Send(databytes, databytes.Length, SocketFlags.None);
//START RELAY
buffer = new byte[2048];
rec = 0;
data = "";
do
{
transferred = 0;
do
{
rec = remoteserver.Receive(buffer, buffer.Length, SocketFlags.None);
sent = client.Send(buffer, rec, SocketFlags.None);
transferred += rec;
data += Encoding.ASCII.GetString(buffer, 0, rec);
} while (rec == buffer.Length);
if (transferred == 0)
break;
} while (transferred > 0);
client.Close();
}
catch (Exception ex)
{
}
}
public void Start(IPAddress ip, int port)
{
TcpListener listener = new TcpListener(ip, port);
listener.Start(100);
while (true)
{
Socket client = listener.AcceptSocket();
Thread th = new Thread(ThreadHandleHTTPClient);
th.Start(client);
}
listener.Stop();
}

Categories

Resources