Call on an Async Task from main activity to a fragment - c#

I have an async task that needs to initilize on a button click inside my bottomsheet fragment. However when I call on the method from my bottomsheet fragment with
private async void _navigationButton_Click(object sender, EventArgs e)
{
await ((MainActivity)Activity).Routing();
}
I get the error:
CS7036 There is no argument given that corresponds to the required formal parameter 'p' of 'MainActivity.Routing(MapPoint)' Maps.
The code below is my method for getting a route when clicking on a mappoint on the map in my mainactivity.
try
{
_textToSpeech = new TextToSpeech(this, this, "com.google.android.tts");
Stop stop0 = new Stop(_startPoint) { Name = "Starting Point" };
// Stop stop1 = new Stop(_endPoint) { Name = "EndPoint" };
if (_endPoint == null)
{
await _geocoder.ReverseGeocodeAsync(p);
_endPoint = p;
RouteTask routeTask = await RouteTask.CreateAsync(_routingUri);
RouteParameters routingParameters = await routeTask.CreateDefaultParametersAsync();
List<Stop> stops = new List<Stop> { new Stop(_startPoint), new Stop(_endPoint) };
routingParameters.SetStops(stops);
RouteResult result = await routeTask.SolveRouteAsync(routingParameters);
Route firstRoute = result.Routes.First();
_routeAheadGraphic = new Graphic(firstRoute.RouteGeometry) { Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 4) };
SimpleLineSymbol(SimpleLineSymbolStyle.Dash, System.Drawing.Color.Red, 2) }; _myMapView.GraphicsOverlays[0].Graphics.Add(_routeAheadGraphic);
await _myMapView.SetViewpointGeometryAsync(firstRoute.RouteGeometry, 100);
return;
}

If the mappoint is not available in Fragment, you could define a public method in Main activity first , call Routing(mapPoint) inside that method .
Main Activity
public void MyMethod(){
Routing(mapPoint);
}
Fragment
private async void _navigationButton_Click(object sender, EventArgs e)
{
await ((MainActivity)Activity).MyMethod();
}

Related

How do I pass a 2D string array to a click event?

I am trying to pass a 2d string array as a parameter to a click event (searchButton_Click) which is generated within a click event so I can perform a search function. However, I get the error No overload for 'searchButton_Click' matches delegate 'RoutedEventHandler'.
I have tried several solutions as seen on stackoverflow and other sources but none has worked.
I'm new to C# programming, any help will be appreciated.
private string[,] LongRunningTask()
{
workSheetName = getWorkSheetName();
var sourceFile = OpenExcelFile(filePath);
var sourceWorkSheet = GetWorkSheet(sourceFile.Item1, sourceFile.Item2, workSheetName); //instantiating the object.
var doc_Max = GetDocRow_Col(sourceWorkSheet.Item1);
var maxRow_Col = GetMaxRow_Col(sourceWorkSheet.Item1, doc_Max.Item1, doc_Max.Item2);
int maxRowCount = maxRow_Col.Item1;
int maxColCount = maxRow_Col.Item2;
WriteLine("Last column with content is Row {0} ", maxRowCount);
WriteLine("Last column with content is Column {0} ", maxColCount);
var getItemsResult = getItems(sourceWorkSheet.Item1, maxRow_Col);
string[,] itemsArr = getItemsResult;
Bindng2DArrayToListview2(listview, itemsArr, maxColCount);
//enableItems();
GarbageCollector(sourceWorkSheet.Item1, sourceWorkSheet.Item2, sourceWorkSheet.Item3, sourceWorkSheet.Item4);
//searchButton.Click += (sender2, e2) => { searchButton_Click(sender2, e2, itemsArr); };
return itemsArr;
}
private async void StartTask()
{
this.progressLabel.Content = "Getting Sheets..";
try
{
await Task.Run(() => LongRunningTask());
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
this.progressLabel.Content = "Done";
}
You could put the result of LongRunningTask into a field on the class (which I assume is the Window itself), then just access that field from searchButton_Click.
For example...
public partial class TheWindow : Window
{
private string[,] LongRunningTask()
{
// Your LongRunningTask implementation.
}
private async Task StartTask()
{
progressLabel.Content = "Getting Sheets...";
try
{
_itemsArr = await Task.Run(() => LongRunningTask());
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
progressLabel.Content = "Done!";
}
private void searchButton_Click(object sender, RoutedEventArgs e)
{
if (_itemsArr == null)
{
// The field is null for some reason. You'll have to decide what to do in this case, but
// naturally you can't use it if it's null.
return;
}
// Do the search using the field _itemsArr.
}
private string[,] _itemsArr = null;
}

TLSharp Telegram API. Check phone registrered

I've got a problem with TLSharp method IsPhoneRegisteredAsync(...).
It always returns true, no matter the number I'm trying to check. Even for an input like "asdhbqaihbqwieuashdq23934327940scj0" it returns true.
Thanks for your help.
My code:
private void button1_Click(object sender, EventArgs e)
{
connectClient(SETS.API_ID, SETS.API_HASH);
}
private async void connectClient(int api_id, string api_hash)
{
client = new TelegramClient(api_id, api_hash);
api_ID_tb.Text = api_id.ToString();
api_hash_tb.Text = api_hash;
await client.ConnectAsync();
if (client.IsConnected)
{
MessageBox.Show("Connect Succefull");
}
}
async void CheckNumber(string number)
{
bool q = await client.IsPhoneRegisteredAsync(number);
MessageBox.Show(q.ToString());
}
private void numberCheckBtn_Click(object sender, EventArgs e)
{
CheckNumber(number_tb.Text);
}
Got same problem.
That`s how i solved it:
var req = new Auth.TLRequestSendCode
{
PhoneNumber = myPhone,
ApiId = ApiID,
ApiHash = ApiHash
};
var resp = await client.SendRequestAsync<Auth.TLSentCode>(req);
var phoneCodeHash = resp.PhoneCodeHash;
var isRegistered = resp.PhoneRegistered;
This is the same code as SendCodeRequestAsync (witch return only hash) but now we have access to Auth.TLSentCode.PhoneRegistered

White tests - folder browser dialog

I have problem with getting of FolderBrowserDialog in white. I think that it should be assigned as a modal window but it isn't.
FolderBrowserDialog in DialogService.cs:
public FolderBrowserResult ShowFolderbrowserDialog(string storageFolder)
{
var dialog = new FolderBrowserDialog
{
Description = storageFolder
};
var result = new FolderBrowserResult
{
Result = dialog.ShowDialog() != DialogResult.OK,
Path = dialog.SelectedPath
};
return result;
}
Method called after click on browse button:
private void OnBrowseForTargetFolder(object sender, RoutedEventArgs e)
{
var result = dialogService.ShowFolderbrowserDialog(Properties.Resources.StorageFolder);
if (result.Result) return;
Project.PathToStorage = result.Path;
completePath = string.Format("{0}\\{1}", result.Path, Guid.NewGuid());
Directory.CreateDirectory(completePath);
}
Test:
public class LoggerTests
{
private Application application;
private MainWindowPage mainWindowPage;
[TestInitialize]
public void TestInitialize()
{
application = Application.Launch(#"PML.exe");
StartBlankApplication();
}
[TestMethod]
public void StartExistingProject()
{
mainWindowPage.StartExistingProjectButton.Click();
var modalWindows = new List<Window>();
Retry.For(() =>
{
modalWindows = mainWindowPage.applicationWindow.ModalWindows();
}, TimeSpan.FromSeconds(5));
var mod = modalWindows;
}
private MainWindowPage StartBlankApplication()
{
var appWindow = application.GetWindow("PML");
mainWindowPage = new MainWindowPage(appWindow);
return mainWindowPage;
}
private NewProjectConfigurationPage ConfigureBlankProject()
{
Window secondAppWindow = null;
Retry.For(() =>
{
secondAppWindow = application.GetWindow("PML");
}, TimeSpan.FromSeconds(5));
var newProjectConfiguration = new NewProjectConfigurationPage(secondAppWindow);
newProjectConfiguration.VesselName.Text = "Test";
newProjectConfiguration.BrowseButton.Click();
return newProjectConfiguration;
}
}
In StartExistingProject method is problem that variable mod is empty. And no FolderBrowserDialog is opened. But when I run app normally everything runs OK.
Solved - There must be setted owner to modal dialog. So
var wrapper = new WindowWrapper(this);
dialog.ShowDialog(wrapper)
solved my problem.

Video recorder app in Windows Phone 8.1

I am going to write a Video Recorder app in Windows Phone 8.1 (RT).
I used the example provided in Windows Reference.
public sealed partial class CamcorderMainPage : Page
{
StatusBar StatusBarObject = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
string StatusBarHeader = "Firefly Moments";
MediaCaptureInitializationSettings _captureInitSettings;
List<Windows.Devices.Enumeration.DeviceInformation> _deviceList;
Windows.Media.MediaProperties.MediaEncodingProfile _profile;
Windows.Media.Capture.MediaCapture _mediaCapture;
bool _recording = false;
bool _previewing = false;
string NoCameraError = "No camera device is found ";
public CamcorderMainPage()
{
this.InitializeComponent();
this.Loaded += CamcorderMainPage_Loaded;
}
void CamcorderMainPage_Loaded(object sender, RoutedEventArgs e)
{
//throw new NotImplementedException();
EnumerateCameras();
}
private async void EnumerateCameras()
{
var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(
Windows.Devices.Enumeration.DeviceClass.VideoCapture);
_deviceList = new List<Windows.Devices.Enumeration.DeviceInformation>();
// Add the devices to deviceList
if (devices.Count > 0)
{
for (var i = 0; i < devices.Count; i++)
{
_deviceList.Add(devices[i]);
}
InitCaptureSettings();
InitMediaCapture();
// rootPage.NotifyUser("Initialization complete.", NotifyType.StatusMessage);
}
else
{
StatusBarObject.ProgressIndicator.Text = NoCameraError;
//rootPage.NotifyUser("No camera device is found ", NotifyType.ErrorMessage);
}
}
private void InitCaptureSettings()
{
_captureInitSettings = null;
_captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
_captureInitSettings.AudioDeviceId = "";
_captureInitSettings.VideoDeviceId = "";
_captureInitSettings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.AudioAndVideo;
_captureInitSettings.PhotoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.VideoPreview;
if (_deviceList.Count > 0)
_captureInitSettings.VideoDeviceId = _deviceList[0].Id;
}
// Create a profile.
private void CreateProfile()
{
_profile = Windows.Media.MediaProperties.MediaEncodingProfile.CreateMp4(
Windows.Media.MediaProperties.VideoEncodingQuality.Qvga);
}
// Create and initialze the MediaCapture object.
public async void InitMediaCapture()
{
_mediaCapture = null;
_mediaCapture = new Windows.Media.Capture.MediaCapture();
// Set the MediaCapture to a variable in App.xaml.cs to handle suspension.
(App.Current as App).MediaCapture = _mediaCapture;
await _mediaCapture.InitializeAsync(_captureInitSettings);
CreateProfile();
}
// Start the video capture.
private async void StartMediaCaptureSession()
{
var storageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(
"cameraCapture.mp4", Windows.Storage.CreationCollisionOption.GenerateUniqueName);
await _mediaCapture.StartRecordToStorageFileAsync(_profile, storageFile);
_recording = true;
}
// Stop the video capture.
private async void StopMediaCaptureSession()
{
await _mediaCapture.StopRecordAsync();
_recording = false;
(App.Current as App).IsRecording = false;
}
private async void ShowFireFlyStatusBar()
{
//this will show the Status Bar
Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().SetDesiredBoundsMode(ApplicationViewBoundsMode.UseVisible);
StatusBarObject.ProgressIndicator.Text = StatusBarHeader;
StatusBarObject.ProgressIndicator.ProgressValue = 0;
StatusBarObject.ForegroundColor = Colors.MintCream;
StatusBarObject.BackgroundColor = Color.FromArgb(255, 166, 62, 59);
StatusBarObject.BackgroundOpacity = .6;
await StatusBarObject.ProgressIndicator.ShowAsync();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ShowFireFlyStatusBar();
}
private void Camcorder_StartCapture_Click(object sender, RoutedEventArgs e)
{
StartMediaCaptureSession();
}
private void Camcorder_StopCapture_Click(object sender, RoutedEventArgs e)
{
StopMediaCaptureSession();
}
}
Its working fine as I am getting the video file from Photos App .
Now how to enable live preview while recording in app? Which control to use for it?
You're looking for the CaptureElement. Once you add it to your XAML, connect it to your MediaCapture object and start preview like so:
PreviewControl.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();
Have a look at the UniversalCameraSample posted on the Microsoft github page for more information. It targets Windows 10, but most of the patterns should work on 8/8.1 as well.

Why do you close the app when I change the page?

I have two List <>.
List<Musei> ListMusei;
List<Regioni> reg;
the object "Musei" has the property "Paese", while the object "Regioni" has the property "NomeProvincia".
The List "reg" is inserted in a ListView, and when pressed on an item, this method is invoked:
private void Listviewcitt_ItemClick(object sender, ItemClickEventArgs e)
{
var result = ((Regioni)e.ClickedItem).NomeProvincia.ToString();
var filtro = ListMusei.Where(x => x.Paese.Equals(result));
try
{
Frame.Navigate(typeof(PageAroundMe), filtro);
}
catch(Exception)
{
}
}
application where I always closes. I thought there was some problem in the "AroundMe", and then paste the code here:
In Page AroundMe I do this:
List<Musei> ListMusei;
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
ListMusei = (List<Musei>) e.Parameter;
List<Pushpin> push = new List<Pushpin>();
foreach (Musei SingoloMuseo in ListMusei)
{
Pushpin Pushpin pushpin1 = new ();
GeoPoint posizioneP;
try
{
MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync (SingoloMuseo.Indirizzo, null);
posizioneP result.Locations.FirstOrDefault = ().Point;
pushpin1.Name = SingoloMuseo.NomeMuseo;
pushpin1.Location = posizioneP;
push.Add (pushpin1);
}
catch (Exception)
{
continue;
}
}
Where is the problem? I can not even figure out where I will close
You can pass the parameter like
Frame.Navigate(typeof(PageAroundMe), filtro.ToList());
The invalid cast exception occurs because you are trying to cast IEnumerable type to List.

Categories