Xamarian - The name 'Resource' does not exist in the current context - visual-studio

I'm aware this question has been asked already - but none provided a resolution.
I have read these links:
Xamarin Forum, Stack Overflow Q and some others.
I have a relatively simple project at the moment and I keep getting the error "The name 'Resource' does not exist in the current context"
I can restart the project & it will work and "resource" is underlined in red and I can still debug the project.
Then after a few tries it goes and complains that it's not in the current context.
I did not make any changes to the project - I have come back to it now from a while ago.
So I'm going to guess that updates to VS 2015 have broken it.
My Code example:
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Views.InputMethods;
using Android.Graphics.Drawables;
using Android.Graphics;
namespace Designer
{
[Activity(Label = "Designer", MainLauncher = true)]
public class MainActivity : Activity
{
// Global Varialble
Button butSignIn;
EditText tbxUsername;
TextView txtErrorMsg;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
butSignIn = FindViewById<Button>(Resource.Id.butSignIn);
butSignIn.Click += ButSignIn_Click;
tbxUsername = FindViewById<EditText>(Resource.Id.txtUsername);
txtErrorMsg = FindViewById<TextView>(Resource.Id.txtErrorMessage);
ActionBar.SetDisplayShowTitleEnabled(false);
ColorDrawable colorDrawable = new ColorDrawable(Color.ParseColor("#ff70bc1e"));
ActionBar.SetBackgroundDrawable(colorDrawable);
}
private void ButSignIn_Click(object sender, System.EventArgs e)
{
if (tbxUsername.Text == "Azmodan")
{
Intent intent = new Intent(this, typeof(MenuActivity));
this.StartActivity(intent);
this.Finish(); // this will close the activity and will close app if we try go back
}
else
{
txtErrorMsg.Visibility = ViewStates.Visible;
txtErrorMsg.Text = "inccorect login details, please try again";
}
}
}
}
Any help would be appreciated.

Related

AdMob Banner wont show up, no error message with test ad and failed to load : 3 with real ad

I have a Xamarin Forms application on which I would like to advertise via Admob. If I set my real ad-id, I get Ad failed to load : 3. When I use the id of a test-ad, there is no error message in the console, but there is also no ad.
Ive tried connecting with firebase, which worked well, but didn't fix the problem. Ive also changed the language of the app and specified in the google play console settings that my App uses ads (even through it isnt live yet).
I used a custom renderer:
Class in forms:
namespace test7
{
public class AdMobView : View
{
}
}
android implementation:
[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobViewRenderer))]
namespace test7.Droid
{
public class AdMobViewRenderer : ViewRenderer<AdMobView, AdView>
{
public AdMobViewRenderer(Context context) : base(context) { }
string id = "ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyy"; //here was my real id and test id
private AdView CreateAdView()
{
var adView = new AdView(Context)
{
AdSize = AdSize.SmartBanner,
AdUnitId = id,
LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent)
};
adView.LoadAd(new AdRequest.Builder().Build());
return adView;
}
protected override void OnElementChanged(ElementChangedEventArgs<AdMobView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null && Control == null)
{
SetNativeControl(CreateAdView());
}
}
}
}
xaml:
<local:AdMobView x:Name="werbung" />
Any ideas how to fix this? Im lost :(
I suggest using this NuGet package. It sets everything up for you

AIML bot cannot find config folder in Xamarin.Forms

I'm creating a Xamarin.Forms application and I'm trying to implement an AIML bot based on this tutorial: https://www.effacestudios.com/how-to-create-artificial-intelligence-chatbot/. I've added all the references and I've added a config and aiml folder into my directory. This is the code for when a button is clicked:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void Button_Clicked(object sender, EventArgs e)
{
string settingsPath = Path.Combine(Environment.CurrentDirectory, Path.Combine("config", "Settings.xml"));
string otherPath = #"C:/Users/PAVILION/Desktop/AimlTest/AimlTest/AimlTest/bin/Debug/netstandard2.0/config/Settings.xml";
Bot AI = new Bot();
AI.loadSettings(otherPath);
AI.loadAIMLFromFiles();
AI.isAcceptingUserInput = false;
User myuser = new User("User1", AI);
AI.isAcceptingUserInput = true;
Request r = new Request(UserEntry.Text, myuser, AI);
Result res = AI.Chat(r);
BotEntry.Text = "Tutorial Bot: " + res.Output;
}
}
Any time I input text into the Entry and tap the button I get an Unable to find specified file on the loadSettings();. I believe the function is looking for a Settings.xml and even though I've directed it to the exact file it still cannot be found. Any help is appreciated.
You need to decompile aiml dll and then change loadsetting path to constant environment.specialfolder.loadapplication.
make sure you have placed your all required file there first.

Unable to load DLL 'e_sqlite3': The specified module could not be found

I have a Xamarin Forms solution. I added sqlite-net-pcl as reference to all projects. It works fine on Android but crashes on Windows 8.1 and Windows Phone 8.1. I have an IOS project but I don't have OSX at the moment to try it.
I use this in the Windows projects to access the database:
using System.IO;
using SQLite;
using Xamarin.Forms;
using HelloXamarin.Windows;
using Windows.Storage;
[assembly: Dependency(typeof(SQLiteDb))]
namespace HelloXamarin.Windows
{
public class SQLiteDb : ISQLiteDb
{
public SQLiteAsyncConnection GetConnection(string databaseName)
{
var documentsPath = ApplicationData.Current.LocalFolder.Path;
var path = Path.Combine(documentsPath, databaseName);
return new SQLiteAsyncConnection(path);
}
}
}
Here are my references:
I get this exception when trying to access the database:
The type initializer for 'SQLite.SQLiteConnection' threw an exception.
Unable to load DLL 'e_sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
at SQLitePCL.SQLite3Provider_e_sqlite3.NativeMethods.sqlite3_win32_set_directory(UInt32 directoryType, String directoryPath)
at SQLitePCL.SQLite3Provider_e_sqlite3..ctor()
at SQLitePCL.Batteries_V2.Init() at SQLite.SQLiteConnection..cctor()
I have no idea how to solve this, please help me!
The whole solution is available on GitHub:
https://github.com/apspot/HelloXamarin
For me, it worked by adding the e_sqlite3 bundle to the executable project
By this time the issue is still open. So before they come with some solid fix, you can use this work around, to solve the issue for now.
Add one helper class
using System;
using System.Diagnostics;
using System.IO;
namespace SQLitePCL
{
public class NativeLibraryHack
{
public static bool Hacked { get; private set; }
public static bool DoHack()
{
if (Hacked) return true;
try
{
const string runtimeFolderName = "/runtimes";
var destinationPath = typeof(SQLitePCL.raw).Assembly.Location
.Replace("\\", "/");
var destinationLength = destinationPath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
var destinationDirectory = destinationPath.Substring(0, destinationLength) + runtimeFolderName;
var sourcePath = new Uri(typeof(SQLitePCL.raw).Assembly.CodeBase)
.AbsolutePath;
var sourceLength = sourcePath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
var sourceDirectory = sourcePath.Substring(0, sourceLength) + runtimeFolderName;
if (Directory.Exists(sourceDirectory))
CopyFilesRecursively(new DirectoryInfo(sourceDirectory), new DirectoryInfo(destinationDirectory));
}
catch (Exception ex)
{
//Ignore Exception
Debug.WriteLine(ex.Message);
return false;
}
return (Hacked = true);
}
private static void CopyFilesRecursively(
DirectoryInfo source,
DirectoryInfo target
)
{
foreach (var dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (var file in source.GetFiles())
{
try
{
var destinationFile = Path.Combine(target.FullName, file.Name);
if (!File.Exists(destinationFile))
file.CopyTo(destinationFile);
}
catch (Exception ex)
{
//Ignore Exception
Debug.WriteLine(ex.Message);
}
}
}
}
}
And add the hack before your db migration script, I am using web api 2
so i did on RouteConfig.RegisterRoutes
NativeLibraryHack.DoHack();
using (KSDBContext db = new KSDBContext())
{
db.Database.Migrate();
}
You need to add the SQLite Extensions.
Go to Tools > Extensions and Updates
Go to Online, then search for SQLite.
Download SQLite for Windows Runtime
In your Windows Project, Add Reference and ensure you add the extension.
Also remove Microsoft.VCLibs from your references.
Try referencing Visual C++ 2015 Runtime for Universal Windows Platform Apps. That sorted it out for me.
Go to References
Add Reference
Extensions.
Check"Visual C++ 2015 Runtime for Universal Windows Platform Apps"
OK

How to open a webView in Windows Phone 7.x?

I would like my app to have only one view.
I need this view to be an external URL.
I tried to use the webBrowser Task following the example on microsoft.
I put on my constractor :
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://msdn.microsoft.com", UriKind.Absolute);
webBrowserTask.Show();
However when i press the back button instead of navigating outside the app , i am navigating to the first page which is empty...
My code looks like this :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
//added this for push
using Microsoft.Phone.Notification;
using System.Text;
//added this to open an external URL using the WebBrowser Task
using Microsoft.Phone.Tasks;
namespace WindowsPush
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
/// Holds the push channel that is created or found.
HttpNotificationChannel pushChannel;
// The name of our push channel.
string channelName = "ToastSampleChannel";
InitializeComponent();
// Try to find the push channel.
pushChannel = HttpNotificationChannel.Find(channelName);
// If the channel was not found, then create a new connection to the push service.
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
//pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.Open();
// Bind this new channel for toast events.
pushChannel.BindToShellToast();
}
else
{
// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
//pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
// Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString());
// MessageBox.Show(String.Format("Channel Uri is {0}", pushChannel.ChannelUri.ToString()));
}
object uniqueID;
if (Microsoft.Phone.Info.DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueID) == true)
{
byte[] bID = (byte[])uniqueID;
string deviceID = Convert.ToBase64String(bID); // There you go
System.Diagnostics.Debug.WriteLine("Device Unique Id is: {0}", deviceID);
}
//opening the external URL using webBrowserTask
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://msdn.microsoft.com", UriKind.Absolute);
webBrowserTask.Show();
}
void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
MessageBox.Show(String.Format("Channel Uri is {0}", e.ChannelUri.ToString()));
});
}
void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
// Error handling logic for your particular application would be here.
Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}", e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)));
}
}
}
What i need is just load an external URL on the first and only view of my app.
How could i do that?
You're looking for the WebBrowser control. Add it to the main application page and handle it like you would a WebBrowserTask.
If you're going to use the WebBrowserTask then you could close the app on returning to it by throwing an unhandled exception:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.NavigationMode == NavigationMode.Back)
{
throw new Exception("deliberately doing this to force the app to close");
}
}
If/when you do this in Windows Phone 8 you can call Application.Current.Terminate(); instead of throwing the exception.
Be sure to check the marketplace certification requirements for apps that just launch an external website before submitting though.

Visual C# - InvalidActiveXStateException

I am getting an error when trying to embed a flash (.swf) file into my Visual C' form - I have notice this is a fairly common error, though the solutions don't mean much to me.
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AxShockwaveFlashObjects;
using ShockwaveFlashObjects;
namespace WindowsFormsApplication1
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
frm1.ShowDialog();
}
private void axShockwaveFlash2_Enter(object sender, EventArgs e)
{
**//this.axShockwaveFlash1.LoadMovie(0, "C:\\Documents and Settings\\Gary\\My Documents\\Flash File\\CalmBay1.swf");**
}
private void Form6_Load(object sender, EventArgs e)
{
AxShockwaveFlash axShockwaveFlash = new AxShockwaveFlash();
axShockwaveFlash.Location = new System.Drawing.Point(50, 50);
this.Controls.Add(axShockwaveFlash);
**axShockwaveFlash.Movie = ("C:\\Documents and Settings\\Gary\\My Documents\\Flash File\\CalmBay1.swf");**
//ShockwaveFlash.Size = new System.Drawing.Size(150, 150);// set size as required
axShockwaveFlash.Play();
}
}
}
The line with the asterix is where the error is, but as i say, i've no idea on how to resolve it!
Even though it's been months since this question was asked, I just had the same problem. When creating AxShockwaveFlash objects programmatically, you have to initialize:
var flashObj = new AxShockwaveFlash();
((ISupportInitialize) (flashObj)).BeginInit(); // <--
flashObj.Dock = DockStyle.Fill;
flashObj.Enabled = true;
((ISupportInitialize) (flashObj)).EndInit(); // <--
Controls.Add(flashObj);
flashObj.AutoSize = true; // All of these properties won't work unless the component has been initialized
flashObj.ScaleMode = 1;
flashObj.AlignMode = 0;
flashObj.LoadMovie(0, #"movie.swf");
flashObj.Stop();
flashObj.Play();
Hopefully this will save future readers some time.
I had the same problem I tried the proposed solutions of calling CreateControl without any success.
It turned out that the interops were generated targeting the .net 2.0 framework and the problem occurred when being called from 4.0 code. The solution was to generate interops using .NET Framework Tools 4.0.

Resources