Duplicated output from process.OutputDataReceived - process

I'm having an issue with duplicated content from redirected output.
In my forms I have two buttons: Run and Clear.
public partial class BatchRun : Form
{
Process process = new Process();
public BatchRun()
{
InitializeComponent();
}
private void RunBTN_Click(object sender, EventArgs e)
{
//initiate the process
this.process.StartInfo.FileName = sMasterBATname;
this.process.StartInfo.UseShellExecute = false;
this.process.StartInfo.CreateNoWindow = true;
this.process.StartInfo.RedirectStandardOutput = true;
this.process.OutputDataReceived += new DataReceivedEventHandler(StandardOutputHandler);
this.process.StartInfo.RedirectStandardInput = true;
this.process.Start();
this.process.BeginOutputReadLine();
}
public void StandardOutputHandler(object sender, DataReceivedEventArgs outLine)
{
BeginInvoke(new MethodInvoker(() =>
{
Label TestLBL = new Label();
TestLBL.Text = text.TrimStart();
TestLBL.AutoSize = true;
TestLBL.Location = new Point(10, CMDpanel.AutoScrollPosition.Y + CMDpanel.Controls.Count * 20);
CMDpanel.Controls.Add(TestLBL);
CMDpanel.AutoScrollPosition = new Point(10, CMDpanel.Controls.Count * 20);
}));
}
private void ClearBTN_Click(object sender, EventArgs e)
{
CMDpanel.Controls.Clear();
this.process.CancelOutputRead();
this.process.Close();
this.process.Refresh();
}
}
This works great if I want to run process only once i.e. close the forms once process has completed.
However, I need to allow user to rerun the same process or run a new one hence I have added a clear button the clear various controls etc.
The problem I'm having is that after clicking clear button, I want to click run button again without closing which should then run the sMAsterBAT file(CMD).
StandardOutputHandler seems to be including content of the previous run as well as the new one resulting in duplicated labels in my CMDpanel.
Is this stored in some kind of buffer? If so, How do i clear it to allow me a rerun?
Could someone explain why this is happening and how to resolve it please.

Spoke to someone at work who fixed it for me. So easy lol
private void ClearBTN_Click(object sender, EventArgs e)
{
CMDpanel.Controls.Clear();
this.process.CancelOutputRead();
this.process.Close();
this.process.Refresh();
this.process = new Process(); // this line resolved my issue!!
}
}

Related

How to block popups in cefsharp browser in vb.net project/ NOT c sharp

i have been looking for a while now, i have found a solution in csharp , but i couldn't translate it (implement it in my vb.net app).
My only aim is that when the user clicks a link no popups appear.
thank you for your help.
My vb.net coding skill is beginner level, c sharp no knowledge.
the working solution in c sharp:
using CefSharp;
using CefSharp.WinForms;
namespace popup_cefsharp
{
public partial class frm_main : Form
{
public frm_main()
{
InitializeComponent();
}
//variable
ChromiumWebBrowser chrome, chrome_popup;
private void initialize_browser()
{
try
{
CefSettings settings = new CefSettings();
Cef.Initialize(settings);
//main browser
chrome = new ChromiumWebBrowser(this.txt_url.Text.Trim());
LifespanHandler life = new LifespanHandler();
chrome.LifeSpanHandler = life;
life.popup_request += life_popup_request;
this.pan_container.Controls.Add(chrome);
chrome.Dock = DockStyle.Fill;
//second browser (popup browser)
chrome_popup = new ChromiumWebBrowser("");
this.pan_container_popup.Controls.Add(chrome_popup);
chrome_popup.Dock = DockStyle.Fill;
}
catch (Exception ex)
{
MessageBox.Show("Error in initializing the browser. Error: " + ex.Message);
}
}
private void carregar_popup_new_browser(string url)
{
//open pop up in second browser
chrome_popup.Load(url);
}
private void frm_main_FormClosing(object sender, FormClosingEventArgs e)
{
//close o object cef
Cef.Shutdown();
Application.Exit();
}
private void frm_main_Load(object sender, EventArgs e)
{
//initialize the browser
this.initialize_browser();
}
private void life_popup_request(string obj)
{
//function for open pop up in a new browser
this.carregar_popup_new_browser(obj);
}
}
}
link original post: https://www.codeproject.com/Articles/1194609/Capturing-a-pop-up-window-using-LifeSpanHandler-an
finally found the solution , if anyone is interested
here is the link, you will need to install the cefsharp nuggets packages, add lifespanhandler as a new class, the file is in the link, then copy the method to call the function from the mainform...
cheers...
https://github.com/messi06/vb.net_CefSharp_popup

Trying to stop SpeechSynthesizer in uwp on click of a button

I'm trying to stop SpeechSynthesizer in uwp on click of a button and also trying to start SpeechSynthesizer on clicking same icon again.Any Help would be appreciated for resolution of this issue.
XAML
<Image x:Name="Sound" Source="ABCD/sound_active.png"
RelativePanel.AlignBottomWithPanel="True"
RelativePanel.RightOf="Pause" Tapped="SoundTap"
Margin="17,0,0,0"
Width="40" Height="40"/>
C# code
private void SoundTap(object sender, TappedRoutedEventArgs e)
{
if ((Sound.Source as BitmapImage).UriSource == new Uri("ms-appx:///ABCD/Sound_active.png", UriKind.Absolute))
{
Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_mute.png"));
textToSpeech.Stop();
}
else
{
Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_active.png"));
textToSpeech.Play();
}
}
public async void Prevevent(object sender, TappedRoutedEventArgs e)
{
currentIndex--;
if (currentIndex < 0)
{
currentIndex = 0;
return;
}
Alph_cap.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Cap_alpha/Cap_" + currentIndex + ".png"));
Alph_small.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Cap_alpha/Sml_" + currentIndex + ".png"));
CapAlphaName.Text = CapsAlpha[currentIndex];
SmallAlphaName.Text = SmallAlpha[currentIndex];
var speechText = this.CapAlphaName.Text;
if (speechText != "")
{
var synth = new SpeechSynthesizer();
var speechStream =await synth.SynthesizeTextToStreamAsync(speechText);
this.textToSpeech.AutoPlay = true;
this.textToSpeech.SetSource(speechStream, speechStream.ContentType);
this.textToSpeech.Play();
}
}
Understanding the question:
Basically you're looking for a toggle switch to turn on and turn off the speech synthesis tts(Text to Speech) in simpler terms.
The Solution:
This couldn't have been simpler enough, never the less, this is how you do it.
Create a Bool property, eg: private IsTTSEnabled = false we'll use this as a flag.
On your Image tap or click, check the current value of IsTTSEnabled and flip it (false if true or true if false) eg: IsTTSEnable = !IsTTSEnable;
Now put a if loop for handling if the TTS is turned on or if it's turned off. Also, since TTS is done using a media element, you don't need to reInitialize your TTS, simple pause and play your media element or start and Stop it as per needs.
So your c# code becomes:
private bool IsTTSEnabled = false;
private void SoundTap(object sender, TappedRoutedEventArgs e)
{
IsTTSEnabled = !IsTTSEnabled;
if(IsTTSEnabled)
{
Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_mute.png"));
textToSpeech.Stop();
}
else
{
Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_active.png"));
textToSpeech.Play();
}
}
Note: This functionality can be easily implemented using Data Binding to provide scalability and ease of management but then the simpler way to do so is like the one I've illustrated

UCMA 3.0 - Recording an incoming call

I am new to UCMA and I am learning as I go through examples. I am trying to build 2 Lync clients A and B with the scenario as follows,
A calls B
B answers
A plays audio
B records it using Recorder.
I am stuck at trying to record the call at B. For B its an incoming call. I need to attach the audiovideoflow to the recorder, but I am not sure on how to do it. I will appreciate any help.
Apologies on the unformatted code, I am not sure how to format it properly, I tried.
Thanks.
Kris
Client B Code:
Accepts an incoming call
Records the media received in the incoming call. ***This is the part I have trouble
using System;
using System.Threading;
using Microsoft.Rtc.Collaboration;
using Microsoft.Rtc.Collaboration.AudioVideo;
using Microsoft.Rtc.Signaling;
using Microsoft.Rtc.Collaboration.Lync;
namespace Microsoft.Rtc.Collaboration.LyncUAS
{
public class LyncUAS
{
#region Locals
private LyncUASConfigurationHelper _helper;
private UserEndpoint _userEndpoint;
private AudioVideoCall _audioVideoCall;
private AudioVideoFlow _audioVideoFlow;
private Conversation _incomingConversation;
//Wait handles are only present to keep things synchronous and easy to read.
private AutoResetEvent _autoResetEvent = new AutoResetEvent(false);
private EventHandler<AudioVideoFlowConfigurationRequestedEventArgs> _audioVideoFlowConfigurationRequestedEventHandler;
private EventHandler<MediaFlowStateChangedEventArgs> _audioVideoFlowStateChangedEventHandler;
private AutoResetEvent _waitForAudioVideoCallEstablishCompleted = new AutoResetEvent(false);
private AutoResetEvent _waitForAudioVideoFlowStateChangedToActiveCompleted = new AutoResetEvent(false);
private AutoResetEvent _waitForPrepareSourceCompleted = new AutoResetEvent(false);
#endregion
#region Methods
/// <summary>
/// Instantiate and run the DeclineIncomingCall quickstart.
/// </summary>
/// <param name="args">unused</param>
public static void Main(string[] args)
{
LyncUAS lyncUAS = new LyncUAS();
lyncUAS.Run();
}
private void Run()
{
string filename = "received.wma";
_helper = new LyncUASConfigurationHelper();
// Create a user endpoint, using the network credential object
// defined above.
_userEndpoint = _helper.CreateEstablishedUserEndpoint("Lync UAS" /*endpointFriendlyName*/);
_userEndpoint.RegisterForIncomingCall<AudioVideoCall>(On_AudioVideoCall_Received);
Console.WriteLine("Waiting for incoming call...");
_autoResetEvent.WaitOne();
Console.WriteLine("came after call is connected");
//start recording for audio.
Recorder recorder = new Recorder();
recorder.StateChanged += new EventHandler<RecorderStateChangedEventArgs>(recorder_StateChanged);
recorder.VoiceActivityChanged += new EventHandler<VoiceActivityChangedEventArgs>(recorder_VoiceActivityChanged);
//**********This is the issue, currently _audioVideoFlow is null, it is not attached to the flow
//So this will fail, how to attach _audioVideoFlow to an incoming call ?? HELP !!!
// recorder.AttachFlow(_audioVideoFlow); ------------> HELP!
WmaFileSink sink = new WmaFileSink(filename);
recorder.SetSink(sink);
recorder.Start();
Console.WriteLine("Started Recording ...");
_autoResetEvent.WaitOne();
recorder.Stop();
Console.WriteLine("Stopped Recording ...");
recorder.DetachFlow();
Console.WriteLine("Exiting");
Thread.Sleep(2000);
}
private void audioVideoFlow_StateChanged(object sender, MediaFlowStateChangedEventArgs e)
{
Console.WriteLine("Flow state changed from " + e.PreviousState + " to " + e.State);
//When flow is active, media operations can begin
if (e.State == MediaFlowState.Active)
{
// Flow-related media operations normally begin here.
_waitForAudioVideoFlowStateChangedToActiveCompleted.Set();
}
// call sample event handler
if (_audioVideoFlowStateChangedEventHandler != null)
{
_audioVideoFlowStateChangedEventHandler(sender, e);
}
}
void recorder_VoiceActivityChanged(object sender, VoiceActivityChangedEventArgs e)
{
Console.WriteLine("Recorder detected " + (e.IsVoice ? "voice" : "silence") + " at " + e.TimeStamp);
}
void recorder_StateChanged(object sender, RecorderStateChangedEventArgs e)
{
Console.WriteLine("Recorder state changed from " + e.PreviousState + " to " + e.State);
}
void On_AudioVideoCall_Received(object sender, CallReceivedEventArgs<AudioVideoCall> e)
{
//Type checking was done by the platform; no risk of this being any
// type other than the type expected.
_audioVideoCall = e.Call;
// Call: StateChanged: Only hooked up for logging, to show the call
// state transitions.
_audioVideoCall.StateChanged += new
EventHandler<CallStateChangedEventArgs>(_audioVideoCall_StateChanged);
_incomingConversation = new Conversation(_userEndpoint);
Console.WriteLine("Call Received! From: " + e.RemoteParticipant.Uri + " Toast is: " +e.ToastMessage.Message);
_audioVideoCall.BeginAccept(
ar =>
{
try {
_audioVideoCall.EndAccept(ar);
Console.WriteLine("Call must be connected at this point. "+_audioVideoCall.State);
_autoResetEvent.Set();
} catch (RealTimeException ex) { Console.WriteLine(ex); }
}, null);
}
//Just to record the state transitions in the console.
void _audioVideoCall_StateChanged(object sender, CallStateChangedEventArgs e)
{
Console.WriteLine("Call has changed state. The previous call state was: " + e.PreviousState +
" and the current state is: " + e.State);
if (e.State == CallState.Terminated)
{
Console.WriteLine("Shutting down");
_autoResetEvent.Set();
_helper.ShutdownPlatform();
}
}
#endregion
}
}
I think I have figured out what's not quite right here.
Your Code
// Create a user endpoint, using the network credential object
// defined above.
_userEndpoint = _helper.CreateEstablishedUserEndpoint("Lync UAS" /*endpointFriendlyName*/);
_userEndpoint.RegisterForIncomingCall<AudioVideoCall>(On_AudioVideoCall_Received);
Console.WriteLine("Waiting for incoming call...");
_autoResetEvent.WaitOne();
Console.WriteLine("came after call is connected");
//start recording for audio.
Recorder recorder = new Recorder();
recorder.StateChanged += new EventHandler<RecorderStateChangedEventArgs>(recorder_StateChanged);
recorder.VoiceActivityChanged += new EventHandler<VoiceActivityChangedEventArgs>(recorder_VoiceActivityChanged);
//**********This is the issue, currently _audioVideoFlow is null, it is not attached to the flow //So this will fail, how to attach _audioVideoFlow to an incoming call ?? HELP !!!
// recorder.AttachFlow(_audioVideoFlow); ------------> HELP!
Looking good so far. I'm assuming you're establishing and such in your CreateEstablishedUserEndpoint method, but I'm not seeing where you're getting the value for _audioVideoFlow.
I'm guessing you might be doing it elsewhere, but on the off chance that's actually where you're running into problems, here's that bit:
Simplest pattern to get AVFlow
public static void RegisterForIncomingCall(LocalEndpoint localEndpoint)
{
localEndpoint.RegisterForIncomingCall
<AudioVideoCall>(IncomingCallDelegate);
}
private static void IncomingCallDelegate(object sender, CallReceivedEventArgs<AudioVideoCall> e)
{
e.Call.AudioVideoFlowConfigurationRequested += IncomingCallOnAudioVideoFlowConfigurationRequested;
}
private static void IncomingCallOnAudioVideoFlowConfigurationRequested(object sender, AudioVideoFlowConfigurationRequestedEventArgs e)
{
AudioVideoFlow audioVideoFlow = e.Flow; // <--- There's your flow, gentleman.
}
Now, instead of registering for your incoming call, just call RegisterForIncomingCall(_userEndpoint);.
Your AVFlow will be hanging off e.Flow above, you could then pass that into your recorder: recorder.AttachFlow(e.Flow) or simply assign the flow to a field in your class and autoResetEvent.WaitOne(); and set that up where you're setting that up now.
Obviously this is a pretty naive implementation. A lot can go wrong in those few lines of code (exception handling/static event handler memory leak comes immediately to mind); don't forget to wire up events related to status changes on the conversation/call and endpoints, as well as any of the recovery related items.

background worker dont work

I want to read a text file from the Internet and I want while reading the file a picturebox, that is a gif animation, show and after the reading is finished picturebox hide.
I use background worker. I have a lable that shows the state, but when I click BtnCheck Button bg doesn't work and the lable doesn't change.
My code:
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
private void BtnCheck_Click(object sender, EventArgs e)
{
PbLoading.Visible = true;
if (backgroundWorker1.IsBusy != true)
{
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
LbleState.Text = "Reading txt File...";
webClient1 = new WebClient();
if (CheckForInternetConnection())
{
try
{
Stream stream = webClient1.OpenRead(TxtWebAdrss);
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
reader.Close();
LbleState.Text = "Reading Finished .";
}
catch
{
LbleState.Text = "Error reading";
}
}
else LbleState.Text = "Internet not connected!";
}
You may just need to do a bit more research into this class. You should perform UI changes on the UI thread.
There are three event handlers that you can use and these are,
backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
The following link should help,
http://msdn.microsoft.com/en-us/library/System.ComponentModel.BackgroundWorker(v=vs.110).aspx

How to open any specific SettingsFlyout in WinRT app

I am working on a Windows 8 metro app and having multiple SettingsFlyout items which get added by below mentioned code
SettingsCommand cmd1 = new SettingsCommand("sample", "Color Settings", (x) =>
{
// create a new instance of the flyout
SettingsFlyout settings = new SettingsFlyout();
// set the desired width. If you leave this out, you will get Narrow (346px)
// optionally change header and content background colors away from defaults (recommended)
// if using Callisto's AppManifestHelper you can grab the element from some member var you held it in
// settings.HeaderBrush = new SolidColorBrush(App.VisualElements.BackgroundColor);
settings.HeaderBrush = new SolidColorBrush(Colors.Black);
settings.HeaderText = string.Format("Color Settings", App.VisualElements.DisplayName);
settings.Background = new SolidColorBrush(_background);
settings.Margin = new Thickness(0);
// provide some logo (preferrably the smallogo the app uses)
BitmapImage bmp = new BitmapImage(App.VisualElements.SmallLogoUri);
settings.SmallLogoImageSource = bmp;
// set the content for the flyout
settings.Content = new ColorSettings();
settings.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Stretch;
// open it
settings.IsOpen = true;
// this is only for the test app and not needed
// you would not use this code in your real app
// ObjectTracker.Track(settings);
});
Currently using (SettingsPane.Show()) i can be able to show the added flyout items list but I want to programmatically open any setting Flyout item instead of opening a flyout list.
Create a new class
public class SettingsFlyout
{
private const int _width = 346;
private Popup _popup;
/// <summary>
/// Show the Flyout with the UserControl as content
/// </summary>
/// <param name="control"></param>
public void ShowFlyout(UserControl control)
{
_popup = new Popup();
_popup.Closed += OnPopupClosed;
Window.Current.Activated += OnWindowActivated;
_popup.IsLightDismissEnabled = true;
_popup.Width = _width;
_popup.Height = Window.Current.Bounds.Height;
control.Width = _width;
control.Height = Window.Current.Bounds.Height;
_popup.Child = control;
_popup.SetValue(Canvas.LeftProperty, Window.Current.Bounds.Width - _width);
_popup.SetValue(Canvas.TopProperty, 0);
_popup.IsOpen = true;
}
private void OnWindowActivated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
{
if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
{
_popup.IsOpen = false;
}
}
void OnPopupClosed(object sender, object e)
{
Window.Current.Activated -= OnWindowActivated;
}
}
In a XAML page take a button and then write the button click event.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
SettingsFlyout flyout = new SettingsFlyout();
flyout.ShowFlyout(new FlyoutContentUserControl());
}
Please note one thing FlyoutContentUserControl is the user control which you would like to show.
Credits goes to Q42.WinRT
The code you posted registers a SettingsCommands to the system settings pane. When your command is invoked from the system settings pane, you new up a SettingsFlyout instance and set IsOpen=True on it.
You just need to refactor this code to a separate method (e.g. ShowColorSettingsFlyout()), and also call that method from your Button.Click event handler. You can create a new Callisto SettingsFlyout and set IsOpen=True on it anywhere.
In App.xaml.cs add the following to register your SettingsFlyout e.g. CustomSetting ...
protected override void OnWindowCreated(WindowCreatedEventArgs args)
{
SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;
}
private void OnCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
{
args.Request.ApplicationCommands.Add(new SettingsCommand(
"Custom Setting", "Custom Setting", (handler) => ShowCustomSettingFlyout()));
}
public void ShowCustomSettingFlyout()
{
CustomSetting CustomSettingFlyout = new CustomSetting();
CustomSettingFlyout.Show();
}
Then anywhere in your code you want to programmatically open the CustomSetting flyout, call ShowCustomSettingFlyout, e.g. in the event handler for a button click...
void Button_Click_1(object sender, RoutedEventArgs e)
{
ShowCustomSettingFlyout()
}
Adapted from: Quickstart: Add app settings (XAML).