Referencing of classes and namespaces Visual Studio 2017 - c#

I noticed for my little project that when importing classes some use full folder reference while otheres don't.
Here is code from project Mini that i am working on.
Models folder
Contains two entities, Auto and Airplane
namespace Mini.Models {
public class Auto {
// code and stuff
}
}
namespace Mini.Models {
public class Airplane {
// code and stuff
}
}
Services folder Contains single service class
namespace Mini.Services
{
public class AutoService : IAutoService {
public bool Get() {
var autoObject = new Models.Auto(); // notice how it references Models folder
var planeObject = new Airplane(); // Same folder but not referencing Models in front of it
// other code
}
}
public interface IAutoService {
bool Get();
// others
}
}
While not a major bugbear, it is still annoying that two classes in same folder get referenced differently, and i cannot figure out why.
Any advice would be appreciated.
Error Message when removing Models folder
Error CS0118: 'Auto' is a namespace but is used like a type (34, 27)

Based on the error message you have provided:
Error CS0118: 'Auto' is a namespace but is used like a type (34, 27)
It would appear that you have a namespace called Auto. Imagine the following example:
namespace MyApp.Auto
{
class Test
{
}
}
namespace MyApp
{
class Auto
{
}
class MyTest
{
private Auto test;
}
}
Because you can see, from the MyApp namespace, both a class called Auto and a namespace called Auto (either namespace MyApp.Auto or simply namespace Auto), C# isn't sure which one you want. As such, it's forcing you to be specific in choosing one or the other.
The easiest solution is to change the MyApp.Auto namespace to something else.

This is not fix but explaining with proper code sample (and why ).
namespace Mini.Models
{
public class Auto
{
// code and stuff
}
}
namespace Mini.Models
{
public class Airplane
{
// code and stuff
}
}
namespace Mini.Auto
{
public class OtherAirplane
{
// code and stuff
}
}
namespace Mini
{
using Mini.Models;
using namespaceAuto = Auto ; /// this also not fix the issue.
class NamespaceIssue
{
void execute()
{
var autoObject = new Auto(); // Error
var planeObject = new Airplane(); // Same folder but not referencing Models in front of it
// other code
}
}
}
now you can see some were in code you have "Mini.Auto" namespace , and it is couching issue.
i tested for VS 2015 have same issue. maybe we have to report to VS team or it is by design .

The issue seemed to be with VS2017 or the way it created the project first time around.
Upon starting brand new project (ASP Core 2.2, Web API, with https enabled and docker disabled), and using same classes the issue was non-existant.

Related

VS “A project with an Output type of Class Library cannot be started directly”

I'm novice in C#. I've cloned the project, built it successfully.
Now I want to debug Postman POST request.
I found the place where that request in handled in Project. That .cs file looks like this:
namespace Blah.Something
{
public class SomethingRequest: IInterface
{
...
public object DoRequest (SomeRequest request)
{
...
}
}
}
When I start SomethingRequest class, I have this error:
I've tried to set .csproj in which SomethingRequest class is located as "Set as a Startup Project" as per suggestion here, and then rebuilt the solution, but I keep receiving same error. Can anyone help me to resolve that issue?
You can't run the classlibrary directly.
I have two solutions and you may refer to it.
First, Please create a new project(such as console app) to call the method in that library.
Like the following:
Classlibrary:
namespace Testlibrary
{
public class Student
{
public void SayHello(string name)
{
Console.WriteLine("Hello, I am {0}",name);
}
}
}
Console app:(Please add reference)
using System;
using Testlibrary;
namespace _1.Test_for_using_library
{
class Program
{
static void Main(string[] args)
{
Student s = new Student();
s.SayHello("Jack");
Console.ReadKey();
}
}
}
Result:
Second, you can change the classlibrary to the console app to call the method.
Right click the Classlibrary->Properties-> Change Output type to Console Application -> Add the following code in the Student Class.
static void Main()
{
Student student = new Student();
student.SayHello("Jack");
Console.ReadKey();
}
Finally, you will the same result as the before.

Unable to access a new class added to a class library

I have a class library that I added another class to that no matter what I try it will not be available in the project that I am referencing the library from. I have no problem with the original class I created in this library referencing and using.
I have tried all of the below:
Cleaning the project solution
Save and rebuild both the debug and release
Closing the project and reopening
Steps one through three on the library project I'm tyring to reference
In the project that I want to reference the library from I have tried loading the .dll form the bin/release folded, and the main library project .dll in the obj/release folder. Neater have made a difference because I still cannot get to the new class I added to the library. I am referencing the DotNetOpenAuth_Library.dll from the release folded in the bin.
If this makes a difference I'm using VS 2012 Express for Web that I downloaded last week.
The class I added to my library that has no build errors is:
namespace DotNetOpenAuth_Library
{
class EmbeddedResourceUrlService : IEmbeddedResourceRetrieval
{
private static string pathFormat = "{0}/Resource/GetWebResourceUrl? assemblyName= {1}&typeName={2}&resourceName={3}";
//private static string pathFormat = "{0}/Resource/GetWebResourceUrl";
public Uri GetWebResourceUrl(Type someTypeInResourceAssembly, string manifestResourceName)
{
if (manifestResourceName.Contains("http"))
{
return new Uri(manifestResourceName);
}
else
{
var assembly = someTypeInResourceAssembly.Assembly;
// HACK
string completeUrl = HttpContext.Current.Request.Url.ToString();
string host = completeUrl.Substring(0,
completeUrl.IndexOf(HttpContext.Current.Request.Url.AbsolutePath));
var path = string.Format(pathFormat,
host,
HttpUtility.UrlEncode(assembly.FullName),
HttpUtility.UrlEncode(someTypeInResourceAssembly.ToString()),
HttpUtility.UrlEncode(manifestResourceName));
return new Uri(path);
}
}
}
}
Put public in front of the class definition. If the class is marked internal1 it can only be accessed by other classes within the same assembly2.
namespace DotNetOpenAuth_Library
{
public class EmbeddedResourceUrlService : IEmbeddedResourceRetrieval
{
//(snip)
}
}
Here is a MSDN link explaining access modifiers.
1: If you do not put a modifier in front of the class it will default to internal.
2: unless you mark the other assembly a friend assembly
It looks to me like the problem is just the lack of an access modifier. By default the c# compiler treats classes as internal. It should work if you change the declaration to
public class EmbeddedResourceUrlService : IEmbeddedResourceRetrieval
The class EmbeddedResourceUrlService is private, use public modifier
namespace DotNetOpenAuth_Library
{
// make class public
public class EmbeddedResourceUrlService : IEmbeddedResourceRetrieval
{
private static string pathFormat = "{0}/Resource/GetWebResourceUrl? assemblyName= {1}&typeName={2}&resourceName={3}";
//private static string pathFormat = "{0}/Resource/GetWebResourceUrl";
public Uri GetWebResourceUrl(Type someTypeInResourceAssembly, string manifestResourceName)
{
if (manifestResourceName.Contains("http"))
{
return new Uri(manifestResourceName);
}
else
{
var assembly = someTypeInResourceAssembly.Assembly;
// HACK
string completeUrl = HttpContext.Current.Request.Url.ToString();
string host = completeUrl.Substring(0,
completeUrl.IndexOf(HttpContext.Current.Request.Url.AbsolutePath));
var path = string.Format(pathFormat,
host,
HttpUtility.UrlEncode(assembly.FullName),
HttpUtility.UrlEncode(someTypeInResourceAssembly.ToString()),
HttpUtility.UrlEncode(manifestResourceName));
return new Uri(path);
}
}
}
}
even if then the class does not shows up (has happended to a couple time)
clean solution
delete all bin folder from both project
rebuilt all
and error wont be there

Stumped on MVC MEF application

I'm trying to implement the the Microsoft Extensibility Framework (MEF) into a sample MVC-based web app. I'm using the SimpleCalculator example solution on the MEF Overview page. My goal is an application that can dynamically load a DLL extension from another project in order to extend the capabilities of the Model, essentially I want the MVC-Application to be a framework for other extensions to plug-into. First my setup:
Project 1 (MVC-Application, MEF Component Host):
I decorate the elements in my Model as follows:
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace ExpressionParserPOC.Models
{
public class ExpressionModel
{
private CompositionContainer _container;
[ImportMany]
IEnumerable<Lazy<IExtensions,IExtensionName>> extensions { get; set; }
public ExpressionModel()
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new DirectoryCatalog("C:\\local_visual_studio\\ExpressionParserPOC\\ExpressionParserPOC\\Extensions"));
//Create the CompositionContainer with the parts in the catalog
_container = new CompositionContainer(catalog);
_container.ComposeParts(_container);
//TEST: Can we access the extensions?
if (extensions != null)//<--NULL WHEN CONSTRUCTOR IS CALLED WHY? Expected GetMatrix() Function from DLL to be exposed
{
foreach (Lazy<IExtensions, IExtensionName> i in extensions)
{
Lazy<IExtensions, IExtensionName> foo = i;
}
}
}
}
public interface IExtensions
{
double[][] GetMatrix(string matrix);
}
public interface IExtensionName
{
Char Symbol { get; }
}
}
To test right now, I'm just calling the constructor for the Model from the Controller:
namespace ExpressionParserPOC.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Enter an Expression for Octave to evaluate";
//Instantiate an ExpressionModel composed of extensible parts
var model = new ExpressionModel();
return View(model);
}
}
}
Project 2 (DLL Project, MEF Component):
//PROJECT BUILD OUTPUTS TO THE EXTENSIONS DIRECTORY IN PROJECT 1 ABOVE
using System.ComponentModel.Composition;
namespace MyExtensions
{
//Project 1 already added as a reference
[Export(typeof(ExpressionParserPOC.Models.IExtensions))]
[ExportMetadata("Symbol", 'o')]
public class Octave : MyExtensions.IExtensions
{
//Other class properties, constructors, functions, etc.
#region FUNCTIONS
public double[][] GetMatrix(string matrix)
{
double[][] mat = new double[][];
//Do Stuff
return mat;
}
#endregion
}
public interface IExtensions : ExpressionParserPOC.Models.IExtensions
{
}
}
Problem is that the the extensions List in the host MVC application project never gets filled when I call the Model constructor from the Controller in that same project. I'm new to MEF development and am not sure what I'm doing wrong, is there something extra I need to consider since I'm working with an MVC application? Why won't the Project 1 extensions list get filled? Are my interface definitions wrong? The sample calculator application is a simple command line project and that seems to work fine, the only difference I see is that the external DLL project is in the same solution space, whereas with my example the solution spaces are independent.
A trivial mistake you have there in the ExpressionModel constructor. You are composing the container itself :)
_container.ComposeParts(_container);
The problem should be apparent instantly, because if the composition of the ExpressionModel actually ever happened, even if no extensions were discovered, the extensions property would be initialized with 0 items, but it wouldn't be null.
You need to compose the current model instance like this:
_container.ComposeParts(this);
Everything else seems to be alright and should be working fine after this correction.

c# Namespace already contains a definition for inherited class so how to add a constructor

I am carefully treading into WCF attempting to follow tutorials and convert my ASMX project to a new WCF project and I've stumbled upon a mystery about coding of my constructor in WCF.
My ASMX webservice allowed me to have a constructor (see: same name, no return value):
namespace sdkTrimFileServiceASMX
{
public class FileService : System.Web.Services.WebService
{
Database db;
string g_EventSource = "CBMI-TrimBroker";
string g_EventLog = "Application";
public FileService()
{
try
{
if (!EventLog.SourceExists(g_EventSource))
EventLog.CreateEventSource(g_EventSource, g_EventLog);
}
catch (InvalidOperationException e)
{
e.ToString();
}
}
My attempt to convert this to a WCF service app gives this compiler complaint:
The namespace 'sdkTRIMFileServiceWCF' already contains a definition for 'FileService'
Here is the WCF code (beginning snippet):
namespace sdkTRIMFileServiceWCF
{
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class FileService : IFileService // err msg points to this line
{
Database db;
string g_EventSource = "CBMI-TrimBroker";
string g_EventLog = "Application";
public FileService()
{
try
{
if (!EventLog.SourceExists(g_EventSource))
EventLog.CreateEventSource(g_EventSource, g_EventLog);
}
catch (InvalidOperationException e)
{
e.ToString();
}
}
This isn't related to the existence of the constructor. I am fairly sure this is a copy/paste error- perform a search for the word "FileService" in any files in your application and you will find another class or a namespace declaration with that name (in the same namespace).
Some things you could do:
do right mouse click > Find references on FileService.
Try a full search (ctrl+f) and search for FileService.
Check any partial classes for a second constructor.
Try clean solution and then rebuild the solution, see if this makes
any difference.
...

ASP.NET MVC 2 Unit Testing Stange Errors

I am working through the book Professional ASP.NET MVC 2 and I am trying to get the unit testing in chapter 1 to work correctly; howver, I am getting some very strange errors.
There are two projects in the solution: NerdDinner, and NerdDinner.Tests.
In the NerdDinner Project I have the following interface:
IDinnerRepository.cs
//...
namespace NerdDinner.Models
{
interface IDinnerRepository
{
//...
}
}
Also in the NerdDinner project, I have the following class:
//...
using NerdDinner.Models;
//...
namespace NerdDinner.Controllers
{
public class DinnersController : Controller
{
IDinnerRepository dinnerRepository;
// Default constructor
public DinnersController() : this(new DinnerRepository()){} // DinnerRepository is another concrete implementation of IDinnerRepository
//Test constructor
public DinnersController(IDinnerRepository repository) {
dinnerRepository = repository;
}
}
}
In the NerdDinner.Tests project, I have the following concrete implementation of IDinnerRepository:
//...
using NerdDinner.Models;
//...
namespace NerdDinner.Tests.Fakes
{
class FakeDinnerRepository : IDinnerRepository
{
//...
public FakeDinnerRepository(List<Dinner> dinners)
{
//...
}
//...
}
}
Now for the actual unit test (in NerdDinner.Tests)
using NerdDinner.Controllers;
//...
using NerdDinner.Models;
using NerdDinner.Tests.Fakes;
namespace NerdDinner.Tests
{
[TestClass]
public class DinnersControllerTest
{
List<Dinner> CreateTestDinners()
{
//...
}
DinnersController CreateDinnersController()
{
return new DinnersController(new FakeDinnerRepository(CreateTestDinners()));
}
}
}
And now for the actual problem:
In the method CreateDinnersController in the class DinnerControllerClass, I am getting the following error:
DinnersController.DinnersController(NerdDinner.Models.IDinnerRepository repository) (+ 1 overload(s))
Error:
The best overloaded method match for 'NerdDinner.Controllers.DinnersController.DinnersController(NerdDinner.Models.IDinnerRepository)' has some invalid arguments.
It gives me the option to create a constructor stub in DinnersController. It generates the following code:
private global::NerdDinner.Tests.Fakes.FakeDinnerRepository repository;
//...
public DinnersController(global::NerdDinner.Tests.Fakes.FakeDinnerRepository repository)
{
// TODO: Complete member initialization
this.repository = repository;
}
Even after generating that code, I still get the same error. But why should I even need that code anyway? As far as I can tell, I am doing everything correctly.
Can anybody help me figure out what is going on here?
Edit
The generated code is giving the following error:
The type or namespace 'Tests' does not exist in the namespace 'NerdDinner' (are you missing any assembly reference?)
From what you've shown the IDinnerRepository interface is not public meaning that it is not visible from your unit test. I would recommend you making it public as I suspect you have two different interfaces : one defined in the unit test and one in your project which conflict. Also I would recommend you to avoid relying on Visual Studio generate all the crap reflection code in order to test private and internal members.
The last error you're getting is due to there being no reference from the production code to the test code - but that's appropriate. You don't want that extra constructor.
Instead, you need to find out why the existing constructor taking an IDinnerRepository isn't being used. Are you sure you only have one interface called IDinnerRepository? If you go to the FakeDinnerRepository source, go to the declaration, put the cursor in IDinnerRepository and hit F12 (go to definition) does it go to the right place?
If you add a new member to IDinnerRepository (just for the sake of testing: void Foo(); would be fine) does it cause both the production and fake implementation to fail to compile?

Categories

Resources