I have been working on Android app Development and now have switched to windows.
1) I have a scenario where i need to create a child project and library project, we have done this Android as given in the link - http://developer.android.com/tools/projects/projects-eclipse.html#SettingUpLibraryProject
How to acheive the same thing in Visual Studio ? for Windows Phone app development.
2) i have to create a class which will have some methods defined with some values,like :
In my base project
Class{
public void string appName(){
return "XYZ"
}
public void int appVersion(){
return 1;
}
}
Now in my child project i should be able to override the above methods and change the implementation and also if i did not give the implementation it should take the default value.
How to acheive this in C# ?
Usually you don't reuse files in C# but reuse classes,
Create your library project and put your base class there :
namespace YourLibraryNameSpace
{
public class BaseClass
{
public virtual void string AppName()
{
return "XYZ";
}
public virtual void int AppVersion()
{
return 1;
}
}
}
then in your main project add a reference to the library project and add your child class like this:
namespace MainProjectNameSpace
{
using YourLibraryNameSpace;
public class ChildClass : BaseClass
{
public override void string AppName()
{
return "ABC";
}
public override void int AppVersion()
{
return 2;
}
}
}
And I suggest following C# naming conventions, like pascal casing method names.
In C# it works in pretty much the same way. A library project is a dll, so you can create this one first. Then create your main project. In the solution explorer tree you can right-click on the main project and add a reference to the library project.
Regarding overriding implementation, in c# you need to explicitly mark your methods as virtual if you want this behaviour:
Class{
public virtual void string appName(){
return "XYZ"
}
public virtual void int appVersion(){
return 1;
}
}
and then when you override them in your child class, change virtual to override (needs to be explicitly stated you are overriding, unlike java).
Related
For a C# Project, I want to include a build step or something integrated in project that should raise build error if any developer is trying to use a specific method from framework classes, instead I want developers to use extension method for same. However I want to impose this as the compile time error. As an example, for a name sake I want developer on given project not to use string.Intern, instead should always use string.SpecialIntern. What are different ways to achieve this? I tried to use Roslyn-code-analysis but could not really write working rule for this, so I am not sure if tha'ts the right solution to this problem. Can someone guide me in details how to solve this with some examples?
This sounds like something you could accomplish with a custom code analyzer. I haven't tried it yet, but I believe it is possible to write your own analyzers.
This article from Microsoft claims to tell you how to do it:
https://learn.microsoft.com/en-us/visualstudio/extensibility/getting-started-with-roslyn-analyzers?view=vs-2017
Here's a direct link to the tutorial referenced in that article:
https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix
AFAIK there's no way to achieve what you're trying to do.
However, a solution would be to simply call the extension method.
public static class Extension
{
public static bool DoStuff(this Class stuff)
{
return false;
}
}
public class Class
{
public bool DontCallMe()
{
return this.DoStuff();
}
}
Class myClass = new Class();
myClass.DontCallMe();
Obviously, that only works if you can change the code of your class (which I suppose you aren't able to)
If that method is marked as virutal, you could create a Wrapper-Class which overrides that method.
public static class Extension
{
public static bool DoStuff(this Class stuff)
{
return false;
}
}
public class Class : Base
{
public override bool DontCallMe()
{
return this.DoStuff();
}
}
public class Base
{
public virtual bool DontCallMe()
{
return false;
}
}
Another approach would be to do what I described in this this post.
C#. I have a base class called FileProcessor:
class FileProcessor {
public Path {get {return m_sPath;}}
public FileProcessor(string path)
{
m_sPath = path;
}
public virtual Process() {}
protected string m_sath;
}
Now I'd like to create to other classes ExcelProcessor & PDFProcessor:
class Excelprocessor: FileProcessor
{
public void ProcessFile()
{
//do different stuff from PDFProcessor
}
}
Same for PDFProcessor, a file is Excel if Path ends with ".xlsx" and pdf if it ends with ".pdf". I could have a ProcessingManager class:
class ProcessingManager
{
public void AddProcessJob(string path)
{
m_list.Add(Path;)
}
public ProcessingManager()
{
m_list = new BlockingQueue();
m_thread = new Thread(ThreadFunc);
m_thread.Start(this);
}
public static void ThreadFunc(var param) //this is a thread func
{
ProcessingManager _this = (ProcessingManager )var;
while(some_condition) {
string fPath= _this.m_list.Dequeue();
if(fPath.EndsWith(".pdf")) {
new PDFProcessor().Process();
}
if(fPath.EndsWith(".xlsx")) {
new ExcelProcessor().Process();
}
}
}
protected BlockingQueue m_list;
protected Thread m_thread;
}
I am trying to make this as modular as possible, let's suppose for example that I would like to add a ".doc" processing, I'd have to do a check inside the manager and implement another DOCProcessor.
How could I do this without the modification of ProcessingManager? and I really don't know if my manager is ok enough, please tell me all your suggestions on this.
I'm not really aware of your problem but I'll try to give it a shot.
You could be using the Factory pattern.
class FileProcessorFactory {
public FileProcessor getFileProcessor(string extension){
switch (extension){
case ".pdf":
return new PdfFileProcessor();
case ".xls":
return new ExcelFileProcessor();
}
}
}
class IFileProcessor{
public Object processFile(Stream inputFile);
}
class PdfFileProcessor : IFileProcessor {
public Object processFile(Stream inputFile){
// do things with your inputFile
}
}
class ExcelFileProcessor : IFileProcessor {
public Object processFile(Stream inputFile){
// do things with your inputFile
}
}
This should make sure you are using the FileProcessorFactory to get the correct processor, and the IFileProcessor will make sure you're not implementing different things for each processor.
and implement another DOCProcessor
Just add a new case to the FileProcessorFactory, and a new class which implements the interface IFileProcessor called DocFileProcessor.
You could decorate your processors with custom attributes like this:
[FileProcessorExtension(".doc")]
public class DocProcessor()
{
}
Then your processing manager could find the processor whose FileProcessorExtension property matches your extension, and instantiate it reflexively.
I agree with Highmastdon, his factory is a good solution. The core idea is not to have any FileProcessor implementation reference in your ProcessingManager anymore, only a reference to IFileProcessor interface, thus ProcessingManager does not know which type of file it deals with, it just knows it is an IFileProcessor which implements processFile(Stream inputFile).
In the long run, you'll just have to write new FileProcessor implementations, and voila. ProcessingManager does not change over time.
Use one more method called CanHandle for example:
abstract class FileProcessor
{
public FileProcessor()
{
}
public abstract Process(string path);
public abstract bool CanHandle(string path);
}
With excel file, you can implement CanHandle as below:
class Excelprocessor: FileProcessor
{
public override void Process(string path)
{
}
public override bool CanHandle(string path)
{
return path.EndsWith(".xlsx");
}
}
In ProcessingManager, you need a list of processor which you can add in runtime by method RegisterProcessor:
class ProcessingManager
{
private List<FileProcessor> _processors;
public void RegisterProcessor(FileProcessor processor)
{
_processors.Add(processor)
}
....
So LINQ can be used in here to find appropriate processor:
while(some_condition)
{
string fPath= _this.m_list.Dequeue();
var proccessor = _processors.SingleOrDefault(p => p.CanHandle(fPath));
if (proccessor != null)
proccessor.Process(proccessor);
}
If you want to add more processor, just define and add it into ProcessingManager by using
RegisterProcessor method. You also don't change any code from other classes even FileProcessorFactory like #Highmastdon's answer.
You could use the Factory pattern (a good choice)
In Factory pattern there is the possibility not to change the existing code (Follow SOLID Principle).
In future if a new Doc file support is to be added, you could use the concept of Dictionaries. (instead of modifying the switch statement)
//Some Abstract Code to get you started (Its 2 am... not a good time to give a working code)
1. Define a new dictionary with {FileType, IFileProcessor)
2. Add to the dictionary the available classes.
3. Tomorrow if you come across a new requirement simply do this.
Dictionary.Add(FileType.Docx, new DocFileProcessor());
4. Tryparse an enum for a userinput value.
5. Get the enum instance and then get that object that does your work!
Otherwise an option: It is better to go with MEF (Managed Extensibility Framework!)
That way, you dynamically discover the classes.
For example if the support for .doc needs to be implemented you could use something like below:
Export[typeof(IFileProcessor)]
class DocFileProcessor : IFileProcessor
{
DocFileProcessor(FileType type);
/// Implement the functionality if Document type is .docx in processFile() here
}
Advantages of this method:
Your DocFileProcessor class is identified automatically since it implements IFileProcessor
Application is always Extensible. (You do an importOnce of all parts, get the matching parts and Execute.. Its that simple!)
This should be simple, but I can't find anything out there.
I have a class in one assembly (a shared library -- it's a set of proxy classes for a Web Service)
I have a class in another assembly (web project)
There is a class called "Profile" which is in the Proxy assembly.
There is a set of classes that "use" a Profile in the web project.
When there is no user logged in, a GenericProfile is used.
Following the principle of "separation of concerns"....
The Proxy assembly is used by other projects and is concerned with only the Web Service stuff.
The web project just has web stuff in there
However, now there is this need for a "GenericProfile" -- think of it as "Guest User".
The logical thing to do is to build an interface called IProfile and cause both classes to derive from it. But that would create a circular dependency between the two assemblies.
The next best idea is to create a 3rd assembly called MyInterfaces and put the IProfile in there -- but that causes a violation of the Separation of Concerns principle in my opinion. At the very least, one instance of this problem seems too small a reason to spring for making an extra module in my solution.
Enter the wrapper class -- or the Composite wrapper class (whatever you want to call it)
I'm looking for something that ends up generating something like this below. Is there a tool or Visual Studio extension that will do it? Maybe a .tt file?
namespace WebProject
{
public interface IProfile
{...}
class MyWrapperClass : IProfile
{
Proxy.Profile _profile;
public MyWrapperClass(Proxy.Profile proxy)
{
_profile = proxy;
}
public string IProfile.Property1{ get { return _profile.Property1; } set { _profile.Property1 = value; } }
public string IProfile.Property2{ get { return _profile.Property2; } set { _profile.Property2 = value; } }
public string IProfile.Property3{ get { return _profile.Property3; } set { _profile.Property3 = value; } }
}
}
In Visual Studio 2017
Create your class
namespace WebProject
{
public interface IProfile
{...}
class MyWrapperClass : IProfile
{
private IProfile _wrapped;
}
}
locate your cursor on the IProfile of class MyWrapperClass : IProfile and hit ctrl-. select Implement interface through _wrapped. No need for ReSharper.
I don't completely understand what you are trying to accomplish, but below is how I would generate a wrapper class with ReSharper.
Personally if my employer doesn't want to pay for ReSharper, I buy it. It makes me a better developer. I strongly suggest you consider acquiring it as an investment in your career. Anti-Disclaimer - I am not at all connected with or sponsored by ReSharper.
add the interface to the class you wish to be the wrapping class
class MyWebElement : IWebElement { }
Find/Click "Delegate implementation of "YourInterfaceHere" to a new field
Select your options
Click finish and enjoy your new class
class MyWebElement : IWebElement
{
private IWebElement _webElementImplementation;
public IWebElement FindElement(By #by)
{
return _webElementImplementation.FindElement(#by);
}
public ReadOnlyCollection<IWebElement> FindElements(By #by)
{
return _webElementImplementation.FindElements(#by);
}
public void Clear()
{
_webElementImplementation.Clear();
}
public void SendKeys(string text)
{
_webElementImplementation.SendKeys(text);
}
public void Submit()
{
_webElementImplementation.Submit();
}
public void Click()
{
_webElementImplementation.Click();
}
public string GetAttribute(string attributeName)
{
return _webElementImplementation.GetAttribute(attributeName);
}
public string GetCssValue(string propertyName)
{
return _webElementImplementation.GetCssValue(propertyName);
}
public string TagName
{
get { return _webElementImplementation.TagName; }
}
public string Text
{
get { return _webElementImplementation.Text; }
}
public bool Enabled
{
get { return _webElementImplementation.Enabled; }
}
public bool Selected
{
get { return _webElementImplementation.Selected; }
}
public Point Location
{
get { return _webElementImplementation.Location; }
}
public Size Size
{
get { return _webElementImplementation.Size; }
}
public bool Displayed
{
get { return _webElementImplementation.Displayed; }
}
}
If I was faced with your original problem, I'd put IProfile in your shared library, alongside the Profile class. Your web project can then implement the GenericProfile class that it needs, nothing else needs to know about it, and other clients of the library can do the same as needed. It would also be useful for testing the library.
I have an application that loads plugins. I have a plugin that has complete access to a form instance. If I have a function in a form that needs to be overridden, but is not a virtual function, is there another way to override it?
Here is a very generic example:
//Form I am modifying
public partial class MyForm : Form
{
public int myVariable1;
public int myVariable2;
//Constructor and other methods here
private void setVar(int replacementValue)
{
myVariable1 = replacementValue;
}
}
...then in a separate dll...
//My plugin
public class MyPlugin : IMyPluginBase
{
MyForm theForm; //Reference to the form in the main application
//Constructor and other methods here
private void setVar(int replacementValue)
{
theForm.myVariable2 = replacementValue;
}
}
In this example the function in the form sets 'myVariable1', but the 'setVar' function in the plugin sets 'myVariable2'.
So, the question is, in the case of this example, can I replace/override the form's 'setVar' function with the one in the plugin? Maybe with messages or reflection?
No. You cannot "replace" or overide private non-virtual methods in C#.
The C# language (and .NET runtime) don't support dynamic replacement of methods in the manner you describe. Very few languages support this capability, to my knowledge (I believe that SmallTalk and Objective-C both do).
If this is the only place in your application where you need this kind of extensibility, you can achieve it through an interface, delegate, or inhertance+virtual methods. Any of these approaches could work ... which one you choose depends on what kind of extensibility you desire.
If you expect to have many such extensibility points in your app, then you should probably take a look at the Managed Extensibility Framework (MEF). It provides a Microsoft-supported model for creating plug-in architectures using patterns and technique that work well in .NET.
If a function is not marked as virtual or part of an interface that your class implements there's exactly 0 chance you would be able to override it. No plugin, no reflection, no nothing, simply forget about it or use some other dynamic language but not C#.
The short answer to your question is no. What you can do, however, is give your form a copy of the IMyPluginBase, and have Form.setVar() call out to MyPluginBase.SetVar().
The code will look something like this:
public partial class MyForm : Form
{
public int myVariable1;
public int myVariable2;
public IMyPluginBase MyPlugin;
//Constructor and other methods here
private void setVar(int replacementValue)
{
MyPlugin.setVar(replacementValue);
//myVariable1 = replacementValue;
}
}
public class MyPlugin : IMyPluginBase
{
MyForm theForm; //Reference to the form in the main application
public void setVar(int replacementValue)
{
theForm.myVariable2 = replacementValue;
}
}
Note that setVar() will need to be defined in IMyPluginBase.
I know that C# does not offer multiple inheritance. And I know there' are workarounds like this one for instance.
But here's a problem that I faced today, can't figure any ELEGANT workaround. I'll add some abstract code-sample so you get it quicker...
(let it be a real-life ASP.NET code - cause those "class A, class B" code-samples are really confusing):
public class AdminPage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
//if not an admin - get out
if(!CurrentUserIsAdmin()) Response.End();
base.OnInit (e);
}
}
public class JQueryPage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
RegisterJQueryScript();
base.OnLoad (e);
}
}
//now here's what I REALLY miss in C#
public class AdminJQueryPage : AdminPage, JQueryPage;
Compose out the functionality? This is better for Single Responsibility. You'd have to think carefully about your constructors.
interface IAdminPage {
public string AdminPageMethod();
}
interface IJQueryPage {
public string JQueryPageMethod();
}
internal class AdminPage : IAdminpage {
private string someString;
internal AdminPage(string value) {
this.someString = value;
}
public string AdminPageMethod() {
return "AdminPage result with some string: " + this.someString;
}
}
internal JQueryPage : IJQueryPage {
private int someNumber;
internal JQueryPage(int value) {
this.someNumber = value;
}
public string JQueryPageMethod() {
return "JQueryPage result with number: " + this.someNumber;
}
}
class AdminJQueryPage : IQueryPage, IAdminpage {
private readonly IAdminPage adminPage;
private readonly IJQueryPage jqueryPage;
public AdminJQueryPage(string someString, int someNumber) {
this.adminPage = new AdminPage(someString);
this.jqueryPage = new JQueryPage(someNumber);
}
public string AdminPageMethod() {
return this.adminPage.AdminPageMethod();
}
public string JQueryPageMethod() {
return this.adminPage.JQueryPageMethod();
}
}
If you really want multiple inheritance, look at Scala's traits
Edit: added passing of constructor values to composed out classes. Also made the classes internal (cannot be accessed or constructed outside the assembly) because they are only ever constructed by the AdminJQueryPage class, which is the 'public-facing' class.
I came from C++ too and dont miss it, especially since reading Refactoring [and using a non-OOTB tool for that].
You can use PostSharp to post process based on placing attributes on your AdminJQueryPage which would achieve the exact same effect.
Or you can Extract Method code into helper classes and call that (i.e., Joe's example)
Or you can put the helpers in a single base class and call from that.
Either way your code will be clearer.
It's only a matter of time before your mixins start overlapping, and then your general suite of techniques for managing that complexity needs to kick in - in C++, MI should only have been one tool in a suite - rather than a very sexy hammer.
its possible to fake a mixin by specifying a interface and creating extension methods for that interface. however I'm not use this will help overriding methods, only adding new ones. you are of course able to then call an extension method when overriding, but that is basically the same as extracting the methods to a helper class, but with a little more sugar
Even if it was possible, one problem with the semantics of an MI-based solution to the specific problem you raised is what happens on the markup side? The Render() method that generates the markup would run first in one class, and then in the other? That's probably not the behavior you want when both classes generate entire pages.
If you're open to solutions that are outside of the language itself, there are several elegant options in ASP.NET that will address the type of issue you raised (changing the actions taken during an event in the page life cycle). For example:
Page Adapters
Control Adapters
Custom user controls
HttpModules
Master Pages
Tag mapping
The best choice will of course depend on the details of your application. In case it's helpful, I cover those options in my book, including sample code: Ultra-Fast ASP.NET.
The simplest approach is to build a hierarchy - allow AdminPage to inherit from JQueryPage like so:
public class AdminPage : JQueryPage
{
protected override void OnInit(EventArgs e)
{
//if not an admin - get out
if(!CurrentUserIsAdmin()) Response.End();
base.OnInit (e);
}
}
public class JQueryPage : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
RegisterJQueryScript();
base.OnLoad (e);
}
}
//now here's what I REALLY miss in C#
public class AdminJQueryPage : AdminPage
My guess is some of this awkwardness comes from the ASP.NET page model, which uses overridden base class methods.
You can to do this with Interfaces
public interface IJQueryPage
{
}
public abstract class AdminPage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
//if not an admin - get out
if(!CurrentUserIsAdmin()) Response.End();
base.OnInit (e);
}
protected override void OnLoad(EventArgs e)
{
if (this is IJQueryPage)
{
RegisterJQueryScript();
}
base.OnLoad (e);
}
}
public class AdminJQueryPage : AdminPage, IJQueryPage
{
}