c# overiding a methond in a Referenced library - c#

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.

Related

Call Excel Add-In function in macro

I am developing Add-in for Excel 2013 and I have created a function in Excel Add-In as below
public string ExcelReturnString()
{
return "This is the string: hi";
}
I have used below code to call the function, but it throws an error.
Application.Run(ExcelReturnString)
How can I call the Add-in function in macro?
This is about the farthest thing from straight-forward, but this is how you accomplish the task. I'm going to be as explicit as possible, because the first two or three times I tried to do this, I missed a LOT.
First, when you create the class that hosts ExcelReturnString(), you need to decorate the class with an interface that has the following attributes and then also tag the attributes for each method you want to expose. I made the add-in class "TestExcelAddIn" for the sake of this example:
using System.Data;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace TestExcelAddIn
{
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IStringGetter
{
string ExcelReturnString();
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class StringGetter : IStringGetter
{
public string ExcelReturnString()
{
return "This is the string: hi";
}
}
}
Then, in the main class, associated with "Excel" in your project, you have to override RequestComAddInAutomationService in the following manner. Again, I am including EVERYTHING so you know which class is which (I didn't when I first read it).
namespace TestExcelAddIn
{
public partial class ExcelTest
{
private StringGetter myAddIn;
protected override object RequestComAddInAutomationService()
{
if (myAddIn == null)
myAddIn = new StringGetter();
return myAddIn;
}
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO generated code
#endregion
}
}
Now VBA is ready to consume this method in the following manner:
Sub Test()
Dim addin As Office.COMAddIn
Dim automationObject As Object
Dim returnString As String
Set addin = Application.COMAddIns("TestExcelAddIn")
Set automationObject = addin.Object
returnString = automationObject.ExcelReturnString
End Sub
You could have given me 100 years to figure this out, and I would not have. Actually credit MSDN for the Rosetta stone on it:
https://msdn.microsoft.com/en-us/library/bb608621.aspx?f=255&MSPPError=-2147217396
In addition to DaveMac's note above, also keep in mind a couple of points when calling another routine:
If you're calling a macro from a routine that resides in the same workbook/addin as that routine, you don't have to use Application.Run. You can just call it by using its name:
MyMacro
If you're calling a macro that is in a different workbook, then you do need to use Application.Run, but you will also want to use the workbook name where the macro resides, otherwise VBA will not know where it should look for the macro:
Application.Run "'My Fancy Spreadsheet.xlsm!'MyMacro"
Your code appears to be java.
Excel uses Visual basic, for example.
Function excelreturnstring()
excelreturnstring = "this is the string: hi"
End function

Design class chaining

I have a third party C# library for ldap operations. It does all operations on connection object as below:
LdapConnection connection = new LdapConnetion(Settings settings);
connection.Search(searchOU, filter,...);
which I feel is not readable. I want to write a wrapper around it so that I should be able to write code like below:
As I would like to have different Ldap classes like
public class AD: LdapServer { }
public class OpenLdap: LdapServer { }
and then
AD myldap = new AD(Settings settings);
myldap.Users.Search(searchOU, filter,...)
myldap.Users.Add(searchOU, filter,...)
myldap.Users.Delete(searchOU, filter,...)
I am thinking about Proxy design pattern, but things are not getting into my head about hot to go about it. What classes should I have etc.
Any help?
The solution posted above inherits from the LdapConnection. This is good if you want to maintain the inheritance chain, but I dont think that is necessary in your case. You simply want to customize and simplify the interface.
The proxy design pattern inherits from the underlying object so that the proxy object can be used anywhere that the underlying object is required, this is good if you want to "inject" extra functionality into the class without the clients of that class realising. I dont think this is your intention here?
The big problem with the solution posted above is that (because it inherits directly from LdapConnection) you can call search in two ways like so:
Settings settings = new Settings();
AD myAD = new AD(settings);
object results = myAD.Users.Search();
// OR
object results2 = myAD.Search();
As I'm sure you can see from the code, both of these call the exact same underlying method. But in my opinion, this is even more confusing to developers than just using the vanilla LdapConnection object. I would always be thinking "whats the difference between these seemingly identical methods??" Even worse, if you add some custom code inside the UsersWrapper Search method, you cannot always guarentee that it will be called. The possibility will always exist for a developer to call Search directly without going through the UsersWrapper.
Fowler in his book PoEAA defines a pattern called Gateway. This is a way to simplify and customize the interface to an external system or library.
public class AD
{
private LdapConnection ldapConn;
private UsersWrapper users;
public AD()
{
this.ldapConn = new LdapConnection(new Settings(/* configure settings here*/));
this.users = new UsersWrapper(this.ldapConn);
}
public UsersWrapper Users
{
get
{
return this.users;
}
}
public class UsersWrapper
{
private LdapConnection ldapConn;
public UsersWrapper(LdapConnection ldapConn)
{
this.ldapConn = ldapConn;
}
public object Search()
{
return this.ldapConn.Search();
}
public void Add(object something)
{
this.ldapConn.Add(something);
}
public void Delete(object something)
{
this.ldapConn.Delete(something);
}
}
}
This can then be used like so:
AD myAD = new AD();
object results = myAD.Users.Search();
Here you can see that the LdapConnection object is completly encapsulated inside the class and there is only one way to call each method. Even better, the setting up of the LdapConnection is also completely encapsulated. The code using this class doesn't have to worry about how to set it up. The settings are only defined in one place (in this class, instead of spread throughout your application).
The only disadvantage is that you loose the inheritance chain back to LdapConnection, but I dont think this is necessary in your case.
Ok, if you simply want to split the methods up into they objects that they act on (i.e. in your example add the .Users. before the method call) you can do something similar to this.. You'll need to get the method parameters and return types correct for your library, I've just used object here.
Is this the sort of thing you're looking for?
public class AD : LdapConnection
{
private UsersWrapper users;
public AD(Settings settings) : base(settings)
{
this.users = new UsersWrapper(this);
}
public UsersWrapper Users
{
get
{
return this.users;
}
}
public class UsersWrapper
{
private AD parent;
public UsersWrapper(AD parent)
{
this.parent = parent;
}
public object Search()
{
return this.parent.Search();
}
public void Add(object something)
{
this.parent.Add(something);
}
public void Delete(object something)
{
this.parent.Delete(something);
}
}
}
This can then be be used as follows:
Settings settings = new Settings();
AD myAD = new AD(settings);
object results = myAD.Users.Search();
Remember that this isn't strictly a "wrapper" because it actually inherits from the underlying class.

Initializing constructor from stored cache in C#

I'm not sure exactly how to describe this question, but here goes. I've got a class hierarchy of objects that are mapped in a SQLite database. I've already got all the non-trivial code written that communicates between the .NET objects and the database.
I've got a base interface as follows:
public interface IBackendObject
{
void Read(int id);
void Refresh();
void Save();
void Delete();
}
This is the basic CRUD operations on any object. I've then implemented a base class that encapsulates much of the functionality.
public abstract class ABackendObject : IBackendObject
{
protected ABackendObject() { } // constructor used to instantiate new objects
protected ABackendObject(int id) { Read(id); } // constructor used to load object
public void Read(int id) { ... } // implemented here is the DB code
}
Now, finally, I have my concrete child objects, each of which have their own tables in the database:
public class ChildObject : ABackendObject
{
public ChildObject() : base() { }
public ChildObject(int id) : base(id) { }
}
This works fine for all my purposes so far. The child has several callback methods that are used by the base class to instantiate the data properly.
I now want to make this slightly efficient. For example, in the following code:
public void SomeFunction1()
{
ChildObject obj = new ChildObject(1);
obj.Property1 = "blah!";
obj.Save();
}
public void SomeFunction2()
{
ChildObject obj = new ChildObject(1);
obj.Property2 = "blah!";
obj.Save();
}
In this case, I'll be constructing two completely new memory instantiations and depending on the order of SomeFunction1 and SomeFunction2 being called, either Property1 or Property2 may not be saved. What I want to achieve is a way for both these instantiations to somehow point to the same memory location--I don't think that will be possible if I'm using the "new" keyword, so I was looking for hints as to how to proceed.
Ideally, I'd want to store a cache of all loaded objects in my ABackendObject class and return memory references to the already loaded objects when requested, or load the object from memory if it doesn't already exist and add it to the cache. I've got a lot of code that is already using this framework, so I'm of course going to have to change a lot of stuff to get this working, but I just wanted some tips as to how to proceed.
Thanks!
If you want to store a "cache" of loaded objects, you could easily just have each type maintain a Dictionary<int, IBackendObject> which holds loaded objects, keyed by their ID.
Instead of using a constructor, build a factory method that checks the cache:
public abstract class ABackendObject<T> where T : class
{
public T LoadFromDB(int id) {
T obj = this.CheckCache(id);
if (obj == null)
{
obj = this.Read(id); // Load the object
this.SaveToCache(id, obj);
}
return obj;
}
}
If you make your base class generic, and Read virtual, you should be able to provide most of this functionality without much code duplication.
What you want is an object factory. Make the ChildObject constructor private, then write a static method ChildObject.Create(int index) which returns a ChildObject, but which internally ensures that different calls with the same index return the same object. For simple cases, a simple static hash of index => object will be sufficient.
If you're using .NET Framework 4, you may want to have a look at the System.Runtime.Caching namespace, which gives you a pretty powerful cache architecture.
http://msdn.microsoft.com/en-us/library/system.runtime.caching.aspx
Sounds perfect for a reference count like this...
#region Begin/End Update
int refcount = 0;
ChildObject record;
protected ChildObject ActiveRecord
{
get
{
return record;
}
set
{
record = value;
}
}
public void BeginUpdate()
{
if (count == 0)
{
ActiveRecord = new ChildObject(1);
}
Interlocked.Increment(ref refcount);
}
public void EndUpdate()
{
int count = Interlocked.Decrement(ref refcount);
if (count == 0)
{
ActiveRecord.Save();
}
}
#endregion
#region operations
public void SomeFunction1()
{
BeginUpdate();
try
{
ActiveRecord.Property1 = "blah!";
}
finally
{
EndUpdate();
}
}
public void SomeFunction2()
{
BeginUpdate();
try
{
ActiveRecord.Property2 = "blah!";
}
finally
{
EndUpdate();
}
}
public void SomeFunction2()
{
BeginUpdate();
try
{
SomeFunction1();
SomeFunction2();
}
finally
{
EndUpdate();
}
}
#endregion
I think your on the right track more or less. You can either create a factory which creates your child objects (and can track "live" instances), or you can keep track of instances which have been saved, so that when you call your Save method it recognizes that your first instance of ChildObject is the same as your second instance of ChildObject and does a deep copy of the data from the second instance over to the first. Both of these are fairly non-trivial from a coding standpoint, and both probably involve overriding the equality methods on your entities. I tend to think that using the first approach would be less likely to cause errors.
One additional option would be to use an existing Obect-Relational mapping package like NHibernate or Entity Framework to do your mapping between objects and your database. I know NHibernate supports Sqlite, and in my experience tends to be the one that requires the least amount of change to your entity structures. Going that route you get the benefit of the ORM layer tracking instances for you (and generating SQL for you), plus you would probably get some more advanced features your current data access code may not have. The downside is that these frameworks tend to have a learning curve associated with them, and depending on which you go with there could be a not insignificant impact on the rest of your code. So it would be worth weighing the benefits against the cost of learning the framework and converting your code to use the API.

Why can I only read properties and not set properties from ASP.NET web app when using .NET remoting?

I'm having an issue with attempting to set a property on a remote object hosted in a Windows Service. I'm trying to change a property of an object and it is not saving for some reason.
Here is the pertinent code of the service:
private static List<Alert> _alerts = new List<Alert>(); // List of the Alerts
private TcpChannel _tcpChannel;
protected override void OnStart(string[] args)
{
loadAlerts(); // This sets up the List (code not req'd)
// Set up the remotelister so that other processes can access _alerts
// Create the TcpChannel
_tcpChannel = new TcpChannel(65000);
ChannelServices.RegisterChannel(_tcpChannel, false);
// Register the Proxy class for remoting.
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(RemoteLister),
"AlertList.soap",
WellKnownObjectMode.Singleton);
}
[Serializable]
public class RemoteLister : MarshalByRefObject
{
public List<Alert> TheList
{
get { return _alerts; }
set { _alerts = value; }
}
public bool save()
{
EventLog.WriteEntry("AlertService", "Calling saveAlerts...");
return saveAlerts();
}
}
Here is the code for the Alert class (a lot of other stuff too):
private string _alertName; // Name of alert
public string AlertName
{
get { return _alertName; }
set { _alertName = value; }
}
Now in my ASP.NET web app, here's how I initialize everything:
AlertService.RemoteLister remoteAlertList;
protected void Page_Load(object sender, EventArgs e)
{
// This is where we create a local object that accesses the remote object in the service
Type requiredType = typeof(AlertService.RemoteLister);
// remoteAlertList is our reference to the List<Alert> in the always running service
remoteAlertList = (AlertService.RemoteLister)Activator.GetObject(requiredType,
"tcp://localhost:65000/AlertList.soap");
}
So now the following code works:
private void fillFields()
{
AlertNameTextBox.Text = remoteAlertList.TheList[AlertDropDownList.SelectedIndex].AlertName;
}
But when I go to change that property as in the following, it doesn't work.
protected void AlertSaveButton_Click(object sender, EventArgs e)
{
remoteAlertList.TheList[AlertDropDownList.SelectedIndex].AlertName = AlertNameTextBox.Text;
}
Does anyone have an idea of why it wouldn't save that property?
Thanks in advance!
I would guess that since List<T> doesn't inherit from MarshalByRefObject, when you call the property remoteAlertList.TheList you get a disconnected object. Perhaps add an indexer to the object instead:
public class RemoteLister : MarshalByRefObject
{
public Alert this[int index] {get {...} set {...}}
}
Actually, I would mainly say ditch remoting and use WCF/SOA. And there is little purpose in RemoteLister being [Serializable]. You might also want to put some thought into thread-safety.
To clarify; the Alert instances will also be standalone, so local updates won't affect the server; basically, you have two scenarios:
if the type is MarshalByRefObject, then it only lives at the server; all client operations are remoted to the actual object - but only for MarshalByRefObjecf types
otherwise, the object is serialized and an actual object is reconstructed.
If you an indexer with (for example)
obj[index].Name = "abc";
then this is:
var tmp = obj[index]; // tmp points to the deserialized disconnected Alert
tmp.Name = "abc"; // we update the local disconnected Alert
(if Alert was MarshalByRefObject, this would update the server, but don't do that). But if we push the value back:
obj[index] = tmp;
then we have updated the server.
As you've discovered, an operation-centric design may be far simpler (i.e. setAlertName). But I really think remoting is a bad idea here.
Tried the indexer, no luck with that. I tried another way shown below and it worked, but it seems like a workaround and not the proper way of doing it. All I did was add this in the RemoteLister class:
public void setAlertName(int index, string name)
{
_alerts[index].AlertName = name;
}
And then changed the save button as follows:
protected void AlertSaveButton_Click(object sender, EventArgs e)
{
remoteAlertList.setAlertName(AlertDropDownList.SelectedIndex, AlertNameTextBox.Text);
}
I suppose this will get me by for now, but i'd rather do it the "right" way if anyone knows why it wasn't working the first way I did it.
I have take a look at your code and it seems to be correct.
but the line of code which may caused the error is here in remoteAlertList initializing:
remoteAlertList = (AlertService.RemoteLister)Activator.GetObject(requiredType, "tcp://localhost:65000/AlertList.soap");
You have initialized a remoteAlertList class with a initial .net convertion method "(newType)obj" and Activator.GetObject(..) which one of them does't return the reference of original obj [I think it's the Activator.GetObject(..)]. It returns an exact copy of "AlertService.RemoteLister" class so when you call "TheList" you called an exact copy of it and when you call Save() it saves in the copied object not in the real object.
Here I can't see your full code but from what I see I can tell you the solution is finding a way to for accessing the referece of AlertService.RemoteLister object from the host.

Exposing a readonly property that can be modified internally

I'm creating a class that will house election results. I have a results class that has a static method that will parse a file and return a results class with the results from the file.
I want to make sure that only the static method can modify the results, so i've been using the internal modifier (Precinct.InternalCandidates) (The prevents instances of my class outside of the dll from accessing the methods, right?).
Anyway, I need to expose the candidates as a read only list to the instantiated version of my class, but I'll obviously need to be able to add candidates during the population process. So, I've created another parameter in the Precinct Class called Precinct.Candidates that exposes a read only version of InternalCandidates
Here's how I'd envision it to work:
Results r = Results.ParseResultsFile("PathToFile.txt");
r.Candidates.Add(new Candidate) // Should error here
Console.WriteLine(r.Candidates[0].Name) // Should work
Here's what I have for my class stubs:
public class Results {
private List<Precinct> precincts = new List<Precinct>();
public ReadOnlyCollection<Precinct> Precincts {
get { return this.precincts.AsReadOnly(); }
}
public Results() {}
public static Results ParseResultsFile(string filePath) { ... }
}
public class Precinct {
internal List<Contest> InternalContests { get; set; }
public ReadOnlyCollection<Contest> Contests {
get { return this.InternalContests.AsReadOnly(); }
}
public Precinct {
this.InternalContests = new List<Contest>();
}
}
Is there a better way to accomplish this?
I'm afraid I have a little bit of bad news Rob... using Reflection, one can completely circumvent access modifiers. They help to protect a team from themselves, but are not suited to providing security.
You will need to ensure the physical security of the code and ensure that nobody can load your DLL into an app domain of their own creation.
UPDATE:
I stand corrected by myself. You can set an attribute that prevents reflection UNLESS THE CALLER HAS FULL TRUST (update from Leppie). See how.
You can prevent callers without full trust from accessing your private/internal methods and fields but a full trust caller cannot be prevented from using reflection.
Again. Cleaning up my old questions... I ended up just rolling my own Collection.
Worked out wonderfully..

Categories

Resources