Volume control for Xamarin iOS using XamarinMediaManager nuget - xamarin.forms

When playing audio using XamarinMediaManager nuget on xamarin ios, the audio is very soft even though the volume is set to maximum. This nuget package works perfectly fine for android.
I have a global variable for the player set on page load:
public IMediaManager NewPlayer { get; set; }
public AudioPage()
{
try
{
InitializeComponent();
NewPlayer = CrossMediaManager.Current;
NewPlayer.MediaItemFinished += NewPlayer_MediaItemFinished;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
DisplayAlert("Error", ex.ToString(), "Ok");
}
}
When the screen loads, the audio file is loaded to the player:
public async void SetAudioPlayer(string AudioPath)
{
try
{
if (File.Exists(AudioPath))
{
if (NewPlayer.Queue.Count > 0)
{
NewPlayer.Queue.Clear();
}
var generatedMediaItem = await CrossMediaManager.Current.Extractor.CreateMediaItem(AudioPath);
// Add media item to queue
NewPlayer.Queue.Add(generatedMediaItem);
}
}
catch (Exception ex)
{
await DisplayAlert("Error", ex.ToString(), "Ok");
}
}
This is the code for when the play button is clicked:
private async void imgPlay_Clicked(object sender, EventArgs e)
{
try
{
if (NewPlayer.Queue.MediaItems.Count > 0)
{
if (Device.RuntimePlatform == Device.iOS)
await NewPlayer.PlayQueueItem(CrossMediaManager.Current.Queue.MediaItems.Count - 1);
else
await NewPlayer.Play();
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
await DisplayAlert("Error", ex.ToString(), "Ok");
}
}

Related

I get same error in try and in catch on context.SaveChangesAsync

I have function:
private async Task<ServiceResponse> deleteCountryByAdmin(Country dataForDelete, CancellationToken cancellationToken)
{
try
{
_context.Set<Country>().Remove(dataForDelete);
_context.SaveChangesAsync(cancellationToken);
return ServiceResponse.Success(dataForDelete.Id);
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
if (sqlException.Number == 547)
{
dataForDelete.Active = false;
await _context.SaveChangesAsync(cancellationToken);
return ServiceResponse.Success(dataForDelete.Id);
}
else throw;
}
else throw;
}
}
Here I try to delete Country, but if that entry exist in another table, instead of delete I set Active property to false. Problem is that even when I enter into this part of code:
if (sqlException.Number == 547)
{
dataForDelete.Active = false;
await _context.SaveChangesAsync(cancellationToken);
return ServiceResponse.Success(dataForDelete.Id);
}
I still get error for trying to delete statement conflicted with reference constraint.

Xamarin Forms Cross Platform App Authentication with Firebase

I want to take the users email and send them a reset password request.
I haven't had any luck with the solution.
private async void ForgetPassword_Clicked(object sende, EventArgs e)
{
var authReset = new FirebaseAuthProvider(new FirebaseConfig(WebAPIkey));
try
{
var email = UserLoginEmail.Text;
var auth = await authReset.SendPasswordResetEmailAsync(UserLoginEmail.Text);
var content = await auth.GetFreshAuthAsync();
var serializedcontent = JsonConvert.SerializeObject(content);
Preferences.Set("MyFirebaseRefreshToken", serializedcontent);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
await App.Current.MainPage.DisplayAlert("Alert", "Invalid email or password", "OK");
}
}
I figured it out. But if there is a better way, please let me know
private async void ForgetPassword_Clicked(object sende, EventArgs e)
{
var authReset = new FirebaseAuthProvider(new FirebaseConfig(WebAPIkey));
try
{
var email = UserLoginEmail.Text;
var auth = authReset.SendPasswordResetEmailAsync(UserLoginEmail.Text);
await App.Current.MainPage.DisplayAlert("Alert", "Email Sent", "OK");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
await App.Current.MainPage.DisplayAlert("Alert", "Invalid email or password", "OK");
}
}

If there is data, how is the stream returning zero bytes?

I have a RXTX project that I'm working on. I have it set ups as follows:
public void doConnect(ActionEvent event)
{
String selectedPort = (String)connectTabController.portList.getValue();
System.out.println("Connecting to: " + selectedPort);
selectedPortIdentifier = (CommPortIdentifier)portMap.get(selectedPort);
CommPort commPort = null;
try
{
commPort = selectedPortIdentifier.open("AT QC ReponseTime", TIMEOUT);
serialPort = (SerialPort)commPort;
setConnected(true);
if (isConnected)
{
if (initIOStream() == true)
{
initListener();
System.out.println("Initializing listener");
connectTabController.gui_changeStatusLabel("Device Connected!");
}
}
}
catch (PortInUseException e)
{
System.out.println("Port In use! " + e.toString());
}
catch (Exception e)
{
System.out.println("Failed to open! " + e.toString());
}
}
public boolean initIOStream()
{
//return value for whether opening the streams is successful or not
boolean successful = false;
try {
//
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
writeData(RESETTPOD);
System.out.println("Writing Reset command");
successful = true;
System.out.println("IO Stream opened successfully!");
return successful;
}
catch (IOException e) {
System.out.println("I/O Streams failed to open. (" + e.toString() + ")");
return successful;
}
}
public void initListener()
{
try
{
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
}
catch (TooManyListenersException e)
{
System.out.println("Too many listeners. (" + e.toString() + ")");
}
}
That's how the connection is made, and it has a listener that's supposed to notify when data is available, which triggers the following:
#Override
public void serialEvent(SerialPortEvent evt) {
BufferedReader reader = null;
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try
{
reader = new BufferedReader(new InputStreamReader(input));
if (reader.ready())
{
fullLine = reader.readLine();
System.out.println(fullLine + "\n");
}
}
catch (Exception e)
{
System.out.println("#SerialEvent Failed to read data. (" + e.toString() + ")");
}
}
}
However, I keep getting "UNDERLYING INPUT STREAM RETURNED ZERO BYTES"
This makes no sense, since if there is nothing to read then the listener shouldnt be triggered int he first place. I tried running the app and I keep getting this error message around every 1/3 second, which corresponds to the burst-output of the device that's sending data. (which works fine in programs like PuttY)
If you are going to use the BufferedReader, take a look at the refence API document for javax.comm, CommPort and getInputStream. Then try using different settings for threshold and receive timeout.
eg).
serialPort.enableReceiveThreshold(3);
serialPort.enableReceiveTimeout(1);
https://docs.oracle.com/cd/E17802_01/products/products/javacomm/reference/api/

How to you fix this code for delegate void system.Action error?

This is my code
private void try_catch(Action method)
{
if (method == null) throw new ArgumentNullException("method");
try
{
Connect();
method();
}
catch (SqlException)
{
DisConnect();
}
catch (Exception)
{
DisConnect();
}
finally
{
DisConnect();
}
}
and this is error
Using the generic type 'System.Action' requires '1' type arguments

ASP.NET: How to persist Page State accross Pages?

I need a way to save and load the Page State in a persistent manner (Session). The Project i need this for is an Intranet Web Application which has several Configuration Pages and some of them need a Confirmation if they are about to be saved. The Confirmation Page has to be a seperate Page. The use of JavaScript is not possible due to limitations i am bound to. This is what i could come up with so far:
ConfirmationRequest:
[Serializable]
public class ConfirmationRequest
{
private Uri _url;
public Uri Url
{ get { return _url; } }
private byte[] _data;
public byte[] Data
{ get { return _data; } }
public ConfirmationRequest(Uri url, byte[] data)
{
_url = url;
_data = data;
}
}
ConfirmationResponse:
[Serializable]
public class ConfirmationResponse
{
private ConfirmationRequest _request;
public ConfirmationRequest Request
{ get { return _request; } }
private ConfirmationResult _result = ConfirmationResult.None;
public ConfirmationResult Result
{ get { return _result; } }
public ConfirmationResponse(ConfirmationRequest request, ConfirmationResult result)
{
_request = request;
_result = result;
}
}
public enum ConfirmationResult { Denied = -1, None = 0, Granted = 1 }
Confirmation.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer != null)
{
string key = "Confirmation:" + Request.UrlReferrer.PathAndQuery;
if (Session[key] != null)
{
ConfirmationRequest confirmationRequest = Session[key] as ConfirmationRequest;
if (confirmationRequest != null)
{
Session[key] = new ConfirmationResponse(confirmationRequest, ConfirmationResult.Granted);
Response.Redirect(confirmationRequest.Url.PathAndQuery, false);
}
}
}
}
PageToConfirm.aspx:
private bool _confirmationRequired = false;
protected void btnSave_Click(object sender, EventArgs e)
{
_confirmationRequired = true;
Response.Redirect("Confirmation.aspx", false);
}
protected override void SavePageStateToPersistenceMedium(object state)
{
if (_confirmationRequired)
{
using (MemoryStream stream = new MemoryStream())
{
LosFormatter formatter = new LosFormatter();
formatter.Serialize(stream, state);
stream.Flush();
Session["Confirmation:" + Request.UrlReferrer.PathAndQuery] = new ConfirmationRequest(Request.UrlReferrer, stream.ToArray());
}
}
base.SavePageStateToPersistenceMedium(state);
}
I can't seem to find a way to load the Page State after being redirected from the Confirmation.aspx to the PageToConfirm.aspx, can anyone help me out on this one?
If you mean view state, try using Server.Transfer instead of Response.Redirect.
If you set the preserveForm parameter
to true, the target page will be able
to access the view state of the
previous page by using the
PreviousPage property.
use this code this works fine form me
public class BasePage
{
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Save the last search and if there is no new search parameter
//Load the old viewstate
try
{ //Define name of the pages for u wanted to maintain page state.
List<string> pageList = new List<string> { "Page1", "Page2"
};
bool IsPageAvailbleInList = false;
foreach (string page in pageList)
{
if (this.Title.Equals(page))
{
IsPageAvailbleInList = true;
break;
}
}
if (!IsPostBack && Session[this + "State"] != null)
{
if (IsPageAvailbleInList)
{
NameValueCollection formValues = (NameValueCollection)Session[this + "State"];
String[] keysArray = formValues.AllKeys;
if (keysArray.Length > 0)
{
for (int i = 0; i < keysArray.Length; i++)
{
Control currentControl = new Control();
currentControl = Page.FindControl(keysArray[i]);
if (currentControl != null)
{
if (currentControl.GetType() == typeof(System.Web.UI.WebControls.TextBox))
((TextBox)currentControl).Text = formValues[keysArray[i]];
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
((DropDownList)currentControl).SelectedValue = formValues[keysArray[i]].Trim();
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.CheckBox))
{
if (formValues[keysArray[i]].Equals("on"))
((CheckBox)currentControl).Checked = true;
}
}
}
}
}
}
if (Page.IsPostBack && IsPageAvailbleInList)
{
Session[this + "State"] = Request.Form;
}
}
catch (Exception ex)
{
LogHelper.PrintError(string.Format("Error occured while loading {0}", this), ex);
Master.ShowMessageBox(enMessageType.Error, ErrorMessage.GENERIC_MESSAGE);
}
}
}

Resources