Sync data between webclient windows phone and webservice - c#

I'm using a webclient on a windows phone 8 app, i have to sync some data with the webservice each minutes (or by pressing a button). I put my webclient in a private data of my object :
private WebClient client_summary;
At the launch of the app the client connects to the webservice :
client_summary = new WebClient();
client_summary.DownloadStringAsync(new Uri("random url" + info_conf.id));
client_sommaire.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadSummaryConf);
I recovered well data, but each time i want to re sync my webclient, data remain the same :(
DispatcherTimer TradeThread = new DispatcherTimer();
TradeThread.Interval = TimeSpan.FromSeconds(10);
TradeThread.Tick += new EventHandler(dispatcherTimer_Tick);
TradeThread.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
pivotMainList.Items.Clear();
summary.Children.Clear();
client_summary.DownloadStringAsync(new Uri("url" + info_conf.id));
}
private void client_DownloadSummaryConf(object sender, DownloadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
e.Result remain the same, whereas if I restart my app the data sync correctly
I don't understand why the sync didn't work ...
Please tell me thanks in advance.

This is a caching issue - the Webclient class (and the HttpClient class if you chose to use that instead) caches server responses. The standard workaround is to append something that varies to your querystring.
For examples see:
How do you disable caching with WebClient and Windows Phone 7
Windows Phone 7 WebRequest caching?

Related

Create Windows Session programmatically from Console or Windows Service

How can I programmatically log in to windows to create a Windows Logon Session?
I need a way that works from a WinForms app, from a Console app, and (most important) from a Windows Service.
One other requirement is that I need it to work on a the local system that the program/service is running on and also for remote systems.
If there's a way to do this using pInvoke/Win32 API I am open to that too.
I found these similar questions/answers in my research:
Programmatically create and launch and RDP session (without gui)
The answer here says it's possible but and gives a link but the sample code from the link doesn't work
Create a Windows Session from a service via the Win32 API
No Solution to the question asked
Create Windows session programmatically
No Solution but the OP mentioned in a comment that http://freerdp.com worked for him.
I've created a simple utility that I believe meets all the requirements in the question. You'll need to add a COM reference to Microsoft Terminal Services Active Client 1.0 Type Library (ActiveX).
I thought it might not work for creating a session on the local machine but I tested in in 2012R2 running as a Service and it actually can. The same exact method can be called from a WinForms app or from a Console app. When launched from a WinForms or Console app, the a form is shown for a few seconds so I made sure to set the control to enabled = false so it can't be interacted with.
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using AxMSTSCLib;
namespace Utility.RemoteDesktop
{
public class Client
{
private int LogonErrorCode { get; set; }
public void CreateRdpConnection(string server, string user, string domain, string password)
{
void ProcessTaskThread()
{
var form = new Form();
form.Load += (sender, args) =>
{
var rdpConnection = new AxMSTSCLib.AxMsRdpClient9NotSafeForScripting();
form.Controls.Add(rdpConnection);
rdpConnection.Server = server;
rdpConnection.Domain = domain;
rdpConnection.UserName = user;
rdpConnection.AdvancedSettings9.ClearTextPassword = password;
rdpConnection.AdvancedSettings9.EnableCredSspSupport = true;
if (true)
{
rdpConnection.OnDisconnected += RdpConnectionOnOnDisconnected;
rdpConnection.OnLoginComplete += RdpConnectionOnOnLoginComplete;
rdpConnection.OnLogonError += RdpConnectionOnOnLogonError;
}
rdpConnection.Connect();
rdpConnection.Enabled = false;
rdpConnection.Dock = DockStyle.Fill;
Application.Run(form);
};
form.Show();
}
var rdpClientThread = new Thread(ProcessTaskThread) { IsBackground = true };
rdpClientThread.SetApartmentState(ApartmentState.STA);
rdpClientThread.Start();
while (rdpClientThread.IsAlive)
{
Task.Delay(500).GetAwaiter().GetResult();
}
}
private void RdpConnectionOnOnLogonError(object sender, IMsTscAxEvents_OnLogonErrorEvent e)
{
LogonErrorCode = e.lError;
}
private void RdpConnectionOnOnLoginComplete(object sender, EventArgs e)
{
if (LogonErrorCode == -2)
{
Debug.WriteLine($" ## New Session Detected ##");
Task.Delay(10000).GetAwaiter().GetResult();
}
var rdpSession = (AxMsRdpClient9NotSafeForScripting)sender;
rdpSession.Disconnect();
}
private void RdpConnectionOnOnDisconnected(object sender, IMsTscAxEvents_OnDisconnectedEvent e)
{
Environment.Exit(0);
}
}
}
On a side note I found this question that says there may be a way to use the ActiveX control (for RDP) without using a windows form at all. I saw the example they gave and I was unsure hot to use their code for this situation.
ActiveX control without a form
If there's anyone out there who understands how to do this without hosting the ActiveX control on a Form please post an example.

Why UploadProgressChanged in WebClient.UploadFileAsync work not correctly?

I'm upload file and get upload progress like this:
using (var wc = new WebClient())
{
wc.UploadProgressChanged += FileUploadProgressChanged;
wc.Headers.Add(HttpRequestHeader.ContentType, "image/png");
wc.UploadFileAsync(new Uri(url), filePath);
}
...
private void FileUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
ProgressBarUpload.Value = e.ProgressPercentage;
}
But after 50% e.ProgressPercentage return -441850 and then immediately returns 100. Why is this happening?
My solution:
private void FileUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
ProgressBarUpload.Value = e.BytesSent * 100 / e.TotalBytesToSend;
}
I also found two questions similar to this, but I have not managed to solve the problem. But it can be useful to others:
WebClient UploadFileAsync strange behaviour in progress reporting (cause of the problem - problems with authorization)
Uploading HTTP progress tracking (cause of the problem - the third-party application)
Note. Аfter downloading the file we receive a response from the server, it would be better to display the download file is 95% and the remaining 5% leave to display the response from the server. And in the end after a successful download and response from the server, we will be 100%.
PS: In the code, I did not show it, just say to those who might need it.

Unity WebSocket4Net

How can I connect a Unity client to a php webserver via WebSocket4Net dll? I
tried an example like that
using WebSocket4Net;
WebSocket websocket = new WebSocket("ws://localhost:2012/");
websocket.Opened += new EventHandler(websocket_Opened);
websocket.Error += new EventHandler<ErrorEventArgs>(websocket_Error);
websocket.Closed += new EventHandler(websocket_Closed);
websocket.MessageReceived += new EventHandler(websocket_MessageReceived);
websocket.Open();
private void websocket_Opened(object sender, EventArgs e)
{
websocket.Send("Hello World!");
}
but got no result
You can check the following links for more information on Unity and web sockets both for the general concept and for the specific to c# implementation.
https://www.youtube.com/watch?v=wfdGw09-rC4
https://www.youtube.com/watch?v=AifcMzEbKnA
https://developer.leapmotion.com/documentation/skeletal/csharp/supplements/Leap_JSON.html
http://docs.unity3d.com/ScriptReference/Network.Connect.html

Web request monitoring for .net

Problem Background
I have few web applications which were developed using Microsoft .net framework 4.0 and running on the IIS 7.0 .so now i need to track traffic information(requested user,ip,application name ,address,request time etc..) for all these application and persist into a database or text file etc.
while i was searching on this i found HTTP handlers concept.
Is this handy to use my case ? or are there any alternatives which can fulfill my requirement?
I need to write this component as plug-abbe one.because i need connect this component easily to another web application also.
appreciate your ideas
Use an HttpModule to intercept all requests via the BeginRequest event, like this:
public class RequestLoggingModule : IHttpModule
{
private HttpApplication httpApp;
public void Init(HttpApplication httpApp)
{
this.httpApp = httpApp;
httpApp.BeginRequest += new EventHandler(OnBeginRequest);
}
void OnBeginRequest(object sender, EventArgs e)
{
// Get the user that made the request
HttpApplication application = (HttpApplication)sender;
HttpResponse response = application.Context.Response;
WindowsIdentity identity =
(WindowsIdentity)application.Context.User.Identity;
LogInformation(identity.Name);
// Do this for other information you want to log here
}
private void LogInformation(string data)
{
EventLog log = new EventLog();
log.Source = "Application XYZ Request Logging";
log.WriteEntry(data, EventLogEntryType.Information);
}
public void Dispose()
{
}
}

Using Web API for a Windows Service to Receive Commands and Perform Tasks via Polling?

I have a project where I need to create a windows service that, when instructed via a command, will perform various tasks. This server would run on multiple servers and would effectively perform the same kind of tasks when requested.
For example, I would like to have a Web API service that listens for requests from the servers.
The service running on the server would send a query to Web API every 25 secs or so and pass to it its SERVERNAME. The Web API logic will then look up the SERVERNAME and look for any status updates for various tasks... I.E., if a status for a DELETE command is a 1, the service would delete the folder containing log files... if a status for a ZIP command is a 1, the service would zip the folder containing log files and FTP them to a centralized location.
This concept seems simple enough, and I think I need a nudge to tell me if this sounds like a good design. I'm thinking of using .NET 4.5 for the Windows Service, so that I can use the HttpClient object and, of course, .NET 4.5 for the Web API/MVC project.
Can someone please get me started on what a basic Web API woudld look like provide status updates to the Windows services that are running and issue commands to them...
I'm thinking of having a simple MVC website that folks will have a list of servers (maybe based on a simple XML file or something) that they can click various radio buttons to turn on "DELETE", "ZIP" or whatever, to trigger the task on the service.
I do something similar. I have a main Web API (a Windows Service) that drives my application and has a resource called /Heartbeat.
I also have a second Windows Service that has a timer fire every 30 seconds. Each time the timer fires it calls POST /heartbeat. When the heartbeat request is handled, it goes looking for tasks that have been scheduled.
The advantage of this approach is that the service makes the hearbeat request is extremely simple and never has to be updated. All the logic relating to what happens on a heartbeat is in the main service.
The guts of the service are this. It's old code so it is still using HttpWebRequest instead of HttpClient, but that's trivial to change.
public partial class HeartbeatService : ServiceBase {
readonly Timer _Timer = new System.Timers.Timer();
private string _heartbeatTarget;
public HeartbeatService() {
Trace.TraceInformation("Initializing Heartbeat Service");
InitializeComponent();
this.ServiceName = "TavisHeartbeat";
}
protected override void OnStart(string[] args) {
Trace.TraceInformation("Starting...");
_Timer.Enabled = true;
_Timer.Interval = Properties.Settings.Default.IntervalMinutes * 1000 * 60;
_Timer.Elapsed += new ElapsedEventHandler(_Timer_Elapsed);
_heartbeatTarget = Properties.Settings.Default.TargetUrl;
}
protected override void OnStop() {
_Timer.Enabled = false;
}
private void _Timer_Elapsed(object sender, ElapsedEventArgs e) {
Trace.TraceInformation("Heartbeat event triggered");
try {
var httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(_heartbeatTarget);
httpWebRequest.ContentLength = 0;
httpWebRequest.Method = "POST";
var response = (HttpWebResponse)httpWebRequest.GetResponse();
Trace.TraceInformation("Http Response : " + response.StatusCode + " " + response.StatusDescription);
} catch (Exception ex) {
string errorMessage = ex.Message;
while (ex.InnerException != null) {
errorMessage = errorMessage + Environment.NewLine + ex.InnerException.Message;
ex = ex.InnerException;
}
Trace.TraceError(errorMessage);
}
}
}
You can do it with ServiceController.ExecuteCommand() method from .NET.
With the method you can sand custom command to windows' service.
Then in your service you need to implement ServiceBase.OnCustomCommand() to serve incomming custom command event in service.
const int SmartRestart = 8;
...
//APPLICATION TO SEND COMMAND
service.ExecuteCommand(SmartRestart);
...
//SERVICE
protected override void OnCustomCommand(int command)
{
if (command == SmartRestart)
{
// ...
}
}

Categories