--repeat comand doesn't work in Vlc.DotNet.WPF - c#

I am trying to retrieve the rtsp stream from my server, and when I disconnect vlc (after sending a Teardown request), I want the vlc to reconnect.
When run from the console (vlc --repeat --rtsp-tcp rtsp://ip:port) everything works. But when running from wpf application, the --repeat command doesn't work.
var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));
this.VlcControl.SourceProvider.CreatePlayer(libDirectory, new string[] { "--rtsp-tcp", "--repeat" });
string liveLink = $"rtsp://{ip}:{port}/{kid}";
this.VlcControl.SourceProvider.MediaPlayer.Play(liveLink);
already tried using the command --loop and --insert-repeat=65535
Nothing works.
Can anyone suggest a solution to the issue?

// Declare a Delegate
delegate void delegate_vlc_play(Uri file, string[] pars);
// Make sure to link the Event
private void OnEndReached(object sender, Vlc.DotNet.Core.VlcMediaPlayerEndReachedEventArgs e)
{
if (_AutoLoop) // private field of externally visible Property "AutoLoop"
{
// Get a new instance of the delegate
delegate_vlc_play del_vlc = new delegate_vlc_play(myVLCControl.Play);
// Call asyncroneously (save _CurrentFile somewhere when you call the Play() in the first place)
del_vlc.BeginInvoke(new Uri(_CurrentFile), new string[] { }, null, null);
}
}
from https://github.com/ZeBobo5/Vlc.DotNet/issues/96

Related

GeckoFx 60 Download + Open File

I want the embedded GeckoFx 60 to download a file and then open it with the default app.
By default it seems like GeckoFx does not do anything when the client requests to download a file.
To handle the download request I enabled an event handler:
LauncherDialog.Download += LauncherDialog_Download;
Then I found two possibilities to download or open a file via the HelperAppLauncher.
This one saves the requested file to a temp folder and opens it:
private void LauncherDialog_Download(object sender, LauncherDialogEvent e)
{
// direct open, file will be stored in C:\Users\Username\AppData\Local\Temp\
e.HelperAppLauncher.LaunchWithApplication(null, false);
}
I did not find a way to configure the save path. This other possible solution allows me to set the save path myself:
private void LauncherDialog_Download(object sender, LauncherDialogEvent e)
{
nsILocalFileWin objTarget = Xpcom.CreateInstance<nsILocalFileWin>("#mozilla.org/file/local;1");
var downloadPath = #Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\CustomFolder\\" + e.Filename;
using (nsAString tmp = new nsAString(downloadPath))
{
objTarget.InitWithPath(tmp);
}
e.HelperAppLauncher.SaveToDisk(objTarget, false);
Task.Run(() =>
{
Thread.Sleep(3000);
System.Diagnostics.Process.Start(downloadPath);
});
}
That Task.Run() works, but is quite ugly and error prone. I could not find a better solution though. I tried adding a WebProgressListener like this:
var webProgressListener = new WebProgressListener();
webProgressListener.OnStatusChangeCallback+= OnStatusChangeCallback;
e.HelperAppLauncher.SetWebProgressListener(webProgressListener);
webProgressListener.IsListening is true, but my method OnStatusChangeCallback is never called. Am I doing something wrong? Is there a newer way?
How can I get notified that the download is completed?
Or how do I set the path for LaunchWithApplication?
Not the best solution but here is my solution :
Task.Run(() =>
{
long sizefirst = 0;
while (true)
{
Thread.Sleep(1000);
if (File.Exists(downloadPath))
{
if (sizefirst == 0)
{
sizefirst = new FileInfo(downloadPath).Length;
continue;
}
long len_now = new FileInfo(downloadPath).Length;
if (len_now > sizefirst)
{
sizefirst = len_now;
continue;
}
else
{
System.Diagnostics.Process.Start(downloadPath);
break;
}
}
}
});

System.Threading.ThreadStateException OpenFileDialog

Today, I was trying to make an adb client in C# with a decent GUI.
So, i 've done some research and found SharpAdbClient.
To do a file push, I use var file = openFileDialog2.ShowDialog(); to select a file.
But if I try pushing a big file, the GUI stops responding (how it's supposed to be).
So, to solve this issue, I've set up a thread that does the push but I've got a ThreadStateException when I try to launch the OpenFileDialog.
Here's an example code:
private void button4_Click(object sender, EventArgs e)
{
Thread pushFile = new Thread(push);
pushFile.Start();
}
private void push()
{
var device = AdbClient.Instance.GetDevices().First();
var file = openFileDialog2.ShowDialog();
var p = new Progress<int>(Progress_Bar);
String newPath = textBox2.Text;
if (file == DialogResult.OK)
{
String filePath = openFileDialog2.InitialDirectory + openFileDialog2.FileName;
using (SyncService service = new SyncService(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)), device))
using (Stream stream = File.OpenRead(filePath))
{
service.Push(stream, newPath, 444, DateTime.Now, p, CancellationToken.None);
}
}
}
You can't invoke UI-methods on threads that are not the GUI thread. You'll have to dispatch that to the correct thread. In WinForms, you'd use Invoke, BeginInvoke and similar to do that.
Have a look at the Control.Invoke documentation for more information on this.

tranfer file via bluetooth to iphone using 32feet

I am trying to transfer a file to my iphone using 32feet bluetooth, but cannot seem to get past the ObexWebResponse.
I have read many post on this but none of the solutions seem to work for me.
The Error i get is
// Connect failed
// The requested address is not valid in its context "address:Guid"
private BluetoothClient _bluetoothClient;
private BluetoothComponent _bluetoothComponent;
private List<BluetoothDeviceInfo> _inRangeBluetoothDevices;
private BluetoothDeviceInfo _hlkBoardDevice;
private EventHandler<BluetoothWin32AuthenticationEventArgs> _bluetoothAuthenticatorHandler;
private BluetoothWin32Authentication _bluetoothAuthenticator;
public BTooth() {
_bluetoothClient = new BluetoothClient();
_bluetoothComponent = new BluetoothComponent(_bluetoothClient);
_inRangeBluetoothDevices = new List<BluetoothDeviceInfo>();
_bluetoothAuthenticatorHandler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(_bluetoothAutenticator_handlePairingRequest);
_bluetoothAuthenticator = new BluetoothWin32Authentication(_bluetoothAuthenticatorHandler);
_bluetoothComponent.DiscoverDevicesProgress += _bluetoothComponent_DiscoverDevicesProgress;
_bluetoothComponent.DiscoverDevicesComplete += _bluetoothComponent_DiscoverDevicesComplete;
ConnectAsync();
}
public void ConnectAsync() {
_inRangeBluetoothDevices.Clear();
_hlkBoardDevice = null;
_bluetoothComponent.DiscoverDevicesAsync(255, true, true, true, false, null);
}
private void PairWithBoard() {
Console.WriteLine("Pairing...");
bool pairResult = BluetoothSecurity.PairRequest(_hlkBoardDevice.DeviceAddress, null);
if (pairResult) {
Console.WriteLine("Success");
Console.WriteLine($"Authenticated equals {_hlkBoardDevice.Authenticated}");
} else {
Console.WriteLine("Fail"); // Instantly fails
}
}
private void _bluetoothComponent_DiscoverDevicesProgress(object sender, DiscoverDevicesEventArgs e) { _inRangeBluetoothDevices.AddRange(e.Devices); }
private void _bluetoothComponent_DiscoverDevicesComplete(object sender, DiscoverDevicesEventArgs e) {
for (int i = 0; i < _inRangeBluetoothDevices.Count; ++i) {
if (_inRangeBluetoothDevices[i].DeviceName == "Uranus") {
_hlkBoardDevice = _inRangeBluetoothDevices[i];
PairWithBoard();
TransferFile();
return;
}
}
// no devices found
}
private void _bluetoothAutenticator_handlePairingRequest(object sender, BluetoothWin32AuthenticationEventArgs e) {
e.Confirm = true; // Never reach this line
}
// not working
// transfers a file to the phone
public void TransferFile() {
string file = "E:\\test.txt",
filename = System.IO.Path.GetFileName(file);
string deviceAddr = _hlkBoardDevice.DeviceAddress.ToString();
BluetoothAddress addr = BluetoothAddress.Parse(deviceAddr);
_bluetoothClient.Connect(BluetoothAddress.Parse(deviceAddr), BluetoothService.SerialPort);
Uri u = new Uri($"obex://{deviceAddr}/{file}");
ObexWebRequest owr = new ObexWebRequest(u);
owr.ReadFile(file);
// error:
// Connect failed
// The requested address is not valid in its context ...
var response = (ObexWebResponse)owr.GetResponse();
Console.WriteLine("Response Code: {0} (0x{0:X})", response.StatusCode);
response.Close();
}
The pairing and authentication works just fine, and I can get the BluetoothService.Handsfree to make a call for me but the transferring of the file fails. Not knowing what the actual error is, I tried almost every service available with no luck.
Can you help me figure out what is going on? This is my first attempt working with Bluetooth services so I still have a ton to learn.
Is it possible to transfer a file from iPhone to Windows desktop via Bluetooth?
However, in case you need to transfer media files (images, videos, etc) from Android device, you can use ObexListener class provided by 32Feet library for this purpose, and then you can simply call _obexListener.GetContext() method that will block and wait for incoming connections.
Once a new connection is received, you can save the received file to local storage, as shown in the below example:
ObexListener _listener = new ObexListener();
_listener.Start();
// This method will block and wait for incoming connections
ObexListenerContext _context = _listener.GetContext();
// Once new connection is received, you can save the file to local storage
_context.Request.WriteFile(#"c:\sample.jpg");
NOTE: When working with OBEX on Windows, make sure to disable the "Bluetooth OBEX Service" Windows service, in order not to let it handle the incoming OBEX requests instead of the desired application.
I walked away from this for a while. and started Trying to use xamiren but then had to create a virtual Mac so that I could have the apple store to just load software on my phone. From there xamerin 'should' work well but its another field and tons more to firgure out.

Get WebDriver of already opened Chrome Browser

I would like to have a IWebDriver of an already opened browser like Chrome. Because then I need to automate a form authentication and/or a basic authentication.
I thought that this
IWebDriver driver = new RemoteWebDriver(new System.Uri("http://localhost:4445/wd/hub"), new ChromeOptions());
would do the trick but it only opens another chrome window. Instead I would like to "read" an already opened one.
Is it possible with selenium? O r should I use another library?
As per the Selenium Issues page:
https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/18
The issue was closed and marked as not feasible
The process of connecting to an existing browser would be on a per-browser basis.
Doing it in IE might be easy, but doing it in Chrome or Firefox would be problematic.
Eg:
Chrome actually receives the commands from Selenium via network / tcp json requests to a specific port.
When Selenium driver stops running - it loses the port number for the Chrome debugging port.
The port may still be open, but it could be anything between 10000 and 30000 etc
Even if you solve it for Chrome, it would then require another bespoke solution for Firefox.
Unless your authentication has a 'Captcha' or bot check in place, I would suggest just automating the authentication stage.
Generally speaking - it is a good practice for Automated tests to be self-contained and not rely on outside interference or external tests.
A browser should start at the start of the test and be terminated at the end of the test.
Assuming you are using Selenium for testing and not for malicious purposes.
Selenium will not be helpful to you at this stage.
If however, you can live with your answer / solution being on Chrome but not the other browsers.
public static Chrome StartChromeDriver(int port)
{
try
{
string Path = Registry.Installation.GetChromeExecutable();
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo(Path);
string args = "--remote-debugging-port="+ port.ToString()+" --user-data-dir=remote-profile";
psi.Arguments = args;
psi.Verb = "runas";
p.StartInfo = psi;
p.Start();
return new Chrome("http://localhost:" + port.ToString());
}
catch (Exception ee)
{
Console.WriteLine(ee.ToString());
return null;
}
}
This will start a chrome process with the debugging port opened to the number you provide.
(You can keep track of this, and reconnect and re-issue commands to the running chrome instance)
public dynamic EnablePage()
{
json = #"{""id"":12345,""method"":""Page.enable""}";
Thread.Sleep(1000);
return this.SendCommand(json);
}
public dynamic EnableRuntime()
{
json = #"{""id"":12345,""method"":""Runtime.enable""}";
Thread.Sleep(1000);
return this.SendCommand(json);
}
public dynamic EnableNetwork()
{
json = #"{""id"":12345,""method"":""Network.enable""}";
Thread.Sleep(1000);
return this.SendCommand(json);
}
This is some code I had lying around.
I was very bored one day and decided to reinvent the wheel with Chrome automation. Basically - this code is how you could automate Chrome without using Selenium at all.
It does have a dependency on WebSockets4Net
But that being said - it could probably be refactored to use TcpClient.
All the commands that are issued to Chrome, are done in the form of a json request.
Eg: the following json command would tell chrome to execute the following javascript - essentially navigating to the url provided.
{
"method": "Runtime.evaluate",
"params": {
"expression": "document.location='urlhere'",
"objectGroup": "console",
"includeCommandLineAPI": true,
"doNotPauseOnExceptions": false,
"returnByValue": false
},
"id": 1
}
public dynamic SendCommand(string cmd)
{
if (EventHandler == null)
{
EventHandler = new Events();
EventHandler.OnNavigateStart += new Events.OnPageNavigateStart(EventHandler_OnNavigateStart);
EventHandler.OnNavigateEnd += new Events.OnPageNavigateEnded(EventHandler_OnNavigateEnd);
}
WebSocket4Net.WebSocket j = new WebSocket4Net.WebSocket(this.sessionWSEndpoint);
ManualResetEvent waitEvent = new ManualResetEvent(false);
ManualResetEvent closedEvent = new ManualResetEvent(false);
dynamic message = null;
byte[] data;
Exception exc = null;
j.Opened += delegate(System.Object o, EventArgs e)
{
j.Send(cmd);
};
j.MessageReceived += delegate(System.Object o, WebSocket4Net.MessageReceivedEventArgs e)
{
message = e.Message;
EventHandler.ParseEvents(e);
waitEvent.Set();
};
j.Error += delegate(System.Object o, SuperSocket.ClientEngine.ErrorEventArgs e)
{
exc = e.Exception;
waitEvent.Set();
};
j.Closed += delegate(System.Object o, EventArgs e)
{
closedEvent.Set();
};
j.DataReceived += delegate(object sender, WebSocket4Net.DataReceivedEventArgs e)
{
data = e.Data;
waitEvent.Set();
};
j.Open();
waitEvent.WaitOne();
if (j.State == WebSocket4Net.WebSocketState.Open)
{
j.Close();
closedEvent.WaitOne();
j = null;
}
if (exc != null)
throw exc;
serializer = null;
serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { converter });
dynamic obj = serializer.Deserialize(message, typeof(object));
message = null;
data = null;
return obj;
}
To demonstrate how this could be used practically - you can implement page-object and create 'types' that encapsulate objects on screen.
For instance:
public class Link : Base.Element
{
public Link(string XPath)
{
this.XPath = String.Copy(XPath);
}
/// <summary>
/// Overriding it - just in case we need to handle clicks differently
/// </summary>
/// <returns></returns>
public virtual bool Click()
{
Sync();
Console.WriteLine(Chrome.Driver.Eval("document.evaluate('" + XPath.Replace("'", "\\\\'") + "', document.documentElement, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ).snapshotItem(0).click();"));
return true;
}
public virtual bool WaitForExistance(int iTimeout)
{
return base.WaitForExistance(iTimeout);
}
public virtual bool Exists()
{
return base.Exists();
}
public virtual string GetText()
{
Sync();
dynamic dval = Chrome.Driver.Eval("document.evaluate('" + XPath.Replace("'", "\\\\'") + "', document.documentElement, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ).snapshotItem(0).innerText");
return dval.result.result.value;
}
}
Be warned - there were memory leaks in WebSockets4Net when I was using this code - so the application eventually had to be restarted.
Perhaps if WebSockets4Net is removed and replaced - it will work better.

Windows 10 opens "You'll need a new app to open myapp" when trying to start a process

In earlier versions of Windows (before 8 and 10). You could simply execute this piece of code:
class Program
{
static void Main(string[] args)
{
TryStart("myapp:", "https://www.google.com");
}
private static void TryStart(String url, String raw = "")
{
try
{
if (!String.IsNullOrEmpty(url))
{
Process.Start(url);
}
}
catch
{
if (!String.IsNullOrEmpty(raw))
{
Process.Start(raw);
}
}
}
}
And it would work perfectly. If the program didn't exist, it would open the webpage. If the program did exist, it would open it.
However, in Windows 8 and 10, if the program doesn't exist, you will get this message instead:
And the website would never be opened. Is there another way around this?
How about just an idea to check if the process exist and launch appropriate program as follows:
private static void TryStart(String url, String raw = "")
{
var processes = Process.GetProcessesByName(url);
if (processes!=null && processes.Any())
{
Process.Start(url);
//Process.Start(processes.First().ProcessName); //This can be used as well to start.
}
else
{
Process.Start(raw);
}
}
Okay, I have tried to run below code myself and it works in Win 10 pro. Check it out and see if this works for you.
string url = "http://stackoverflow.com";
var processes = Process.GetProcessesByName(url);
if (processes != null && processes.Any())
{
Process.Start(processes.First().ProcessName); //This can be used as well to start.
}
else
{
Process.Start(url);
}
It worked when I tried to run a registered app, even if the app was not running. And if I use url, it opens default browser.

Categories

Resources