Is it a way of using a dependency from a project to another while they are in the same solution? For example:
ComputerVisionProject (solution):
1. ComputerVision.FaceRecognition
2. ComputerVision.Core
3 .ComputerVision.UI
In the first project: ComputerVision.FaceRecognition, I install a nugget, for example, "OpenCV" and I can use all the functions from it with "using OpenCV", but only in the ComputerVision.FaceRecognition project.
What I want is to use the same functions in the second project, ComputerVision.Core. but I don't want to install again the nugget, and seems that only "using OpenCV" doesn't work (even if I add the entire project as a reference to the second one) Is it possible to make another type of reference or something like: "using ComputerVision.FaceRecognition.OpenCV" ?
Use a project reference.
https://learn.microsoft.com/en-us/visualstudio/ide/managing-references-in-a-project?view=vs-2019
To test; create a new solution with two projects within it.
Within one project, add a nuget package. Say, Newtonsoft.Json
Add a project reference from your second project to the first
Dependencies should now look like so;
Now within TestConsoleApp, you can add using statements to access the nuget package used in TestConsoleApp2.
eg;
using System;
using Newtonsoft.Json;
namespace TestConsoleApp
{
class Program
{
static void Main(string[] args)
{
var output = JsonConvert.SerializeObject(new ExampleObject() { field = "value" });
Console.WriteLine(output);
}
}
public class ExampleObject
{
public string field;
}
}
When run outputs {"field":"value"}
Related
I have two dotnetcore2.1 projects. First project calls a method of the second project via reflection.
using System;
using System.Reflection;
namespace experiment1
{
class Program
{
static void Main(string[] args)
{
Type _type = Type.GetType("experiment2.Program");
object _object = Activator.CreateInstance(_type);
MethodInfo info = _type.GetMethod("SecondProjectsMethod");
info.Invoke(_object, new object[]{});
}
}
}
I can't give any reference to the Second Project nor changes its code. How can I make this call successfully without adding a Reference to the First Project? I tried to add records to the first project's deps-file and execute the first program like this:
dotnet exec --depsfile experiment1.deps.json experiment1.dll
It didn't work. Is it even possible to do this by changing deps-file or any other config? Or should I manipulate .dll file somehow? Which direction I should go?
You can manually load the assembly by calling:
Assembly.Load("experiment2");
It should look for the assembly in the current folder, or use the deps file to locate it. After that, you should be able to use Type.GetType just fine.
If you want to specify the full path to the assembly, use AssemblyLoadContext.Default.LoadFromAssemblyPath instead.
You can refer to this page for more information on the different ways of loading an assembly in .net core.
How to include one c# file into another c# file?
I have two c# file like one is test.cs and another one is main.cs. I want to include test.cs into main.cs.
test.cs file code
// you can use Console.WriteLine for debugging
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Solution
{
public bool solution(long number1, int[,] arr1,int dim_2,int dim_3)
{
//some code here
}
}
main.cs code
using System;
include test.cs;
class Group
{
public static void Main(String[] args)
{
long number1 = 5;
int [,] arr1 = new int[,] {{0, 0},{1, 1},{2, 2},{3, 3},{4, 4}};
int dim_2 = 5;
int dim_3 = 2;
Solution object_class = new Solution();
bool result = object_class.solution ( number1, arr1, dim_2, dim_3 );
Console.WriteLine("Return :");
Console.WriteLine( result );
}
}
what i am doing wrong here?? Please Help me.
Thank you in Advance
I guess your problem is because both files are not added in the same project.
If you are using Visual Studio.
To add test.cs in the Group class project.
Go to Solution Explorer -> Add Existing item -> Browse your file i.e.
test.cs -> OK
If you are using DOS mode.
Make sure that both files must be in same folder.
And in either case. first delete include test.cs; from Main file. then Compile & RUN
We create object of classes declared in other source code files with the way you have already followed:
Solution object_class = new Solution();
Provided that the Solution class is declared in a source code file in the same project (console application as I can infer from your post), you don't have to mark the Solution class as a public. Otherwise, you should mark it as a public. Actually, you have to do so in case of this class is going to be used outside of your current project.
Your problem, I think is about namespaces. You might have declared this class inside a folder. Anyways, the way to solve this is to right click on the name of the Solution and then click resolve references.
ASP.NET C# Classes
this solution was helpfull for class files outside the App_Code
you need add follow line in every page(aspx) or usercontrol(asc)
<%# Assembly Src="~/App_Ctrl/PraxisPdfs/class_pdf.cs" %>
I have an ASP.Net website that references a class library. In the class library I need to read a file into memory.
At the top level of my class library there is a folder called EmailTemplateHtml containing the file MailTemplate.html that I want to read in.
How can I do this?
In Visual Studio, you can configure your library such that the file is copied into the build directory of any project that depends upon it. Then you can get the path to the build directory at runtime in order to read your file.
Step by step instructions, starting from a fresh solution:
Create your application project and your class library project.
Add a reference to the class library project from the application project via Properties->Add->Reference from the application's context menu in Solution Explorer:
Create the file in your class library project that you need to read, then set its Copy to Output Directory property to either Copy always or Copy if newer via the Properties pane in Solution Explorer:
From within either the class library project or your application (either will work with exactly the same code), reference your file relative to Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location). For example:
using System.Reflection;
using System.IO;
namespace MyLibrary
{
public class MyClass
{
public static string ReadFoo()
{
var buildDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var filePath = buildDir + #"\foo.txt";
return File.ReadAllText(filePath);
}
}
}
(Note that back before .NET Core, you could use a file path relative to System.IO.Directory.GetCurrentDirectory() instead, but this doesn't work in a .NET Core application because the initial working directory for .NET Core apps is the source directory instead of the build directory, apparently because this was needed by ASP.NET Core.)
Go ahead and call your library code from your application code, and everything will work fine. e.g.:
using Microsoft.AspNetCore.Mvc;
using MyLibrary;
namespace AspCoreAppWithLib.Controllers
{
public class HelloWorldController : Controller
{
[HttpGet("/read-file")]
public string ReadFileFromLibrary()
{
return MyClass.ReadFoo();
}
}
}
using System.IO;
using System.Reflection;
public static string ExecutionDirectoryPathName()
{
var dirPath = Assembly.GetExecutingAssembly().Location;
dirPath = Path.GetDirectoryName(dirPath);
return Path.GetFullPath(Path.Combine(dirPath, "\EmailTemplateHtml\MailTemplate.html"));
}
If you want to find the path where the assembly is located; from within the assembly then use the following code:
public static string ExecutionDirectoryPathName
{
get
{
var dirPath = Assembly.GetExecutingAssembly().Location;
dirPath = Path.GetDirectoryName(dirPath);
return dirPath + #"\";
}
}
I am not sure what you mean by a folder in the class library but you can use the current working directory if you wish to build a path as follows:
System.IO.Directory.GetCurrentDirectory()
You can then use the Path.Combine() method to build file paths.
You can add a Static class in your class library with some static methods/properties to set. Set the values from Global.ascx.cs on start app method. Now you can get the values of class library.
Hope this makes clear.
Happy coding
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 created a solution called Foo.
Added a class library called Foo.Common
Added a console app to call the library code from called ConsoleApp.
I referenced the Foo.Common from ConsoleApp and typed :
using Foo.Common;
public class Program
{
CommonClass c = new CommonClass();
static void Main(string[] args)
{
}
}
and get this back :
Error 1 The type or namespace name '**Foo**' could not be found (are you missing a using directive or an assembly reference?) Z:\Foo\Solution1\ConsoleApplication1\Program.cs 3 11 ConsoleApplication1
Why am i getting this?
what s going on?
Make sure that
The ConsoleApp project has a reference to the Foo.Common project (do not browse for Foo.Common.dll),
the file contains a using directive for the namespace in which CommonClass is declared, and
CommonClass is declared as public.
So your files should look like this:
CommonClass.cs in Foo.Common project:
namespace Foo.Common
{
public class CommonClass
{
public CommonClass()
{
}
}
}
Program.cs in ConsoleApp project:
using Foo.Common;
namespace ConsoleApp
{
public class Program
{
public static void Main()
{
CommonClass x = new CommonClass();
}
}
}
Ensure that under your project settings, the target framework is set as .NET Framework 4 and not .NET Framework 4 Client Profile. I got this same behavior when it was set to Client Profile and it was fixes as soon as I set it to just the regular .NET Framework 4.
Right Click on the new console app solution/project and Add Reference and add the project that contains the Foo namespace
Did you add a reference to the library? Look under "References" in the console project. If its not there, you need to add it.
I posted this as a comment, but I want to expand on it here. What's probably happening is it's seeing using as a statement and not a keyword. It appears you have something like the following:
using System;
namespace TestNamespace
{
using Foo.Common;
public Class { }
}
Try
using System;
using Foo.Common;
namespace TestNamespace
{
public Class { }
}
Instead.
It looks like Foo Bar got this error because his project's target framework was set to the client profile.
Just thought I'd add one more 'solution' -- I created a library that targeted the 4.5 framework. My older project was tarting the 4 framework. I got this error.
Changing the older project to 4.5 made it work.