IDE: VS 2010, C# .net,
I have two win projects in 1 solution,
ProjA, and ProjB
now ProjA contains classA.cs
namespace ProjA
{
class ClassA
{
public static int aValue = 5;
}
}
same way ProjB contains ClassB.cs
namespace ProjB
{
public class ClassB
{
public static int bValue = 10;
}
}
and here is FormA.cs
using System;
using System.Windows.Forms;
using ProjB;
namespace ProjA
{
public partial class FormA : Form
{
public FormA()
{
InitializeComponent();
}
private void FormA_Load(object sender, EventArgs e)
{
int va = ProjB.ClassB.bValue;; //Here getting error.???
}
}
}
Error : Cannot resolve symbol ProjB
Hint: This Problem Is related to namespace, I am trying to access ClassB which is in ProjB from FormA which is in ProjA, Here ProjA and ProjB are the 2 winforms project in Same solution
---xxxx----------- THis problem has been solved.
but now I want to access ClassA.cs in FormB.cs (just reverse of above problem),
when I tried same way ProjB(RighClick) -> Add reference -> ProjName(Tab) ProjA(Click)
The new problem I am facing is its saying unable to add it will create circular dependency, Please suggest How to solve this issue.
I want to access ClassA.cs in ProjB->FormB.cs here FormB is in ProjB
You need to create new instance of class or make it static.
So this:
namespace ProjB
{
public static class ClassB
{
public static int bValue = 10;
}
and then
int va = ClassB.bValue;
OR
int va = new ClassB().bValue;
ProjB is the namespace, so it doesn't know which class to use. If they're in the same solution(package of projects), just use the classname ClassB.(Or ProjB.ClassB.bValue)
If your projects aren't in the same Solution, go to Project A, File->Add->Existing Project, and add ProjB.
Provided you have referenced correctly ProjB you just need to instatinate classB in ProjA:
using System;
using System.Windows.Forms;
using ProjB;
namespace ProjA
{
ProjB.ClassB classb=new ProjB.ClassB();
public FormA()
{
InitializeComponent();
....
classb.bValue=....//set desired valued
}
private void FormA_Load(object sender, EventArgs e)
{
int va =classb.bValue;
}
The problem was with reference,
I added reference
Right click ProjA -> References -> Add Reference, then I added ProjB.
And Problem resolved. :-)
In your visual studio
1-) Right click to your solution
2-) Then open Properties of the solution..
In the properties page, on the left you'll see menus..
3-) Click to Project Dependencies
In Details of project Dependencies (right side of the page )
4-) Select your Project A from the DropDownList which has a label with "Project"
5-) Under the DropDownList Check (Mark as checked) the ProjectB
6-) Click to save / ok
This operation what you did, warns the compiler as so :
"When you start to build ProjectA, Before build/compile ProjectA First build/Compile ProjectB and then continue to build ProjectA"
or in another saying
" Dear Compiler !
When you work with my ProjectA, You will need My ProjectB to do your work properly.
So please also check my ProjectB.
Best Regards, Your Lovely Developer "
NOTE : Never circular reference (ProjectA depends to ProjectB and ProjectB depends to ProjectA) to eachother..this gets infinitive recursion error of the compiling your code..!
Visual Representation of The VS2010-ProjectDependencies Box
Related
I am programming an application that checks some data in a DB (the DB continuously updated).
For getting the data from the DB I am using an assembley (.dll file) programmed by another team (I can't get/change the code of the .dll file).
I want to "stress test" my algorithem/porgram with my own data (extreme data), I can't change the DB.
a simplified code example:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//timer1.Interval = 10000
private void timer1_Tick(object sender, EventArgs e)
{
DataTable values = someLib.GetData(DateTime.Now.AddDays(-1),DateTime.Now);
CheckData(values); //checking the data form the DB, I want to "stress test" this function/logic.
}
}
I want someLib.GetData function to return a specific data (ment to check my program).
I can write a new function that returns the same DataTable like someLib.GetData (same colums etc.) but with my own data, the problem is that this solution requires to manually check all the occurrences of GetData (and more functions that take data from the DB) and change them manually.
I am searching for some systematic way for approaching this.
Another way I thought of is to just delete the reference and "repair" all the errors, the problem is there is a lot of functions I am using in the aforementioned library that I am still in need of.
My qustion is, is there any way to override/disable a function/s (or even whole classes) from an assembly I dont have the code of?
Thank you.
EDIT: the method/s are not virtual.
What about this solution (if I understand the problem correctly):
public class MyLib {
public SomeLib someLib { get; set; }
public MyLib (SomeLib someLib) {
this.someLib = someLib;
}
public void methodFromSomeLibWhichIsRequired(...) {
return someLib.methodFromSomeLibWhichIsRequired(...);
}
// ... so on for any used methods of SomeLib
public DataTable getData() {
// my own implementation of method of SomeLib
}
}
Than all that you need is change the declaration of your SomeLib instance to MyLib instance, i.e. instead of
SomeLib someLib = new SomeLib();
use this
MyLib someLib = new MyLib(new SomeLib());
So you don't need to change the name of someLib everywhere and you just implement those methods in your MyLib which you need from SomeLib.
I have 2 projects in my asp.net C# solution. One project is 'AeS.PIMS_Education_2275.IL' and the other is 'AeS.PIMS_Education_2275.PL'. I just created a new method in a class called 'PIMS_Education_IL_2275' belonging to 'AeS.PIMS_Education_2275.IL'. The project 'AeS.PIMS_Education_2275.PL' has a reference to 'AeS.PIMS_Education_2275.IL', but when I create an object of the class 'PIMS_Education_IL_2275' inside the class 'PIMS_Education_2275' of 'AeS.PIMS_Education_2275.PL' and try to access the methods in it, I am able to access all methods apart from the newly created method. What might be wrong here ? Below are the code snippets:
Class - AeS.PIMS_Education_2275.IL
namespace AeS.PIMS_EducationDetails_IL_2275
{
public class PIMS_Education_IL_2275
{
public DataSet ValidateEducationDiscipline() //newly created method
{}
}
}
Class - PIMS_Education_2275
using AeS.PIMS_EducationDetails_IL_2275;
namespace AeS.PIMS_Education_2275.PL
{
public partial class PIMS_Education_2275
{
public bool FormValidation()
{
PIMS_Education_IL_2275 o = new PIMS_Education_IL_2275(); //Creating an object
o.ValidateEducationDiscipline(); //Not able to call the method here
}
}
}
Additional information - I had just one project in the solution initially and then added the second one in which I created a new method.
Screen shots of dependencies:
1) Use the project reference instead of direct reference.
2) verify the build order of the solution. The project AeS.PIMS_Education_2275.IL should build first and then AeS.PIMS_Education_2275.PL
Let's say I have multiple projects within a solution. I have the main project parent_project and another project child_project.
How can I access classes / namespaces residing in parent_project from child_project ?
I have already added a Reference to child_project in parent_project so I can't add a Reference to parent_parent in child_project as it would create a circular dependency.
Is this possible?
If you're sharing logic between projects, you need to isolate that dependency and move it to a shared location (new project for example), restructure your dependencies so that your core logic lives in a core domain-like project or mash your projects together.
The latter is not really the cleanest of solutions. I would recommend thinking about your own question and really try to answer "Why do I NEED a circular reference? How can I restructure so that my dependencies make sense?".
You can inject your dependency using an interface defined in the child project (this can be useful where major refactoring is not possible/too expensive).
e.g. In the child project:
interface IA {
DoLogicInB();
}
In the parent project:
class ConcreteA : ChildProject.IA
{
DoLogicInB() { ... }
}
In the child project, where you need the logic:
class ChildB {
void DoSomethingWithParent(IA logicEngine) {
logicEngine.DoLogicInB();
}
}
You need to then be able to inject a concrete implementation of the parent object from outside the child project.
FYI
I ended up just copying the logic to a shared location, and "child" projects can access this version. I know from a maintainability point of view this isn't the best solution but it seemed like the best compromise..
I didn't require entire namespace, but just reading some data dictionary or calling one particular method from parent project class. Here is how we got it working.
using System;
using NUnit.Framework;
using System.Collections.Concurrent;
namespace MyProject.tests
{
public class ParentChildTest
{
[Test]
public void dataAndMethodTest()
{
// add the data in parent project
Parent.propertyCache["a"] = "b";
// read the data in child project
Console.WriteLine("Read from child: " + Child.getProperty("a"));
// use Child project to call method of parent project
Console.WriteLine("Call from child: Populate method in parent: " + Child.populate("c"));
}
}
class Parent
{
// data is in Child project. Parent project just has the reference.
public static ConcurrentDictionary<string, string> propertyCache = Child.getPropertyCache();
public static string populate(string key)
{
//calculation
string value = key + key;
propertyCache[key] = value;
return value;
}
// Pass the parent project method reference to child project
public static int dummy = Child.setPopulateMethod(populate);
}
class Child
{
// data store
static ConcurrentDictionary<string, string> propertyCache = new ConcurrentDictionary<string, string>();
public static ConcurrentDictionary<string, string> getPropertyCache()
{
return propertyCache;
}
public static string getProperty(string key)
{
if (propertyCache.ContainsKey(key))
{
return propertyCache[key];
}
return null;
}
// reference to parent project method
static Func<string, string> populateMethodReference = null;
public static int setPopulateMethod(Func<string, string> methodReference)
{
populateMethodReference = methodReference;
return 0;
}
public static string populate(string key)
{
return populateMethodReference(key);
}
}
}
Using parent project class data in child
Earlier the propertyCache was in parent class. Child needed to access it.
So, the propertyCache has been moved to Child. Parent also reads and populates the same.
Using parent project class method in child
Pass the method reference to the child somehow (by some static method).
use the reference to invoke that parent method.
Output of the program
Read from child: b
Call from child: Populate method in parent: cc
I have to say that Yannicks answer is the way to go there normally. In your special situation (as outlined in your comment to his answer) it sounds like that would be problematic. A different way would be (only possible if the mainclass compiles into a dll):
Include the compiled dll of the mainproject in the child project
Use the methods you need via reflection
This is one possible other route BUT has quite a few pitfalls as reflection has troubles of its own.
Ok so let's say you have a Project with 2 solution in it S1 and S2 and you have reference S1 in S2, inside S1 it you have a class P and in S2 you have three Class defined by user A B an C. now make A inherit P so when you invoke constructor of A it will invoke constructor of P (that's in In S1) noe inside P's Constructor if you want the list of all the class declared in S2 use this code.
Assembly assembly = this.GetType().Assembly;
// DefinedTypes will list all Userdefined class
foreach (var typeInfo
inassembly.DefinedTypes )
{
// typeInfo.FullName //you will have A B and C
}
I have made desktop application. I have make class library and then make its DLL from University assembly. Now i want to make library DLL optional. In short i want to run the application weather or not library DLL is refereed.
Right now if i remove reference of library DLL then it gives error on library methods that they are not defined. I want this application to run with oujt giving error of library method.
I have search on google but i am unable to find out any reliable answer.
Check if assembly exists on disk, and if it's true use dynamic assembly loading:
http://msdn.microsoft.com/en-us/library/25y1ya39.aspx
Called classes/methods in your library can be replaced by stubs(new level of abstraction), in which you can check if assembly is successfully loaded, and invoke from it if yes.
Ok.. Very simple example:
"Real Assembly" code(First project, compiled as class library "RealAssembly.dll"):
namespace RealAssembly
{
using System;
public class RealClass
{
Random rand = new Random();
public int SomeProperty { get { return rand.Next(); } }
public string SomeMethod()
{
return "We used real library! Meow!";
}
}
}
"Our project" code with Fake(stub) class(Second project, compiled as Console applicaiton - "ClientApp.exe"):
using System;
using System.IO;
using System.Reflection;
namespace ClientApp
{
class FakeClass
{
public int SomeProperty { get { return 0; } }
public string SomeMethod()
{
return "Library not exists, so we used stub! :)";
}
}
class Program
{
// dynamic instance of Real or Fake class
private static dynamic RealOfFakeObject;
static void Main(string[] args)
{
TryLoadAssembly();
Console.WriteLine(RealOfFakeObject.SomeMethod());
Console.WriteLine(RealOfFakeObject.SomeProperty);
Console.WriteLine("Press any key...");
Console.ReadKey();
}
private static void TryLoadAssembly()
{
string assemblyFullName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RealAssembly.dll");
if (File.Exists(assemblyFullName))
{
var RealAssembly = Assembly.LoadFrom(assemblyFullName);
var RealClassType = RealAssembly.GetType("RealAssembly.RealClass");
RealOfFakeObject = Activator.CreateInstance(RealClassType);
}
else
{
RealOfFakeObject = new FakeClass();
}
}
}
}
This two projects are not referenced directly. "System" is the only reference used in this two projects.
So now, if compiled "RealAssembly.dll" exists in same directory we will have "We used real library! Meow!" string and random integer at console output. Otherwise if "RealAssembly.dll" not exists in same directory - "Library not exists, so we used stub! :)" and 0 will be shown.
I have 3 class libraries, LibA, LibB & LibC. These libraries have defined classes A, B & C respectively.
class C
{
public IEnumerable<X> FuncInC()
{
return something;
}
}
LibC is added as a reference in LibB. And class B uses class C. Using MEF, I have exported class B from LibB.
[Export(typeof(InterfaceForB))]
class B : InterfaceForB
{
public IEnumerable<X> FuncInB()
{
return new C().FuncInC();
}
}
In class A, i am using the exported class from B, as follows.
public class A : InterfaceForA
{
[Import(typeof(InterfaceForB))]
private InterfaceForB _b;
private CompositionContainer _container;
public A()
{
var _catalog = new DirectoryCatalog(System.IO.Directory.GetCurrentDirectory());
_container = new CompositionContainer(_catalog);
_b = _container.GetExportedValue<InterfaceForB>();
}
public IEnumerable<X> FuncInA()
{
return _b.FuncInB();
}
}
When i run FuncInA(), it raises FileNotFoundException with the following details:
"Could not load file or assembly
'LibC, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null'
or one of its dependencies. The system
cannot find the file specified."
Note:
LibC reference exists in LibB, and it is build without errors.
And all the assemblies (output dlls in this case) exist in the the same folder.
If I comment the code "return new C().FuncInC();" in FuncInB() definition, & return a dummy object, it works without errors. The problem is because of the reffered LibC use.
In the LibB References shown in the solution explorer, right click on LibC, "properties", set "Specific Version" to "False".
Or better yet, delete the binary reference and replace it by a project reference (assuming that LibC is in the same solution as LibB).