System Device Location not working - c#

I have code for using the system.device.location api found in windows computers. This should be fairly straightfoward code
var watcher = new GeoCoordinateWatcher();
watcher.PositionChanged +=
new EventHandler<GeoPositionChangedEventArgs<
GeoCoordinate>>(GeoPositionChanged);
watcher.Start();
var coord = watcher.Position.Location;
I mean all I need to do is start a geo watcher and then read the location. But it only ever returns "Location Unknown" and I am wondering if there is an issue with the code, or if something needs to be installed on the computer, or what. I have tried this with a few windows 7 pcs and 1 windows 10 pc and all of them have the share location turned on in the settings. So what is wrong with this code? Also this is the code for the geopositionchanged if that makes any difference.
private static void GeoPositionChanged(object sender,
GeoPositionChangedEventArgs<GeoCoordinate> e)
{
MessageBox.Show("The current location is: " +
e.Position.Location.Latitude + "/" +
e.Position.Location.Longitude + ".");
}

Wait for location services to be ready. Your GeoCoordinateWatcher has an event for status change and another one for position change.
GeoCoordinateWatcher _watcher;
public Class1()
{
_watcher = new GeoCoordinateWatcher();
_watcher.StatusChanged += Watcher_StatusChanged;
_watcher.PositionChanged += GeoPositionChanged;
_watcher.Start();
var coord = _watcher.Position.Location;
}
private void Watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
if (e.Status == GeoPositionStatus.Ready)
{
MessageBox.Show("Watcher is ready. First location: The current location is: " +
_watcher.Position.Location.Latitude + "/" +
_watcher.Position.Location.Longitude + ".");
}
}
private static void GeoPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
MessageBox.Show("The current location is: " +
e.Position.Location.Latitude + "/" +
e.Position.Location.Longitude + ".");
}

Related

Windows Forms - detecting an external application closing to trigger an event

I am in need of a solution to trigger code when an external application is closing / closes.
I am unable to use System.Diagnostics Process.GetProcessByName to detect if the process is running since it might conflict with an anticheat system. I would need trigger the snippet of code only when the program closes and only then.
I made a good, event-based implementation.
class Monitor
{
public event EventHandler ProgramStarted;
public event EventHandler ProgramClosed;
public Monitor(string process)
{
string pol = "2";
if (!process.EndsWith(".exe")) process += ".exe";
var queryString =
"SELECT *" +
" FROM __InstanceOperationEvent " +
"WITHIN " + pol +
" WHERE TargetInstance ISA 'Win32_Process' " +
" AND TargetInstance.Name = '" + process + "'";
var s = #"\\.\root\CIMV2";
ManagementEventWatcher watcher = new ManagementEventWatcher(s, queryString);
watcher.EventArrived += new EventArrivedEventHandler(OnEventArrived);
watcher.Start();
}
private void OnEventArrived(object sender, EventArrivedEventArgs e)
{
if (e.NewEvent.ClassPath.ClassName.Contains("InstanceDeletionEvent"))
{
EventHandler handler = ProgramClosed;
handler?.Invoke(this, e);
}
else if (e.NewEvent.ClassPath.ClassName.Contains("InstanceCreationEvent"))
{
EventHandler handler = ProgramStarted;
handler?.Invoke(this, e);
}
}
}
To use it, you just create an instance of the class and set up the events. For example:
static void Main(string[] args)
{
var mon = new Monitor("chrome");
mon.ProgramClosed += Mon_ProgramClosed;
mon.ProgramStarted += Mon_ProgramStarted;
Console.ReadKey(true);
}
private static void Mon_ProgramStarted(object sender, EventArgs e)
{
MessageBox.Show("Program started.");
}
private static void Mon_ProgramClosed(object sender, EventArgs e)
{
MessageBox.Show("Program closed.");
}
Make sure to add reference to System.Drawing if you're using a console app, and ,for winforms, adjust the modifiers.

Beginner Thread or Dispatcher direction

I was hoping someone could point me in the right direction. I want to make a simple WPF application that has a button and a textbox. I click the button, and it starts to loop downloading a bunch of files. I can't seem to figure out how to not let the downloading stop the UI from updating. From what I can gather I'm probably going to have to use some threading code; but so far all the examples I've found and tried don't work for me. Any help or direction on where I should look and learn would be great. I can't seem to figure out how I can output those textbox.text messages around each file download.
foreach (var ticker in tickers)
{
var url = string.Format(urlPrototype, ticker, startMonth, startDay, startYear, finishMonth, finishDay, finishYear, "d");
var csvfile = directory + "\\" + ticker.ToUpper() + ".csv";
tbOutput.Text += "Starting Download of : " + ticker + "\n";
webClient.DownloadFile(url, csvfile);
tbOutput.Text += "End Download of : " + ticker + "\n";
numStocks++;
}
tbOutput.Text += "Total stocks downloaded = " + numStocks + "\n";
If you mark your method as async, you can use the DownloadFileTaskAsync method
await webClient.DownloadFileTaskAsync(url, csvfile)
If you choose to use the BackgroundWorker, it allows you to output those messages into the TextBox around each file download. Here is a crude example adapted for your requirement.
1) At the class level, create an instance of the BackgroundWorker class and add event handlers to the BackgroundWorker instance's events:
BackgroundWorker workerDownload = new BackgroundWorker();
workerDownload.WorkerReportsProgress = true;
workerDownload.DoWork += workerDownload_DoWork;
workerDownload.ProgressChanged += workerDownload_ProgressChanged;
workerDownload.RunWorkerCompleted += workerDownload_RunWorkerCompleted;
2) Create an event handler for the background worker's DoWork event:
The DoWork event handler is where you run the time-consuming operation
on the background thread. Any values that are passed to the background
operation are passed in the Argument property of the DoWorkEventArgs
object that is passed to the event handler.
private void workerDownload_DoWork(object sender, DoWorkEventArgs e)
{
foreach (var ticker in tickers)
{
// you can pass the required info as argument:
string[] arrArg = (string[])e.Argument;
string theUrl = arrArg[0];
string directory = arrArg[1];
var url = string.Format(theUrl, ticker);
var csvfile = directory + "\\" + ticker.ToUpper() + ".csv";
// perform the download operation and report progress:
workerDownload.ReportProgress(0, "Starting Download of : " + ticker + "\n");
webClient.DownloadFile(url, csvfile);
workerDownload.ReportProgress(100, "End Download of : " + ticker + "\n");
numStocks++;
}
}
3) Create an event handler for the background worker's ProgressChanged event:
In the ProgressChanged event handler, add code to indicate the
progress, such as updating the user interface.
private void workerDownload_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
tbOutput.Text += e.UserState.ToString();
}
4) Create an event handler for the RunWorkerCompleted event:
The RunWorkerCompleted event is raised when the background worker has
completed.
private void workerDownload_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
tbOutput.Text += "Total stocks downloaded = " + numStocks + "\n";
}
5) Start running the background operation by calling the RunWorkerAsync method:
int numStocks = 0;
string strDirectory = "<a_directory>";
string strUrl = string.Format(urlPrototype, startMonth, startDay, startYear, finishMonth, finishDay, finishYear, "d");
string[] args = new string[2] { strUrl, strDirectory };
workerDownload.RunWorkerAsync(args);
There are a lot ways to implement it. For example:
1) Using async/await if you programming in .Net Framework 4.5. It is simpler than BackgroundWorker
https://msdn.microsoft.com/en-us/library/hh191443.aspx
private async void button_Click(object sender, RoutedEventArgs e)
{
Uri someUrl=new Uri(#"http://dotnetperls.com");
WebClient webClient=new WebClient();
await webClient.DownloadFileTaskAsync(someUrl, csvFile);
}
2) BackgroundWorker. This class is really intended to make asynchronous operations to avoid freezing UI.
See http://www.wpf-tutorial.com/misc/multi-threading-with-the-backgroundworker
public partial class MainWindow : Window
{
BackgroundWorker bw;
public MainWindow()
{
InitializeComponent();
bw = new BackgroundWorker();
bw.DoWork += bw_DoWok;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;
}
}
void bw_RunWorkerComleted(object sender, RunWorkerCompletedEventAgs e)
{
MessageBox.Show("The result is " + e.Result.ToString());
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
foreach (var ticker in tickers)
{
var url = string.Format(urlPrototype, ticker, startMonth, startDay, startYear, finishMonth, finishDay, finishYear, "d");
var csvfile = directory + "\\" + ticker.ToUpper() + ".csv";
webClient.DownloadFile(url, csvfile);
numStocks++;
}
e.Result = "End Of Download ";
}
private void button_Click(object sender, RoutedEventArgs e)
{
bw.RunWorkerAsync();
tbOutput.Text += "Starting Download of : " + ticker + "\n";
}
3) Use Thread class and update using Dispatcher class:
ThreadStart job = new ThreadStart(() =>
{
foreach (var ticker in tickers)
{
var url = string.Format(urlPrototype, ticker, startMonth, startDay, startYear, finishMonth, finishDay, finishYear, "d");
var csvfile = directory + "\\" + ticker.ToUpper() + ".csv";
webClient.DownloadFile(url, csvfile);
numStocks++;
}
Dispatcher.BeginInvoke((Action)(()=> tbOutput.Text += "End Download of : " + ticker + "\n";}));
});
Thread thread = new Thread(job);
thread.Start();
http://www.beingdeveloper.com/use-dispatcher-in-wpf-to-build-responsive-applications

Automatically send text every 10 seconds

I have a program that gets the app name, place them on a listbox and sends them to the other window if you click the send button.
What I wanted to know is, is it possible for it to automatically send every 10 seconds after a single click on the send button? If yes, how can I possibly do that?
There's the codes, in case if it brings of any help.
private void cmd_send_Click_1(object sender, EventArgs e)
{
String processID = "";
String processName = "";
String processFileName = "";
String processPath = "";
string hostName = System.Net.Dns.GetHostName();
listBox1.BeginUpdate();
try
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
piis = GetAllProcessInfos();
try
{
// String pno = textBox4.Text.ToString();
// String path = textBox5.Text.ToString();
// String name = textBox6.Text.ToString();
// String user = textBox7.Text.ToString();
// output.Text += "\n Sent data : " + pno + " " + user + " " + name + " " + path ;
processID = piis[i].Id.ToString();
processName = piis[i].Name.ToString();
processFileName = piis[i].FileName.ToString();
processPath = piis[i].Path.ToString();
output.Text += "\n\nSENT DATA : \n\t" + processID + "\n\t" + processName + "\n\t" + processFileName + "\n\t" + processPath + "\n";
}
catch (Exception ex)
{
wait.Abort();
output.Text += "Error..... " + ex.StackTrace;
}
NetworkStream ns = tcpclnt.GetStream();
String data = "";
//data = "--++" + " " + textBox4.Text + " " + textBox5.Text + " " + textBox6.Text + " " + textBox7.Text;
data = "--++" + " " + processID + " " + processPath + " " + processFileName + " " + hostName;
if (ns.CanWrite)
{
byte[] bf = new ASCIIEncoding().GetBytes(data);
ns.Write(bf, 0, bf.Length);
ns.Flush();
}
}
}
finally
{
listBox1.EndUpdate();
}
}
Any help would be greatly appreciated.
You could place your code inside a single method, call that method initially on button click and start/stop your timer depending on it's current state.
private Timer _timer;
public Form() // Initialize timer in your form constructor
{
InitializeComponent();
_timer = new Timer();
_timer.Interval = 10000; // miliseconds
_timer.Tick += _timer_Tick; // Subscribe timer to it's tick event
}
private void _timer_Tick(object sender, EventArgs e)
{
SendData();
}
private void cmd_send_Click_1(object sender, EventArgs e)
{
if (!_timer.Enabled) // If timer is not running send data and start refresh interval
{
SendData();
_timer.Enabled = true;
}
else // Stop timer to prevent further refreshing
{
_timer.Enabled = false;
}
}
private void SendData()
{
// Your code here
}
EDIT:
If you're using .NET framework 4.5 or above you can do the same thing in using async/await.
private bool keepRefreshing;
private async void cmd_send_Click_1(object sender, EventArgs e)
{
if (keepRefreshing)
{
keepRefreshing = false;
return;
}
keepRefreshing = true;
while (keepRefreshing)
{
// Your code here
await Task.Delay(10000);
}
}
On button click it will send data and it will keep sending with delay of 10 seconds. When you press the button second time it will stop refreshing interval, third time it will start again and so on..
// Declare a timer
Timer tmr = new Timer();
tmr.Interval = 10000; // 10 second
tmr.Tick += timerHandler; // We'll write it in a bit
tmr.Start(); // The countdown is launched!
private void timerHandler(object sender, EventArgs e) {
// Here the code what you need each 10 seconds
tmr.Stop(); // Manually stop timer, or let run indefinitely
}
Their are many ways one is follow.
private void cmd_send_Click_1(object sender, EventArgs e)
{
bool isResend=true;
while (isResend==true)
{
// Put all your here
System.Threading.Thread.Sleep(10000);
}
}
Other ways are using Timer, etc...
Everyone's answer is cool, but as for me if you really need that "click" as start, i'll do it this way.
Initiate events for timer & background worker inside form load.
set timer.start(); inside click.
Once ticking, if backgroundworker is not busy, execute background worker.
Ensure that you don't directly set label1.text = "send some works here." inside the background worker, it will cause error.
Hope this helps.

c# how to insert into database

I need help on this, I'm inserting file directory into the database but it does not take into account of the txtStoryTitle.Text in the database, for example, if I type HelloWorld in txtStoryTitle. It appears as Images/Story//(filename) instead of Images/Story/HelloWorld/(filename) in the DB. I am using MySQL (workbench).
please give me an advice/solutions on this, thanks in advance!
Here are the partial codes:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
EnsureDirectoriesExist();
String filepathImage = (#"Images/Story/" + txtStoryTitle.Text + "/" + e.FileName);
AjaxFileUpload1.SaveAs(Server.MapPath(filepathImage));
Session["filepathImage"] = filepathImage;
}
public void EnsureDirectoriesExist()
{
if (!System.IO.Directory.Exists(Server.MapPath(#"Images/Story/" + txtStoryTitle.Text + "/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath(#"Images/Story/" + txtStoryTitle.Text + "/"));
}
}
protected void btnDone_Click(object sender, EventArgs e)
{
if (Session["filepathImage"] != null)
{
string filepathImage = Session["filepathImage"] as string;
act.ActivityName = dropListActivity.SelectedItem.Text;
act.Title = txtStoryTitle.Text;
act.FileURL = filepathImage;
daoStory.Insert(act);
daoStory.Save();
}
As per your code.. the file path is "Images/Story/" + txtStoryTitle.Text + "/" + e.FileName"
and after providing txtStoryTitle.Text it saved as "Images/Story//FileName".. then it means txtStoryTitle.Text does'nt contain any text..
If its in .Net then make sure you set autopostback property of txtStoryTitle textbox to true.
and if it is already true then try to find out why this textbox does'nt resist its state.

Code is not executed in server side?

The code tested and working in local computer but not in server side. So, i use log4net to see what happen, and here is what the log4net produce: http://pastebin.com/Xr3iq68t As you all can see, i put log4net almost in every line of my code.
What is the differences between my local computer with server(i'am using somee.com free hosting to test the code).
If it because of permission problem, i have tested another code which is downloading a snapshot from same source and save it in server side folder and it can save it.
So, is there anything wrong with the code?
The code executed until Rec class only, not proceed to the rest of the code. It should go to video_NewFrame after that, but from log file record, it not continue.Complete code can be viewed here: http://pastebin.com/VCjVj3uc
protected void Button1_Click(object sender, EventArgs e)
{
string usr = "http://IPaddress.com:8081/snapshot.cgi";
log.Info("DDNS: " + usr);
log.Info("Starting JPEG stream...");
//camera source
JPEGSource = new JPEGStream(usr);
log.Info("***JPEGSource = new JPEGStream(usr);***");
JPEGSource.Login = login;
JPEGSource.Password = password;
log.Info("***JPEG login & password***");
JPEGSource.Start();
log.Info("JPEGSource.Start()");
JPEGSource.NewFrame += new NewFrameEventHandler( video_NewFrame );
log.Info("***Goto video_NewFrame class***");
//System.Threading.Thread.Sleep(6000);
//Label2.Text = Label2.Text + streamingSource + "<br> ";
this.Label1.Text = "Camera Source: " + usr;
}
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap image = (Bitmap)eventArgs.Frame.Clone();
log.Info("***Bitmap image = (Bitmap)eventArgs.Frame.Clone();***");
width = image.Width;
height = image.Height;
frames.Enqueue((Bitmap)image.Clone());
log.Info("***Cloning frame***");
if (!IsRecording)
{
log.Info("Entering thread");
IsRecording = true;
Thread th = new Thread(DoRecording);
th.Start();
}
}
Note: camera Ip address is DDNS ip address.

Categories