Help needed on Uploading Files in windows mobile - c#

I have an desktop application running on my desktop.
I need to send the file path to the CGI script running at server.
CGI script taks the file path and upload the contents from my machine.
I tried to send the file path through httppost method; it is not working - can any one suggest me how to do.. methods I have tried are:
WebClient upload = new WebClient();
NetworkCredential nc = new NetworkCredential("test", "admin");
Uri URL = new Uri("http:\\10.10.21.55\\cgi-bin\\file_upload.cgi");
upload.Credentials = nc;
byte [] data = upload.UploadFile(filepath, "c:/Data.txt");
Console.WriteLine(data.ToString());
and the other way I tried is:
byte[] buf = new byte[8192];
// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://10.10.21.55/cgi-bin/file_upload.cgi");
WebResponse rsp = null;
request.Method = "POST";
request.ContentType = "text/xml";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.WriteLine("hi hiw are you");
writer.Close();
both ways are not working.
but the below answered code works in desktop in winmo its telling WebClient not implimented...
please tell how to send data to script present in server in windows mobile

Is this as simple as getting the WebClient parameters right? (you seem to be passing in file-path as the url, and not using the encoding):
using(WebClient upload = new WebClient()) {
NetworkCredential nc = new NetworkCredential("test", "admin");
upload.Credentials = nc;
byte[] data = upload.UploadFile(
#"http://10.10.21.55/cgi-bin/file_upload.cgi", #"c:\Data.txt");
Console.WriteLine(upload.Encoding.GetString(data));
}

Related

HttpWebRequest error 401 on Pi3 with IoT Core c#

I've used the search funktion before but the Solutions won't help in my case (don't know why). I've written a Code to call a IIS Webservice. The Code will run on my Desktop without any issues. On my Pi3 i will get an
(One or more errors occurred. (The remote server returned an error: (401) Unauthorized.)
error. What I'm doing wrong?
Thx Forward for helping me.
Uri uri = new Uri(Url); //TempUrl is assigned a string beforehand
request = HttpWebRequest.Create(uri);
// Add authentication to request
NetworkCredential c = new NetworkCredential("USER", "PASSWORD","DOMAIN");
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(uri, "NTLM", c);
request.Credentials = c;
Task<WebResponse> x = request.GetResponseAsync();
x.Wait(20000);
response = x.Result;
// Get the response stream into a reader
reader = new StreamReader(response.GetResponseStream());
Got it. I've Change the NetworCredentials as follows:
NetworkCredential c = new NetworkCredential(#"<Domain>\<USER>", "<PASSWORD>");
I don't know why, but it works.

Post JSON over HTTPS

In the past I have successfully called a JSON webservice over HTTP
But, now I have to make a JSON POST over HTTPS.
I have tried using the code that works for HTTP and simply changed the url that is being called to https but it won't work.
This is the code i am using...
WebRequest wrGETURL;
wrGETURL = WebRequest.Create("https://apitest.example.com/geo/coverage/v1/?appId=2644571&appKey=836621d715b6ce4db5f007d8fa2214f");
wrGETURL.Method = "POST";
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string responseFromServer = objReader.ReadToEnd();
and the error message i am seeing in fiddler is:
fiddler.network.https> Failed to secure existing connection for apitest.example.com. A call to SSPI failed, see inner exception. InnerException: System.ComponentModel.Win32Exception (0x80004005): The client and server cannot communicate, because they do not possess a common algorithm
Can anyone help me with that I need to do to make a call over HTTPS please?
Do you need to authenticate or maybe a callback for the server certificate?
This works for me in most cases:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://someurl/");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
// Create NetworkCredential Object
NetworkCredential admin_auth = new NetworkCredential("username", "password");
// Set your HTTP credentials in your request header
httpWebRequest.Credentials = admin_auth;
// callback for handling server certificates
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"name\":\"TEST_123\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
}
I am using React and Expressjs and ran into this issue. Send your ie: https://www.google.com with out the https:
part of my router.js
router('/vod')
.rout.get('/vod', (req,res)=>{
res.send({message: "//www.google.com"});
App.js
function App() {
const [vod, setVod] = React.useState(null);
React.useEffect(() => {
fetch("/vod")
.then((res) => res.json())
.then((vod) => setVod(vod.message));
},
[]);
return (
<div className="App">
<header className="App-header">
<iframe src={"https:"+vod}
id="myIframe" autoPlay width={1000} height=
{500} frame></iframe>
</header>
</div>
);
in the iframe to change the source I used {"https:"+vod} to simulate the full url.
in your case try to combine your "result" like ("https:"+result)
I noticed that json grabs the : and messes the string up.

Can a curl command passing in a username and password credentials in the URL work in a C# program/.net environment

Can a curl command passing in a username and password credentials in the URL work in a C# program/.net environment?
Example:
curl -T testfile.txt 'http://user:password#domain.net/dir/
What would be the equivalent of the Curl command in a C# .net environment?
My original problem started by trying to uplaod a file to a webdav server. I tried using C# webclient and httpwebrequest...... and keep getting 401 autnetication errors even though the credentials was in the actual header of the request.
When I use Curl in a unix environment I had no problems uploading the file.
I am not sure if the problem is with the redirect that HttpWebrequest does:
webclient how to keep basic authorization when redirect
Thats is:
401 - authentication error - No username and password in header
Then - 301 redirect - This includes username and password in header
just try the below code... it will help you...
string fileToUpload = #"c:\testfile.txt";
FileStream rdr = new FileStream(fileToUpload, FileMode.Open);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/Upload");
req.PreAuthenticate = true;
req.Credentials = new NetworkCredential ("username", "password");
req.Method = "POST";
req.ContentLength = rdr.Length;
req.AllowWriteStreamBuffering = true;
Stream reqStream = req.GetRequestStream();
Console.WriteLine(rdr.Length);
byte[] inData = new byte[rdr.Length];
// Get data from upload file to inData
int bytesRead = rdr.Read(inData, 0, (int)rdr.Length);
// put data into request stream
reqStream.Write(inData, 0, (int)rdr.Length);
rdr.Close();
req.GetResponse();
// after uploading close stream
reqStream.Close();

pass string from C# Windows Form Application to php webpage

How can I pass some data to a webpage from C#.net? I'm currently using this:
ProcessStartInfo p1 = new ProcessStartInfo("http://www.example.com","key=123");
Process.Start(p1);
but how can I access it from PHP? I tried:
<?php echo($_GET['key']); ?>
but it prints nothing.
Try passing it with the url itself
ProcessStartInfo p1 = new ProcessStartInfo("http://timepass.comule.com?key=123","");
Process.Start(p1);
you should put the key parameter as a query string :
ProcessStartInfo p1 = new ProcessStartInfo("http://timepass.comule.com?key=123");
I would suggest using the HttpWebRequestClass.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
This way, you would also have the ability to post data to your page, add auth parameters, cookies etc - in case you might need it.
I'm not sure if this matters in your particular setup, passing data thru the query string is not secure. But if security is an issue as well, I would POST the data thru an SSL connection.
Update:
so if you POST'ed data to your php page like so:
string dataToSend = "data=" + HttpUtility.UrlEncode("this is your data string");
var dataBytes = System.Text.Encoding.UTF8.GetBytes(dataToSend);
HttpWebRequest req = (HttpWebRequest) WebRequest.Create("http://localhost/yourpage.php");
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = dataBytes.Length;
req.Method = "POST";
using (var stream = req.GetRequestStream())
{
stream.Write(dataBytes, 0, dataBytes.Length);
}
// -- execute request and get response
HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
if (resp.StatusCode == HttpStatusCode.OK)
Console.WriteLine("Hooray!");
you can retrieve it by using the following code in your php page:
echo $_POST["data"])
Update 2:
AFAIK, ProcessStartInfo/Process.Start() actually starts a process - in this case, I think it will start your browser. The second parameter is the command line arguments. This information is used by programs so they know how to behave when started (hidden, open a default document etc). Its not related to the Query string in anyway. if you prefer to use Process.Start(), then try something like this:
ProcessStartInfo p1 = new ProcessStartInfo("iexplore","http://google.com?q=test");
Process.Start(p1);
If you run that, it will open internet explorer and open google with test on the search box. If that were you're page, you could access "q" by calling:
echo $_GET["q"])
In my applications i used different method i.e using webClient i done it
WebClient client1 = new WebClient();
string path = "dtscompleted.php";//your php path
NameValueCollection formData = new NameValueCollection();
byte[] responseBytes2=null;
formData.Add("key", "123");
try
{
responseBytes2 = client1.UploadValues(path, "POST", formData);
}
catch (WebException web)
{
//MessageBox.Show("Check network connection.\n"+web.Message);
}

c# making http put request to azure storage

Hi Im wondering if the azure blob service api http://msdn.microsoft.com/en-us/library/dd135733.aspx
can be called using c#. Id like to upload a file e.g a word document to a storage location, the http method is "put" and the rest url is
"http://myaccount.blob.core.windows.net/mycontainer/myblob"
would this code work?
string username = "user";
string password = "password";
string data = "path to word document;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "PUT";
request.Credentials = new NetworkCredential(username, password);
request.ContentLength = data.Length;
request.ContentType = "text/plain";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream( ))) {
writer.WriteLine(data);
}
WebResponse response = request.GetResponse( );
using (StreamReader reader = new StreamReader(response.GetResponseStream( ))) {
while (reader.Peek( ) != -1) {
Console.WriteLine(reader.ReadLine( ));
No, this wouldn't work. Authentication to Windows Azure storage involves signing the headers of the request. (See http://msdn.microsoft.com/en-us/library/dd179428.aspx.)
Note that the .NET StorageClient library that ships with the SDK is redistributable, so you can just add a reference to that and do (from memory):
CloudStorageAccount.Parse("<connection string>")
.CreateCloudBlobClient()
.GetBlobReference("mycontainer/myblob")
.UploadByteArray(data);

Categories