I have a question regarding correct way to structure my application. I am a beginner on C# so excuse if I have some basis missing.
I looked on the web(not only stackoverflow) but didn't find any answer, so maybe this is just because I am doing something wrong?
I have a project in which there are several classes to define my objects.
Object1.class.cs
Object2.class.cs
...
Now for some functions, I created class libraries (.dll files) to externalise the code. The idea is if I need to make an update, I just need to replace .dll file, and not all the code.
But I meet a problem when I want to send objects to that class, I think because they are external to the solution?
So I begin to wonder if I do it correctly.
1) Is there a way to send an object from my project to a class I created separately?
2) Is this a good idea to work this way? I mean, I could of course add the library in my project, but in that case I will not have separated .dll files, and all get in a single .exe file.
3) When I need to test my class, I always need to close my project, and open the class to edit it, then come back to my project to test it. Is there an easier way to do it?
Thanks in advance for your advises
Edit 2.
Simone Cifani perfercly answered to my question :
1) Classes must be externalised
2) Add references to necessary classes in my external libraries
3) Add references to each class and external libraries in my main project
As I don't know how to use Interfaces I will do without it, but I think all will be fine even without.
A very common way to externalize part of the code is by using interfaces.
A simple example is:
//CalculatorInterface.dll
namespace Calculator.Interface
{
interface ICalculator
{
int DoCalculus(List<object> list);
}
}
//CalculatorImplementation_1.dll
// Add a reference to CalculatorInterface.dll
namespace Calculator.Implementation
{
using Calculator.Interface;
class CalculatorImplementation_1 : ICalculator
{
public int DoCalculus(List<object> list)
{
int result = 0;
foreach (Object obj in list)
{
if (obj is int)
{
result += (int)obj;
}
}
return result;
}
}
}
//Calculator.dll
// Add a reference to CalculatorInterface.dll
// Add a reference to CalculatorImplementation_1.dll (or dynamically load it)
namespace Calculator
{
using Calculator.Interface;
using Calculator.Implementation;
class MyCalculator
{
void CalculateSomething()
{
List<Object> list = new List<Object>();
list.Add(1);
list.Add(2);
list.Add("SomeString");
ICalculator calculator = new CalculatorImplementation_1();
int result = calculator.DoCalculus(list);
Console.Write(result);
}
}
}
Related
At first I have a Multi-platform Project where I created a Class which transfers Data and my problem is that as example if I click a Button a method in this class should be called but I cannot reach the method.
This is my project structure:
The red part is where the Data Handler is located
the green part from where I get the clicked event and call the method.
I'll hope someone can help me with this problem!
As Jason mentioned in comment, you can not reach code from platform specific just like that, because you are not referencing platform specific projects, and there is something called DependencyService (which Jason also mentioned) and that will help you to solve this "issue" that you have.
This is how you can use DependencyService, inside your shared code project, create one interface in my case that will be:
public interface IDataHandler
{
string GetSomeStringValue();
}
Go to your iOS or other platform specific project and create new class DataHandler.cs (which you already have). And it should implement this interface that we created. Something like this:
[assembly: Dependency(typeof(DataHandler))]
namespace provisioning.ios
{
public class DataHandler: IDataHandler
{
public DataHandler()
{
}
public string GetSomeStringValue()
{
return "Some string value or whatever";
}
}
}
After that when you want to reach this method you will use DepedencyService inside of your shared code project like this:
private void SomeMethod()
{
string fromSpecificProject = DependencyService.Get<IDataHandler>().GetSomeStringValue();
}
If you want or need you can use this to pass some values to platform specific project and to return the data like I did it this mini example.
Note that implementations must be provided for each platform project
in your solution. Platform projects without implementations will fail
at runtime!
Strongly recommend you to take a look at official docs here.
Also I made this mini blogpost about usage of Dependency Service in Xamarin.Forms apps you can find it here.
I have a dll named ExpensiveAndLargeObfuscatedFoo.dll.
Lets says it defines a type named ExpensiveAndLargeObfuscatedFooSubClass.
It's been compiled for .NET.
Are there any tools (free, paid, whatever) that will generate c# or vb class files that will do nothing but wrap around everything defined in this expensive dll? That way I can add functionality, fix bugs (that CorpFUBAR won't fix), add logging, etc?
Literally, I want output that looks like this
namespace easytoread {
public class SubClass {
private ExpensiveAndLargeObfuscatedFoo.SubClass _originalSubClass;
public SubClass() {
this._originalSubClass = new ExpensiveAndLargeObfuscatedFoo.SubClass ();
}
public string StupidBuggyMethod(string param1,int param2) {
return _originalSubClass.StupidBuggyMethod(param1, param2);
}
}
}
It would have to handle custom return types as well as primitives
namespace easytoread {
public class SubFooClass {
private ExpensiveAndLargeObfuscatedFoo.SubFooClass _originalSubFooClass;
public SubFooClass() {
this._originalSubFooClass= new ExpensiveAndLargeObfuscatedFoo.SubFooClass ();
}
private SubFooClass(ExpensiveAndLargeObfuscatedFoo.SubFooClass orig) {
this._originalSubFooClass = orig;
}
public SubFooClass StupidBuggyMethod(string param1,int param2) {
return new SubFooClass(_originalSubFooClass.StupidBuggyMethod(param1, param2));
}
}
}
And so on and so forth for every single defined class.
Basically, poor mans dynamic proxy? (yay, Castle Project is awesome!)
We'd also like to rename some of our wrapper classes, but the tool doesn't need to do that.
Without renaming, we'd be able to replace the old assembly with our new generated one, change using statements and continue on like nothing happened (except the bugs were fixed!)
It just needs to examine the dll and do code generation. the generated code can even be VB.NET, or ironpython, or anything CLR.
This is a slippery slope and I'm not happy that I ended up here, but this seems to be the way to go. I looked at the Castle Project, but unless I'm mistaken that won't work for two reasons: 1) I can't rename anything (don't ask), 2) none of the assemblies methods are declared virtual or even overridable. Even if they were, there's hundreds of types I'd have to override manually, which doesn't sound fun.
ReSharper can do much of the work for you.
You will need to declare a basic class:
namespace easytoread {
public class SubClass {
private ExpensiveAndLargeObfuscatedFoo.SubClass _originalSubClass;
}
}
Then, choose ReSharper > Edit > Generate Code (Alt+Ins), select "Delegating Members", select all, and let it generate the code.
It won't wrap return values with custom classes (it will return the original type), so that would still have to be added manually.
It seems the best answer is "There is no such tool". So, I'll be taking a stab at writing my own later as an off-hours project. If I ever get something useful working I'll github it and update here.
UPDATE
Visual Studio 2012 Fakes seem to be promising. http://msdn.microsoft.com/en-us/library/tfs/hh549175(v=vs.110).aspx - we've moved on but I might try creating a fake and then dropping it in as a replacement dll sometime in the future
If you have access to the source code, rename and fix in the source
code.
If you don't have access (and you can do it legally) use some
tool like Reflector or dotPeek to get the source code and then,
goto to the first point.
I have to be able to connect to two different versions of the an API (1.4 and 1.5), lets call it the Foo API. And my code that connects to the API and processes the results is substantially duplicated - the only difference is the data types returned from the two APIs. How can I refactor this to remove duplication?
In Foo14Connector.cs (my own class that calls the 1.4 API)
public class Foo14Connector
{
public void GetAllCustomers()
{
var _foo = new Foo14WebReference.FooService();
Foo14WebReference.customerEntity[] customers = _foo.getCustomerList;
foreach (Foo14WebReference.customerEntity customer in customers)
{
GetSingleCustomer(customer);
}
}
public void GetSingleCustomer(Foo14WebReference.customerEntity customer)
{
var id = customer.foo_id;
// etc
}
}
And in the almost exact duplicate class Foo15Connector.cs (my own class that calls the 1.5 API)
public class Foo15Connector
{
public void GetAllCustomers()
{
var _foo = new Foo15WebReference.FooService();
Foo15WebReference.customerEntity[] customers = _foo.getCustomerList;
foreach (Foo15WebReference.customerEntity customer in customers)
{
GetSingleCustomer(customer);
}
}
public void GetSingleCustomer(Foo15WebReference.customerEntity customer)
{
var id = customer.foo_id;
// etc
}
}
Note that I have to have two different connectors because one single method call (out of hundreds) on the API has a new parameter in 1.5.
Both classes Foo14WebReference.customerEntity and Foo15WebReference.customerEntity have identical properties.
If the connectors are in different projects, this is an easy situation to solve:
Add a new class file, call it ConnectorCommon and copy all of the common code, but with the namespaces removed. Make this class a partial class and rename the class (not the file) to something like Connector.
You will need to add a link to this to each project.
Next, remove all of the code from your current connector classes, rename the class (not necessarily the file) to the same as the partial class, and add a using statement that references the namespace.
This should get what you are looking for.
So, when you are done you will have:
File ConnectorCommon:
public partial class Connector
{
public void GetAllCustomers()
{
var _foo = new FooService();
customerEntity[] customers = _foo.getCustomerList;
foreach (customerEntity customer in customers)
{
GetSingleCustomer(customer);
}
}
public void GetSingleCustomer(customerEntity customer)
{
var id = customer.foo_id;
// etc
}
}
File Magento15Connector
using Foo15WebReference;
partial class Connector
{
}
File Magento14Connector
using Foo14WebReference;
partial class Connector
{
}
Update
This process can be a little confusing at first.
To clarify, you are sharing source code in a common file between two projects.
The actual classes are the specific classes with the namespaces in each project. You use the partial keyword to cause the common file to be combined with the actual project file (i.e. Magneto14) in each project to create the full class within that project at compile time.
The trickiest part is adding the common file to both projects.
To do this, select the Add Existing Item... menu in the second project, navigate to the common file and click the right-arrow next to the Add button.
From the dropdown menu, select Add as link. This will add a reference to the file to the second project. The source code will be included in both projects and any changes to the common file will be automatically available in both projects.
Update 2
I sometimes forget how easy VB makes tasks like this, since that is my ordinary programming environment.
In order to make this work in C#, there is one more trick that has to be employed: Conditional compilation symbols. It makes the start of the common code a little more verbose than I would like, but it still ensures that you can work with a single set of common code.
To employ this trick, add a conditional compilation symbol to each project (ensure that it is set for All Configurations). For example, in the Magento14 project, add Ver14 and in the Magento15 project add Ver15.
Then in the common file, replace the namespace with a structure similar to the following:
#if Ver14
using Magneto14;
namespace Magento14Project
#elif Ver15
using Magneto15;
namespace Magento15Project
#endif
This will ensure that the proper namespace and usings are included based on the project the common code is being compiled into.
Note that all common using statements should be retained in the common file (i.e., enough to get it to compile).
If the FooConnectors are not sealed and you are in control to create new instances, then you can derive your own connectors and implement interfaces at the same time. In c# you can implement members by simply inheriting them from a base class!
public IFooConnector {
void GetAllCustomers();
}
public MyFoo14Connector : Foo14Connector, IFooConnector
{
// No need to put any code in here!
}
and then
IFooConnector connector = new MyFoo14Connector();
connector.GetAllCustomers();
You should introduce an interface that is common to both of the implementations. If the projects are written in the same language and are in different projects, you can introduce a common project that both projects reference. You are then making a move towards having dependencies only on your interface which should allow you to swap in different implementations behind the scenes somewhere using inversion of control (google, dependency injection or service locator or factory pattern).
Difficulties for you could be:
1) Public static methods in the implementations are not able to be exposed staticly via an interface
2) Potentially have code in one implementation class ie Foo14Connector or Foo15Connector that doesnt make sense to put into a generic interface
I'm writing a simple plugin based program. I have an interface IPlugin which has some methods and functions, and a List<Plugin> in my main program. For the sake of simplicity, lets say its defined like this:
public interface IPlugin
{
public void OnKeyPressed(char key);
}
Everytime a key is pressed, I loop through the Plugin list, and call OnKeyPressed(c) on each of them.
I can create a class like so, and add it to the list...
public class PrintPlugin
{
public void OnKeyPressed(char key)
{
Console.WriteLine(c);
}
}
And then whenever you press a key, its printed out. But I want to be able to load plugins from DLL files. This link was helpful, but it doesn't explain how to have the classes in the DLL implement my IPlugin interface... How can I do that? I really don't want to have to copy the IPlugin.cs file every time I want to make a plugin...
If I am understanding you correctly...
Create 3 Projects:
Project 1: Your main program (the one with List in it)
Project 2: the project with your interface
public interface IPlugin
{
public void OnKeyPressed(char key);
}
Project 3: A sample Plugin
public class PrintPlugin : IPlugin
{
public void OnKeyPressed(char key)
{
Console.WriteLine(c);
}
}
Then Add project 2 as a reference to both project 1 and 3.
This way you share the interface with both your main project and any of your plugins.
I have used this on a couple of projects and it has served me well.
You may want to look into the Managed Extensibility Framework as well. It provide a complete API for writing plugin based programs and covers a lot of concerns such as security if you're ever going to plan to make the plugin API available to third parties.
If you need to load user defined plugins, you should search for new DLLs when the application starts (or any other action). This can be done by using:
1) AppDomain.CurrentDomain.GetAssemblies() method returns the list of loaded assemblies in the current AppDomain
2) Search all DLLs in a folder where plugins should be positioned and check if a certain assembly is in the list. If not, use the Assembly.Load method to load this assembly, find the IPlugin class in it and finally add it to the List object.
It sounds strange but this is exactly what I want because I am using a data structure named "Project" which gets serialized to a save file. I would like to be able to de-serialize an older version of a save file with deprecated fields in tact, but then re-serialize it using only the currently used fields. The problem is that I want to get rid of those deprecated fields when re-serializing the structure in order to minimize file size. Is it possible to mark a field as "de-serializable only"?
Edit:
Thanks for the ideas! I decided to build mostly off of NickLarsen's suggestions and create an old version of the project structure with all depreciated fields in a separate namespace. The difference is that I decided to perform the upgrade upon deserialization. This is great because I can do it all in one line (hopefully you can get the gist what I'm doing here):
Project myProject = new Project((Depreciated.Project)myFormatter.Deserialize(myStream));
The constructor simply returns a new instance of the fresh minimal data structure based on the old bloated one.
Second Edit:
I decided to follow the advice of bebop instead and create new classes for each project version with the oldest version including all depreciated and new fields. Then the constructor of each project upgrades to the next version getting rid of depreciated fields along the way. Here is an illustrative example of converting from version 1.0.0 -> 1.0.5 -> current.
Project myProject = new Project(new Project105((Project100)myFormatter.Deserialize(myStream)));
One key to this is to forced the deserialized file as well as any fields into the older versions of the classes by using a SerializationBinder.
could you not create a new version of your data structure class each time the structure changes, and have the constructor for the new class take an instance of the previous class, and populate itself from there. To load the newest class you try and create the earliest class from the serialised file until one succeeds, and then pass that into the constructor of the next class in the chain repeatedly until you get the latest version of the data structure then you can save that.
Having a new class for each change in format would avoid having to change any existing code when the data structure changed, and your app could be ignorant of the fact that the save file was some older version. It would allow you to load from any previous version, not just the last one.
This sort of thing implemented by a chain of responsibility can make it easy to slot in a new format with minimal changes to your existing code.
Whilst not a textbook chain of responsibility you could implement with something like this:
(NOTE: untested code)
public interface IProductFactory<T> where T : class
{
T CreateProduct(string filename);
T DeserializeInstance(string filename);
}
public abstract class ProductFactoryBase<T> : IProductFactory<T> where T : class
{
public abstract T CreateProduct(string filename);
public T DeserializeInstance(string filename)
{
var myFormatter = new BinaryFormatter();
using (FileStream stream = File.Open(filename, FileMode.Open))
{
return myFormatter.Deserialize(stream) as T;
}
}
}
public class ProductV1Factory : ProductFactoryBase<ProductV1>
{
public override ProductV1 CreateProduct(string filename)
{
return DeserializeInstance(filename);
}
}
public class ProductV2Factory : ProductFactoryBase<ProductV2>
{
ProductV1Factory successor = new ProductV1Factory();
public override ProductV2 CreateProduct(string filename)
{
var product = DeserializeInstance(filename);
if (product==null)
{
product = new ProductV2(successor.CreateProduct(filename));
}
return product;
}
}
public class ProductV2
{
public ProductV2(ProductV1 product)
{
//construct from V1 information
}
}
public class ProductV1
{
}
this has the advantage that when you want to add ProductV3 you only need to change the class you are using in your app to be a ProductV3 type, which you need to do anyway, then you change your loading code so that it uses a ProductV3Factory, which is basically the same as a ProductV2Factory, but it uses a ProductV2Factory as the successor. You don't need to change any existing classes. you could probably refactor this a bit to get the commanality of CreateProduct into a base class, but it gets the idea across.
You have a couple options for this.
First you could create a version of your class (maybe in a different namespace) for the old format, and one for the new format. In the old class, overload the serialize function to throw an error, or convert itself to the new class and serialize that.
Second, you could just write your own serializer, which would be a bit more involved. There are plenty of resources which can help you though.
As far as I know .NET is very careful to only serialise things it can deserialise and vice versa.
I think what you are searching for is the OptionalFieldAttribute.
There isn't an attribute defined to explicitly support that but one possbility may be to define custom serialization using either ISerializable or by defining a custom serializer class for your type that takes no action when serializing