My problem is:
My WebClient uses a function in the Cloud (http://127.0.0.1:81/Service1.svc/Data).
But it is impossible to call several times (for example to make an update).
Here is my code:
private void button_Click(object sender, RoutedEventArgs e)
{
WebClient cnt = new WebClient();
cnt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(cnt_DownloadStringCompleted);
cnt.DownloadStringAsync(new Uri("http://127.0.0.1:81/Service1.svc/Data"));
}
void cnt_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
int num = JsonHelper.FromJson<int>(e.Result);
textbox.Dispatcher.BeginInvoke(() => textbox.Text = Convert.ToString(num));
}
After each click, the application goes well in cnt_DownloadStringCompleted but the result (e.Result) never changes after an update in the server.
At the Azure service, I noticed through a break that the function (Data) is called only once (first time).
How can I do to call my service more than once?
Check your server side to make sure that you aren't allowing caching. If you have the response context in your service, set:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Alternatively, if you don't have the ability to do this, send in a changing nonsense parameter on the querystring, something like:
http://127.0.0.1:81/Service1.svc/Data?nonsense=190AF142-4341-47DC-9CF5-3BC3ACBD02EE
You can either generate and send in a new guid each time, or even use DateTime.Now.Ticks.ToString(). That being said, if you have control over the server side, eliminate caching, as this way is a serious hack.
I believe web requests are often cached by the emulator (maybe the real phone too).
Here are a few blog posts that mention this, as well as some solutions:
http://www.benday.com/2011/10/06/disable-rest-webrequest-url-caching-on-wp7-mango/
http://www.nickharris.net/2010/10/windows-phone-7-httpwebrequest-returns-same-response-from-cache/
Related
I wrote this little bit of C# code to test an implementation I intend to use for an internal tool at work. Much to my surprise, it functions exactly as I hoped but I do not understand why.
private void button1_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadFile("http://url censored", #"C:\Users\Dustin\Desktop\flashplayer.exe");
bool dlComplete = System.IO.File.Exists(#"C:\Users\Dustin\Desktop\flashplayer.exe");
if (dlComplete == true)
{
System.Diagnostics.Process.Start(#"C:\Users\Dustin\Desktop\flashplayer.exe");
}
else
{
System.Windows.Forms.MessageBox.Show("Something's jacked!");
}
}
When I press on button1, my machine downloads the Flash installer and then checks if the file exists (this is my roundabout way of avoiding event handlers which I have not learned to deal with yet), and continues on.
Why doesn't my computer check for the file's existence while the file is downloading? How does this wizard of a computer know to hold on a moment while the file download completes?
WebClient.DownloadFile is a Synchronous method in which downloads to a local data file.
As stated on the MSDN link here - "[t]his methods blocks while downloading the resource."
In other words, the process is waiting for completion (blocking the calling function), before returning control and execution to the thread.
This results in the wizardry you're experiencing with the application knowing when to check for the file's presence. I know magic can be ruined once you know the trick; however, I hope this ins't the case..
For reference, here's a way that would work the way you didn't expect, asynchronously.
var webClient = new WebClient())
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync("http://www.server.com/file.txt", "C:\\file.txt");
In fact, there's a whole set of Asynchronous C# functions. It's worth reading up on if you're interested in getting into development.
https://msdn.microsoft.com/en-us/library/mt674882.aspx
I have the following code which will fetch some data from a .php file on a website and it will format the data and show it on the form. (Using visual studio)
Sometimes the fetching of data takes some time. So I want a label named U to be changed to "Refreshing..." during the time it fetches the data.
So I used the below code.(I am showing the relevant part)
private void refresh(object sender, MouseEventArgs e)
{
U.Text = "Refreshing ...";
string r = HttpGet("http://www.example.com/?Fetch=OK");
U.Text = "Done";
}
But this code is not changing the text to "Refreshing ..." ,it's only being changed to "Done" even if the fetching takes 1 minute.
What's happening here? How can I make it work?
The best way to handle this is typically to fetch the data asynchronously:
private async void Refresh(object sender, MouseEventArgs e)
{
U.Text = "Refreshing...";
string r = await HttpGetAsync("http://www.example.com/?Fetch=OK"); // Requires an async version
U.Text = "Done";
}
This requires changing your HttpGet method to get the data asynchronously, and return a Task<string> instead of string.
The issue is that your code executes and somehow, due to either low resources on machine, the application stops while loading the resources. Once done, it updates the content. You should use Threading of .NET for this, to perform different tasks using threads.
Assign each function to a different thread, UI thread must be different, resource loading must be different too.
Have a look here, msdn.microsoft.com/en-us/library/system.threading.thread(v=vs.110).aspx
I am beginner in c# with a huge problem.
An application with datagridview in front (Termin plan for one work day) works on many PC's in LAN with MS Windows Server and with MySQL database.
How can I become the changes made on one workstation AUTOMATICALY on all other PC's WITHOUT any action on them (application only started).
I have a procedure for data and datagridview refresh, I must only know WHEN I must start this procedure, that means I must know WHEN any other workstation made any changes.
Thanks for any help!
A simple solution would be to use a timer and when it elapses you refresh you gridview. so on defined period of time it will be refreshed automatically. the problem can be that if you update to often there's a overload of accessing the db. to prevent this, you could make an serverapplication which handles all data
Let's say PC 1 is starting the client application.
First it connects to server application (the server stores the reference of the client e.g. in an list).
After that the user on PC1 makes changes and click on save, the software will send the changes to the server (e.g. a custom object with all needed information).
Server saves the changes to the DB
Serverapplication give a response to the specific client if it worked or not
If it worked, Send an custom object (for example named ChangesDoneEvent) to all clients that indicates that changes have been done.
All connected clients will receive that object and know now that the have to refresh their gridview.
For further information just search for C# Multi threaded Server Socket programming. For sending custom objects over network you will find many resources in the internet too, maybe this will help you Sending and receiving custom objects using Tcpclient class in C#
Declare Delegate on your form
public delegate void autocheck();
private System.Timers.Timer TTTimer = new System.Timers.Timer();
public void autofilldgv()
{
if (this.InvokeRequired)
{
this.Invoke(new autocheck(UpdateControls));
}
else
{
UpdateControls();
}
}
private void UpdateControls()
{
//call your method here
filldgv();
}
void TTTimer_Elapsed(object sender System.Timers.ElapsedEventArgs e)
{
mymethod();
}
public void mymethod()
{
//this method is executed by the background worker
autofilldgv();
}
private void frm_receptionView_Load(object sender, EventArgs e)
{
this.TTTimer.Interval = 1000; //1 sec interval
this.TTTimer.Elapsed += new System.Timers.ElapsedEventHandler(TTTimer_Elapsed);
this.TTTimer.Start();
}
The solution provided above is actually a good way to handle this scenario. Before implementing you might also want to think about the potential fall backs. It is possible that Client PC 's IP could change and since you are using sockets. The object reference added in the list could be faulted state. You might want to think of handling this pitfall.
Hi i am trying to use a timer to execute it each minute , in the first minute he will redirect me at my first page that what i used but the problem that i get a null Referencexpection in the redirection method
public partial class wait1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Timers.Timer t = new System.Timers.Timer(6000);
t.AutoReset = true;
t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
t.Start();
}
private static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
HttpContext.Current.Response.Redirect("~/Default.aspx", false);
}
}
WebForms (i.e. ASP.NET) apps are not the same as WinForms apps. Because of
the fundamental architecture of the web, they are stateless. This means that
they work in a request / response scenario - a client sends an HttpRequest
to a webserver, the webserver process the HttpRequest and sends back an
HttpResponse. After the HttpResponse has been sent down to the client,
nothing else happens between server and client until / unless the client
sends back another HttpRequest.
When a client makes a request to an aspx page, the Page object goes through
a predefined lifecycle firing events such as Page_Load etc. The very end of
this predefined lifecycle involves sending the HttpResponse down to the
client and then unloading the page. Once the page is unloaded, it's gone.
use
ClientScript.RegisterStartupScript(GetType(), "redirect",
"parent.location.href='Default.aspx';");
instead of response of redirect
You simply cannot do it like that. Once you request a web page to the server and the rendering is done, the client is not connected anymore to the server.
This means that only the client (Javascript) can take actions.
Use the JavaScript set time out:
<script>
setTimeout(function(){window.location='...';)}, 6000);
<script>
This is telling the broser: "in 6000ms run the function", and the function is redirecting to the required page.
I simply want to be able to make a callback on a function in the windows phone code from the server side when something is being updated there. Examples abound on the Internet make use of wsDualHttpBinding, but some wise man has decided to remove support for that from the windows store application API list. I can't find any other way to get the same functionality, does anybody know how to do this?
The reasoning behind not allowing for internet based callbacks is that it puts a big drain on the phone's battery to be constantly listening for them. Instead, they allow you to run PeriodicTask's that will let you occasionally call a server to poll whether there is a change.
Alternatively you could use their notification service:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402558%28v=vs.105%29.aspx
You can try something like this
System.Net.WebClient wc = new System.Net.WebClient();
public void Initialize(object sender, EventArgs e)
{
wc.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(done);
}
public string version = "1.0.0";
public void done(object sender, System.Net.DownloadStringCompletedEventArgs e)
{
if (version != e.Result)
{
//Do your code here
}
}
You can create a place online that stores the current version then check on start up.