I want to display a message box after posting data to a remote php file..
PS: The php file return the string "END" when the data is completely processed
if (1 == outputToGui)
{
CompressFile("allFilesList.txt");
byte[] allFilesList = File.ReadAllBytes("allFilesList.txt.gz");
string URIx = "http://example.com/post.php";
System.Collections.Specialized.NameValueCollection data = new System.Collections.Specialized.NameValueCollection();
data.Add("serial", serial);
data.Add("data", Convert.ToBase64String(allFilesList));
using (WebClient tayba = new System.Net.WebClient())
{
try
{
tayba.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
tayba.Proxy = null;
tayba.UploadValues(URIx, "POST", data);
}
catch (Exception E) { }
}
}
MessageBox.Show("upload completed"); // this message show up before the php file process the posted data sometimes.. ?!!!!
The problem is that the message box show up before the php file process the posted data sometimes.. ?!!!!
Thats because operation is asynchronous. Upload might still be in progress when messagebox is called.
Search webclient for correct completion event and add your message there. META: _webClient.eventName += (sender, args) => MessageBox.Show("Ta-dah!");
Assign event listener before you start the upload.
Related
I'm trying to submit a from using c# to a website and am trying to get the response from the server as a message box after the data is sent. the website does redirect to another page to show an output.
What happens so far is the data is not submitted until I click OK on the message box that is displaying the data before it is send not after.
WebBrowser browser = new WebBrowser();
string target = "http://www.awebsite.com";
browser.Navigate(target);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(XYZ);
}
}
private void XYZ(object sender, WebBrowserDocumentCompletedEventArgs e) // fail was here.
{
WebBrowser b = (WebBrowser)sender;
string text = richTextBox1.Text.ToString();
if (text == null)
{
MessageBox.Show("the messgae was empty");
}
b.Document.GetElementById("idmsg").InnerText = richTextBox1.Text.ToUpper().ToString();
b.Document.GetElementById("idpassw").InnerText = ".....";
b.Document.GetElementById("idpagers").InnerText = id;
b.Document.GetElementById("Send").InvokeMember("click");
// allow server response time
System.Threading.Thread.Sleep(5000);
string output = b.Document.Body.OuterText.ToString();
MessageBox.Show(output);
}
I'v also tried adding another Document complete with the //allow server response time code but again did'nt send till OK was pressed.
what am I doing wrong?
You do it totally wrong. Never rely on the.Sleep(...). C# provides rich enough async environment, namely Task DoAsync(...) which is to be used somewhat like await DoAsync(). This guarantees that no code going below the DoAsync() would ever be executed unless the async operation either completed successfully, either failed with error. As such, by the time you'll get to the last MessageBox.Show(...), all the data would be there, displayed properly as expected.
I'm trying to upload a Word document to a webserver when it's closed in Word.
My code looks like this:
((DocumentEvents_Event)doc).Close += DocumentClose;
private void DocumentClose()
{
var url = Config.GetValue("ApiUrl");
try
{
using (var client = new WebClient())
{
var response = client.UploadData(url, File.ReadAllBytes(_applicationWord.ActiveDocument.FullName));
}
}
catch (Exception e)
{
_notifyIcon.ShowBalloonTip("Word " + WordTools.WordVersionValueToKey(_applicationWord.Version), e.Message, BalloonIcon.Error);
}
}
But unfortunatelly this is not working. ReadAllBytes throws exception "The process cannot access the file because it is being used by another process." Well, quite obvious this other process must be Word itself ;)
What would be a proper way to handle this? As far as I know there is no DocumentAfterClose event...
When I use DownloadFileAsync, it seems to 'block' something. I need the program to be able to download more strings while the file is downloading (downloading a file, but user is still able to search a directory for links to download more files).
The UI is not 100% being blocked, but when the user clicks the 'search' button it doesn't work properly, nor do clicks in the DataGridView get handled. The search button however clears the DataGridView as programmed, but the await thing that I wrote to download the directory as a string (asynchronously with DownloadStringTaskAsync) does not work. However, when the download finishes, the search finally goes through and then populates the DataGridView, which seems like very abnormal behavior to me.
When I comment out the DownloadFileAsync, everything is able to perform normally again. I have also tried to comment out the event handlers that I have put in place, but this also does not fix the issue. I am not sure, thanks for any help.
Some code snippets:
Downloading the file:
var bmclient = new WebClient();
bmclient.DownloadFileAsync(new Uri(downloadURL), Path.Combine(Application.StartupPath, originalFileName + ".nexd"));
bmclient.DownloadProgressChanged += (o, e) =>
{
int rowIndex = -1;
DataGridViewRow row = form1.dataGridView2.Rows
.Cast<DataGridViewRow>()
.Where(r => r.Cells[0].Value.ToString().Equals(setID))
.First();
rowIndex = row.Index;
MethodInvoker action = () => form1.dataGridView2[2, rowIndex].Value = e.ProgressPercentage.ToString() + "%";
form1.BeginInvoke(action);
};
Searching the directory, which is being called by a button on the main form:
public static async Task<string> GetBloodcatSearch(string query)
{
var return_data = string.Empty;
try
{
using (var client = new WebClient())
{
return return_data = await client.DownloadStringTaskAsync(new Uri("directory/" + query));
}
}
catch (Exception e)
{
return null;
}
}
I wrote a C# chat software that uses a new (at least for me) system that I called request system. I don't know if that has been created before, but for now I think of it as my creation :P
Anyhow, this system works like this:
soc receives a signal
checks the signal
if the data it just received is the number 2, the client software knows that the server is about to send a chat message. if the number is 3, so the client knows that the server is about to send the member list, and so on.
The problem is this: when I do step-by-step in VS2012 it works fine, the chat is working properly. When I use it on debug mode or just run it on my desktop, there seems to be missing data, and it shouldn't be because the code is working just fine...
Example of code for the sending&receiving message on client:
public void RecieveSystem()
{
while (true)
{
byte[] req = new byte[1];
soc.Receive(req);
int requestID = int.Parse(Encoding.UTF8.GetString(req));
if (requestID == 3)
{
byte[] textSize = new byte[5];
soc.Receive(textSize);
byte[] text = new byte[int.Parse(Encoding.UTF8.GetString(textSize))];
soc.Receive(text);
Dispatcher.Invoke(() => { ChatBox.Text += Encoding.UTF8.GetString(text) + "\r\n"; });
}
}
}
public void OutSystem(string inputText)
{
byte[] req = Encoding.UTF8.GetBytes("3");
soc.Send(req);
byte[] textSize = Encoding.UTF8.GetBytes(Encoding.UTF8.GetByteCount(inputText).ToString());
soc.Send(textSize);
byte[] text = Encoding.UTF8.GetBytes(inputText);
soc.Send(text);
Thread.CurrentThread.Abort();
}
and on the server:
public void UpdateChat(string text)
{
byte[] req = Encoding.UTF8.GetBytes("3");
foreach (User user in onlineUsers)
user.UserSocket.Send(req);
byte[] textSize = Encoding.UTF8.GetBytes(Encoding.UTF8.GetByteCount(text).ToString());
foreach (User user in onlineUsers)
user.UserSocket.Send(textSize);
byte[] data = Encoding.UTF8.GetBytes(text);
foreach (User user in onlineUsers)
user.UserSocket.Send(data);
}
public void RequestSystem(Socket soc)
{
~~~
}
else if (request == 3)
{
byte[] dataSize = new byte[5];
soc.Receive(dataSize);
byte[] data = new byte[int.Parse(Encoding.UTF8.GetString(dataSize))];
soc.Receive(data);
UpdateChat(Encoding.UTF8.GetString(data));
}
}
catch
{
if (!soc.Connected)
{
Dispatcher.Invoke(() => { OnlineMembers.Items.Remove(decodedName + " - " + soc.RemoteEndPoint); Status.Text += soc.RemoteEndPoint + " Has disconnected"; });
onlineUsers.Remove(user);
Thread.CurrentThread.Abort();
}
}
}
}
What could be the problem?
You're assuming that you'll have one packet for each Send call. That's not stream-oriented - that's packet-oriented. You're sending multiple pieces of data which I suspect are coalesced into a single packet, and then you'll get them all in a single Receive call. (Even if there are multiple packets involved, a single Receive call could still receive all the data.)
If you're using TCP/IP, you should be thinking in a more stream-oriented fashion. I'd also encourage you to change the design of your protocol, which is odd to say the least. It's fine to use a length prefix before each message, but why would you want to encode it as text when you've got a perfectly good binary connection between the two computers?
I suggest you look at BinaryReader and BinaryWriter: use TcpClient and TcpListener rather than Socket (or at least use NetworkStream), and use the reader/writer pair to make it easier to read and write pieces of data (either payloads or primitives such as the length of messages). (BinaryWriter.Write(string) even performs the length-prefixing for you, which makes things a lot easier.)
I am trying to extract content from a blog article like this:
static void GetBlogData (string blogPostUrl)
{
string blogPostContent = null;
WebClient client = new WebClient ();
//client.Headers.Add (HttpRequestHeader.Referer, "http://www.stackoverflow.com");
TextWriter writer = new StreamWriter ("/home/nanda/projects/mono/common/article");
try
{
blogPostContent = client.DownloadString (blogPostUrl);
}
catch (Exception ex)
{
Term.PrintLn ("Unable to download\n{0}", ex.Message);
}
if (blogPostContent != null)
{
writer.WriteLine (blogPostContent);
}
else
{
Term.PrintLn ("No content found");
}
}
I am aware that this is too simple of an approach, but I want to know why I am unable to extract content from some URLs like they have a block or something. How can I detect if a website/blog is blocking me from downloading its content?
A website cannot block you from downloading its content without blocking the site's consultation from a browser.
If your download fails, it means either:
a) your url is wrong
b) the website needs some form of identification and your request lacks something (probably a cookie)