How to use dynamic global in c# Roslyn csharpscripting - dynamic

c# Csharpscripting
I've an external source code :
static int Prina2() { rexu = rexu*2; }
when calling it with :
public class Globals { public static int rexu ; }
it's working. But doesn't work when I call it with :
public class Globals : DynamicObject { .... }
it says : error cs0103 the name rexu does not exist in the current context.
I'd made references :
System.Dynamic.DynamicObject
System.Linq.Expressions.DynamicExpression
Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.
But it's Always fail
Can you help?

Related

Using both Microsoft.Web.RedisSessionStateProvider and Microsoft.Web.RedisOutputCacheProvider

I have installed and used Microsoft.Web.RedisSessionStateProvider for a while and after looking at OutputCaching I thought of installing Microsoft.Web.RedisOutputCacheProvider as well but they both have Microsoft.Web.Redis.ISerializer interface which breaks my JsonCacheSerializer as it uses the ISerializer interface.
I am getting an error in VS 2017, which reads ...
"The type 'ISerializer' exists in both Microsoft.Web.RedisOutputCacheProvider and Microsoft.Web.RedisSessionStateProvider"
The JsonCacheSerializer code I use for SessionState is :
public class JsonCacheSerializer : Microsoft.Web.Redis.ISerializer
{
private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
Error = (serializer, err) => {
err.ErrorContext.Handled = true;
}
};
public byte[] Serialize(object data)
{
return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data, Settings));
}
public object Deserialize(byte[] data)
{
return data == null ? null : JsonConvert.DeserializeObject(Encoding.UTF8.GetString(data), Settings);
}
}
Does this mean one has to use one or the other, not both?
You may use extern alias feature of C#
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/extern-alias
Visual Studio example:
1) right click Microsoft.Web.RedisOutputCacheProvider and put following into Aliases field:
global,redisoutputcacheprovider
2) right click Microsoft.Web.RedisSessionStateProvider and put following into Aliases field:
global,redissessionstateprovider
then on top of your code file add:
extern alias redissessionstateprovider;
extern alias redisoutputcacheprovider;
and finally declare your class as:
public class JsonCacheSessionStateSerializer : redissessionstateprovider::Microsoft.Web.Redis.ISerializer

Passing native class pointer to another C++/CLI

I have two wrappers written in C++/CLI as followings.
One wrapper get a native class handle and it send this native handle to another class, however, I got a compile error.
I think there are some work-around,
1) #pragme make_public()
2) using IntPtr(sender) and static_cast with IntPtr.ToPointer(receiver).
What is the best solution?
namespace AWrapper {
public ref class AClass
{
public:
NativeClass* GetInfo() { return nativeClass; }
...
private:
NativeClass* nativeClass;
}
namespace BWrapper {
...
void ImageSensor::SetClass(AWrapper::AClass^ aclass)
{
NativeClass* native_tpr;
native_tpr = aclass->GetInfo(); // Not visible, like private
}
}

Mocking and Expecting from a Class instance created using new operator in Google Mock

Need your inputs regarding the below:
I am facing an issue regarding how to write a mock for a base class (StackBT) of which an instance is created in the derived class's constructor (ApplicationBT) that I want to test.
My intention is to write a mock for the StackBT class (Mock_StackBT) and then link this to the unit test so that the instance of the mock is created when doing "new StackBT()" in ApplicationBT's constructor. So that using this I can mock the expectations on StackBT class while testing ApplicationBT class.
out/linux_host/obj/TestApplicationBT.o: In function `TestApplicationBT::SetUp()':
tst/_src/TestApplicationBT.cpp:33: undefined reference to `mockPtr_StackBT'
out/linux_host/lib/libServer.a(ApplicationBT.o): In function `ApplicationBT::init()':
/_src/ApplicationBT.cpp:36: undefined reference to `StackBT::registerCallbacks()'
/_src/ApplicationBT.cpp:43: undefined reference to `StackBT::sendBTMacAddress(std::string)'
collect2: error: ld returned 1 exit status
make: *** [out/linux_host/bin/Test] Error 1
I get the above compiler error while compiling the below code snippet:
StackBT.h:
class StackBT
{
StackBT(){}
void registerCallbacks();
void sendBTMacAddress(std::string str);
}
Mock_StackBT.h:
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <string>
using ::testing::NiceMock;
class Mock_StackBT;
extern NiceMock < Mock_StackBT >* mockPtr_StackBT;
class Mock_StackBT: public StackBT
{
Mock_StackBT(){}
MOCK_METHOD0(registerCallbacks, void());
MOCK_METHOD1(sendBTMacAddress, void(std::string str));
}
Mock_StackBT.cpp:
#include "Mock_StackBT.h"
NiceMock < Mock_StackBT >* mockPtr_StackBT;
void registerCallbacks()
{
mockPtr_StackBT->registerCallbacks();
}
void sendBTMacAddress(std::string str)
{
mockPtr_StackBT->sendBTMacAddress(std::string str);
}
ApplicationBT.h:
class ApplicationBT
{
public:
ApplicationBT() : mpoStackBT(new StackBT())
void init()
{
mpoStackBT->registerCallbacks();
mpoStackBT->sendBTMacAddress("AB:CD:EF:GH:IJ:KL");
}
friend class TestApplicationBT;
scoped_ptr<StackBT> mpoStackBT;
}
TestApplicationBT.h
class TestApplicationBT : public ::testing::Test
{
protected:
virtual void SetUp ()
{
mockPtr_StackBT = &stackBTMock;
ptrApplicationBT = new ApplicationBT();
}
void TearDown()
{
delete ptrApplicationBT;
}
public:
TestApplicationBT ()
{
}
~TestApplicationBT ()
{
ptrApplicationBT = NULL;
}
scoped_ptr<ApplicationBT> ptrApplicationBT;
StackBT* ptrStackBT;
NiceMock<Mock_StackBT> stackBTMock;
};
TEST_F(TestApplicationBT, Init)
{
EXPECT_CALL(stackBTMock, registerCallbacks() ).Times(1);
EXPECT_CALL(stackBTMock, sendBTMacAddress(_) ).Times(1);
ptrApplicationBT->init();
}
First problem is that you are using mockPtr_StackBT in TestApplicationBT.cpp, but it is defined in
Mock_StackBT.cpp. The second issue is that the call to ApplicationBT::init method calls functions
registerCallbacks and sendBTMacAddress through pointer mpoStackBT, but if you look closely at
the constructor for class ApplicationBT you will se that this pointer is set to an object of class StackBT
and not Mock_StackBT. This causes a linker error because you did not implement functions
registerCallbacks and sendBTMacAddress for class StackBT, you have only declared them.
The main problem is that you are not swapping your real implementation with a mock, your approach is
not correct. First of all, you are not suppossed to create implementations for functions registerCallbacks
and sendBTMacAddress in the mock class, googlemock does that for you (file Mock_StackBT.cpp is completely
unnecessary). Also, you need a common interface for classes StackBT and Mock_StackBT so you can
switch implementations. Here is how you do it:
Create interface:
class IStackBT
{
public:
virtual IStackBT() {}
virtual void registerCallbacks() = 0;
virtual sendBTMacAddress(std::string str) = 0;
}
Create class for production:
class StackBT : public IStackBT
{
public:
void registerCallbacks() override
{
// Your code that registers callbacks
}
void sendBTMacAddress(std::string str) override
{
// Your code that sends mac address
}
}
Create mock class:
class StackBTMock : public IStackBT
{
public:
MOCK_METHOD0(registerCallbacks, void());
MOCK_METHOD1(sendBTMacAddress, void(std::string str));
}
Now, make your class ApplicationBT hold a IStackBT pointer and use some form of factory method
to create a real or mock object, depending on the fact if you are building unit test or deployment code. There
are several ways, here is how I did it on my gmock project. Create a preprocessor define for your unit testing
project that indicates the code is built for unit tests. If it is, for example, named MY_UNIT_TESTS, then in
constructor of ApplicationBT do the following:
ApplicationBT() : mpoStackBT(createStackBT())
where createStackBT is a function defined as:
IStackBT * createStackBT()
{
#ifdef MY_UNIT_TESTS
return new StackBTMock;
#else
return new StackBT;
#endif
}
This will perform the swapping of implementation during compilation time when you are building your unit test executable. Since you will be performing this swapping on several classes as you write more tests, I suggest that you wrap the factory functions in some class that provides the desired implementations (mock or production) of your classed. For instance, my project has a class named ImplementationProvider that performs this task.

Accesing arraylist property from another class using constructor

So i have a class that makes an array list for me and i need to access it in another class through a constructor but i don't know what to put into the constructor because all my methods in that class are just for manipulating that list. im either getting a null pointer exception or a out of bounds exception. ive tried just leaving the constructor empty but that dosent seem to help. thanks in advance. i would show you code but my professor is very strict on academic dishonesty so i cant sorry if that makes it hard.
You are confusing the main question, with a potential solution.
Main Question:
I have a class ArrayListOwnerClass with an enclosed arraylist property or field.
How should another class ArrayListFriendClass access that property.
Potential Solution:
Should I pass the arraylist from ArrayListOwnerClass to ArrayListFriendClass,
in the ArrayListFriendClass constructor ?
It depends on what the second class does with the arraylist.
Instead of passing the list thru the constructor, you may add functions to read or change, as public, the elements of the hidden internal arraylist.
Note: You did not specify a programming language. I'll use C#, altought Java, C++, or similar O.O.P. could be used, instead.
public class ArrayListOwnerClass
{
protected int F_Length;
protected ArrayList F_List;
public ArrayListOwnerClass(int ALength)
{
this.F_Length = ALength;
this.F_List = new ArrayList(ALength);
// ...
} // ArrayListOwnerClass(...)
public int Length()
{
return this.F_Length;
} // int Length(...)
public object getAt(int AIndex)
{
return this.F_List[AIndex];
} // object getAt(...)
public void setAt(int AIndex, object AValue)
{
this.F_List[AIndex] = AValue;
} // void setAt(...)
public void DoOtherStuff()
{
// ...
} // void DoOtherStuff(...)
// ...
} // class ArrayListOwnerClass
public class ArrayListFriendClass
{
public void UseArrayList(ArrayListOwnerClass AListOwner)
{
bool CanContinue =
(AListOwner != null) && (AListOwner.Length() > 0);
if (CanContinue)
{
int AItem = AListOwner.getAt(5);
DoSomethingWith(Item);
} // if (CanContinue)
} // void UseArrayList(...)
public void AlsoDoesOtherStuff()
{
// ...
} // void AlsoDoesOtherStuff(...)
// ...
} // class ArrayListFriendClass
Note, that I could use an indexed property.

Rhino.Mocks how to test abstract class method calls

I'm trying to test if the method I want to test calls some external (mock) object properly.
Here is the sample code:
using System;
using Rhino.Mocks;
using NUnit.Framework;
namespace RhinoTests
{
public abstract class BaseWorker
{
public abstract int DoWork(string data);
}
public class MyClass
{
private BaseWorker worker;
public BaseWorker Worker
{
get { return this.worker; }
}
public MyClass(BaseWorker worker)
{
this.worker = worker;
}
public int MethodToTest(string data)
{
return this.Worker.DoWork(data);
}
}
[TestFixture]
public class RhinoTest
{
[Test]
public void TestMyMethod()
{
BaseWorker mock = MockRepository.GenerateMock<BaseWorker>();
MyClass myClass = new MyClass(mock);
string testData = "SomeData";
int expResponse = 10;
//I want to verify, that the method forwards the input to the worker
//and returns the result of the call
Expect.Call(mock.DoWork(testData)).Return(expResponse);
mock.GetMockRepository().ReplayAll();
int realResp = myClass.MethodToTest(testData);
Assert.AreEqual(expResponse, realResp);
}
}
}
When I run this test, I get:
TestCase 'RhinoTests.RhinoTest.TestMyMethod'
failed: System.InvalidOperationException : Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).
at Rhino.Mocks.LastCall.GetOptions[T]()
at Rhino.Mocks.Expect.Call[T](T ignored)
RhinoTest.cs(48,0): at RhinoTests.RhinoTest.TestMyMethod()
The exception is thrown on the Expect.Call line, before any invocation is made.
How do I approach this - i.e. how to check if the method under test properly forwards the call?
This is .Net 2.0 project (I can no change this for now), so no "x =>" syntax :(
I have to admit, I'm not entirely sure what's going on here, but using Rhino.Mocks 3.6 and the newer syntax, it works fine for me:
[Test]
public void TestMyMethod()
{
MockRepository mocks = new MockRepository();
BaseWorker mock = mocks.StrictMock<BaseWorker>();
MyClass myClass = new MyClass(mock);
string testData = "SomeData";
int expResponse = 10;
using (mocks.Record())
{
//I want to verify, that the method forwards the input to the worker
//and returns the result of the call
Expect.Call(mock.DoWork(testData)).Return(expResponse);
}
using (mocks.Playback())
{
int realResp = myClass.MethodToTest(testData);
Assert.AreEqual(expResponse, realResp);
}
}
It doesn't have anything to do with the Rhino.Mocks version. With the old syntax, I get the same error as you're getting. I didn't spot any obvious errors in your code, but then again, I'm used to this using syntax.
Edit: removed the var keyword, since you're using .NET 2.0.