I recently started working with Xamarin to build Android apps in C#.
There is one issue I have had in particular that makes it very hard for me to make any progress:
error CS0117
I have two identical projects, the issue only shows up in one of them.
It originally occured in both but rebuilding a few times fixed the first one.
The second one seems to be more persistent.
I really need to find a solution to this issue, as referencing is very basic and needed. Not to mention, it happens in every new project.
Here is my code:
NoteMath
using System;
using Android.App;
using Android.Content;
using Android.Widget;
using Android.OS;
namespace NoteMath_v1._0._1
{
[Activity(Label = "noteMath", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Window.RequestFeature(Android.Views.WindowFeatures.NoTitle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
EditText etInput = FindViewById<EditText>(Resource.Id.etInput);
TextView tvConsole = FindViewById<TextView>(Resource.Id.tvConsole);
etInput.KeyPress += (object sender, EditText.KeyEventArgs e) =>
{
e.Handled = false;
if (e.Event.Action == Android.Views.KeyEventActions.Down && e.KeyCode == Android.Views.Keycode.Enter)
{
tvConsole.Append("\n>" + HandleInput.TransferInput(etInput.Text));
etInput.Text = "";
e.Handled = true;
}
};
}
}
}
The code you posted looks good. The error is clearly not coming from there. You´ve got something wrong in any of your resource layout or xml files.
The problem actually is that Visual Studio won´t show up Resource generation errors in the Errors panel, eventhough it should be like that (I think this will be fixed in future versions). At the moment it is just telling you that the class Id doesn´t exists.
Resources.designer.cs is a class generated by Xamarin when you edit any resource file. It containts references to any declaration, id, etc in the xml/axml files. If the resource has an error, Resources.designer.cs generation will fail, but you get a really vague error hint.
The first thing you can try is rebuilding your Android project, forcing all resources to be generated again. Otherwise try the following:
Good news is that you can see generation errors by changing build output verbosity to "detailed":
Now compile your project again and check the output window. It will tell you exactly what the problem is.
After you fix it, Resource.Id class will be generated.
For me, this worked:
Step 1.
Project > Update NugetPackages
Step 2.
Build > Clean All
Step 3.
Build > Build All
I am super new. The only thing that really worked for me was manually running this powershell script in my project root:
Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }
I am not sure why the live view/build output isn't more helpful, or that visual studio isn't cleaning these files correctly in my xamarin project.
Special thanks to this guy:
https://montemagno.com/easily-clean-bin-obj-folders/
Related
First let make clear that this is my first Android project ever that I'm trying to complete, so I'm still very new to all this.
I've been stuck with this extremely annoying problem where I can't compile my project anymore even after removing a lot things. At one point in my project I added the 'System' namespace to use the 'Exception' keyword(to test a DB connection). All was working fine and well right before this point. But after trying to compile I got the error:
/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets: error : Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'System.Drawing.dll'
So I just added 'using System.Drawing' on top but later I read that Xamarin Android doesn't support that. So I removed it again and tried to remove whatever I did to try stop getting this Exception. Then this error got stuck forever even if I comment all things out. I can write 'using System.Drawing' without the system giving that line an error, which I thought was weird because it's nowhere to found in the references. I also really don't get it since I don't draw anything and don't think use anything from System.Drawing. Any time I reference the 'System' package I get this error, I can't go without because some android files rely on it. I've now lost hours now without any progress and basically am at the end of my road here.
Here's my MainActivity.cs file as it is now, narrowed down, it's my only .cs file:
using Android.Graphics;
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using MySql.Data.MySqlClient;
using System;
namespace MapApp
{
[Activity(Label = "MapApp", MainLauncher = true, Icon = "#mipmap/icon")]
public class MainActivity : Activity, IOnMapReadyCallback
{
GoogleMap GMap;
/// database
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
}
private void SetUpMap()
{
if (GMap == null)
{
FragmentManager.FindFragmentById<MapFragment>(Resource.Id.googlemap).GetMapAsync(this);
}
}
public void OnMapReady(GoogleMap map)
{
GMap = map;
GMap.SetLatLngBoundsForCameraTarget(new LatLngBounds(
new LatLng(51.873176, 4.393930),
new LatLng(51.994576, 4.598036)));
GMap.MoveCamera(CameraUpdateFactory.NewLatLngZoom(new LatLng(51.917879,4.481134),13));
/*MarkerOptions markerOpt1 = new MarkerOptions();
markerOpt1.SetPosition(new LatLng(51.917879, 4.481134));
markerOpt1.SetTitle("Vimy Ridge");
GMap.AddMarker(markerOpt1);*/
CircleOptions dangerZone = new CircleOptions();
dangerZone.InvokeCenter(new LatLng(51.917879, 4.481134));
dangerZone.InvokeRadius(100);
dangerZone.InvokeFillColor(0x7F00FF00);
dangerZone.InvokeStrokeWidth(0);
GMap.AddCircle(dangerZone);
}
}
}
Here is a picture of my references and packages.(a lot of Xamarin packages in there because those were needed to load Google Maps):
Here another picture of my project structure as is, if it may help identify the problem.
I have tried to delete all my packages and clean my Big/Debug folder and rebuild everything but error still proceeds.
Everything worked perfectly and now I just can't build it anymore. I wrote "using System" once, got this error, and then never couldn't get rid of this error anymore.
I really do not want to restart my project for the second time, after getting getting unknown errors every hour so any help would GREATLY be appreciated.
I have found the problem thanks to using Diagnostic logging.
Turns out the 'MySql.Data' package loads 'System.Drawing' which of course is not supported in Xamarin.Android.
Dependency System.Drawing, Version=4.0.0.0, Culture=neutral,
Required by MySql.Data, Version=6.9.9.0, Culture=neutral
Thanks to Lexi Li for giving the one tip I exactly needed!
I want to create simple toast notification to action center in windows 10 from this example. But I got problem on Step 2:
using Windows.UI.Notifications;
It`s missing. But I have spent a lot of time to find it and got no result. I really have no idea where I can find or at least download it.
What I tried:
After long search I found Windows.UI.dll in C:\Windows\System32 but when I try to add it as reference into project I got this error. Even after I tried to copy it and made this fully accessible nothing changed
I tried to reinstall .Net (I`m using 4.5.2)
Installed Windows 10 SDK
Tried to import with global
Added
<PropertyGroup>
<TargetPlatformVersion>10.0</TargetPlatformVersion>
</PropertyGroup>
Added System.Runtime.dll reference
Example code which probably is useless for you:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Toolkit.Uwp.Notifications;
using Microsoft.QueryStringDotNET;
using Windows.UI.Notifications;
namespace MessagerClient.Notifications {
class DefaultWindowsNotification {
public static void notificationTest() {
string title = "Andrew sent you a picture";
string content = "Check this out, Happy Canyon in Utah!";
string image = "http://blogs.msdn.com/something.jpg";
string logo = "ms-appdata:///local/Andrew.jpg";
ToastVisual visual = new ToastVisual() {
BindingGeneric = new ToastBindingGeneric() {
Children =
{
new AdaptiveText()
{
Text = title
},
new AdaptiveText()
{
Text = content
},
new AdaptiveImage()
{
Source = image
}
},
AppLogoOverride = new ToastGenericAppLogo() {
Source = logo,
HintCrop = ToastGenericAppLogoCrop.Circle
}
}
};
Console.WriteLine("NOTIFICATION");
//Can`t use because of Windows.UI library
ToastNotificationManager.CreateToastNotifier().Show(visual);
}
}
}
You have to fight Visual Studio pretty hard to use these UWP contracts in a Winforms app. You got off on the wrong foot right away with the wrong TargetPlatformVersion, pretty hard to recover from that. Full steps to take:
Edit the .csproj file with a text editor, Notepad will do. Insert this:
<PropertyGroup>
<TargetPlatformVersion>10.0.10586</TargetPlatformVersion>
</PropertyGroup>
Which assumes you have the 10586 SDK version installed on your machine. Current right now, these versions change quickly. Double-check by looking in the C:\Program Files (x86)\Windows Kits\10\Include with Explorer, you see the installed versions listed in that directory.
Open the Winforms project, use Project > Add Reference > Windows tab > tick the Windows.Data and the Windows.UI contract. Add Reference again and use the Browse tab to select System.Runtime. I picked the one in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\ .NETFramework\v4.6.1\Facades. This reference displays with a warning icon, not sure what it is trying to say but it doesn't appear to have any side-effects.
Test it by dropping a button on the form, double-click to add the Click event handler. The most basic code:
using Windows.UI.Notifications;
...
private void button1_Click(object sender, EventArgs e) {
var xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
var text = xml.GetElementsByTagName("text");
text[0].AppendChild(xml.CreateTextNode("Hello world"));
var toast = new ToastNotification(xml);
ToastNotificationManager.CreateToastNotifier("anythinggoeshere").Show(toast);
}
Embellish by using a different ToastTemplateType to add an image or more lines of text. Do keep in mind that your program can only work on a Win10 machine.
If anyone should happen to stumble on this, see this similar but newer post -
Toast Notifications in Win Forms .NET 4.5
Read Stepan Hakobyan's comment at the bottom.
Essentially, I'm seeing the same thing. This code runs, I can step through it line by line with no exceptions but the toast notification is never shown within a Form app.
I'm trying to allow a user to enter data into a textbox that will be added to the web.config file. I've added the relevent lines to the web.config file but when I make this class all goes wrong.
I keep getting the are you missing a using directive or assembly refenrence error whenever I try to run my app. I have looked at the other times this question has been asked and can't seem to figure out where I'm going wrong. The thing is that I am extremely new to Visual Studio and am just left blank at what could be the answer.
Below here is the class file that's generating the error. I hope I've included everything you need to assist me. Thank you.
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
namespace WebConfigDemo
{
public class CompanyConfigSection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
public CompanyConfigCollection Companies
{
get
{
return (CompanyConfigCollection)this[""];
}
set
{
this[""] = value;
}
}
}
public class CompanyConfigElement : ConfigurationElement
{
[ConfigurationProperty("id", IsKey = true, IsRequired = true)]
public int Id
{
get
{
return (int)this["id"];
}
set
{
this["id"] = value;
}
}
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"].ToString();
}
set
{
this["name"] = value;
}
}
} '
public class CompanyConfigCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new CompanyConfigElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((CompanyConfigElement)element).Id;
}
}
public class CompaniesConfig
{
private static readonly Dictionary<int, CompanyConfigElement>
Elements;
static CompaniesConfig()
{
Elements = new Dictionary<int, CompanyConfigElement>();
var section = (CompanyConfigSection)ConfigurationManager.GetSection ("companies");
foreach (CompanyConfigElement system in section.Companies)
Elements.Add(system.Id, system);
}
public static CompanyConfigElement GetCompany(int companyId)
{
return Elements[companyId];
}
public static List<CompanyConfigElement> Companies
{
get
{
return Elements.Values.ToList();
}
}
}
} '
Any help is appreciated
You probably don't have the System.Configuration dll added to the project references. It is not there by default, and you have to add it manually.
Right-click on the References and search for System.Configuration in the .net assemblies.
Check to see if it is in your references...
Right-click and select Add Reference...
Find System.Configuration in the list of .Net Assemblies, select it, and click Ok...
The assembly should now appear in your references...
.Net framework of the referencing dll should be same as the .Net framework version of the Project in which dll is referred
If you've tried the above solutions and haven't found the answer, make sure that the .NET versions of all projects are the same.
I ran into this problem when importing a .NET version 4.6.1 into a .NET version 4.6.2 project. Without any warnings from Visual Basic!
More Info: The type or namespace name could not be found
Your using statements appear to be correct.
Are you, perhaps, missing the assembly reference to System.configuration.dll?
Right click the "References" folder in your project and click on "Add Reference..."
This problem would be caused by your application missing a reference to an external dll that you are trying to use code from. Usually Visual Studio should give you an idea about which objects that it doesn't know what to do with so that should be a step in the right direction.
You need to look in the solution explorer and right click on project references and then go to add -> and look up the one you need. It's most likely the System.Configuration assembly as most people have pointed out here while should be under the Framework option in the references window. That should resolve your issue.
I have observed a quote ' in your 1st line and also at the end of your last line.
'using System.Collections.Generic;
Is this present in your original code or some formatting mistake?
I had the same problem earlier today. I could not figure out why the class file I was trying to reference was not being seen by the compiler. I had recently changed the namespace of the class file in question to a different but already existing namespace. (I also had using references to the class's new and previous namespaces where I was trying to instantiate it)
Where the compiler was telling me I was missing a reference when trying to instantiate the class, I right clicked and hit "generate class stub". Once Visual Studio generated a class stub for me, I coped and pasted the code from the old class file into this stub, saved the stub and when I tried to compile again it worked! No issues.
Might be a solution specific to my build, but its worth a try.
In some cases, when necessary using has been obviously added and studio can't see this namespace, studio restart can save the day.
I was getting warnings about different versions in .NET framework; I ignored them.
The project compiles fine making the change in the solution's properties.
I'm using Visual Studio Code and could not use instructions from above so I found another way to fix the problem with referencing to namespace from another file.
All what need to be done is to add include to your .csproj file e.g:
<ItemGroup>
<Compile Include="filename.cs" />
</ItemGroup>
Then you can use namespaces from filename.cs
The following technique worked for me:
1) Right click on the project Solution -> Click on Clean solution
2) Right click on the project Solution -> Click on Rebuild solution
I am having a problem using Visual Studio data driven testing. I have tried to deconstruct this to the simplest example.
I am using Visual Studio 2012. I create a new unit test project.
I am referencing system data.
My code looks like this:
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[DeploymentItem(#"OrderService.csv")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "OrderService.csv", "OrderService#csv", DataAccessMethod.Sequential)]
[TestMethod]
public void TestMethod1()
{
try
{
Debug.WriteLine(TestContext.DataRow["ID"]);
}
catch (Exception ex)
{
Assert.Fail();
}
}
public TestContext TestContext { get; set; }
}
}
I have a very small csv file that I have set the Build Options to to 'Content' and 'Copy Always'. I have added a .testsettings file to the solution, and set enable deployment, and added the csv file.
I have tried this with and without |DataDirectory|, and with/without a full path specified (the same path that I get with Environment.CurrentDirectory). I've tried variations of "../" and "../../" just in case. Right now the csv is at the project root level, same as the .cs test code file.
I have tried variations with xml as well as csv.
TestContext is not null, but DataRow always is.
I have not gotten this to work despite a lot of fiddling with it. I'm not sure what I'm doing wrong.
Does mstest create a log anywhere that would tell me if it is failing to find the csv file, or what specific error might be causing DataRow to fail to populate?
I have tried the following csv files:
ID
1
2
3
4
and
ID, Whatever
1,0
2,1
3,2
4,3
So far, no dice.
I am using ReSharper, could it be interfering in some way?
Updated
I have it mostly working now! I am able to use XML, but when I use CSV my column, which is named ID comes back as ID
Not sure why. I've checked the actual file of course, and no weird characters are present.
For anyone having a similar problem, I turned off Just My Code and enabled Net Framework source stepping, etc. so that I could get more detailed debug information. This allowed me to determine that ReSharper was causing me problems. I disabled resharper and modified my attributes like this:
[DeploymentItem("UnitTestProject1\\OrderService.csv")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\bin\\Debug\\OrderService.csv", "OrderService#csv", DataAccessMethod.Sequential)]
And it worked (except as noted). I am still suspicious of the "bin\debug" in my path, but I'm just happy my DataRow is no longer null.
Thanks!
Any ideas?
I was struggling with a similar problem today when trying to make data-driven tests work with CSV input file. The name of the first column had some garbage at the beggining of it, i.e. ID instead of just ID.
It turned out it was an encoding issue. The CSV file was saved in UTF-8 which adds a byte order mark at the beginning, obviously confusing the parser. Once I saved the file in ANSI encoding, it worked as expected.
I know it's an old question, but this information might help someone else ending up on this page.
Have you tried adding it through the properties window?
Go to Test menu -> Windows -> Test View -> the tests will load up.
Click on the test to alter i.e. TestMethod1 and press F4 (properties).
Look for 'Data Source' and click the ellipses next to it
It will walk you through a wizard that sets up the attributes properly for the TestMethod
You have the deployment part set up properly, which is normally the big stumbling block.
You also don't have to set the build action to Copy Always as the deployment does this for you. This option is used if you include items like .xml files you use for configs, or icons/images as part of your project.
Update 1:
Also try this tutorial on MSDN.
Update 2:
Try this post, involving ProcMon
I see that you said you tried putting the CSV itself into the testsettings file, but have you tried just putting in the directory?
<Deployment>
<DeploymentItem filename="Test\Data\" />
</Deployment>
Then your DataSource line will look something like this:
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\YOURCSV.csv", "YOURCSV#csv", DataAccessMethod.Sequential)]
If you do it this way, you don't need to specify the DeploymentItem line.
Our folder structure looks like this: Trunk\Test\Test\Data
We include: Test\Data in the deployment
We then access Test\Data via the |DataDirectory|\
All CSVs live within the \Data folder
I am using the Spark View engine with asp.net mvc3, gotta say I love spark bindings are awesome!
Everything works fine however development is extremely painful at the moment because any time I change
any of my code I get Runtime Binder errors such as
The type or namespace name 'RuntimeBinder' does not exist in the namespace 'Microsoft.CSharp'
I am forced to clean and rebuild my solution and restart it and it works fine after that. Well at least until I make another code change and am then forced to do it again.
Stopping IIS instance and starting project does not work I have to do full rebuild first.
I am running in Debug.
I have Rebooted,Checked Referenced DLL's, Cleared all files out off Tmp,Checked my web.config and spark file.
I have added the following code in my global.asx file as explained here.
Spark views work initially, but then get a "Dynamic view compilation failed" error after 30 minutes or so
private void PreLoadAssemblies()
{
// Deal with the compiling issue with Spark.
var initialAssemblies = AppDomain.CurrentDomain.GetAssemblies();
var di = new DirectoryInfo(Server.MapPath("~/bin"));
var files = di.GetFiles("*.dll");
foreach (var fi in files)
{
var found = false; //already loaded?
foreach (var asm in initialAssemblies)
{
var a = Assembly.ReflectionOnlyLoadFrom(fi.FullName);
if (asm.FullName == a.FullName)
found = true;
}
if (!found)
Assembly.LoadFrom(fi.FullName);
}
}
I guess this is not a crucial bug/problem and may not be worthy of stackoverflow users time as I can work around it but its bugging me more and more each day, and maybe someone has fix.