Improve software responsiveness when slider is manipulated in windows phone - windows-phone

I have a slider in my windows phone 7.1 project. When manipulated, this slider fires an event which starts a background worker to performs several trigonometric operations.
If I move the cursor on the slider, I have a certain delay in the response although I have implement background worker cancelAsync method in manipulationstarted event, I would like more responsiveness, how can I achieve this?
Code:
private void sliderCosinus_ManipulationStarted(object sender,ManipulationStartedEventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync(); // Cancel the asynchronous operation.
}
}
private void sldCosinus_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
try
{
Value = Convert.ToInt32(sldCosinus.Value) * 10;
}
catch
{
// errore message here
}
finally
{
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
}
else
{
Dispatcher.BeginInvoke(() => app.IsEffectApplied=TrigonometricTrans()
// TrigonomtriecTrans calculate sin and cosinus for every pixel in image
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// progress bar here
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
//this.tbProgress.Text = "Canceled!";
}
else if (!(e.Error == null))
{
//this.tbProgress.Text = ("Error: " + e.Error.Message);
}
else
{
DoubleBufferToScreen();
}
}

Related

Webcam motion Detection using AForge C#

I am using code for motion detection webcam using Aforge. When running the program, it can run perfectly, but when edit libel1 "motion Detection" and libel2 "no motion Detection" it cannot running. Why?
The code I'm using for motion detection:
public Form1()
{
InitializeComponent();
}
FilterInfoCollection fic;
VideoCaptureDevice Device;
MotionDetector motionDetector;
float f;
private void Form1_Load(object sender, EventArgs e)
{
motionDetector = new MotionDetector(new TwoFramesDifferenceDetector(), new MotionAreaHighlighting());
fic = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo item in fic)
{
comboBoxDevice.Items.Add(item.Name);
}
comboBoxDevice.SelectedIndex = 0;
}
private void BtnStart_Click(object sender, EventArgs e)
{
Device = new VideoCaptureDevice(fic[comboBoxDevice.SelectedIndex].MonikerString);
videoSourcePlayer1.VideoSource = Device;
videoSourcePlayer1.Start();
}
private void BtnStop_Click(object sender, EventArgs e)
{
videoSourcePlayer1.Stop();
}
private void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
{
if (motionDetector == null) return;
f = motionDetector.ProcessFrame(image);
if (f >0)
{
label1.ForeColor = Color.Red;
label1.Text = "Motion Detected";
}
else
{
label1.ForeColor = Color.Green;
label1.Text = "No Motion Detected";
}
}
private void timer_Tick(object sender, EventArgs e)
{
label3.Text = "Value: " + f.ToString();
}
}
}
I think you want to change a label in your UI when you detect a motion. If you want to change a label in UI, you can't run the change function in the same thread. So, you can change it by defining another thread. Just make sure you prevent race conditions.
// Changing UI Labels (Make thread)
Label1.Invoke((MethodInvoker)delegate {
// What do you want to change?
Label1.Text = "Detecting Motions";
});

Playing videos with TextureViews in RecyclerView, like Vine

I have a RecyclerView and each ViewHolder of the RecyclerView has a MediaPlayer object. I am using a TextureView to hold the MediaPlayer objects, the issue is that when i am scrolling down it is very laggy. Why is this the case? I believe I am properly deallocating the MediaPlayer objects when the surface is destroyed.
For a reference I am using the following TextureView implementation taken from this repo: TextureVideoView
TextureVideoView.java
public class TextureVideoView extends TextureView implements TextureView.SurfaceTextureListener {
// Indicate if logging is on
public static final boolean LOG_ON = true;
// Log tag
private static final String TAG = TextureVideoView.class.getName();
private MediaPlayer mMediaPlayer;
private float mVideoHeight;
private float mVideoWidth;
private boolean mIsDataSourceSet;
private boolean mIsViewAvailable;
private boolean mIsVideoPrepared;
private boolean mIsPlayCalled;
private ScaleType mScaleType;
private State mState;
public enum ScaleType {
CENTER_CROP, TOP, BOTTOM
}
public enum State {
UNINITIALIZED, PLAY, STOP, PAUSE, END
}
public TextureVideoView(Context context) {
super(context);
initView();
}
public TextureVideoView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public TextureVideoView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
private void initView() {
if (!isInEditMode()) {
initPlayer();
setScaleType(ScaleType.CENTER_CROP);
setSurfaceTextureListener(this);
}
}
public void setScaleType(ScaleType scaleType) {
mScaleType = scaleType;
}
private void updateTextureViewSize() {
float viewWidth = getWidth();
float viewHeight = getHeight();
float scaleX = 1.0f;
float scaleY = 1.0f;
if (mVideoWidth > viewWidth && mVideoHeight > viewHeight) {
scaleX = mVideoWidth / viewWidth;
scaleY = mVideoHeight / viewHeight;
} else if (mVideoWidth < viewWidth && mVideoHeight < viewHeight) {
scaleY = viewWidth / mVideoWidth;
scaleX = viewHeight / mVideoHeight;
} else if (viewWidth > mVideoWidth) {
scaleY = (viewWidth / mVideoWidth) / (viewHeight / mVideoHeight);
} else if (viewHeight > mVideoHeight) {
scaleX = (viewHeight / mVideoHeight) / (viewWidth / mVideoWidth);
}
// Calculate pivot points, in our case crop from center
int pivotPointX;
int pivotPointY;
switch (mScaleType) {
case TOP:
pivotPointX = 0;
pivotPointY = 0;
break;
case BOTTOM:
pivotPointX = (int) (viewWidth);
pivotPointY = (int) (viewHeight);
break;
case CENTER_CROP:
pivotPointX = (int) (viewWidth / 2);
pivotPointY = (int) (viewHeight / 2);
break;
default:
pivotPointX = (int) (viewWidth / 2);
pivotPointY = (int) (viewHeight / 2);
break;
}
Matrix matrix = new Matrix();
matrix.setScale(scaleX, scaleY, pivotPointX, pivotPointY);
setTransform(matrix);
}
private void initPlayer() {
if (mMediaPlayer == null) {
mMediaPlayer = new MediaPlayer();
} else {
mMediaPlayer.reset();
}
mIsVideoPrepared = false;
mIsPlayCalled = false;
mState = State.UNINITIALIZED;
}
/**
* #see android.media.MediaPlayer#setDataSource(String)
*/
public void setDataSource(final String path) {
initPlayer();
((Activity) getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
try {
mMediaPlayer.setDataSource(path);
} catch (IOException e) {
e.printStackTrace();
}
}
});
mIsDataSourceSet = true;
prepare();
}
/**
* #see android.media.MediaPlayer#setDataSource(android.content.Context, android.net.Uri)
*/
public void setDataSource(Context context, Uri uri) {
initPlayer();
try {
mMediaPlayer.setDataSource(context, uri);
mIsDataSourceSet = true;
//prepare();
mMediaPlayer.setWakeMode(context.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
/**
* #see android.media.MediaPlayer#setDataSource(java.io.FileDescriptor)
*/
public void setDataSource(AssetFileDescriptor afd) {
initPlayer();
try {
long startOffset = afd.getStartOffset();
long length = afd.getLength();
mMediaPlayer.setDataSource(afd.getFileDescriptor(), startOffset, length);
mIsDataSourceSet = true;
prepare();
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
private void prepare() {
try {
// Adjust the size of the MediaPlayer based on the Screen Resolution
mMediaPlayer.setOnVideoSizeChangedListener(
new MediaPlayer.OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
mVideoWidth = width * metrics.density;
mVideoHeight = height * metrics.density;
updateTextureViewSize();
}
}
);
// Add a completion listener for when video ends and pass it to the listener
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mState = State.END;
if (mListener != null) {
mListener.onVideoEnd();
}
}
});
// don't forget to call MediaPlayer.prepareAsync() method when you use constructor for
// creating MediaPlayer
mMediaPlayer.prepareAsync();
// Play video when the media source is ready for playback.
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mIsVideoPrepared = true;
if (mIsPlayCalled && mIsViewAvailable) {
log("Player is prepared and play() was called.");
play();
}
if (mListener != null) {
mListener.onVideoPrepared();
}
}
});
} catch (IllegalArgumentException e) {
Log.d(TAG, "IllegalArgumentException");
Log.d(TAG, e.getMessage());
} catch (SecurityException e) {
Log.d(TAG, "SecurityException");
Log.d(TAG, e.getMessage());
} catch (IllegalStateException e) {
Log.d(TAG, "IllegalStateException");
Log.d(TAG, e.toString());
}
}
/**
* Play or resume video. Video will be played as soon as view is available and media player is
* prepared.
* <p/>
* If video is stopped or ended and play() method was called, video will start over.
*/
public void play() {
if (!mIsDataSourceSet) {
log("play() was called but data source was not set.");
return;
}
mIsPlayCalled = true;
if (!mIsVideoPrepared) {
log("play() was called but video is not prepared yet, waiting.");
return;
}
if (!mIsViewAvailable) {
log("play() was called but view is not available yet, waiting.");
return;
}
if (mState == State.PLAY) {
log("play() was called but video is already playing.");
return;
}
if (mState == State.PAUSE) {
log("play() was called but video is paused, resuming.");
mState = State.PLAY;
mMediaPlayer.start();
return;
}
if (mState == State.END || mState == State.STOP) {
log("play() was called but video already ended, starting over.");
mState = State.PLAY;
mMediaPlayer.seekTo(0);
mMediaPlayer.start();
return;
}
mState = State.PLAY;
mMediaPlayer.start();
}
/**
* Pause video. If video is already paused, stopped or ended nothing will happen.
*/
public void pause() {
if (mState == State.PAUSE) {
log("pause() was called but video already paused.");
return;
}
if (mState == State.STOP) {
log("pause() was called but video already stopped.");
return;
}
if (mState == State.END) {
log("pause() was called but video already ended.");
return;
}
mState = State.PAUSE;
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
}
/**
* Stop video (pause and seek to beginning). If video is already stopped or ended nothing will
* happen.
*/
public void stop() {
if (mState == State.UNINITIALIZED) {
log("stop() was called but video already released.");
}
if (mState == State.STOP) {
log("stop() was called but video already stopped.");
return;
}
if (mState == State.END) {
log("stop() was called but video already ended.");
return;
}
mState = State.STOP;
if (mMediaPlayer.isPlaying()) {
Log.d(TAG, "MediaPlayer is playing");
mMediaPlayer.pause();
mMediaPlayer.seekTo(0);
mMediaPlayer.stop();
}
}
/**
* Reset the video (only if the video has been stopped). This will reset the mediaplayer, else
* nothing happens
*/
public void reset() {
if (mState == State.PLAY) {
log("reset() was called but video is currently playing.");
return;
}
if (mState == State.PAUSE) {
log("reset() was called but video is currently paused.");
return;
}
if (mState == State.STOP) {
mMediaPlayer.reset();
}
}
public void release() {
if (mState == State.PLAY) {
log("release() was called but video is currently playing.");
return;
}
if (mState == State.PAUSE) {
log("release() was called but video is currently paused.");
return;
}
if (mState == State.STOP) {
log("release() was called but video is currently stopped.");
return;
}
mMediaPlayer.release();
mMediaPlayer = null;
mState = State.UNINITIALIZED;
}
/**
* #see android.media.MediaPlayer#setLooping(boolean)
*/
public void setLooping(boolean looping) {
Log.d(TAG, "Looping");
mMediaPlayer.setLooping(looping);
}
/**
* #see android.media.MediaPlayer#seekTo(int)
*/
public void seekTo(int milliseconds) {
mMediaPlayer.seekTo(milliseconds);
}
/**
* #see android.media.MediaPlayer#getDuration()
*/
public int getDuration() {
return mMediaPlayer.getDuration();
}
static void log(String message) {
if (LOG_ON) {
Log.d(TAG, message);
}
}
private MediaPlayerListener mListener;
/**
* Listener trigger 'onVideoPrepared' and `onVideoEnd` events
*/
public void setListener(MediaPlayerListener listener) {
mListener = listener;
}
public interface MediaPlayerListener {
void onVideoPrepared();
void onVideoEnd();
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
Surface surface = new Surface(surfaceTexture);
mMediaPlayer.setSurface(surface);
mIsViewAvailable = true;
if (mIsDataSourceSet && mIsPlayCalled && mIsVideoPrepared) {
play();
}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
// Deallocate MediaPlayer
if (mMediaPlayer != null) {
mMediaPlayer.pause();
mMediaPlayer.stop();
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
}
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
}
When I get an asset downloaded I serve it inside my adapter like so:
final TextureVideoView videoView = holder.videoview;
videoView.setDataSource(path);
videoView.setLooping(true);
videoView.setScaleType(TextureVideoView.ScaleType.CENTER_CROP);
videoView.play();
The issue is that when I am scrolling it is really laggy, how can I fix this? How can I make a RecyclerView like Vine where the TextureView pauses unless the view is mostly visible.
Looking for a very thorough answer to this question and good optimized implementation.

How to hide rows while editing a specific row from the user in gridview

I have a web application which is connected to SQL server management studio.
I have one problem to finish my application.
In my gridview users are able to edit their own reservation, but once i reach update part for the gridview it shows me that the users are able to edit the other reservation and here are some images to show you the meaning of this:
1) this the code in my gridview events
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if ((row.Cells[9].Text.Trim()).Equals(HttpContext.Current.User.Identity.Name) == false)
{
//row.BackColor = Color.Red;
row.Cells[0].Controls.Clear();
}
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Label1.Text = "Changed";
GridViewRow selectedRow = GridView1.Rows[e.NewEditIndex];
foreach (GridViewRow row in GridView1.Rows)
{
int currentIndex = row.RowIndex;
if (currentIndex != e.NewEditIndex)
{
row.Visible = false;
}
}
}
}
2) this is to show you that user can edit only their own reservation
so how can i solve this ?
I have updated GridView's RowEditing event:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
// Bind Grid Again Here
}

ContentSharingModality ContentAdded event is not getting triggered (Lync silverlight application)

My ultimate aim is to transfer a file from one Lync client to another. I have following code.
First of all I have following 2 events registered
1.
((Modality)_conversation.Modalities[ModalityTypes.ContentSharing]).ModalityStateChanged += Modality_ModalityStateChanged;
2.
((ContentSharingModality)_conversation.Modalities[ModalityTypes.ContentSharing]).ContentAdded += _sharingModality_ContentAdded;
code for those event is
void _sharingModality_ContentAdded(object sender, ContentCollectionChangedEventArgs e)
{
MessageBox.Show("content added\n"+e.Item);
}
void Modality_ModalityStateChanged(object sender, ModalityStateChangedEventArgs e)
{
if (e.NewState == ModalityState.Connected)
{
textBox1.Text += "\nconnected";
send_file();
}
if (e.NewState == ModalityState.Connecting)
{
textBox1.Text += "\nconnecting";
}
}
Then I have a method which creates a file in isolated storage named "abc.txt".
Next there is a code which connects the content sharing modality.
private void button4_Click(object sender, RoutedEventArgs e)
{
if (_conversation.State == ConversationState.Active)
{
((Modality)_conversation.Modalities[ModalityTypes.ContentSharing])
.BeginConnect((ar) =>{((Modality)_conversation.Modalities[ModalityTypes.ContentSharing]).EndConnect(ar); }
, null);
else { MessageBox.Show("conversation not active"); }
}
After this there is 'send_file' method which actually upload the file. (this method id previously called when modality state changes to 'connected' but there (I think) conversation changes to multiparty and method returns false at 'canInvoke' statement. So Im calling it again and this time it succeeds. It is as below
void send_file()
{
if (((ContentSharingModality)_conversation.Modalities[ModalityTypes.ContentSharing]).State == ModalityState.Connected)
{
try
{
if (((ContentSharingModality)_conversation.Modalities[ModalityTypes.ContentSharing]).CanInvoke(ModalityAction.CreateShareableNativeFileOnlyContent))
{
ContentSharingModality contentSharingModality = (ContentSharingModality)_conversation.Modalities[ModalityTypes.ContentSharing];
contentSharingModality.BeginCreateContentFromFile(ShareableContentType.NativeFile, "samplefile.txt", fileNameFromIsolatedStorage, true,
(ar) =>
{
ShareableContent sContent = contentSharingModality.EndCreateContentFromFile(ar);
//_NativeFileNameAndPath = string.Empty;
sContent.Upload();
}
, null);
MessageBox.Show("upload done");
}
else { MessageBox.Show("u cannot invoke"); }
}
catch (Exception e1) { MessageBox.Show(e1.Message); }
}
else { MessageBox.Show("modality inactive"); }
}
Finally this is all I'm trying to do. The same code will lie on both sender & receiver machines. I'm new to lync development and very confused about what is going wrong. Please help. Thanks!

Show back button in charm settings with my privacy page in windows store apps

I have a code which show privacy policy URL in charm settings bar.But what I need is like when user clicks on the privacy policy link it should open another page in charm settings with a back button.How to do the same in the below code
private async void OpenPrivacyPolicy(IUICommand command)
{
Uri uri = new Uri("https://sites.google.com/site/mysite/");
await Windows.System.Launcher.LaunchUriAsync(uri);
}
Finally I figured out the solution,thanks to windows 8.1 Appsetting sample app . First of all add a settingsFlyout XAML page to your project.I added the privacy flyout code in my app's home page like this
protected override void OnNavigatedTo(NavigationEventArgs e)
{
SettingsPane.GetForCurrentView().CommandsRequested += onCommandsRequested;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
SettingsPane.GetForCurrentView().CommandsRequested -= onCommandsRequested;
}
void onCommandsRequested(SettingsPane settingsPane, SettingsPaneCommandsRequestedEventArgs e)
{
SettingsCommand defaultsCommand = new SettingsCommand("Privacy", "Privacy",
(handler) =>
{
Privacy sf = new Privacy();
sf.Show();
});
e.Request.ApplicationCommands.Add(defaultsCommand);
}
then in my Privacy.xaml page I added the following code
public Privacy()
{
this.InitializeComponent();
this.Loaded += (sender, e) =>
{
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += SettingsFlyout1_AcceleratorKeyActivated;
};
this.Unloaded += (sender, e) =>
{
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated -= SettingsFlyout1_AcceleratorKeyActivated;
};
}
void SettingsFlyout1_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs args)
{
// Only investigate further when Left is pressed
if (args.EventType == CoreAcceleratorKeyEventType.SystemKeyDown &&
args.VirtualKey == VirtualKey.Left)
{
var coreWindow = Window.Current.CoreWindow;
var downState = CoreVirtualKeyStates.Down;
bool menuKey = (coreWindow.GetKeyState(VirtualKey.Menu) & downState) == downState;
bool controlKey = (coreWindow.GetKeyState(VirtualKey.Control) & downState) == downState;
bool shiftKey = (coreWindow.GetKeyState(VirtualKey.Shift) & downState) == downState;
if (menuKey && !controlKey && !shiftKey)
{
args.Handled = true;
this.Hide();
}
}
}
Thanks for all the help everyone! And this code works!If anyone facing difficulty just hit me ;)