Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all 204402 articles
Browse latest View live

Xamarin new release in vs 2015 problem

$
0
0

I have update to xamarin 4.8.0.752. Every time i'm opening vs 2015 i'm getting this problem.
I get many bugs in my projects and also it asks always for update the same version what is going on?


AppSettings Reader for Xamarin and Xamarin.Forms

$
0
0

Reading app.config files in a Xamarin.Forms Xaml project

While each mobile platforms do offer their own settings management api, there are no built in ways to read settings from a good old .net style app.config xml file; This is due to a bunch of good reasons reasons, notably the .net framework configuration management api being on the heavyweight side, and each platform having their own file system api.

So we built a simple PCLAppConfig library nicely nuget packaged for your immediate consumption.

This library makes use of the lovely PCLStorage library

This example assumes you are developing a Xamarin.Forms Xaml project, where you would need to access settings from your shared viewmodel.

FOR FILESYSTEM APP.CONFIG

Initialize ConfigurationManager.AppSettings on each of your platform project, just after the ‘Xamarin.Forms.Forms.Init’ statement, as per below:
iOS (AppDelegate.cs)

Xamarin.Forms.Forms.Init();
ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);
LoadApplication(new App());

Android (MainActivity.cs)

Xamarin.Forms.Forms.Init(this, bundle);
ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);
LoadApplication(new App());

UWP / Windows 8.1 / WP 8.1 (App.xaml.cs)

Xamarin.Forms.Forms.Init(e);
ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);
LoadApplication(new App());

Add an app.config file to your shared PCL project, and add your appSettings entries, as you would do with any app.config file

<configuration>
  <appSettings>
    <add key="config.text" value="hello from app.settings!" />
  </appSettings>
</configuration>

Add this PCL app.config file as a linked file on all your platform projects. For android, make sure to set the build action to ‘AndroidAsset’, for UWP set the build action to ‘Content’
Access your setting:

ConfigurationManager.AppSettings["config.text"];

FOR EMBEDDED APP.CONFIG

Initialize ConfigurationManager.AppSettings on your pcl project like below:

Assembly assembly = typeof(App).GetTypeInfo().Assembly;
ConfigurationManager.AppSettings = new ConfigurationManager(assembly.GetManifestResourceStream("DemoApp.App.config")).GetAppSettings;

Add an app.config on your shared pcl project and ensure that Build Action:EmbeddedResource, and add your appSettings entries, as you would do with any app.config
The source code and demo app are available in github

Toolbar elevation

$
0
0

Hi,

(I've seen this issue in other posts, but no good solution or explanation to this problem)

I have a toolbar that gets an elevation in a custom renderer (android) and displays a shadow just as expected. However, when I place a contentview just below the toolbar with the same elevation (set in a custom renderer as well), I still get the shadow from the toolbar drawn ontop of the new contentview. Using visual inspector shows that both the toolbar and the contentview has the same z and elevation. Placing two of the contentviews with the same elevation next to each other does not produce a shadow between them, so something works different with the toolbar. I do not want to create a custom toolbar. I also know that I could make a workaround by setting the elevation of the toolbar to 0 and make sure only the bottom shadow is shown on the contentview, but this doesn't feel right. Any suggestions?

Azure search is not working with typeahead functionality.

$
0
0

Hello guys, I have implemented azure search for searching workspaces from database which I have imported in azure. The issue is when I give a request call for searching the results, it has some time delay into it. My requirement is that I need a flawless azure search without hanging user for every work he types in the Entry field.

private async void SearchEntryTextChanged(object sender, TextChangedEventArgs e)
{
var entry = sender as CustomEntry;
string searchedString = entry.Text;
if (searchedString.Length > 2)
{
_workspaceSearchService = new AzureWorkspaceSearchApi();
List workspaceSearchData = new List();
//workspaceSearchData = await _workspaceSearchService.SearchWorkspaceFromAzure(searchedString);
workspaceSearchData = await _workspaceSearchService.ExecSuggest(searchedString);

               viewModel.SearchWorkspaceRecord = workspaceSearchData;
           }

}

For every character that enter after 2 length I am calling azure search. This request needs some time to get completed and hangs the user until it gets search result. I need these request to be done using typeahead phenomenon. Can anyone suggest me a solution to achieve this?

Below is the azure request:-

public async Task<List> ExecSuggest(string q)
{
try
{
// Execute /suggest API call to Azure Search and parse results
//string url = _serviceUri + AzureSuggestUrl + q;
string url = "https://meelosearchbasic.search.windows.net/indexes/indworkspacesearch/docs/suggest?api-version=2016-09- > >01&suggesterName=sgworkspacesearch&$top=5&$filter=TenantId eq '" + App.userTenantId + "'&search=" + q;
_httpClient = new HttpClient();
Uri uri = new Uri(url);
List Suggestions = new List();

           HttpResponseMessage response = AzureSearchHelper.SendSearchRequest(_httpClient, HttpMethod.Get, uri);
           AzureSearchHelper.EnsureSuccessfulSearchResponse(response);

           var obj = JsonConvert.DeserializeObject<SearchResult>(response.Content.ReadAsStringAsync().Result);
           Suggestions = obj.value;

           return Suggestions.Distinct().OrderBy(x => x.SearchText).ToList();
       }
       catch(Exception e)
       {
           return null;
       }
   }

In Xamarin forms not able set different Orientation for different pages in Pcl Proj?

$
0
0

I am not able to set Orientation for specific page in xamarin forms and

MessagingCenter callback executes viewmodel's method but doesn't update UI

$
0
0

i subscribe at a MessageCenter instance on my MainPage like that:

MessagingCenter.Subscribe<App, int>(this, App.TIMER_TICK_ACTION, (sender, arg) => {
       Device.BeginInvokeOnMainThread(() =>
       {
             TimerTickAction(arg);
       });
 });

private void TimerTickAction(int counter)
{
    try
    {
          if ((counter % 5) == 0)
          {
               matchViewModel.UpdateLiveMatches();
               System.Diagnostics.Debug.WriteLine("Update");
          }
          else
          {
               matchViewModel.TimeTick();
               System.Diagnostics.Debug.WriteLine("Tick");
           }
     }
     catch (Exception ex)
     {

         System.Diagnostics.Debug.WriteLine(ex.Message);
     }
}

The Send<> is executed on App.cs class every 1 sec :

Device.StartTimer(new TimeSpan(0,0,1), () =>{
      counter++;
      MessagingCenter.Send<App, int>(this, TIMER_TICK_ACTION, counter);
      return pageIsActive;
});

The viewmodel's methods TimeTick and UpdateLiveMatches are getting executed successfully. I set breakpoints and i see that the all blocks inside the ViewModel class are getting executed and setting log prints the updated data. But the UI is not getting updated. Like if the binding mechanism is not working. The strange thing is that if i StartTimer on MainPage() and start executing the exact same TimerTickAction(arg) method, is it successfully updating the UI.

Conclusion

Executing View Model method from MessagingCenter labmda is not updating UI.

Any help / explanation would be greatly appreciated,
Thanks in advance

EDIT: Please not that my binding is tested and working fine. The methods are the same. The only thing that changes is the scope they're being called

Image Overlay on Live Camera

$
0
0

Hi all,

I've been searching this form and the internet for an answer to this for some time now but just cannot find any solid leads on it.

Basically what I'm hoping to create is an application which lets you take a picture on your device camera, with an image (local image file) overlaid on the top. So similar to Snapchat's face detection filters, but just a static image.

So I need to be able to render a live view of the camera AND the overlay on the content page/view and then when the "take" button is used, the image is saved to the camera roll/library with the overlay rasterised. Also I need to be able to perform this on both iOS and Android, but since I haven't been able to find any sort of plugin or library to do this, I'm guessing using the Dependency Service is my best chance.

If anyone could point me in the right direction for achieving this, that would be greatly appreciated.

How to set a button with an underscore?

$
0
0

I want to set a button with an underscore;I have created a button inheritance and ButtonRenderer on the iOS and Android projects, but I can't set the underscore. Can anyone tell me how to do this?Thank you very much!


How to create simple TabbedPageRenderer for iOS and Android in Xamarin Forms

$
0
0

Need Simple working Tabbedpage Renderer

Android WindowManager issue "Force clearing orientation change"

$
0
0

Hi all

After rotating the device (or emulator) several times from portrait to landscape there will be layout issues with black screen and app hangs and no responsiveness anymore.
In logcat i can see warnings like WindowManager "Force clearing orientation change: Window{..."
First i thought this is due to the use of ListView, but it isn't. The phenomena occurs even if i have a blank ContentPage with no controls on it.
No problems on iOS with that.
I use the latest stable Xamarin.Forms Nuget and my Xamarin.Android.Support-Libs are on the latest version 26.1.0.1.

Please help!

Cheers
Philipp

How to find label reaches maximum lines.

$
0
0

I have developed a App. In my app i need to show the label with truncated text. when click the arrow the label should show all the text without truncating. when click again on arrow the text should be hide. It is like "See more", "See less" functionality. Is there any controls available in xamarin. Can any one knows how to resolve this?

Inspector thinks AVD is a physical device and will not load

$
0
0

I'm using the Android SDK emulator with a x86 system image and VS 2017. When I try to use the latest version of the Inspector I get an error launching it; "Inspector is not supported on physical Android devices".

I'm debugging the app fine with the emulator.

Guide to APK Expansion File for Google Play Store

$
0
0

Background:

"Google Play currently requires that your APK file be no more than 100MB (API level 9-10 and 14+) or 50 MB (API level 8 or lower)... Google Play allows you to attach two large expansion files that supplement your APK ... Each expansion file can be up to 2GB in size.". Your apps can easily exceed the limit if you have a lot of local content (images, videos, etc). This is most common among mobile games. Unfortunately, there seems to be lack of a detailed step-by-step tutorial on how to use expansion files in Xamarin. That is until now ...

Tutorial:

This tutorial assume that you have a lot of high resolution images in your app, and those images have previously been stored in the resource folder of your android project.

  1. Move all the images from the resource folder to somewhere outside of your project, for example a folder named "Images" on your Desktop. The following steps assume that you have all the images names stored in a local database. If you haven't done that yet, look into "https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/databases/" on how to add a database to your application.
  2. Zip the folder named "Images". Note that for videos, you have to use uncompressed format. You can either do it via command line ("zip -r0 Videos.zip Videos") or with using an application like WinZip.
  3. You need to rename the zip file "Main.VERSION_NUMBER.YOUR_BUNDLE_ID.obb". VERSION_NUMBER and BUNDLE_ID must match whatever that is in your AndroidManifest.xml. For example "Main.1.com.example.myapp.obb". Make sure that you have "hide file extension" checked off on your computer, otherwise your file name would still have a hidden ".zip" extension. Then your code won't be able to locate the expansion files.
  4. To test or debug with the expansion file, you need to copy the .obb file to your android testing device in "Android/obb/YOUR_BUNDLE_ID/". For example, it will look like "Android/obb/com.example.myapp/Main.1.com.example.myapp.obb". Note that if you want to test on a simulator, I'm sure there is place that you need to copy the file to. But I didn't really look into where it should be.
  5. Add "Android APK Expansion Downloader" package to your Xamarin.Android project.
  6. Create a new file named "ExpansionFile.cs". The following code basically copies all the images from your expansion file to the Personal folder on the device.

        public static class ExpansionFile
        {
            static string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
    
            public static bool CopyFromExpansionFile()
            {
                var context = Forms.Context;
                var packageInfo = Forms.Context.PackageManager.GetPackageInfo(context.PackageName, 0);
                var expansionFile = ApkExpansionSupport.GetApkExpansionZipFile(context, packageInfo.VersionCode, 0);
    
                // assuming you have the names of all the images stored in a database
                var imageNames = MyDataBase.GetAllImages();
                foreach (string imageName in imageNames)
                {
                    var imageLocalPath = Path.Combine(documentsPath, imageName);
                    var iconLocalPath = Path.Combine(documentsPath, iconName);
    
                    if (!File.Exists(imageLocalPath))
                    {
                        var imageFileEntry = expansionFile.GetEntry("Images/" + imageName);
                        if (imageFileEntry == null)
                            return false;
                        var success = CopyFile(imageFileEntry, imageLocalPath);
                        if (!success)
                            return false;
                    }
                }
                return true;
            }
    
            private static bool CopyFile(ZipFileEntry fileEntry, string path)
            {
                var zipFile = new ZipFile(fileEntry.ZipFileName);
                return zipFile.ExtractFile(fileEntry, path);
            }
        }
    
  7. In the MainActivity.cs of your Xamarin.Android project add:

            if (!ExpansionFile.CopyFromExpansionFile();)
                    Log.WriteLine(LogPriority.Warn, "Expansion Files", "Could not load expansion files.");
    
  8. In your cross platform (Xamarin.Forms) code where you reference the images:
    Instead of

        Image.Source = ImageSource.FromFile("Image0.jpg");
    

You need:

            if (Device.RuntimePlatform == Device.Android)
            {
        string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                    Image.Source = ImageSource.FromFile(Path.Combine(documentsPath, "Image0.jpg"));
            }
            else
                    Image.Source = ImageSource.FromFile("Image0.jpg");

The same goes if you are only doing (Xamarin.Android).

  1. Some sources say that the expansion file might not be successfully downloaded from the google play store when the apk file is downloaded. So you need to add some code to manually trigger the download. I didn't find this to be the case with my app. So I didn't add this part. But if you want to, here is where you can find that code: https://github.com/mattleibow/android.Play.ExpansionLibrary
  2. You need to have "ReadExternalStorage" checked in your AndroidManifest.xml
  3. In some cases (API 23 and above), the app will crash with an error "System.UnauthorizedAccessException: Access to the path "/storage/emulated/0/Android/obb/com.example.myapp/Main.1.com.example.myapp.obb is denied" even when you have "ReadExternalStorage" checked from step 10. This issue is reported in the following posts:
    https://code.google.com/p/android/issues/detail?id=197287
    https://code.google.com/p/android/issues/detail?id=217899
    But it was never acknowledged or fixed by Google. It is reported to happen 100% of the time on Samsung S5 S6 S7 running android 6.0. That's big percentage of your user base there. So you have to pick up Google's slack and fix it yourself.

To fix this issue, you need to add code to explicitly ask for permission in runtime.

            const string storagePermission = Manifest.Permission.ReadExternalStorage;
            if ((int)Build.VERSION.SdkInt >= 23 && CheckSelfPermission(storagePermission) != (int)Permission.Granted)
            {
                string[] PermissionsStorage = { storagePermission };
                const int RequestLocationId = 0;
                // You have to explicityly ask for storage permission in runtime for API 23 and above
                RequestPermissions(PermissionsStorage, RequestLocationId);
            }

(note that CheckSelfPermission and RequestPermissions only works on API 23 and above, so make sure the conditional statement for checking the version goes before checking permission.)

then your code for copying the images over becomes:

        if ((int)Build.VERSION.SdkInt >= 23)
        {
            if (CheckSelfPermission(storagePermission) == (int)Permission.Granted)
            {
                // copy images from expansion file to personal folder
                if (!ExpansionFile.CopyFromExpansionFile();)
                    Log.WriteLine(LogPriority.Warn, "Expansion Files", "Could not load expansion files.");
            }
        }
        else
        {
            // The issue with storage permission doesn't exist on API 22 and below
            // copy images from expansion file to personal folder
            if (!ExpansionFile.CopyFromExpansionFile();)
                Log.WriteLine(LogPriority.Warn, "Expansion Files", "Could not load expansion files.");
        }
  1. When you upload the expansion file to Google Play Store, follow the instructions here: https://support.google.com/googleplay/android-developer/answer/2481797?hl=en

Afterthought:

It's been a struggle to get my app published in the google play store. I place partial blame on google to place this antiquated restriction on apk file size. We used HockeyApp for beta testing / crash reports. HockeyApp doesn't support Expansion files, because expansion files are proprietary to Google Play Store. So I can see in the future that it is going to cause me more pain to undo everything in this tutorial and return the images back to resources folder. So unless you have to have local content for some reason, I suggest you host all your high resolution images and videos online and make your .apk file super small.

References:

http://www.applandeo.com/en/5-steps-using-expansion-files-android-xamarin-forms/
https://dotnetdevaddict.co.za/2014/12/21/downloading-expansion-files-in-xamarin-android/

Credit goes to Matthew Leibowitz who did most of the heavy lifting. I just complied everything together.

Xamarin Forms app stops on iOS as soon as WiFi is disabled and app is on cellular only.

$
0
0

Hello guys,

first: i´m really new to programming and completely selftaught, so it may happen that my mistakes are rather obvious.

I have the following problem:
I wrote an Xamarin Forms app using the sockets for pcl plugin and the connectivity plugin. The app listens for- and sends UDP commands to an ARM based development board.

On UWP and Android the app works perfect.
I now distributed the app via Testflight for internal beta test and when WiFi is enabled everything works fine. Funny thing is, that as soon as i disable WiFi, the app shutsdown during the launch screen. It also shuts down as soon as i disable WiFi during its use.... also when using a vpn tunnel..

So, i suspect that i am missing a permission or a key in the info.plist. I suspect it is something rather obvious...

Can somebody of you give me a hint?

Thanks, Vinc

p.s. I compile the iOS App on a mac of a friend. As soon as i´m able to use his computer for debug i can upload the output.. (i forgot it today, grr..)

Xamarin Android Exception while loading assemblies: System.IO.FileNotFoundException: Could not load

$
0
0

Hello everyone, I am working on Shared Xamarin Forms project for iOS and Android. And android just stopped building at one point. I tried switching from mac to windows, installing Xamarin fresh and I still got the same error.

So far everything seemed to be OK. And then suddenly I cannot build debug or release on Android project. I am getting this error:

/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets(2,2): Error: Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'Xamarin.Android.Support.Compat, Version=1.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'Xamarin.Android.Support.Compat.dll'
  at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference reference, Mono.Cecil.ReaderParameters parameters) [0x00099] in /Users/builder/data/lanes/5147/c2a33d8e/source/xamarin-android/external/Java.Interop/src/Java.Interop.Tools.Cecil/Java.Interop.Tools.Cecil/DirectoryAssemblyResolver.cs:220
  at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference reference) [0x00000] in /Users/builder/data/lanes/5147/c2a33d8e/source/xamarin-android/external/Java.Interop/src/Java.Interop.Tools.Cecil/Java.Interop.Tools.Cecil/DirectoryAssemblyResolver.cs:170
  at Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences (Java.Interop.Tools.Cecil.DirectoryAssemblyResolver resolver, System.Collections.Generic.ICollection`1[T] assemblies, Mono.Cecil.AssemblyDefinition assembly, System.Boolean topLevel) [0x0015c] in <593a6fd557984367bb21e275d0fa0659>:0
  at Xamarin.Android.Tasks.ResolveAssemblies.Execute (Java.Interop.Tools.Cecil.DirectoryAssemblyResolver resolver) [0x0019c] in <593a6fd557984367bb21e275d0fa0659>:0

I am pretty sure I haven't changed any source files, it was building up until now.. The only App Compat I use is "Xamarin.Android.Support.v7.Compat".

The things I tried:

Removing all packages and adding them again.
Creating fresh Xamarin.Forms project and pulling code from git - same error
Installing Xamarin.Android.Support.Compat - Error I got:
You are trying to install this package into a project that targets 'MonoAndroid,Version=v6.0', but the package does not contain any assembly references or content files that are compatible with that framework.
Made sure my target framework is same as target version (Use API 23) and my minimum target version is API 19.
Deleting Bin and Obj directories, restarting solution and building again.
I am using Xamarin.Forms 2.4.0.38779. I tried removing all packages and updating for the newest Forms - still got same error.


System.IO.FileNotFoundException: Could not load assembly 'Xamarin.Android.Support.Compat'

$
0
0

Hello Everyone! I am working on Xamarin.Forms project for my company and we plan to release our app on IOS and Android (Using Visual Studio Community Edition on Macbook pro). So far everything seemed to be OK. And then suddenly I cannot build debug or release on Android project. I am getting this error:

/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets(2,2): Error: Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'Xamarin.Android.Support.Compat, Version=1.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'Xamarin.Android.Support.Compat.dll'
  at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference reference, Mono.Cecil.ReaderParameters parameters) [0x00099] in /Users/builder/data/lanes/5147/c2a33d8e/source/xamarin-android/external/Java.Interop/src/Java.Interop.Tools.Cecil/Java.Interop.Tools.Cecil/DirectoryAssemblyResolver.cs:220
  at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference reference) [0x00000] in /Users/builder/data/lanes/5147/c2a33d8e/source/xamarin-android/external/Java.Interop/src/Java.Interop.Tools.Cecil/Java.Interop.Tools.Cecil/DirectoryAssemblyResolver.cs:170
  at Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences (Java.Interop.Tools.Cecil.DirectoryAssemblyResolver resolver, System.Collections.Generic.ICollection`1[T] assemblies, Mono.Cecil.AssemblyDefinition assembly, System.Boolean topLevel) [0x0015c] in <593a6fd557984367bb21e275d0fa0659>:0
  at Xamarin.Android.Tasks.ResolveAssemblies.Execute (Java.Interop.Tools.Cecil.DirectoryAssemblyResolver resolver) [0x0019c] in <593a6fd557984367bb21e275d0fa0659>:0

I am pretty sure I haven't changed any source files, it was building up until now.. The only App Compat I use is "Xamarin.Android.Support.v7.Compat".

The things I tried:

  • Removing all packages and adding them again.
  • Creating fresh Xamarin.Forms project and pulling code from git - same error
  • Installing Xamarin.Android.Support.Compat - Error I got:
You are trying to install this package into a project that targets 'MonoAndroid,Version=v6.0', but the package does not contain any assembly references or content files that are compatible with that framework.
  • Made sure my target framework is same as target version (Use API 23) and my minimum target version is API 19.
  • Deleting Bin and Obj directories, restarting solution and building again.
  • I am using Xamarin.Forms 2.4.0.38779. I tried removing all packages and updating for the newest Forms - still got same error.
  • Company gave me windows laptop, I installed Visual Studio 2017, tried to build repo pulled from version control and still got the same error.

I will provide any logs as needed.

ToolBarItems Left side

$
0
0

Is it possible to specify toolbar button items to go to the left side ?

Web page Navigation

$
0
0

Long story short, new to programming and I am helping to build a phone app with a friend. Basically a way to learn what develops do and hopefully try to acquire basics. With that said could someone provide point me to a page that shows xaml examples of how you would be able to take someone to a web page via label click within a app? Have googled plenty and have messed around with gesture recognizers but unable to figure out who you take someone to a specific site once you click on the label. Any help would be much appreciated

FreshMVVM vs. MVVM Light

$
0
0

Hi,

can anybody share with me their experiences with both frameworks? If someboby has used both the better.

Thanks a lot

Thomas

This project type requires Xamarin.Android to be installed help!

$
0
0

After updating, this error appeared

This project type requires Xamarin.Android to be installed help!

Viewing all 204402 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>