FileNotFoundException ResourceManage::GetString C++/CLI - .net-4.0

I have a MFC DLL with CLR enabled and using .Net v4.0 in VS2010 SP1. I have added a new managed resource file called ReportStrings.resx to the root of the project. I am using the code below to access the resources. No matter what I put in the ResourceManger constructor. I am getting a FileNotFoundException when rmResources->GetString(sKey) is called. The exception says "Could not find file 'Report.resources'." I searched my application for any references to Report.resources and did not find any. Any help would be gretaly appreciated.
Thanks,
Josh
public ref class ResourceGetter
{
static ResourceManager^ rmResources = gcnew ResourceManager("Report.ReportStrings", Assembly::GetExecutingAssembly());
public:
static String^ GetResource(String^ sKey)
{
String^ sReturn = nullptr;
String^ sTheme = String::Empty;
try
{
sReturn = rmResources->GetString(sKey);
}
catch (Exception^ ex)
{
ex;
}
return (sReturn == nullptr) ? "[" + sKey + " not found]" : sReturn;
}
};

Okay, after creating several test projects and recreating my application project from scratch I seem to have found the issue. If I initialize the resources in the app constructor of my main file everything works correctly. So for example, my project is named Report, so I add the initailization code to the CReportApp constructor in the Report.cpp file and all is well. Thanks for your help Hans Passant. My code is below:
ResourceGetter.h
#pragma once
using namespace System;
using namespace System::Resources;
public ref class ResourceGetter
{
static ResourceManager^ rmResources = nullptr;
public:
static ResourceGetter()
{
}
static void Initialize()
{
if ( rmResources == nullptr )
{
rmResources = gcnew ResourceManager("Report.ReportStrings", Assembly::GetExecutingAssembly());
ResourceProxy::Initialize(gcnew Mnc::Utilities::GetResourceDelegate(&ResourceGetter::GetResource));
}
}
static String^ GetResource(String^ sKey)
{
String^ sReturn = nullptr;
try
{
if ( rmResources != nullptr )
sReturn = rmResources->GetString(sKey);
else
System::Diagnostics::Debug::WriteLine("Failed to retrieve resource (" + sKey + "): Returned null.");
}
catch (Exception^ ex)
{
ex;
}
return (sReturn == nullptr) ? "[" + sKey + " not found]" : sReturn;
}
};
Report.cpp
CReportApp::CReportApp()
{
ResourceGetter::Initialize();
}

Related

Unable to unload DLL in .NET Core 3

I am trying to unload an external assemble but it still sitting in the memory and I can not delete the dll file. Here is my code - What am I doing wrong ?
The uploaded dll is very simple - just 1 class and one method. no dependencies.
I had a look at many samples and see no issue in the code but it still does not work.
Thank you !
class SimpleUnloadableAssemblyLoadContext : AssemblyLoadContext
{
public SimpleUnloadableAssemblyLoadContext( ) : base(isCollectible: true)
{
}
protected override Assembly Load(AssemblyName name)
{
return null;
}
}
public class PluginLoader2
{
[MethodImpl(MethodImplOptions.NoInlining)]
public string getExternalText()
{
string res = "";
var sourcesPath = Path.Combine(Environment.CurrentDirectory, "Plugins");
string[] fileEntries = Directory.GetFiles(sourcesPath);
foreach (string fileName in fileEntries)
{
SimpleUnloadableAssemblyLoadContext context = new SimpleUnloadableAssemblyLoadContext();
WeakReference w_r = new WeakReference(context, trackResurrection: true);
var myAssembly = context.LoadFromAssemblyPath(fileName);
context.Unload();
for (var i = 0; i < 10 && w_r.IsAlive; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
res += "<br /><br />" + fileName + " live status is " + w_r.IsAlive.ToString();
}
return res;
}
}

Osmdroid - from offline folder

I am using OSMdroid to display both online and offline data in my app. The offline data are stored in a .zip file with the required structure.
Is it possible to have these offline tiles stored in a directory (extracted .zip file with the same structure)?
Could somebody please tell me how could I achive this?
Thank you.
I am sorry. I should try more before asking. But I am leaving this question here, somebody could find it useful.
Solution:
New MapTileFileProvider. I called it MapTileFileFolderProvider, it is a lightly modified MapTileFileArchiveProvider. It is using folders instead of archives. The modifications are not perfect, it is a "hot solution" that needs someone more experienced in Java/Android to make it properly.
Benefits from loading Tiles from folders:
Faster loading of tiles (I know, I won't recognize the difference).
Easier updates focused only on changed tiles not whole map plans.
Application can download tiles when is in "online mode" and then use the downloaded Tiles offline.
MapTileFileFolderProvider - only modifications
public class MapTileFileArchiveProvider extends MapTileFileStorageProviderBase
public class MapTileFileFolderProvider extends MapTileFileStorageProviderBase {
private final boolean mSpecificFoldersProvided;
private final ArrayList<String> mFolders = new ArrayList<String>();
private final AtomicReference<ITileSource> mTileSource = new AtomicReference<ITileSource>();
...
}
public MapTileFileArchiveProvider(...)
public MapTileFileFolderProvider(final IRegisterReceiver pRegisterReceiver,
final ITileSource pTileSource,
final String[] pFolders) {
super(pRegisterReceiver, NUMBER_OF_TILE_FILESYSTEM_THREADS,
TILE_FILESYSTEM_MAXIMUM_QUEUE_SIZE);
setTileSource(pTileSource);
if (pFolders == null) {
mSpecificFoldersProvided = false;
findFolders();
} else {
mSpecificFoldersProvided = true;
for (int i = pFolders.length - 1; i >= 0; i--) {
mFolders.add(pFolders[i]);
}
}
}
findArchiveFiles()
private void findFolders() {
mFolders.clear();
if (!getSdCardAvailable()) {
return;
}
String baseDirPath = Environment.getExternalStorageDirectory().toString()+"/ctu_navigator"; // TODO get from Config
File dir=new File(baseDirPath);
final File[] files = dir.listFiles();
if (files != null) {
String fileName;
for (File file : files) {
if (file.isDirectory()) {
fileName = baseDirPath + '/' + file.getName();
mFolders.add(fileName);
Utils.log(PlanTileProviderFactory.class, "Added map source: " + fileName);
}
}
}
}
#Override
protected String getName() {
return "Folders Provider";
}
#Override
protected String getThreadGroupName() {
return "folder";
}
protected class TileLoader extends MapTileModuleProviderBase.TileLoader {
#Override
public Drawable loadTile(final MapTileRequestState pState) {
ITileSource tileSource = mTileSource.get();
if (tileSource == null) {
return null;
}
final MapTile pTile = pState.getMapTile();
// if there's no sdcard then don't do anything
if (!getSdCardAvailable()) {
Utils.log("No sdcard - do nothing for tile: " + pTile);
return null;
}
InputStream inputStream = null;
try {
inputStream = getInputStream(pTile, tileSource);
if (inputStream != null) {
Utils.log("Use tile from folder: " + pTile);
final Drawable drawable = tileSource.getDrawable(inputStream);
return drawable;
}
} catch (final Throwable e) {
Utils.log("Error loading tile");
Utils.logError(getClass(), (Exception) e);
} finally {
if (inputStream != null) {
StreamUtils.closeStream(inputStream);
}
}
return null;
}
private synchronized InputStream getInputStream(final MapTile pTile, final ITileSource tileSource) {
for (final String folder : mFolders) {
final String path = folder + '/' + tileSource.getTileRelativeFilenameString(pTile);
File mapTileFile = new File(path);
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(mapTileFile));
} catch (IOException e) {
//Utils.log("Tile " + pTile + " not found in " + path);
}
if (in != null) {
Utils.log("Found tile " + pTile + " in " + path);
return in;
}
}
Utils.log("Tile " + pTile + " not found.");
return null;
}
}
Well, as far as I understand what you are trying to get... this is more or less what the standard XYTileSource is already doing.
So if you simply use a ready-to-use tile source like this one:
map.setTileSource(TileSourceFactory.MAPNIK);
you will see downloaded tiles files stored in /sdcard/osmdroid/tiles/Mapnik/
The main difference is that it adds a ".tile" extension at the end of each tile file (probably to prevent tools like Android gallery to index all those images).
If you have a ZIP file with tiles ready to use, you could extract them in this directory, and add .tile extension to each tile (355.png => 355.png.tile)
And TileSourceFactory.MAPNIK will be able to use them.

How to add and configure asmack in android

Please can you help with a break down of how you got asmack working in your android. I cant get it to work for my application. I keep geting java.lang.verifyError.
Be sure to include latest version i.e. asmack-android-17-0.8.3 of asmack library in libs folder.
Adding this might remove java.lang.VerifyError.
I do it the following way, it works perfectly.
public void login(View view)
{
new Connection().execute("username", "password");
}
private class Connection extends AsyncTask<String, Void, Integer>
{
private static final int CONNECTION_FAILURE = 0;
private static final int LOGIN_FAILURE = 1;
private static final int SUCCESS = 2;
#Override
protected Integer doInBackground(String... strings)
{
ConnectionConfiguration conConfig = new ConnectionConfiguration("192.168.1.100", 5222, "domain");
connection = new XMPPConnection(conConfig);
try
{
connection.connect();
Log.i("AppName", "CONNECTED TO " + connection.getHost());
}
catch(Exception e)
{
Log.e("AppName", e.getMessage());
return CONNECTION_FAILURE;
}
try
{
connection.login(strings[0], strings[1]);
Log.i("AppName", "LOGGED IN AS " + connection.getUser());
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
}
catch(Exception e)
{
Log.e("AppName", e.getMessage());
return LOGIN_FAILURE;
}
return SUCCESS;
}
}

How to handle design errors in a Custom Control in XPages?

In a custom control there is this repeat control that refers to a column in a folder (not a view). The folder's default design can be changed in time, in combination with the custom control. So it could happen that the code of the custom control is newer than the design of the folder, and hence the design doesn't match and the XPage errors out.
What I specifically want is that the custom control handles errors related to a missing view/folder column or similar design errors. The error is to be reported somewhere, informing the user that he/she can activate something that will repair the situation.
I know how to trap JavaScript errors, unfortunately all column values are in Expression Language. I could recode them, of course, but I'd like to know if there's a better way.
In short: how can I trap Expression Language errors?
You can trap EL language errors by adding your own VariableResolverand your own PropertyResolver. To do this, you have to create two Java classes:
The Variable resolver
package ch.hasselba.xpages.demo;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.el.EvaluationException;
import javax.faces.el.VariableResolver;
public class ELErrVariableResolver extends VariableResolver {
private final VariableResolver delegate;
public ELErrVariableResolver(VariableResolver resolver) {
delegate = resolver;
}
#Override
public Object resolveVariable(FacesContext context, String name) throws EvaluationException {
Object variable = null;
try{
variable = delegate.resolveVariable(context, name);
}catch( EvaluationException ee ){
addResolveErrMessage( context, name );
}
return variable;
}
public void addResolveErrMessage( FacesContext context , String name ){
FacesMessage msg = new FacesMessage();
msg.setSummary( "BAD EL! Variable '" + name + "' not found." );
msg.setSeverity( FacesMessage.SEVERITY_FATAL );
context.addMessage("BAD EL!", msg);
}
}
The Property resolver
package ch.hasselba.xpages.demo;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.el.EvaluationException;
import javax.faces.el.PropertyNotFoundException;
import javax.faces.el.PropertyResolver;
public class ELErrPropertyResolver extends PropertyResolver{
private final PropertyResolver delegate;
public ELErrPropertyResolver(PropertyResolver resolver) {
delegate = resolver;
}
#Override
public Class getType(Object paramObject1, Object paramObject2)
throws EvaluationException, PropertyNotFoundException {
Class c = null;
try{
c = delegate.getType(paramObject1, paramObject2);
}catch(Exception e){
addResolveErrMessage( FacesContext.getCurrentInstance(), paramObject1.toString() + "." + paramObject2.toString() );
}
return c;
}
#Override
public Class getType(Object paramObject, int paramInt)
throws EvaluationException, PropertyNotFoundException {
Class c = null;
try{
c = delegate.getType(paramObject, paramInt);
}catch(Exception e){
addResolveErrMessage( FacesContext.getCurrentInstance(), paramObject.toString() + "." + paramInt );
}
return c;
}
#Override
public Object getValue(Object paramObject1, Object paramObject2)
throws EvaluationException, PropertyNotFoundException {
Object c = null;
try{
c = delegate.getValue(paramObject1, paramObject2);
}catch(Exception e){
addResolveErrMessage( FacesContext.getCurrentInstance(), paramObject1.toString() + "." + paramObject2.toString() );
}
return c;
}
#Override
public Object getValue(Object paramObject, int paramInt)
throws EvaluationException, PropertyNotFoundException {
Object c = null;
try{
c = delegate.getValue(paramObject, paramInt);
}catch(Exception e){
addResolveErrMessage( FacesContext.getCurrentInstance(), paramObject.toString() + "." + paramInt );
}
return c;
}
#Override
public boolean isReadOnly(Object paramObject1, Object paramObject2)
throws EvaluationException, PropertyNotFoundException {
boolean c = false;
try{
c = delegate.isReadOnly(paramObject1, paramObject2);
}catch(Exception e){
addResolveErrMessage( FacesContext.getCurrentInstance(), paramObject1.toString() + "." + paramObject2.toString() );
}
return c;
}
#Override
public boolean isReadOnly(Object paramObject, int paramInt)
throws EvaluationException, PropertyNotFoundException {
boolean c = false;
try{
c = delegate.isReadOnly(paramObject, paramInt);
}catch(Exception e){
addResolveErrMessage( FacesContext.getCurrentInstance(), paramObject.toString() + "." + paramInt );
}
return c;
}
#Override
public void setValue(Object paramObject1, Object paramObject2,
Object paramObject3) throws EvaluationException,
PropertyNotFoundException {
try{
delegate.setValue(paramObject1, paramObject2, paramObject3);
}catch(Exception e){
addResolveErrMessage( FacesContext.getCurrentInstance(), paramObject1.toString() + "." + paramObject2.toString() );
}
}
#Override
public void setValue(Object paramObject1, int paramInt, Object paramObject2)
throws EvaluationException, PropertyNotFoundException {
try{
delegate.setValue(paramObject1, paramInt, paramObject2);
}catch(Exception e){
addResolveErrMessage( FacesContext.getCurrentInstance(), paramObject1.toString() + "." + paramInt );
}
}
public void addResolveErrMessage( FacesContext context , String name ){
FacesMessage msg = new FacesMessage();
msg.setSummary( "BAD EL! Property '" + name + "' not found." );
msg.setSeverity( FacesMessage.SEVERITY_FATAL );
context.addMessage("BAD EL!", msg);
}
}
Add the new resolvers to your faces-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config>
<application>
<variable-resolver>ch.hasselba.xpages.demo.ELErrVariableResolver
</variable-resolver>
<property-resolver>ch.hasselba.xpages.demo.ELErrPropertyResolver
</property-resolver>
</application>
</faces-config>
On your CC add a xp:messages component to display your message (or change the error routine in the classes to add whatever you want.
In the custom control you can check if the folder/view you are going to work with is correct. Aka has the correct design. This can be done in the beforepageload event. When the design check reports an error it should be written to a log file and a 'nice' message should be displayed to the user.
The error logging could be done with the various logging projects on openntf like xlogger
When your code reports an error you can than set a scoped value called 'displayRepeat' to false. The repeat control ( and other controls ) should be rendered according to this displayRepeat value.
To display the nice error message to the user. Place a errors control on the top of your control and add the following code:
facesContext.addMessage( null,
new javax.faces.application.FacesMessage( "your error message" ) );

How to send Ctrl+C signal to a console process created with CreateNoWindow flag

If I use Process.Kill(), the process is killed. However, I would like to terminate it.
I tried with GenerateConsoleCtrlEvent(ConsoleCtrlEvent.CTRL_C, Process.Id) API, without success.
If I set False to CreateNoWindow flag, when I send Ctrl+C from keyboard, the program says "Caught signal: 2; Terminating". So it wait a "2" signal to terminate.
How can I do that?
There is a solution. I will try to describe it for you:
When you write the application which wraps the entire console - console into can't receive control codes for some reason (question going to Microsoft), but the console can still receive those events. How? From an external app.
This is the code for cas.exe
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleAppStopper
{
class cas
{
[STAThread]
static void Main( string[] args )
{
if (args.Length < 2)
{
Help ();
return;
}
int processId = int.Parse (args[0]);
ConsoleCtrlEvent CtrlEvent = (ConsoleCtrlEvent)int.Parse(args[1]);
FreeConsole ();
AttachConsole (processId);
GenerateConsoleCtrlEvent (CtrlEvent, 0);
}
static void Help()
{
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine ("Console Application Eventer(Stopper)");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine ("cas.exe ProcessId ControlEvent");
Console.WriteLine ("Events:");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine ("\tCTRL_C - 0");
Console.WriteLine ("\tCTRL_BREAK - 1");
Console.WriteLine ("\tCTRL_LOGOFF - 5");
Console.ResetColor ();
}
public enum ConsoleCtrlEvent
{
CTRL_C = 0, // From wincom.h
CTRL_BREAK = 1,
CTRL_CLOSE = 2,
CTRL_LOGOFF = 5,
CTRL_SHUTDOWN = 6
}
[DllImport ("kernel32.dll")]
static extern bool GenerateConsoleCtrlEvent( ConsoleCtrlEvent sigevent,
int dwProcessGroupId );
[DllImport ("kernel32.dll")]
static extern bool FreeConsole();
[DllImport ("kernel32.dll")]
static extern bool AttachConsole( int dwProcessId );
}
}
and how to use it:
public void SendConsoleEvent( ConsoleCtrlEvent ev )
{
if (!Running)
return;
try
{
String current_dir = System.Environment.CurrentDirectory;
String stopper = "cas.exe";
String args = pr.Id + " " + (int)ev;
CommandExecutor ex = new CommandExecutor (null, null);
ex.Start (current_dir, stopper, args);
// sometimes stop prevent CAS do work. just throw cas and forget about
//Timer.DelayCall (TimeSpan.FromSeconds (10), ex.Stop);
//ex.Stop ();
}
catch (Exception e)
{
Log ("SendConsoleEvent: " + e.ToString ());
}
}
Here, CommandExecutor is my threaded wrapper around Process.
pr.Id is the ID of previously started using Process console (where we need to send our CTRL_C or other events