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
Related
Here is info about our technical development environment :
• .NET Core 3.1
• PostgreSQL 14.2, compiled by Visual C++ build 1914, 64-bit
• EntityFramework.Functions Version=1.5.0
• Microsoft.EntityFrameworkCore.Design Version=5.0.17
• Microsoft.EntityFrameworkCore.Tools Version=5.0.17
• Npgsql.EntityFrameworkCore.PostgreSQL Version=5.0.10
The location of a C# code file called JohnDoeCSharp.cs is located in VisualStudioProjectDir\Migrations\1.0.5
It contains the following code constructor:
public class JohnDoeCSharp
{
public JohnDoeCSharp()
{
}
}
Within the aforementioned constructor, I’m trying to get the name of the parent directory called 1.0.5
The problem with using the following code is that they give runtime directory paths values back:
string strExeFilePath =
System.Reflection.Assembly.GetExecutingAssembly().Location;
string strWorkPath = System.IO.Path.GetDirectoryName(strExeFilePath);
For lack of a better term, I suppose I’m trying to get the directory path values at design time / “coding time”.
What can I try next?
You can write a helper method that uses the CallerFilePath attribute to get the directory of a code file.
Helper class:
public static class CodeHelper
{
public static string GetCodeDirectory([CallerFilePath]string filepath = "")
{
return Path.GetDirectoryName(filepath);
}
}
Usage:
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine(CodeHelper.GetCodeDirectory());
}
}
I have a static variable inside of my main project (mvc), I am wanting to be able to pass/use that variable in my other project (asp.net core 5.0 web api) project. I was reading up on how you can perform this task, one of the ways is using a static variable which I have. I read this post and one of the solutions mentions you can call that static variable from the first project into the other project by calling the namespace of that first project in the first project. However, when I do so it does not let me it says it does not exist. Is there a way to be able to do this?
On the post their example was:
using System.Windows.Forms;
namespace Demo1
{
public class Sample1
{
public static string x = "initial value of 'x";
public void sampleFn1() {x = "value of 'x set in function";}
}
}
namespace Demo2
{
public class Sample2
{
public void sampleFn2(){MessageBox.Show(Demo1.Sample1.x);}
}
}
For me, Project 1 is CustomerApp and Project 2 is Service.Api:
namespace CustomerApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public static Guid uniqueId = Guid.NewGuid();
}
}
Then in my ServiceApi I tried performing the same as the example from the post, but when I call the namespace CustomerApp it does not give me any options to reference it to the other project. Is there a specific using I need to use in order to replicate the example from the post?
namespace Service.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly ILogger<ValuesController> _logger;
public ValuesController(ILogger<ValuesController> logger)
{
_logger = logger;
}
// GET: api/<ValuesController>
[HttpGet]
[Route("sample")]
public ActionResult Get()
{
_logger.LogInformation("Target method invoked.....{#CorrelationId}", CustomerApp.); // here I am trying to perform CustomerApp.Controllers.HomeController.uniqueId.ToString()
}
}
}
You will want to make sure that the static variable is defined in a Class Library project, and that the Web project has a reference to the Class Library project.
The way your code is currently constructed, it looks like both projects are web projects (your first project mentions the HomeController). As much as possible, avoid this type of co-mingling. Move business logic into the class library, and keep the web logic in the web project.
I think you forgot to add the project reference to destination project where you want to use the variable ,
Add reference like this :
right-click on your destination project and select Add > Project Reference
and in final choose the variable project
this will help you
first, if you haven't, add it to the HomeController class (using CustomerApp.Controllers.HomeController;). Your own example does not match the example you reference. In the first example, a static variable is used between two different classes in the same namespaces, but in your example you are trying to operate between different namespaces and different classes.
So if your service is inside your main project you should add.
then you can use it as below.
public ActionResult Get()
{
_logger.LogInformation("Target method invoked.....{#CorrelationId}", HomeController.uniqueId.ToString());
}
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.
I am trying to get my head around sharing common Log class across C# Libraries that reference each other. The problem is that I am confused as to which direction to choose.
Example C# Log class code
namespace MyLogger.Log
{
public class MyLogger
{
public void Error(string message)
{
var eventArgs = new LogGeneratedEventArgs();
eventArgs.Message = message;
eventArgs.Type = LogType.Error;
LogGenerated?.Invoke(this, eventArgs);
}
public void Info(string message)
{
var eventArgs = new LogGeneratedEventArgs();
eventArgs.Message = message;
eventArgs.Type = LogType.Info;
LogGenerated?.Invoke(this, eventArgs);
}
public event EventHandler<LogGeneratedEventArgs> LogGenerated;
}
public class LogGeneratedEventArgs : EventArgs
{
public string Message { get; set; }
public LogType Type { get; set; }
}
public enum LogType
{
Error, Info
}
}
Say I got 2 other Libraries
Library 1
Library 2
Both the libraries need to log information of their internal working and depend on each other. So I have a new project for the above Log management class. But I do not intend to create a new reference dependency just to handle logging.
If I create a standalone C# library for the class then I have to update the NuGet package for that Log class library whenever I create new versions of the other 2.
If I add the code of the Log class as "Add to Link" in Visual Studio I get a namespace conflict error when working with other projects that need both the libraries. Moreover, when working with large projects I get multiple namespace options for the same Log class.
How should I go about sharing the Code across the 2 Libraries without having to add new reference dependency and hitting conflicts? :)
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.
...