Strange in ShakeGesture Library on Windows Phone Application - c#

i've a problem with windows phone shakegesture library.
I build an application which its shaking the sound will go out and its work nicely but strange bug make me confused. I've two page of it. This is my seperated code :
void Instance_ShakeGesture1(object sender, ShakeGestureEventArgs e)
{
Stream stream = TitleContainer.OpenStream("Sounds/C.wav");
effect = SoundEffect.FromStream(stream);
effectInstance = effect.CreateInstance();
if (effectInstance.State != SoundState.Playing || effectInstance == null)
{
FrameworkDispatcher.Update();
effectInstance.Play();
}
else if (effectInstance.State == SoundState.Playing || effectInstance != null)
{
effectInstance.Stop();
}
}
void Instance_ShakeGesture2(object sender, ShakeGestureEventArgs e)
{
Stream stream = TitleContainer.OpenStream("Sounds/D.wav");
effect = SoundEffect.FromStream(stream);
effectInstance = effect.CreateInstance();
FrameworkDispatcher.Update();
if (effectInstance.State == SoundState.Stopped || effectInstance == null)
{
effectInstance.Play();
}
else if (effectInstance.State == SoundState.Playing || effectInstance != null)
{
effectInstance.Stop();
}
}
Instance_ShakeGesture1 is my procedure to play a music when its shaking in Page 1 and Instance_ShakeGesture2 in Page 2.
Strange bug was come when its shaking, if i shake page 1 Instance_ShakeGesture1 will executed after that I try move to page 2 and i shake it will execute Instance_ShakeGesture1 first and than Instance_ShakeGesture2.
The Problem was come same when i try to shake Page 2 first and than Page 1, Instance_ShakeGesture2 will execute first and Instance_ShakeGesture2 in the second.
I know this bug when i use breakpoint.
Anyone know how to solve this problem? Thanks before :)

Possibly the event Instance_ShakeGesture1 is still active when you navigate to the second page. try
Instance.ShakeEvent -= new EventHandler(Instance_ShakeGesture1);
inside the Instance_ShakeGesture1 method.

try this, it worked for me,
protected override void OnBackKeyPress(CancelEventArgs e)
{
e.Cancel = false;
ShakeGesturesHelper.Instance.ShakeGesture -= new EventHandler<ShakeGestureEventArgs>(Instance_ShakeGesture1);
}
Because you should delete the events when you leaving first page. So you can clean hakeGestureEventArgs when back key button is pressed.

Okay my bad. Didn't know that you needed it to work multiple times.
Try this and let me know if it works good:
Write the same line of code that you've added, inside the OnNavigatedFrom method and delete it from your current method('Instance_ShakeGesture2')

Related

My AdMob Ad only loading up when I navigate to another page then back

Is this because of the OnElementChanged event?
Can I load the ads when the app is starting?
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
var adView = new AdView(Context);
switch ((Element as AdBanner).Size)
{
case AdBanner.Sizes.Standardbanner:
adView.AdSize = AdSize.Banner;
break;
...
}
adView.AdUnitId = "ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx";
var requestbuilder = new AdRequest.Builder();
adView.LoadAd(requestbuilder.Build());
SetNativeControl(adView);
}
}
I able to solve same issue by setting the VerticalOptions="FillAndExpand" and HorizontalOptions="FillAndExpand"
To create a native control in OnElementChanged in a renderer, test on e.NewElement != null and Control == null:
base.OnElementChanged(e);
if (e.NewElement != null && Control == null)
{
_adView = CreateNativeControl(...);
SetNativeControl(_adView);
}
According to the renderer documentation, the OnElementChanged method "is called when the Xamarin.Forms custom control is created to render the corresponding native control".
When the App is calling the OnElementChanged method at the start of the program it doesn’t showing up any ads. Only when it called to the second time.
I can't find the reason to issue happens, but after a doze of tries I found a workaround that worked for me, I did put the below code in end of OnAppearing override:
if (!this.initialized)
{
this.initialized = true;
this.adMobView.IsVisible = false;
Task.Run(async () =>
{
await Task.Delay(delay).ConfigureAwait(false);
Device.BeginInvokeOnMainThread(() => this.adMobView.IsVisible = true);
});
}
Basically, I change the visibility of admob view to false and, after some time (test good delay values for you), I change it to true again.
That is far away from a good solution and a best one will be very welcome, but for now it worked for me and can be usefull temporarily.

Watin can't find element when running outside main thread

The problem is with the button:contains('Deal') selector, the button containing deal does exist on the page and Watin can find it without problems when running in main thread.
// Add bet, deal cards and wait for animation
private void dealCards()
{
// Start the game if chip exists
if (browser.Image(Find.BySrc(chipURL)).Exists)
{
browser.Image(Find.BySrc(chipURL)).Click();
// This is where the thread stops
browser.Button(Find.BySelector("button:contains('Deal')")).Click();
Thread.Sleep(dealCardsAnimationTime);
if (Convert.ToInt32(browser.Span(Find.ByClass("player-points")).Text) == 21)
{
consoleTextBox.AppendText("You won by blackjack.");
gameOver = true;
}
return;
}
}
Update:
Browser is a Internet Explore window that I interact with using WatiN, other than the UI changes, the problem seems to be that WatiN can't find the button.
However it's still somewhat related to multithreading, as the same code works fine without multithreading and the element that it's searching for does exist.
Update 2: Changed title and description of problem as the old one appeared to be unrelated.
Context ( in case it's necessary )
// When bet button is clicked
private void button2_Click(object sender, EventArgs e)
{
blackjackThread = new Thread(blackjackGame);
if (dealInProgress == false)
{
blackjackThread.Start();
// blackjackGame();
}
}
// Blackjack deal handler
private void blackjackGame()
{
consoleTextBox.AppendText("\r\n");
resetVariables();
dealCards();
if (gameOver == true)
{
checkResult();
dealInProgress = false;
blackjackThread.Abort();
return;
}
checkCards();
logPoints();
while (gameOver == false)
{
botAction();
}
checkResult();
dealInProgress = false;
blackjackThread.Abort();
return;
}

C# why two same thread fire same method at same time?

First of all my question is quite complicated (for me) and I try to explain.
I have a WPF application which is working with NFC tags. Couple days ago this code was worked properly but now somethings messed up.
First I have a method which is reading data from NFC tag like this:
private void NFCCard_OnCardInserted()
{
CheckCard();
}
private bool CheckCard()
{
try
{
lock (_object)
{
NFCCard.Connect(CardReader, SHARE.Shared, PROTOCOL.T0orT1);
APDUPlayer player = new APDUPlayer(ApduListFile, NFCCard);
if (nfcFunction.NFCLogin(player))
{
string TempCompanyID = "";
//--Read data
}
DateTime cartOpenedDate = Convert.ToDateTime(OpenedDate);
if (CartNo == "" || CompanyID.ToString() == "" || Convert.ToInt32(limit) <= 0 || isactive == "False" || cartOpenedDate.ToShortDateString() != DateTime.Today.ToShortDateString() || CartType == "Staff")
{
Dispatcher.BeginInvoke(new Action(delegate
{
ShowCardNo(txtCardNo, "Geçersiz Kart!");
}));
}
else
{
//-- Some internal code
}
}
}
catch (Exception exc)
{
StationSession.WriteLog("write log bla bla", exc);
}
}
Now is the funny thing when I check the threads windows of VS two same thread try to run NFCCard_OnCardInserted() method at same time.
For this reason I put lock state but the problem is this method firing two times. And its make big trouble for me because the card transaction time is being double right now (almost 3 second for some transaction. I cannot explain to people you will wait with cart at cart reader like this :/ ). By the way I check whole page for this method reference, just this code should use this method.
NFCCard.OnCardInserted += new CardInsertedEventHandler(NFCCard_OnCardInserted);
So how can I fix this problem without workaround. Because I have several page and method which is using NFC cart thread. I need to find clear way for this problem. Thanks.

Document is not ready in DocumentReady event?

I am using Awesomium 1.7.0.5 in order to load a page, fill some textboxes and click a button. I am trying to fill a textbox using an example from this thread: http://answers.awesomium.com/questions/857/webcontrol-type-in-webbrowser.html
Here is my code (I am using WPF control):
private void WbAwsOnDocumentReady(object sender, UrlEventArgs urlEventArgs)
{
if (wbAws == null || !wbAws.IsLive)
return;
//Thread.Sleep(555);
dynamic document = (JSObject)wbAws.ExecuteJavascriptWithResult("document");
if (document == null)
return;
using (document)
{
dynamic textbox = document.getElementById("email");
if (textbox == null)
return;
using (textbox)
{
textbox.value = "gaaffa";
}
}
}
It works but only with Thread.Sleep for 0.1-0.5 sec. Otherwise document is empty (not null) and/or textbox is null.
What should I do? Why it is not ready in DocumentReadyEvent?
Here is how I solved it:
WbAws.LoadingFrameCompleted += OnLoadingFrameCompleted;
WbAws.Source = new Uri("http://google.com");
private void OnLoadingFrameCompleted(...)
{
if (webView == null || !webView.IsLive ||
webView.ParentView != null || !e.IsMainFrame)
return;
LoadingFrameCompleted -= OnLoadingFrameCompleted;
// do something
}
LoadingFrameCompleted instead of DocumentReady and because it fires not only when I need it but also on app startup I subscribe to it just before navigating and unsubscribe after it. Also checking that it IsMainFrame.
edit: but with this solution it sometimes throws exception that document is not ready. So I am also waiting for it using Thread.Sleep.
Very old question. but for someone like me, who is facing this problem-
use LoadingFrameCompleted event with WebControl.IsNavigating == false and e.IsMainFrame == true condition.
if these conditions are true in this event then page is finished loading and you are ready to get HTML content.

Creating a gesture definition for a simple static gesture using Kinect - part 2

I have implemented the sample code and used the 'Joint.ID' instead of 'Joint.Type', I just need to work out whether/how this code can be continuously checked within a loop. Any advice would be much appreciated. Thanks.
Notes of advice:-
void newSensor_AllFramesReady fires when Color/Depth/Skeleton are synchronized. I'm not too sure where to place this method.
checkHand method needs to be checked every round of the thread.
Code so far:-
void newSensor_AllFramesReady(object sender, SkeletonFrameReadyEventArgs e)
{
//Get a skeleton
SkeletonFrame skeletonSet = e.SkeletonFrame;
SkeletonData skeleton = (from s in skeletonSet.Skeletons
where s.TrackingState == SkeletonTrackingState.Tracked
select s).FirstOrDefault();
if (skeleton == null)
{
return;
}
else if (skeleton != null)
{
checkHand(skeleton.Joints[JointID.Head], skeleton.Joints[JointID.HandRight], skeleton.Joints[JointID.HandLeft]);
}
}
public void checkHand(Joint head, Joint rhand, Joint lhand)
{
if (rhand.Position.X > head.Position.Y)
{
MessageBox.Show("Right hand up!");
}
else if (lhand.Position.Y > head.Position.Y)
{
MessageBox.Show("Left hand up!");
}
}
Make sure you assign newSensor_AllFramesReady as the event handler for AllFramesReady event. There's no need to put any of it in the loop. newSensor_AllFramesReady will be called 30 times a second (or whatever is kinect's refresh rate).
Kinect.AllFramesReady += new EventHandler<AllFramesReadyEventArgs>(newSensor_AllFramesReady);

Categories

Resources