scriptcs Mixed mode assembly error - scriptcs

I have added an application in scriptcs and added some references to assemblies which have the version v2.0.50727. So while running the scriptcs file it returns as Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime.Setting attribute useLegacyV2RuntimeActivationPolicy="true" in app.config may resolve the issue in asp.net web application. but in scriptcs its not working. further searching reveals that above attribbute useLegacyV2RuntimeActivationPolicy="true" should be added as scriptcs.exe.config. I have an application file named FMUpgrade.csx and how can we reference this scriptcs.exe.config in the FMUpgrade.csx file.scriptcs docs doesn't say much about scriptcs.exe.config.Also added program.exe.config with app.config but still not success.

After much research I got a workaround solution to the above problem.
By make use of class ExeConfigurationFileMap we could able to get the key values from app.config, its not able to bypass the supported runtime error caused by mixed mode assembly error.
Server server = new Server(new ServerConnection(con)); server.ConnectionContext.ExecuteNonQuery(script);
The error is caused while executing the statement ExecuteNonQuery.
So before executing the statement
if( RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully )
server.ConnectionContext.ExecuteNonQuery(script);
Solution is below
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public static class RuntimePolicyHelper
{
public static bool LegacyV2RuntimeEnabledSuccessfully
{ get; private set; }
static RuntimePolicyHelper()
{
ICLRRuntimeInfo clrRuntimeInfo =
(ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
Guid.Empty,
typeof(ICLRRuntimeInfo).GUID);
try
{
clrRuntimeInfo.BindAsLegacyV2Runtime();
LegacyV2RuntimeEnabledSuccessfully = true;
}
catch (COMException)
{
// This occurs with an HRESULT meaning
// "A different runtime was already bound to the legacy CLR version 2 activation policy."
LegacyV2RuntimeEnabledSuccessfully = false;
}
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
private interface ICLRRuntimeInfo
{
void xGetVersionString();
void xGetRuntimeDirectory();
void xIsLoaded();
void xIsLoadable();
void xLoadErrorString();
void xLoadLibrary();
void xGetProcAddress();
void xGetInterface();
void xSetDefaultStartupFlags();
void xGetDefaultStartupFlags();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void BindAsLegacyV2Runtime();
}
} using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public static class RuntimePolicyHelper
{
public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; }
static RuntimePolicyHelper()
{
ICLRRuntimeInfo clrRuntimeInfo =
(ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
Guid.Empty,
typeof(ICLRRuntimeInfo).GUID);
try
{
clrRuntimeInfo.BindAsLegacyV2Runtime();
LegacyV2RuntimeEnabledSuccessfully = true;
}
catch (COMException)
{
// This occurs with an HRESULT meaning
// "A different runtime was already bound to the legacy CLR version 2 activation policy."
LegacyV2RuntimeEnabledSuccessfully = false;
}
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
private interface ICLRRuntimeInfo
{
void xGetVersionString();
void xGetRuntimeDirectory();
void xIsLoaded();
void xIsLoadable();
void xLoadErrorString();
void xLoadLibrary();
void xGetProcAddress();
void xGetInterface();
void xSetDefaultStartupFlags();
void xGetDefaultStartupFlags();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void BindAsLegacyV2Runtime();
}
}

Related

error 1053: the service did not respond to the start or control request in a timely fashion on visual studio 2015

I made a windows service using C# as follow
public partial class Housekeeping : ServiceBase
{
#region Fields
private ManualResetEvent _ResetEvent = new ManualResetEvent(false);
private RegisteredWaitHandle _RegisteredWaitHandle;
private long _Interval = 60000;
private Logger _Logger;
#endregion
#region Constructors
public Housekeeping()
{
InitializeComponent();
_Interval = _Interval * Convert.ToInt32(ConfigurationManager.AppSettings["RunningInterval"]);
_Logger = new Logger();
}
#endregion
#region Properties
#endregion
#region Behaviors
public void Housekeep(object state, bool timeout)
{
try
{
// my code
}
catch (Exception ex)
{
// my code
}
}
protected override void OnStart(string[] args)
{
_RegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_ResetEvent, new WaitOrTimerCallback(Housekeep), null, _Interval, false);
}
protected override void OnStop()
{
}
protected override void OnContinue()
{
base.OnContinue();
}
protected override void OnPause()
{
base.OnPause();;
}
}
and on the main
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Housekeeping()
};
ServiceBase.Run(ServicesToRun);
}
}
I Installed the WS using InstallUtil.exe, but when I tried to start the WS I got this error "error 1053: the service did not respond to the start or control request in a timely fashion". I surfed around but all the solution are for a windows server 2003 issue and I'm running Windows 10.
How can I solve this issue?
Last time I have seen this issue, it got resolved by changing the compiling option from 'Debug' to 'Release'.

How to get plugins by setting a path

I created console c# project. and in the code I have made a module. My code looks like this.
[Import]
public IMessageSender MessageSender { get; set; }
public static void Main(string[] args)
{
Program p = new Program();
p.Run();
}
public void Run()
{
Compose();
Console.ReadLine(MessageSender.Send("Message Sent"));
}
private void Compose()
{
AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
public interface IMessageSender
{
string Send(string message);
}
[Export(typeof(IMessageSender))]
public class EmailSender : IMessageSender
{
public void Send(string message)
{
return message;
}
}
It works perfectly fine. But now I added a new project in my solution and added module into that
AnotherProject->EmailSender.cs
[Export(typeof(IMessageSender))]
public class EmailSender : IMessageSender
{
public void Send(string message)
{
return message;
}
}
Now in the main console program I changed some of my code.
private void Compose()
{
var catalog = new DirectoryCatalog(path);
//AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
But now when I run this program. It doesnt load the module. MessageSender in main program is null. What wrong I have done.
There are a few things you need to check:
Have you correctly referenced the assemblies?
The DirectoryCatalog by default uses the search pattern *.dll. Because you have a console application, which uses the .exe extension, no exports in that assembly will get picked up by the DirectoryCatalog - with the default search pattern. You'll likely want to use an AggregateCatalog, passing in the DirectoryCatalog (*.dll), and either another DirectoryCatalog (*.exe), or an AssemblyCatalog, of the entry assembly.
You currently have one [Import] where you may end up with multiple [Export(typeof(IMessageSender))], you didn't state that you have moved the EmailSender to the class library, merely that you have created a new one, which means you'll likely end up with a cardinality mismatch where it is expecting a sinple import, you have many exports. This will explicitly throw an exception, which is what will happen even it couldn't find a single instance of IMessageSender, because your [Import] attribute is not set to allow a default value where no part can be provided. If you need to be fault tollerant, you can use [Import(AllowDefault = true)]
Incidentally... the above code won't compile, I assume it was just an example and not a copy-paste from your current code?
public void SendMessage(string message)
{
return message;
}
You're retuning a message to a void method - that can't be done, and it also means that EmailSender doesn't correctly implement IMessageSender. Not too bothered, as I think it is an example more than actual code.

how to generate deployment descriptor using ejbGen for weblogic?

I was reading the tutorial on this page:
http://edocs.bea.com/docs/cd/E13222_01/wls/docs81/medrec_tutorials/ejbgen.html#858279
And I have the following file BankAccountEJB.java
import javax.ejb.CreateException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
public abstract class BankAccountEJB implements EntityBean {
private EntityContext context;
public void setEntityContext(EntityContext aContext) {
context = aContext;
}
public void ejbActivate() {
}
public void ejbPassivate() {
}
public void ejbRemove() {
}
public void unsetEntityContext() {
context = null;
}
public void ejbLoad() {
}
public void ejbStore() {
}
public abstract String getName();
public abstract void setName(String name);
public abstract Float getBalance();
public abstract void setBalance(Float balance);
public java.lang.Long ejbCreate(String name, Float balance) throws CreateException {
if (name == null) {
throw new CreateException("The field \"key\" must not be null");
}
// TODO add additional validation code, throw CreateException if data is not valid
setName(name);
setBalance(balance);
return null;
}
public void ejbPostCreate(java.lang.Long key) {
// TODO populate relationships here if appropriate
}
}
and I run java weblogic.tools.ejbgen.EJBGen -ddOnlyGen BankAccountEJB.java which produces the following error:
Exception in thread "main" com.bea.wls.ejbgen.EJBGenException: ejbName is a required attribute
at com.bea.wls.ejbgen.Bean.createBeanSpecificTags(Bean.java:202)
at com.bea.wls.ejbgen.Bean.(Bean.java:127)
at com.bea.wls.ejbgen.EntityBean.(EntityBean.java:76)
at com.bea.wls.ejbgen.EJBFactory.createBean(EJBFactory.java:135)
at com.bea.wls.ejbgen.EJBFactory.createBean(EJBFactory.java:99)
at com.bea.wls.ejbgen.EJBGenSGen.initModule(EJBGenSGen.java:106)
at com.bea.sgen.SGen.run(SGen.java:205)
at com.bea.wls.ejbgen.EJBGen.main(EJBGen.java:212)
at com.bea.wls.ejbgen.EJBGen.main(EJBGen.java:238)
at weblogic.tools.ejbgen.EJBGen.main(EJBGen.java:21)
Any input will be greatly appreciated~!
Note: Are you still running Weblogic 8.1 - it's already reached end of life. Also ejbgen works with EJB 2.x and over the last 2 years, development has moved on to EJB 3, so i'd advise you to catch up on those.
Now to your specific problem.
Your code does not seem to have the required annotations for ejbgen to work.
Annotations like this which are used in generation of the descriptors.
* #ejbgen:entity
* ejb-name = containerManaged
* table-name = ejbAccounts
* data-source-name = examples-dataSource-demoPool
* prim-key-class = AccountPK
* invalidation-target = ServiceDesignEJB
As your URL says the code in the tutorial has the right data as a sample - make sure you replicate those correctly in your own code.
EJBGen uses annotations in the bean
file to generate the deployment
descriptor files and the EJB Java
source files. EJB files in the MedRec
application are already annotated for
EJBGen.
For another version of ejbgen, see http://www.beust.com/ejbgen/

GWT Void remote services fail for seemingly no reason

I'm working on a GWT project and have several void remote services that seem to execute just fine, but on the client side, end up firing the onFailure() method. No exceptions are thrown anywhere, and the expected behavior is observed on the backend. I have no idea what could be going wrong. Here is the relevant code:
Interfaces and implementation...
#RemoteServiceRelativePath("DeleteSearchService")
public interface DeleteSearchService extends RemoteService {
/**
* Utility class for simplifying access to the instance of async service.
*/
public static class Util {
private static DeleteSearchServiceAsync instance;
public static DeleteSearchServiceAsync getInstance(){
if (instance == null) {
instance = GWT.create(DeleteSearchService.class);
}
return instance;
}
}
public void delete(SearchBean search);
}
public interface DeleteSearchServiceAsync {
public void delete(SearchBean bean, AsyncCallback<Void> callback);
}
public class DeleteSearchServiceImpl extends RemoteServiceServlet implements DeleteSearchService {
private static final long serialVersionUID = 1L;
#Override
public void delete(SearchBean search) {
try {
Connection conn = SQLAccess.getConnection();
String sql = "DELETE FROM `searches` WHERE `id`=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, search.getSearchId());
ps.execute();
sql = "DELETE FROM `searchsourcemap` WHERE `search-id` = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, search.getSearchId());
ps.execute();
return;
} catch (Exception e) {
// TODO Log error
e.printStackTrace();
}
}
}
Calling code...
private class DeleteListener implements ClickListener {
public void onClick(Widget sender) {
DeleteSearchServiceAsync dss = DeleteSearchService.Util.getInstance();
SearchBean bean = buildBeanFromGUI();
dss.delete(bean, new AsyncCallback<Void>(){
//#Override
public void onFailure(Throwable caught) {
// TODO log
SearchNotDeleted snd = new SearchNotDeleted();
snd.show();
}
//#Override
public void onSuccess(Void result) {
SearchDeleted sd = new SearchDeleted();
sd.show();
searchDef.getParent().removeFromParent();
}
});
}
}
I know I'm a jerk for posting like 500 lines of code but I've been staring at this since yesterday and can't figure out where I'm going wrong. Maybe a 2nd set of eyes would help...
Thanks,
brian
LGTM I'm afraid.
Are you using the hosted mode or a full-fledged browser? You can try switching and see if it helps.
Also, it might help listening to that //TODO and perform a GWT.log when onFailure is invoked.

Why does MSTest and TestDriven.NET behave differently using this code?

Check out this code:
internal static readonly Dictionary<Type, Func<IModel>> typeToCreator = new Dictionary<Type, Func<IModel>>();
protected static object _lock;
public virtual void Register<T>(Func<IModel> creator)
{
lock (_lock)
{
if (typeToCreator.ContainsKey(typeof(T)))
typeToCreator[typeof(T)] = creator;
else
typeToCreator.Add(typeof(T), creator);
}
}
When I use run the code in this test (testframework is MSTest):
[TestMethod]
public void Must_Be_BasePresenterType()
{
var sut = new ListTilbudPresenter(_tilbudView);
Assert.IsInstanceOfType(sut, typeof(BasePresenter));
}
...MSTest passes it and TestDriven.NET fails it because _lock is null.
Why does MSTest NOT fail the test???